Search is not available for this dataset
text
string
meta
dict
#pragma once #include <DirectXMath.h> #include <d3d11.h> #include <gsl\gsl> namespace Library { class Mesh; template <typename T> struct VertexDeclaration { static constexpr uint32_t VertexSize() { return gsl::narrow_cast<uint32_t>(sizeof(T)); } static constexpr uint32_t VertexBufferByteWidth(size_t vertexCount) { return gsl::narrow_cast<uint32_t>(sizeof(T) * vertexCount); } static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const T>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer); }; class VertexPosition : public VertexDeclaration<VertexPosition> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPosition() = default; VertexPosition(const DirectX::XMFLOAT4& position) : Position(position) { } DirectX::XMFLOAT4 Position; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements { _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPosition>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexPositionColor : public VertexDeclaration<VertexPositionColor> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPositionColor() = default; VertexPositionColor(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT4& color) : Position(position), Color(color) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT4 Color; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionColor>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexPositionTexture : public VertexDeclaration<VertexPositionTexture> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPositionTexture() = default; VertexPositionTexture(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates) : Position(position), TextureCoordinates(textureCoordinates) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT2 TextureCoordinates; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionTexture>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexPositionSize : public VertexDeclaration<VertexPositionSize> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "SIZE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPositionSize() = default; VertexPositionSize(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& size) : Position(position), Size(size) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT2 Size; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionSize>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexPositionNormal : public VertexDeclaration<VertexPositionNormal> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPositionNormal() = default; VertexPositionNormal(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT3& normal) : Position(position), Normal(normal) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT3 Normal; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionNormal>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexPositionTextureNormal : public VertexDeclaration<VertexPositionTextureNormal> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPositionTextureNormal() = default; VertexPositionTextureNormal(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates, const DirectX::XMFLOAT3& normal) : Position(position), TextureCoordinates(textureCoordinates), Normal(normal) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT2 TextureCoordinates; DirectX::XMFLOAT3 Normal; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionTextureNormal>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexPositionTextureNormalTangent : public VertexDeclaration<VertexPositionTextureNormalTangent> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; public: VertexPositionTextureNormalTangent() = default; VertexPositionTextureNormalTangent(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates, const DirectX::XMFLOAT3& normal, const DirectX::XMFLOAT3& tangent) : Position(position), TextureCoordinates(textureCoordinates), Normal(normal), Tangent(tangent) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT2 TextureCoordinates; DirectX::XMFLOAT3 Normal; DirectX::XMFLOAT3 Tangent; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexPositionTextureNormalTangent>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; class VertexSkinnedPositionTextureNormal : public VertexDeclaration<VertexSkinnedPositionTextureNormal> { private: inline static const D3D11_INPUT_ELEMENT_DESC _InputElements[] { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "BONEINDICES", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "BONEWEIGHTS", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; public: VertexSkinnedPositionTextureNormal() = default; VertexSkinnedPositionTextureNormal(const DirectX::XMFLOAT4& position, const DirectX::XMFLOAT2& textureCoordinates, const DirectX::XMFLOAT3& normal, const DirectX::XMUINT4& boneIndices, const DirectX::XMFLOAT4& boneWeights) : Position(position), TextureCoordinates(textureCoordinates), Normal(normal), BoneIndices(boneIndices), BoneWeights(boneWeights) { } DirectX::XMFLOAT4 Position; DirectX::XMFLOAT2 TextureCoordinates; DirectX::XMFLOAT3 Normal; DirectX::XMUINT4 BoneIndices; DirectX::XMFLOAT4 BoneWeights; inline static const gsl::span<const D3D11_INPUT_ELEMENT_DESC> InputElements{ _InputElements }; static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer); static void CreateVertexBuffer(gsl::not_null<ID3D11Device*> device, const gsl::span<const VertexSkinnedPositionTextureNormal>& vertices, gsl::not_null<ID3D11Buffer**> vertexBuffer) { VertexDeclaration::CreateVertexBuffer(device, vertices, vertexBuffer); } }; } #include "VertexDeclarations.inl"
{ "alphanum_fraction": 0.7873223842, "avg_line_length": 44.4180327869, "ext": "h", "hexsha": "a035a08b94d9cd4d8f7d47c84e8fde9b538d0b2d", "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/VertexDeclarations.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/VertexDeclarations.h", "max_line_length": 226, "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/VertexDeclarations.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3049, "size": 10838 }
/* -*- linux-c -*- */ /* fewbody_int.c Copyright (C) 2002-2004 John M. Fregeau 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 <stdio.h> #include <stddef.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #include "fewbody.h" /* allocate memory for ks_params */ void fb_malloc_ks_params(fb_ks_params_t *ks_params) { ks_params->m = fb_malloc_vector(ks_params->nstar); ks_params->M = fb_malloc_vector(ks_params->kstar); ks_params->amat = fb_malloc_matrix(ks_params->nstar, ks_params->kstar); ks_params->Tmat = fb_malloc_matrix(ks_params->kstar, ks_params->kstar); } /* initialize ks_params; assumes ks_params is already malloc()ed */ void fb_init_ks_params(fb_ks_params_t *ks_params, fb_hier_t hier) { int i, j, k; double *y; /* exit if hier is not consistent with ks_params */ if (ks_params->nstar != hier.nobj) { fprintf(stderr, "fb_init_ks_params(): ks_params->nstar != hier.nobj: ks_params->nstar=%d hier.nobj=%d\n", \ ks_params->nstar, hier.nobj); exit(1); } /* first set the mass matrix */ for (i=0; i<hier.nobj; i++) { ks_params->m[i] = hier.obj[i]->m; } /* calculate the M_k */ k = -1; for (i=0; i<hier.nobj-1; i++) { for (j=i+1; j<hier.nobj; j++) { k++; ks_params->M[k] = ks_params->m[i] * ks_params->m[j]; } } /* calculate and set the a and T matrices */ fb_calc_amat(ks_params->amat, ks_params->nstar, ks_params->kstar); fb_calc_Tmat(ks_params->amat, ks_params->m, ks_params->Tmat, ks_params->nstar, ks_params->kstar); /* set Einit */ y = fb_malloc_vector(8*ks_params->kstar+1); fb_euclidean_to_ks(hier.obj, y, ks_params->nstar, ks_params->kstar); ks_params->Einit = fb_ks_Einit(y, *ks_params); fb_free_vector(y); } /* free memory for ks_params */ void fb_free_ks_params(fb_ks_params_t ks_params) { fb_free_vector(ks_params.m); fb_free_vector(ks_params.M); fb_free_matrix(ks_params.amat); fb_free_matrix(ks_params.Tmat); } /* allocate memory for nonks_params */ void fb_malloc_nonks_params(fb_nonks_params_t *nonks_params) { nonks_params->m = fb_malloc_vector(nonks_params->nstar); } /* initialize nonks_params; assumes nonks_params is already malloc()ed */ void fb_init_nonks_params(fb_nonks_params_t *nonks_params, fb_hier_t hier) { int i; /* exit if hier is not consistent with nonks_params */ if (nonks_params->nstar != hier.nobj) { fprintf(stderr, "fb_init_nonks_params(): nonks_params->nstar != hier.nobj: nonks_params->nstar=%d hier.nobj=%d\n", \ nonks_params->nstar, hier.nobj); exit(1); } /* set the mass vector */ for (i=0; i<hier.nobj; i++) { nonks_params->m[i] = hier.obj[i]->m; } } /* free memory for ks_params */ void fb_free_nonks_params(fb_nonks_params_t nonks_params) { fb_free_vector(nonks_params.m); }
{ "alphanum_fraction": 0.7131147541, "avg_line_length": 29.7043478261, "ext": "c", "hexsha": "6ed036af99fdaf766253eefbefba5fe21019d24c", "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": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": [ "PSF-2.0" ], "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_int.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_licenses": [ "PSF-2.0" ], "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody_int.c", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": [ "PSF-2.0" ], "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_int.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1022, "size": 3416 }
#pragma once #include <Runtime/Runtime.h> #include <napi/napi.h> #include <memory> #include <gsl/gsl> namespace babylon { class ScriptHost final { public: explicit ScriptHost(RuntimeImpl&); ScriptHost(const ScriptHost&) = delete; ~ScriptHost(); void RunScript(gsl::czstring<> script, gsl::czstring<> url); Napi::Env& Env(); private: class Impl; std::unique_ptr<Impl> m_impl; }; }
{ "alphanum_fraction": 0.6052060738, "avg_line_length": 17.7307692308, "ext": "h", "hexsha": "d2c32c51b9792abfdfcd25c710f5eedcd1dfa528", "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": "6d15ec5d418f7f723eba574665233049c785cc72", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "TrevorDev/BabylonNative", "max_forks_repo_path": "Library/Source/ScriptHost.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "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": "TrevorDev/BabylonNative", "max_issues_repo_path": "Library/Source/ScriptHost.h", "max_line_length": 68, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "TrevorDev/BabylonNative", "max_stars_repo_path": "Library/Source/ScriptHost.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 114, "size": 461 }
#ifndef math_utility_c__H #define math_utility_c__H /********************************* TRICK HEADER ******************************* PURPOSE: (Math functions C Version) LIBRARY DEPENDENCY: ((../src/math_utility_c.c) (../../cad/src/global_constants.c)) *******************************************************************************/ #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <math.h> #ifdef __cplusplus extern "C" { #endif extern const double ___PI; extern const double __RAD; extern const double __EPS; int pol_from_cart_C(const gsl_vector *cart, gsl_vector *pol); int build_psivg_thtvg_TM_C(const double psivg, const double thtvg, gsl_matrix *AMAT); int build_psi_tht_phi_TM_C(const double psi, const double tht, const double phi, gsl_matrix *TM); int Matrix2Quaternion_C(gsl_matrix *Matrix_in, gsl_vector *Quaternion_out); int Quaternion2Matrix_C(const gsl_vector *Quaternion_in, gsl_matrix *Matrix_out); int Quaternion_cross_C(const gsl_vector *Quaternion_in1, const gsl_vector *Quaternion_in2, gsl_vector *Quaternion_out); int Quaternion2Euler_C(const gsl_vector *Quaternion_in, double *Roll, double *Pitch, double *Yaw); int Euler2Quaternion_C(const double Roll, const double Pitch, const double Yaw, gsl_vector *Quaternion_out); int QuaternionMultiply_C(const gsl_vector *Quaternion_in1, const gsl_vector *Quaternion_in2, gsl_vector *Quaternion_out); int Quaternion_rotation_C(const gsl_vector *Vector_in, const gsl_vector *Quaternion_in, gsl_vector *Vector_out); int build_321_rotation_matrix(const gsl_vector *angle, gsl_matrix *mat_out); int sign(const double variable); int euler_angle(gsl_matrix *TBD, gsl_vector *euler_ang); gsl_matrix* moore_penrose_pinv(gsl_matrix *A, const double rcond); gsl_matrix *skew_sym_C(const gsl_vector *vec); gsl_vector *Quaternion_conjugate_C(const gsl_vector *Quaternion_in); gsl_vector *QuaternionInverse_C(const gsl_vector *Quaternion_in); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.746993988, "avg_line_length": 42.4680851064, "ext": "h", "hexsha": "9fc111a79890e2932aaa77f2cd79384c0a9b15c5", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_path": "models/math/include/math_utility_c.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "cihuang123/Next-simulation", "max_issues_repo_path": "models/math/include/math_utility_c.h", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_path": "models/math/include/math_utility_c.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 469, "size": 1996 }
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SIM_MATH_UTIL_H_ #define SIM_MATH_UTIL_H_ #include <stdint.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <functional> #include <limits> #include <random> #include <string> #include "common/c_math/util.h" // Generates random numbers using a generator seeded by a string hash. This // facilitates binding of generators to simulator models. // // A static seed offset can be specified using SetSeedOffset, supporting // deterministic perturbation of the generators used by all models. class NamedRandomNumberGenerator { public: explicit NamedRandomNumberGenerator(const std::string &name) : generator_(static_cast<uint32_t>(std::hash<std::string>{}(name)) + seed_offset_), normal_(0.0, 1.0), uniform_real_(0.0, 1.0), uniform_int32_(0, std::numeric_limits<int32_t>::max()) {} // Returns a random number drawn from a normal distribution with mean=0.0 // and stddev=1.0. double GetNormal() { return normal_(generator_); } // Returns a random number drawn from a uniform distribution on [0.0, 1.0). double GetUniformReal() { return uniform_real_(generator_); } // Returns a random integer drawn from a uniform distribution on // [0, std::numeric_limits<int32_t>::max()]. int32_t GetUniformInt32() { return uniform_int32_(generator_); } static void SetSeedOffset(uint32_t offset) { seed_offset_ = offset; } private: static uint32_t seed_offset_; // 32-bit Mersenne Twister generator. std::mt19937 generator_; std::normal_distribution<double> normal_; std::uniform_real_distribution<double> uniform_real_; std::uniform_int_distribution<int32_t> uniform_int32_; }; // The hypergeometric function, {_2}F_1(a, b; c; z) double HyperGeom(double a, double b, double c, double z); uint32_t Factorial(uint32_t n); // The rising factorial, denoted by the Pochhammer symbol (q)_n, is // defined by: // // (q)_n = 1 if n == 0 // q*(q+1)*...*(q+n-1) if n > 0 // // Warning: The Pochhammer symbol can denote either rising or falling // factorial depending on context. double RisingFactorial(double q, int32_t n); // Computes the intersection point of two circles in a coordinate // system centered at the first circle and with the positive x-axis // along the line between the centers of the first and second circles. // For both the non-degenerate intersecting and single point // intersecting cases, this returns the intersection point with // non-negative y. For the identical center case, this returns the // point (r1, 0) where r1 is the radius of the first circle. For the // remaining non-intersecting case, this returns the point: // // ((d^2 + r1^2 - r2^2) / (2 * d), 0) // // For a derivation of the formulas used here, see: // http://mathworld.wolfram.com/Circle-CircleIntersection.html // // Args: // d: Distance, always positive, between circle centers. // r1: Radius of first circle. // r2: Radius of second circle. // x: Output pointer to x coordinate of intersection (i.e. the // distance along line between first and second circle). // y: Output pointer to y coordinate of intersection (i.e. the // perpendicular distance, always positive, from line connecting // circle centers). // // Returns: // True if the circles intersect. bool IntersectCircles(double d, double r1, double r2, double *x, double *y); // Finds the fractional index of a value x_i in a GSL vector x // assuming x is monotonically increasing. double gsl_interp_index(const gsl_vector *x, double x_i); // Performs a linear interpolation along a pair of GSL vectors. The // function to interpolate on is described by the input GSL vector x // and the output GSL vector y. Interp1 linearly interpolates to find // the value of y for input x_i. If opt is kInterpOptionDefault, // extrapolate linearly beyond the end of the vectors. If opt is // kInterpOptionSaturate, saturate the output value at the // ends of the output (y) vector. // // Warning: This currently assumes a monotonically increasing x. double gsl_interp1(const gsl_vector *x, const gsl_vector *y, double xi, InterpOption opt); // Linear interpolation along a pair of vectors and a matrix. // // The function to interpolate on is described by the input vectors x // and y and the output matrix z, with corresponding entries for its // value at each (x,y) input pair. Interp2 bilinearly interpolates to // find the value of z for inputs x_i and y_i. If opt is // kInterpOptionDefault, extrapolate linearly beyond the end of the // vectors. If opt is kInterpOptionSaturate, saturate the // output value at the edges of the output (z) matrix. // // Warning: This currently assumes a monotonically increasing x, y. double gsl_interp2(const gsl_vector *x, const gsl_vector *y, const gsl_matrix *z, double x_i, double y_i, InterpOption opt); double gsl_interp2_scaled(double s, double t, const gsl_matrix *z, InterpOption opt); void gsl_interp2_indices(double s, double t, int32_t size1, int32_t size2, InterpOption opt, int32_t *s0, int32_t *t0, double *ds, double *dt); double gsl_interp2_scaled_helper(const gsl_matrix *z, int32_t s0, int32_t t0, double ds, double dt); // Linear interpolation along a set of three vectors and a // three-dimensional matrix. // // The function to interpolate on is described by the input vectors x, // y, and z and the output matrix mat, with corresponding entries for // its value at each (x,y,z) input pair. Interp3 bilinearly // interpolates to find the value of mat for inputs x_i, y_i, and z_i. // If opt is kInterpOptionDefault, extrapolate linearly beyond the // end of the vectors. If opt is kInterpOptionSaturate, // saturate the output value at the edges of the output (mat) matrix. // // Warning: This currently assumes a monotonically increasing x, y, z. double gsl_interp3(const gsl_vector *x, const gsl_vector *y, const gsl_vector *z, const gsl_vector *mat, double x_i, double y_i, double z_i, InterpOption opt); double gsl_interp3_scaled(double u, double v, double w, const gsl_vector *z, int32_t size1, int32_t size2, int32_t size3, InterpOption opt); void gsl_interp3_indices(double u, double v, double w, int32_t size1, int32_t size2, int32_t size3, InterpOption opt, int32_t *indices, double *du, double *dv, double *dw); double gsl_interp3_scaled_helper(const gsl_vector *z, int32_t indices[], double du, double dv, double dw); #endif // SIM_MATH_UTIL_H_
{ "alphanum_fraction": 0.7042348803, "avg_line_length": 42.2342857143, "ext": "h", "hexsha": "8684c33bdb8e67fca410beea097ef0788c3ce9b0", "lang": "C", "max_forks_count": 107, "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "leozz37/makani", "max_forks_repo_path": "sim/math/util.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "sim/math/util.h", "max_line_length": 80, "max_stars_count": 1178, "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "leozz37/makani", "max_stars_repo_path": "sim/math/util.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "num_tokens": 1821, "size": 7391 }
/** * @file localization.h * @brief source localization * @author Ulrich Klee */ #ifndef LOCALIZATION_H #define LOCALIZATION_H #include <stdio.h> #include <assert.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_fit.h> #include "common/jexception.h" gsl_vector* getSrpPhat(double delta_f, gsl_matrix_complex *mFramePerChannel, gsl_vector *searchRangeX, gsl_vector *searchRangeY, gsl_matrix *arrgeom, int zPos); void calcDelays(int x, int y, int z, const gsl_matrix* mpos, gsl_vector* delays); void calcDelaysOfLinearMicrophoneArray(float azimuth, const gsl_matrix* mpos, gsl_vector* delays); void calcDelaysOfCircularMicrophoneArray(float azimuth, float elevation, const gsl_matrix* mpos, gsl_vector* delays); gsl_vector* getDelays(double delta_f, gsl_matrix_complex* mFramePerChannel, gsl_vector* searchRange); double getAzimuth(double delta_f, gsl_matrix_complex *mFramePerChannel, gsl_matrix *arrgeom, gsl_vector *delays); double getPlaneWaveSrp(double delta_f, gsl_matrix_complex *mFramePerChannel, gsl_vector *searchRangeY, gsl_matrix *arrgeom); //void halfComplexPack(double* tgt, const gsl_vector_complex* src); void getGCCRaw(const gsl_matrix_complex* spectralSample, double sampleRate, gsl_vector* gcc); const gsl_vector* getGCC(gsl_matrix_complex *spectralSample, double sampleRate); const gsl_vector* getWindowedGCC(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay); const gsl_vector* getWindowedGCCratio(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay); const gsl_vector* getWindowedGCCdirect(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay); const gsl_vector* getWindowedGCCabs(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay); const gsl_vector* getDynWindowedGCC(gsl_matrix_complex *spectralSample, double sampleRate, double minDelay, double maxDelay, double wMinDelay, double wMaxDelay, double threshold); double getInterpolation(gsl_matrix *crossResult, int delayPos); gsl_vector* get3DPosition(gsl_vector *yCoord, gsl_vector *azimuth1, gsl_vector *azimuth2, double xPos, double zPos); gsl_vector* get3DPosition_T_shape(gsl_matrix *arrgeom1, int arrayNr1, gsl_matrix *arrgeom2, int arrayNr2, gsl_matrix *arrgeom3, double azimuth1, double azimuth2, double azimuth3); gsl_vector* getGCC_old(gsl_matrix_complex *spectralSample, double delta_f, gsl_vector *delays); gsl_matrix* getLowerTriangMatrix(gsl_matrix* fullMatrix); gsl_vector* getXi(gsl_matrix* D1_2); class PhaseTransform { public: PhaseTransform(unsigned sz); ~PhaseTransform(); private: gsl_vector_complex* _crossSpectrum; double* _crossCorrelation; }; class NoisePowerSpectrum { public: NoisePowerSpectrum(double alpha = 0.95); ~NoisePowerSpectrum() { if (powerSpectrum != NULL) gsl_vector_free(powerSpectrum); } void setAlpha(double alpha) { this->alpha = alpha; alpha1 = 1 - alpha; } double getAlpha() { return alpha; } void add(const gsl_vector_complex *noiseSpectrum, double timestamp); const gsl_vector *get() { return powerSpectrum; } private: gsl_vector *powerSpectrum; double alpha, alpha1; double timestamp; }; class NoiseCrossSpectrum { public: NoiseCrossSpectrum(double alpha = 0.95); ~NoiseCrossSpectrum() { if (crossSpectrum != NULL) gsl_vector_complex_free(crossSpectrum); } void setAlpha(double alpha) { this->alpha = alpha; alpha1 = 1 - alpha; } double getAlpha() { return alpha; } const gsl_vector_complex *get() { return crossSpectrum; } void add(const gsl_vector_complex *noiseSpectrum1, const gsl_vector_complex *noiseSpectrum2); private: gsl_vector_complex *crossSpectrum; double alpha, alpha1; }; class GCC { public: GCC(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true); ~GCC(); void calculate(const gsl_vector_complex *spectralSample1, unsigned chan1, const gsl_vector_complex *spectralSample2, unsigned chan2, unsigned pair, double timestamp, bool sad = false, bool smooth = true); const gsl_vector* findMaximum(double minDelay = -HUGE_VAL, double maxDelay = HUGE_VAL); double getPeakDelay() { return delay; } double getPeakCorr() { return maxCorr; } double getRatio() { return ratio; } const gsl_vector* getNoisePowerSpectrum(unsigned chan) { return noisePowerSpectrum[chan].get(); } const gsl_vector_complex* getNoiseCrossSpectrum(unsigned pair) { return noiseCrossSpectrum[pair].get(); } const gsl_vector_complex* getCrossSpectrum() { return crossSpectrum; } const gsl_vector* getCrossCorrelation() { return crossCorrelation; } void setAlpha(double alpha) { for(unsigned i=0; i < pairs; i++) noiseCrossSpectrum[i].setAlpha(alpha); for(unsigned i=0; i < nChan; i++) noisePowerSpectrum[i].setAlpha(alpha); } double getAlpha() { return noiseCrossSpectrum[0].getAlpha(); } protected: virtual gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i) { throw jdimension_error("Not implemented!!!\n"); }; //auxiliary variables gsl_complex x1, x2, Gx1x2, Gs1s2, G; double W1, W2, X1, X12, X2, X22; double sampleRate; unsigned fftLen; unsigned fftLen2; unsigned len; unsigned nChan; unsigned pairs; unsigned delayPos; double q, q1, q2, beta, beta1; double ratio; double delay; double maxCorr; double maxCorr2; gsl_vector *crossCorrelation; gsl_matrix *interpolValues; gsl_vector* retValues; gsl_vector *powerSpectrum1, *powerSpectrum2; gsl_vector_complex *cSpectrum; gsl_vector_complex *crossSpectrum; NoisePowerSpectrum* noisePowerSpectrum; NoiseCrossSpectrum* noiseCrossSpectrum; bool noisereduction; bool sad; bool interpolate; }; class GCCRaw : public GCC { public: GCCRaw(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {}; protected: gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i); }; class GCCGnnSub : public GCC { public: GCCGnnSub(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {}; protected: gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i); }; class GCCPhat : public GCC { public: GCCPhat(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {}; protected: gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i); }; class GCCGnnSubPhat : public GCC { public: GCCGnnSubPhat(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {}; protected: gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i); }; class GCCMLRRaw : public GCC { public: GCCMLRRaw(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {}; protected: gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i); }; class GCCMLRGnnSub : public GCC { public: GCCMLRGnnSub(double sampleRate = 44100.0 , unsigned fftLen = 2048, unsigned nChan = 16, unsigned pairs = 6, double alpha = 0.95, double beta = 0.5, double q = 0.3, bool interpolate = true, bool noisereduction = true) : GCC(sampleRate, fftLen, nChan, pairs, alpha, beta, q, interpolate, noisereduction) {}; protected: gsl_complex calcCrossSpectrumValue(gsl_complex x1, gsl_complex x2, const gsl_vector_complex* Gn1n2, const gsl_vector* N1, const gsl_vector* N2, unsigned i); }; #endif
{ "alphanum_fraction": 0.7594936709, "avg_line_length": 42.0136363636, "ext": "h", "hexsha": "4ec24a2a529181ab177981bce300fc9ac6ff1d4c", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/localization/localization.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/localization/localization.h", "max_line_length": 308, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/localization/localization.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 2604, "size": 9243 }
/** * * @file core_stsmqr_sytra1.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 * @author Azzam Haidar * @date 2010-11-15 * @generated s Tue Jan 7 11:44:48 2014 * **/ #include <lapacke.h> #include "common.h" #undef COMPLEX #define REAL /***************************************************************************//** * * @ingroup CORE_float * * CORE_stsmqr_sytra1: see CORE_stsmqr * * This kernel applies a left transformation on | A1'| * | A2 | * * Needs therefore to make the explicit transpose of A1 before * and after the application of the block of reflectors * Can be further optimized by changing accordingly the underneath * kernel ztsrfb! * ******************************************************************************* * * @param[in] side * @arg PlasmaLeft : apply Q or Q**T from the Left; * @arg PlasmaRight : apply Q or Q**T from the Right. * * @param[in] trans * @arg PlasmaNoTrans : No transpose, apply Q; * @arg PlasmaTrans : ConjTranspose, apply Q**T. * * @param[in] m1 * The number of rows of the tile A1. M1 >= 0. * * @param[in] n1 * The number of columns of the tile A1. N1 >= 0. * * @param[in] m2 * The number of rows of the tile A2. M2 >= 0. * M2 = M1 if side == PlasmaRight. * * @param[in] n2 * The number of columns of the tile A2. N2 >= 0. * N2 = N1 if side == PlasmaLeft. * * @param[in] k * The number of elementary reflectors whose product defines * the matrix Q. * * @param[in] ib * The inner-blocking size. IB >= 0. * * @param[in,out] A1 * On entry, the M1-by-N1 tile A1. * On exit, A1 is overwritten by the application of Q. * * @param[in] lda1 * The leading dimension of the array A1. LDA1 >= max(1,M1). * * @param[in,out] A2 * On entry, the M2-by-N2 tile A2. * On exit, A2 is overwritten by the application of Q. * * @param[in] lda2 * The leading dimension of the tile A2. LDA2 >= max(1,M2). * * @param[in] V * The i-th row must contain the vector which defines the * elementary reflector H(i), for i = 1,2,...,k, as returned by * CORE_STSQRT in the first k columns of its array argument V. * * @param[in] ldv * The leading dimension of the array V. LDV >= max(1,K). * * @param[in] T * The IB-by-N1 triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. LDT >= IB. * * @param[out] WORK * Workspace array of size * LDWORK-by-N1 if side == PlasmaLeft * LDWORK-by-IB if side == PlasmaRight * * @param[in] ldwork * The leading dimension of the array WORK. * LDWORK >= max(1,IB) if side == PlasmaLeft * LDWORK >= max(1,M1) if side == PlasmaRight * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_stsmqr_sytra1 = PCORE_stsmqr_sytra1 #define CORE_stsmqr_sytra1 PCORE_stsmqr_sytra1 #define CORE_stsmqr PCORE_stsmqr int CORE_stsmqr(PLASMA_enum side, PLASMA_enum trans, int M1, int N1, int M2, int N2, int K, int IB, float *A1, int LDA1, float *A2, int LDA2, const float *V, int LDV, const float *T, int LDT, float *WORK, int LDWORK); #endif int CORE_stsmqr_sytra1( PLASMA_enum side, PLASMA_enum trans, int m1, int n1, int m2, int n2, int k, int ib, float *A1, int lda1, float *A2, int lda2, const float *V, int ldv, const float *T, int ldt, float *WORK, int ldwork) { int i, j; if ( (m1 != n1) ) { coreblas_error(3, "Illegal value of M1, N1"); return -3; } /* in-place transposition of A1 */ for (j = 0; j < n1; j++){ A1[j + j*lda1] = (A1[j + j*lda1]); for (i = j+1; i < m1; i++){ *WORK = *(A1 + i + j*lda1); *(A1 + i + j*lda1) = (*(A1 + j + i*lda1)); *(A1 + j + i*lda1) = (*WORK); } } CORE_stsmqr(side, trans, m1, n1, m2, n2, k, ib, A1, lda1, A2, lda2, V, ldv, T, ldt, WORK, ldwork); /* in-place transposition of A1 */ for (j = 0; j < n1; j++){ A1[j + j*lda1] = (A1[j + j*lda1]); for (i = j+1; i < m1; i++){ *WORK = *(A1 + i + j*lda1); *(A1 + i + j*lda1) = (*(A1 + j + i*lda1)); *(A1 + j + i*lda1) = (*WORK); } } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.5083978109, "avg_line_length": 31.3550295858, "ext": "c", "hexsha": "ec6873b0606f48eadec0e0fe8f80b184fbeb010c", "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_stsmqr_sytra1.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_stsmqr_sytra1.c", "max_line_length": 102, "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_stsmqr_sytra1.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1538, "size": 5299 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "tests.h" void test_gbmv (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha = -1.0f; float beta = -1.0f; float A[] = { 0.423f, -0.143f, -0.182f, -0.076f, -0.855f, 0.599f, 0.389f, -0.473f, 0.493f, -0.902f, -0.889f, -0.256f, 0.112f, 0.128f, -0.277f, -0.777f }; float X[] = { 0.488f, 0.029f, -0.633f, 0.84f }; int incX = -1; float Y[] = { 0.874f, 0.322f, -0.477f }; int incY = -1; float y_expected[] = { -0.101941f, 0.764086f, 0.481914f }; cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "sgbmv(case 794)"); } }; }; { int order = 102; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha = -1.0f; float beta = -1.0f; float A[] = { 0.423f, -0.143f, -0.182f, -0.076f, -0.855f, 0.599f, 0.389f, -0.473f, 0.493f, -0.902f, -0.889f, -0.256f, 0.112f, 0.128f, -0.277f, -0.777f }; float X[] = { 0.488f, 0.029f, -0.633f, 0.84f }; int incX = -1; float Y[] = { 0.874f, 0.322f, -0.477f }; int incY = -1; float y_expected[] = { -0.656261f, 0.19575f, 0.055905f }; cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "sgbmv(case 795)"); } }; }; { int order = 101; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha = 0.0f; float beta = 0.1f; float A[] = { -0.066f, -0.153f, -0.619f, 0.174f, 0.777f, 0.543f, 0.614f, -0.446f, -0.138f, -0.767f, 0.725f, 0.222f, 0.165f, -0.063f, -0.047f, 0.267f }; float X[] = { -0.096f, -0.007f, -0.657f }; int incX = -1; float Y[] = { -0.88f, 0.102f, -0.278f, 0.403f }; int incY = -1; float y_expected[] = { -0.088f, 0.0102f, -0.0278f, 0.0403f }; cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "sgbmv(case 796)"); } }; }; { int order = 102; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha = 0.0f; float beta = 0.1f; float A[] = { -0.066f, -0.153f, -0.619f, 0.174f, 0.777f, 0.543f, 0.614f, -0.446f, -0.138f, -0.767f, 0.725f, 0.222f, 0.165f, -0.063f, -0.047f, 0.267f }; float X[] = { -0.096f, -0.007f, -0.657f }; int incX = -1; float Y[] = { -0.88f, 0.102f, -0.278f, 0.403f }; int incY = -1; float y_expected[] = { -0.088f, 0.0102f, -0.0278f, 0.0403f }; cblas_sgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[i], y_expected[i], flteps, "sgbmv(case 797)"); } }; }; { int order = 101; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha = 0.1; double beta = 0; double A[] = { -0.688, 0.29, 0.442, -0.001, 0.313, -0.073, 0.991, -0.654, -0.12, 0.416, 0.571, 0.932, -0.179, -0.724, 0.492, -0.965 }; double X[] = { 0.187, -0.338, -0.976, -0.052 }; int incX = -1; double Y[] = { -0.101, 0.8, 0.026 }; int incY = -1; double y_expected[] = { 0.0083289, -0.0279986, -0.0446472 }; cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dgbmv(case 798)"); } }; }; { int order = 102; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha = 0.1; double beta = 0; double A[] = { -0.688, 0.29, 0.442, -0.001, 0.313, -0.073, 0.991, -0.654, -0.12, 0.416, 0.571, 0.932, -0.179, -0.724, 0.492, -0.965 }; double X[] = { 0.187, -0.338, -0.976, -0.052 }; int incX = -1; double Y[] = { -0.101, 0.8, 0.026 }; int incY = -1; double y_expected[] = { -0.1141297, 0.0088824, -0.0320568 }; cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dgbmv(case 799)"); } }; }; { int order = 101; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha = -0.3; double beta = -0.3; double A[] = { 0.746, 0.262, -0.449, -0.954, -0.093, 0.108, -0.496, 0.927, 0.177, 0.729, -0.92, -0.469, 0.87, -0.877, -0.308, -0.806 }; double X[] = { 0.662, -0.887, 0.261 }; int incX = -1; double Y[] = { 0.771, 0.637, -0.177, -0.018 }; int incY = -1; double y_expected[] = { -0.048588, -0.467865, 0.0818433, -0.0398619 }; cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dgbmv(case 800)"); } }; }; { int order = 102; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha = -0.3; double beta = -0.3; double A[] = { 0.746, 0.262, -0.449, -0.954, -0.093, 0.108, -0.496, 0.927, 0.177, 0.729, -0.92, -0.469, 0.87, -0.877, -0.308, -0.806 }; double X[] = { 0.662, -0.887, 0.261 }; int incX = -1; double Y[] = { 0.771, 0.637, -0.177, -0.018 }; int incY = -1; double y_expected[] = { -0.404082, -0.2887797, 0.1876263, -0.1345935 }; cblas_dgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[i], y_expected[i], dbleps, "dgbmv(case 801)"); } }; }; { int order = 101; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.107f, 0.926f, -0.246f, -0.555f, -0.301f, 0.276f, 0.471f, -0.084f, -0.754f, 0.082f, -0.952f, -0.394f, 0.659f, 0.054f, 0.795f, 0.923f, 0.232f, -0.788f, 0.478f, 0.775f, -0.118f, 0.691f, -0.933f, 0.809f, 0.164f, -0.263f, -0.923f, -0.88f, 0.819f, -0.521f, -0.045f, 0.034f }; float X[] = { 0.407f, 0.895f, 0.301f, 0.769f, -0.269f, -0.465f, 0.455f, -0.628f }; int incX = -1; float Y[] = { -0.116f, -0.744f, -0.936f, -0.064f, -0.232f, -0.665f }; int incY = -1; float y_expected[] = { -0.806176f, -1.559f, -1.57611f, -0.155463f, 0.098816f, -0.274361f }; cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "cgbmv(case 802) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "cgbmv(case 802) imag"); }; }; }; { int order = 102; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.107f, 0.926f, -0.246f, -0.555f, -0.301f, 0.276f, 0.471f, -0.084f, -0.754f, 0.082f, -0.952f, -0.394f, 0.659f, 0.054f, 0.795f, 0.923f, 0.232f, -0.788f, 0.478f, 0.775f, -0.118f, 0.691f, -0.933f, 0.809f, 0.164f, -0.263f, -0.923f, -0.88f, 0.819f, -0.521f, -0.045f, 0.034f }; float X[] = { 0.407f, 0.895f, 0.301f, 0.769f, -0.269f, -0.465f, 0.455f, -0.628f }; int incX = -1; float Y[] = { -0.116f, -0.744f, -0.936f, -0.064f, -0.232f, -0.665f }; int incY = -1; float y_expected[] = { -0.245235f, -0.313725f, -0.798094f, 0.691455f, -0.164015f, -0.242714f }; cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "cgbmv(case 803) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "cgbmv(case 803) imag"); }; }; }; { int order = 101; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.258f, 0.838f, -0.106f, -0.066f, 0.395f, 0.982f, -0.546f, 0.565f, 0.14f, -0.18f, 0.165f, -0.186f, 0.499f, -0.038f, -0.305f, -0.653f, -0.811f, -0.466f, -0.674f, -0.013f, -0.552f, -0.807f, -0.536f, 0.864f, -0.027f, -0.606f, 0.459f, 0.564f, -0.968f, 0.717f, -0.312f, -0.485f }; float X[] = { -0.399f, 0.459f, 0.398f, 0.358f, -0.161f, -0.359f }; int incX = -1; float Y[] = { 0.572f, 0.293f, -0.813f, -0.096f, -0.611f, -0.717f, 0.736f, 0.259f }; int incY = -1; float y_expected[] = { -0.619961f, -0.011425f, -0.477499f, 0.059361f, -0.886984f, 0.44008f, -0.139432f, 0.04644f }; cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "cgbmv(case 804) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "cgbmv(case 804) imag"); }; }; }; { int order = 102; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.258f, 0.838f, -0.106f, -0.066f, 0.395f, 0.982f, -0.546f, 0.565f, 0.14f, -0.18f, 0.165f, -0.186f, 0.499f, -0.038f, -0.305f, -0.653f, -0.811f, -0.466f, -0.674f, -0.013f, -0.552f, -0.807f, -0.536f, 0.864f, -0.027f, -0.606f, 0.459f, 0.564f, -0.968f, 0.717f, -0.312f, -0.485f }; float X[] = { -0.399f, 0.459f, 0.398f, 0.358f, -0.161f, -0.359f }; int incX = -1; float Y[] = { 0.572f, 0.293f, -0.813f, -0.096f, -0.611f, -0.717f, 0.736f, 0.259f }; int incY = -1; float y_expected[] = { -0.318227f, -0.172201f, -0.109343f, 0.698685f, 0.208261f, -0.269065f, 0.175074f, -0.507326f }; cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "cgbmv(case 805) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "cgbmv(case 805) imag"); }; }; }; { int order = 101; int trans = 113; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.804f, 0.232f, -0.448f, -0.558f, -0.078f, -0.056f, -0.345f, -0.379f, 0.369f, -0.662f, -0.169f, -0.391f, -0.215f, 0.467f, 0.374f, 0.889f, -0.698f, 0.734f, 0.377f, -0.955f, 0.498f, 0.151f, -0.725f, -0.728f, -0.655f, -0.581f, 0.389f, 0.949f, -0.553f, -0.434f, 0.237f, 0.641f }; float X[] = { -0.262f, -0.823f, -0.357f, -0.994f, -0.347f, -0.375f }; int incX = -1; float Y[] = { -0.683f, -0.87f, -0.708f, 0.071f, 0.575f, -0.575f, 0.845f, 0.032f }; int incY = -1; float y_expected[] = { 0.341749f, 0.301992f, -0.306848f, 0.109252f, -0.018347f, -0.747479f, -0.894201f, 0.713246f }; cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "cgbmv(case 806) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "cgbmv(case 806) imag"); }; }; }; { int order = 102; int trans = 113; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.804f, 0.232f, -0.448f, -0.558f, -0.078f, -0.056f, -0.345f, -0.379f, 0.369f, -0.662f, -0.169f, -0.391f, -0.215f, 0.467f, 0.374f, 0.889f, -0.698f, 0.734f, 0.377f, -0.955f, 0.498f, 0.151f, -0.725f, -0.728f, -0.655f, -0.581f, 0.389f, 0.949f, -0.553f, -0.434f, 0.237f, 0.641f }; float X[] = { -0.262f, -0.823f, -0.357f, -0.994f, -0.347f, -0.375f }; int incX = -1; float Y[] = { -0.683f, -0.87f, -0.708f, 0.071f, 0.575f, -0.575f, 0.845f, 0.032f }; int incY = -1; float y_expected[] = { -0.562773f, -0.455143f, -0.213881f, -0.466169f, -0.183683f, 0.097891f, -0.451416f, 0.052586f }; cblas_cgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "cgbmv(case 807) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "cgbmv(case 807) imag"); }; }; }; { int order = 101; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha[2] = {0, 0.1}; double beta[2] = {1, 0}; double A[] = { -0.919, -0.002, 0.105, -0.338, -0.358, -0.715, -0.157, 0.307, 0.334, 0.121, 0.366, 0.029, -0.006, -0.662, -0.314, 0.061, -0.322, -0.865, -0.586, 0.556, 0.507, 0.581, 0.855, -0.09, 0.836, -0.788, -0.209, -0.694, -0.695, 0.11, -0.234, 0.17 }; double X[] = { 0.356, -0.76, -0.96, 0.437, -0.849, 0.397, -0.382, -0.826 }; int incX = -1; double Y[] = { 0.288, -0.832, 0.889, 0.576, -0.809, 0.4 }; int incY = -1; double y_expected[] = { 0.3241775, -0.6761577, 0.8458527, 0.5705165, -0.8597295, 0.4268499 }; cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zgbmv(case 808) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zgbmv(case 808) imag"); }; }; }; { int order = 102; int trans = 111; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha[2] = {0, 0.1}; double beta[2] = {1, 0}; double A[] = { -0.919, -0.002, 0.105, -0.338, -0.358, -0.715, -0.157, 0.307, 0.334, 0.121, 0.366, 0.029, -0.006, -0.662, -0.314, 0.061, -0.322, -0.865, -0.586, 0.556, 0.507, 0.581, 0.855, -0.09, 0.836, -0.788, -0.209, -0.694, -0.695, 0.11, -0.234, 0.17 }; double X[] = { 0.356, -0.76, -0.96, 0.437, -0.849, 0.397, -0.382, -0.826 }; int incX = -1; double Y[] = { 0.288, -0.832, 0.889, 0.576, -0.809, 0.4 }; int incY = -1; double y_expected[] = { 0.4026074, -0.8033768, 0.7510795, 0.5671044, -0.8162255, 0.3349099 }; cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 3; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zgbmv(case 809) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zgbmv(case 809) imag"); }; }; }; { int order = 101; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha[2] = {1, 0}; double beta[2] = {1, 0}; double A[] = { 0.511, -0.707, -0.906, 0.345, -0.524, -0.933, 0.154, -0.529, -0.651, -0.851, 0.104, 0.532, -0.297, 0.477, 0.511, 0.469, -0.888, -0.789, 0.656, 0.288, -0.749, 0.961, 0.571, 0.539, 0.465, 0.647, 0.653, -0.994, -0.515, 0.297, 0.35, -0.707 }; double X[] = { -0.991, 0.658, -0.909, -0.99, -0.517, -0.071 }; int incX = -1; double Y[] = { 0.451, 0.351, -0.113, -0.62, 0.983, 0.511, 0.142, -0.186 }; int incY = -1; double y_expected[] = { 0.560921, -1.094193, -0.210397, -0.613323, 3.018979, 0.641612, 0.384166, 1.11801 }; cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zgbmv(case 810) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zgbmv(case 810) imag"); }; }; }; { int order = 102; int trans = 112; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha[2] = {1, 0}; double beta[2] = {1, 0}; double A[] = { 0.511, -0.707, -0.906, 0.345, -0.524, -0.933, 0.154, -0.529, -0.651, -0.851, 0.104, 0.532, -0.297, 0.477, 0.511, 0.469, -0.888, -0.789, 0.656, 0.288, -0.749, 0.961, 0.571, 0.539, 0.465, 0.647, 0.653, -0.994, -0.515, 0.297, 0.35, -0.707 }; double X[] = { -0.991, 0.658, -0.909, -0.99, -0.517, -0.071 }; int incX = -1; double Y[] = { 0.451, 0.351, -0.113, -0.62, 0.983, 0.511, 0.142, -0.186 }; int incY = -1; double y_expected[] = { -0.435541, 0.015793, -0.926518, 1.122561, 1.671751, -0.257493, 0.187543, 1.066818 }; cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zgbmv(case 811) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zgbmv(case 811) imag"); }; }; }; { int order = 101; int trans = 113; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha[2] = {0, 0.1}; double beta[2] = {-0.3, 0.1}; double A[] = { 0.534, 0.67, -0.621, 0.143, -0.794, 0.073, 0.414, -0.9, 0.155, -0.368, 0.122, -0.583, 0.03, 0.646, -0.768, -0.892, -0.741, -0.397, 0.626, 0.004, -0.515, 0.355, 0.196, -0.989, -0.982, 0.985, 0.445, 0.63, -0.849, -0.528, 0.146, -0.319 }; double X[] = { -0.199, -0.259, 0.386, -0.131, -0.867, 0.888 }; int incX = -1; double Y[] = { 0.106, 0.874, 0.962, 0.636, -0.759, 0.415, -0.053, 0.315 }; int incY = -1; double y_expected[] = { -0.139603, -0.250546, -0.3107376, -0.1144656, 0.2181809, -0.0877031, 0.0149724, -0.0224571 }; cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zgbmv(case 812) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zgbmv(case 812) imag"); }; }; }; { int order = 102; int trans = 113; int M = 3; int N = 4; int KL = 1; int KU = 1; int lda = 4; double alpha[2] = {0, 0.1}; double beta[2] = {-0.3, 0.1}; double A[] = { 0.534, 0.67, -0.621, 0.143, -0.794, 0.073, 0.414, -0.9, 0.155, -0.368, 0.122, -0.583, 0.03, 0.646, -0.768, -0.892, -0.741, -0.397, 0.626, 0.004, -0.515, 0.355, 0.196, -0.989, -0.982, 0.985, 0.445, 0.63, -0.849, -0.528, 0.146, -0.319 }; double X[] = { -0.199, -0.259, 0.386, -0.131, -0.867, 0.888 }; int incX = -1; double Y[] = { 0.106, 0.874, 0.962, 0.636, -0.759, 0.415, -0.053, 0.315 }; int incY = -1; double y_expected[] = { -0.1642353, -0.2575697, -0.3610975, -0.1305629, 0.1713576, -0.2514988, 0.0195631, -0.0648656 }; cblas_zgbmv(order, trans, M, N, KU, KL, alpha, A, lda, X, incX, beta, Y, incY); { int i; for (i = 0; i < 4; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zgbmv(case 813) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zgbmv(case 813) imag"); }; }; }; }
{ "alphanum_fraction": 0.4965078061, "avg_line_length": 35.7941176471, "ext": "c", "hexsha": "9baf6c6834f1d8f245ed7a158dc0424efd372c85", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_gbmv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_gbmv.c", "max_line_length": 293, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_gbmv.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": 9566, "size": 19472 }
#include <math.h> #include <gsl/gsl_ntuple.h> #include <gsl/gsl_histogram.h> struct data { double x; double y; double z; }; int sel_func (void *ntuple_data, void *params); double val_func (void *ntuple_data, void *params); int main (void) { struct data ntuple_row; gsl_ntuple *ntuple = gsl_ntuple_open ("test.dat", &ntuple_row, sizeof (ntuple_row)); double lower = 1.5; gsl_ntuple_select_fn S; gsl_ntuple_value_fn V; gsl_histogram *h = gsl_histogram_alloc (100); gsl_histogram_set_ranges_uniform(h, 0.0, 10.0); S.function = &sel_func; S.params = &lower; V.function = &val_func; V.params = 0; gsl_ntuple_project (h, ntuple, &V, &S); gsl_histogram_fprintf (stdout, h, "%f", "%f"); gsl_histogram_free (h); gsl_ntuple_close (ntuple); return 0; } int sel_func (void *ntuple_data, void *params) { struct data * data = (struct data *) ntuple_data; double x, y, z, E2, scale; scale = *(double *) params; x = data->x; y = data->y; z = data->z; E2 = x * x + y * y + z * z; return E2 > scale; } double val_func (void *ntuple_data, void *params) { struct data * data = (struct data *) ntuple_data; double x, y, z; x = data->x; y = data->y; z = data->z; return x * x + y * y + z * z; }
{ "alphanum_fraction": 0.6209302326, "avg_line_length": 17.6712328767, "ext": "c", "hexsha": "a92652203fd5e0ab71201bd19c35cb1d269b5239", "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/doc/examples/ntupler.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/doc/examples/ntupler.c", "max_line_length": 53, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ntupler.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": 426, "size": 1290 }
/* cheb/deriv.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_chebyshev.h> int gsl_cheb_calc_deriv(gsl_cheb_series * deriv, const gsl_cheb_series * f) { const size_t n = f->order + 1; const double con = 2.0 / (f->b - f->a); size_t i; if(deriv->order != f->order) { GSL_ERROR ("order of chebyshev series must be equal", GSL_ENOMEM); } /* set the other parameters in the chebyshev struct */ deriv->a = f->a; deriv->b = f->b; /* error in derivative is n^2 c_n */ /* deriv->err = n * n * f->c[n-1];*/ /* FIXME: should probably set deriv->f[] as well */ deriv->c[n-1] = 0.0; if(n > 1) { deriv->c[n-2] = 2.0 *(n-1.0) * f->c[n-1]; for(i = n; i>=3; i--) deriv->c[i-3] = deriv->c[i-1] + 2.0 *(i-2.0) * f->c[i-2]; for(i = 0 ; i<n ; i++) deriv->c[i] *= con; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6345707657, "avg_line_length": 28.262295082, "ext": "c", "hexsha": "8f7c223cc1dc073fc987a87bf0a5f3c09149d9b6", "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/cheb/deriv.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/cheb/deriv.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/cheb/deriv.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": 552, "size": 1724 }
/** * @file cblas.h * @brief Header file to handle Intel MKL, OpenBLAS, or Netlib includes. * * `npypacke` can be linked with a reference CBLAS implementation, OpenBLAS, or * Intel MKL, but Intel MKL uses a different header file, `mkl.h`, while * OpenBLAS uses the CBLAS header `cblas.h`. This file includes the correct * header file given an appropriate preprocessor macro is defined, and defines * some types appropriately so that the user can simply write in terms of the * Intel MKL interface, whether or not Intel MKL is actually linked. */ #ifndef NPY_LPK_CBLAS_H #define NPY_LPK_CBLAS_H // if linking with Netlib CBLAS #if defined(CBLAS_INCLUDE) #include <cblas.h> // define MKL_INT used in extension modules as in mkl.h #ifndef MKL_INT #define MKL_INT int #endif /* MKL_INT */ // else if linking with OpenBLAS CBLAS #elif defined(OPENBLAS_INCLUDE) #include <cblas.h> // OpenBLAS has blasint typedef, so define MKL_INT using blasint #ifndef MKL_INT #define MKL_INT blasint #endif /* MKL_INT */ // else if linking to Intel MKL #elif defined(MKL_INCLUDE) #include <mkl.h> // else error, no LAPACKE includes specified #else // silence error squiggles in VS Code (__INTELLISENSE__ always defined) #ifndef __INTELLISENSE__ #error "no CBLAS includes specified. try -D(CBLAS|OPENBLAS|MKL)_INCLUDE" #endif /* __INTELLISENSE__ */ #endif // silence error squiggles in VS Code. use mkl.h since it also define MKL types #ifdef __INTELLISENSE__ #include <mkl.h> #endif /* __INTELLISENSE__ */ #endif /* NPY_LPK_CBLAS_H */
{ "alphanum_fraction": 0.7585078534, "avg_line_length": 33.9555555556, "ext": "h", "hexsha": "0ad607e338e58b73488d483638879be63f57b80c", "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": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "phetdam/numpy-lapacke-demo", "max_forks_repo_path": "npypacke/include/npypacke/cblas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "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": "phetdam/numpy-lapacke-demo", "max_issues_repo_path": "npypacke/include/npypacke/cblas.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "phetdam/npy_openblas_demo", "max_stars_repo_path": "npypacke/include/npypacke/cblas.h", "max_stars_repo_stars_event_max_datetime": "2021-10-16T00:59:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-16T00:59:11.000Z", "num_tokens": 437, "size": 1528 }
/* * 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 linequ_546582d4_5f60_4938_9ce8_1beb1678ba61_h #define linequ_546582d4_5f60_4938_9ce8_1beb1678ba61_h #include <gslib/type.h> #include <gslib/std.h> #include <gslib/error.h> __gslib_begin__ class _trait_dimcol {}; class _trait_dimrow {}; template<class _fty, class _mty, class _trdim> class ledimsel { public: typedef _fty type; typedef _mty matrix; typedef ledimsel<_fty, _mty, _trdim> selection; public: ledimsel(matrix& mat, int cr): _mat(mat), _sel(cr) {} int index() const { return _sel; } int capacity() const { return capacity<_trdim>(); } int cols() const { return _mat.cols(); } int rows() const { return _mat.rows(); } type& get(int i) { return get<_trdim>(i); } const type& get_const(int i) const { return get_const<_trdim>(i); } void set(int i, const type& t) { get(i) = t; } protected: template<class _trdim> int capacity() const; template<class _trdim> type& get(int i); template<class _trdim> const type& get_const(int i) const; template<> int capacity<_trait_dimcol>() const { return rows(); } template<> int capacity<_trait_dimrow>() const { return cols(); } template<> type& get<_trait_dimcol>(int i) { return _mat.get(i, _sel); } template<> type& get<_trait_dimrow>(int i) { return _mat.get(_sel, i); } template<> const type& get_const<_trait_dimcol>(int i) const { return _mat.get_const(i, _sel); } template<> const type& get_const<_trait_dimrow>(int i) const { return _mat.get_const(_sel, i); } protected: matrix& _mat; int _sel; public: template<class _op> ledimsel& operator*=(_op t) { for_each([&t](type& n) { n *= t; }); return *this; } template<class _op> ledimsel& operator/=(_op t) { return operator*=(t); } template<class _opset> ledimsel& operator+=(const _opset& rhs) { assert(capacity() == rhs.capacity()); int cap = capacity(); for(int i = 0; i < cap; i ++) get(i) += rhs.get_const(i); return *this; } template<class _opset> ledimsel& operator-=(const _opset& rhs) { assert(capacity() == rhs.capacity()); int cap = capacity(); for(int i = 0; i < cap; i ++) get(i) -= rhs.get_const(i); return *this; } public: template<class _lambda> void for_each(_lambda lam) { int cap = capacity(); for(int i = 0; i < cap; i ++) lam(get(i)); } template<class _lambda> void const_for_each(_lambda lam) const { int cap = capacity(); for(int i = 0; i < cap; i ++) lam(get_const(i)); } }; /* optimize for row selector */ template<class _fty, class _mty> class ledimsel<_fty, _mty, _trait_dimrow> { public: typedef _fty type; typedef _mty matrix; typedef ledimsel<_fty, _mty, _trait_dimrow> selection; public: ledimsel(matrix& mat, int cr): _mat(mat), _sel(cr), _data(mat.data() + mat.accpos(cr, 0)) {} int index() const { return _sel; } int capacity() const { return cols(); } int cols() const { return _mat.cols(); } int rows() const { return _mat.rows(); } type& get(int i) { return _data[i]; } const type& get_const(int i) const { return _data[i]; } void set(int i, const type& t) { get(i) = t; } protected: matrix& _mat; int _sel; type* _data; public: template<class _op> ledimsel& operator*=(_op t) { for_each([&t](type& n) { n *= t; }); return *this; } template<class _op> ledimsel& operator/=(_op t) { return operator*=(t); } template<class _opset> ledimsel& operator+=(const _opset& rhs) { assert(capacity() == rhs.capacity()); int cap = capacity(); for(int i = 0; i < cap; i ++) get(i) += rhs.get_const(i); return *this; } template<class _opset> ledimsel& operator-=(const _opset& rhs) { assert(capacity() == rhs.capacity()); int cap = capacity(); for(int i = 0; i < cap; i ++) get(i) -= rhs.get_const(i); return *this; } public: template<class _lambda> void for_each(_lambda lam) { int cap = capacity(); for(int i = 0; i < cap; i ++) lam(get(i)); } template<class _lambda> void const_for_each(_lambda lam) const { int cap = capacity(); for(int i = 0; i < cap; i ++) lam(get_const(i)); } }; template<class _opset1, class _opset2> static void swap_opset(_opset1& ops1, _opset2& ops2) { assert(ops1.capacity() == ops2.capacity()); int cap = ops1.capacity(); for(int i = 0; i < cap; i ++) std::swap(ops1.get(i), ops2.get(i)); } template<class _opset> static int first_non_zero(const _opset& ops) { int cap = ops.capacity(); for(int i = 0; i < cap; i ++) { if(ops.get_const(i) != 0) return i; } return cap; } template<class _opset> static int last_non_zero(const _opset& ops) { for(int i = ops.capacity() - 1; i >= 0; i --) { if(ops.get_const(i) != 0) return i; } return ops.capacity(); } template<class _fty> class levector { public: typedef _fty type; typedef levector<_fty> vector; protected: int _size; type* _data; public: levector() { _data = 0, _size = 0; } levector(int s) { assert(s > 0); _data = 0; setup(s); } ~levector() { if(_data) { delete [] _data; _data = 0; } } void setup(int s) { if(_data != 0) delete [] _data; _size = s; _data = new type[s]; } int capacity() const { return _size; } type& get(int i) { return _data[i]; } const type& get_const(int i) const { return _data[i]; } type* data() const { return _data; } void set(int i, const type& t) { get(i) = t; } public: template<class _lambda> void for_each(_lambda lam) { int cap = capacity(); for(int i = 0; i < cap; i ++) lam(get(i)); } template<class _lambda> void const_for_each(_lambda lam) const { int cap = capacity(); for(int i = 0; i < cap; i ++) lam(get_const(i)); } }; template<class _fty> class lematrix { public: typedef _fty type; typedef lematrix<_fty> matrix; typedef levector<_fty> vector; typedef ledimsel<_fty, lematrix, _trait_dimrow> rowselector; typedef ledimsel<_fty, const lematrix, _trait_dimrow> const_rowselector; typedef ledimsel<_fty, lematrix, _trait_dimcol> colselector; typedef ledimsel<_fty, const lematrix, _trait_dimcol> const_colselector; protected: int _rows; int _cols; type* _data; public: lematrix() { _rows = _cols = 0; _data = 0; } lematrix(int r, int c) { assert(r > 0 && c > 0); _data = 0; set_dim(r, c); } ~lematrix() { if(_data != 0) { delete [] _data; _data = 0; } } void set_dim(int r, int c) { if(_data != 0) delete [] _data; assert(r > 0 && c > 0); _rows = r; _cols = c; _data = new type[r * c]; } int accpos(int r, int c) const { assert(r >= 0 && r < _rows && c >= 0 && c < _cols); int p = r * _cols + c; return p; } type& get(int r, int c) { assert(r >= 0 && r < _rows && c >= 0 && c < _cols); int p = accpos(r, c); return _data[p]; } const type& get_const(int r, int c) const { assert(r >= 0 && r < _rows && c >= 0 && c < _cols); int p = accpos(r, c); return _data[p]; } int dump_row(vector& v, int r) { int s = cols(); v.setup(s); memcpy_s(v.data(), sizeof(type) * s, &get(r, 0), sizeof(type) * s); return s; } int dump_col(vector& v, int c) { int s = rows(); v.setup(s); auto& sel = select_col(c); assert(s == sel.capacity()); for(int i = 0; i < s; i ++) v.set(i, sel.get_const(i)); return s; } bool gauss_elim() { assert(rows() >= 2); int cap = rows(); arrange(0, cap); for(int i = 1; i < cap; i ++) gauss_elim(i); return row_rank() <= col_rank(); } public: int rows() const { return _rows; } int cols() const { return _cols; } type* data() const { return _data; } colselector select_col(int c) { return colselector(*this, c); } const_colselector select_col(int c) const { return const_colselector(*this, c); } rowselector select_row(int r) { return rowselector(*this, r); } const_rowselector select_row(int r) const { return const_rowselector(*this, r); } bool fuzzy_solvable() const { return rows() >= cols() - 1; } int row_rank() const { return cols() - first_non_zero(select_row(0)) - 1; } int col_rank() const { return last_non_zero(select_col(cols() - 1)) + 1; } protected: void arrange(int start, int end) { assert(start >= 0 && end <= rows()); if(end - start <= 1) return; struct node { int index, first; node(int i, int f): index(i), first(f) {} }; list<node> stlist; for(int i = start; i < end; i ++) stlist.push_back(node(i, first_non_zero(select_row(i)))); stlist.sort([](const node& n1, const node& n2)->bool { return n1.first < n2.first; }); assert(!stlist.empty()); matrix mt; mt.set_dim(end - start, cols()); auto j = stlist.begin(); for(int i = 0; j != stlist.end(); ++ i, ++ j) { auto& r = mt.select_row(i); memcpy_s(&r.get(0), sizeof(type)*cols(), &get_const(j->index, 0), sizeof(type)*cols()); } int cpsize = sizeof(type) * cols() * (end - start); memcpy_s(&get(start, 0), cpsize, mt.data(), cpsize); } void gauss_elim(int i) { assert(i > 0 && i < rows()); auto& select1 = select_row(i - 1); auto& select2 = select_row(i); int first1 = first_non_zero(select1); if(select2.get(first1) == 0) return; int cap = rows(); for(int j = i; j < cap; j ++) { if(!gauss_elim(i - 1, j, first1)) break; } arrange(i, cap); } bool gauss_elim(int i, int j, int first) { assert(i < j); auto& select1 = select_row(i); auto& select2 = select_row(j); if(select2.get(first) == 0) return false; select2 *= (select1.get_const(first) / select2.get_const(first)); select2 -= select1; return true; } protected: void trace_data() const { for(int i = 0; i < rows(); i ++) { auto& sel = select_row(i); for(int j = 0; j < sel.capacity(); j ++) trace(_t("%lf "), sel.get_const(j)); trace(_t("\r")); } } }; template<class _fty> class linequ { public: typedef _fty type; typedef linequ<_fty> myref; typedef levector<_fty> vector; typedef lematrix<_fty> matrix; static double qnan() { static const struct nan_struct { union { uint a[2]; double b; }; } qnan_struct = { 0xffffffff, 0x7fffffff }; return qnan_struct.b; } public: void set_variable_count(int c) { _variables.setup(c); } int get_variable_count() const { return _variables.capacity(); } void set_equation_count(int c) { _matrix.set_dim(c, get_variable_count() + 1); } int get_equation_count() const { return _matrix.rows(); } const vector& get_results() const { return _variables; } type get_variable(int i) const { return _variables.get_const(i); } void set_equation(int i, ...) { va_list ptr; va_start(ptr, i); auto& selection = _matrix.select_row(i); int cap = _matrix.cols(); for(int j = 0; j < cap; j ++) selection.set(j, va_arg(ptr, type)); } void set_equation(int i, const type d[], int s) { auto& selection = _matrix.select_row(i); if(s > selection.capacity()) s = selection.capacity(); for(int j = 0; j < s; j ++) selection.set(j, d[j]); } int solve() { if(!_matrix.fuzzy_solvable() || !_matrix.gauss_elim()) return 0; set_unsolved<_fty>(); int rkcol = _matrix.col_rank(); int c = 0; for(int i = rkcol - 1; i >= 0; i --, c ++) { if(!solve(i)) break; } return c; } protected: vector _variables; matrix _matrix; protected: template<class _fty> void set_unsolved(); template<> void set_unsolved<double>() { _variables.for_each([](type& v) { v = qnan(); }); } template<> void set_unsolved<float>() { float fqnan = static_cast<float>(qnan()); assert(sizeof(fqnan) == sizeof(int)); memset(_variables.data(), *(int*)&fqnan, _variables.capacity()); } bool solve(int c) { auto& selection = _matrix.select_row(c); int first = first_non_zero(selection); for(int i = get_variable_count() - 1; i > c; i --) { if((((type)qnan())) == get_variable(i)) return false; } int cap = get_variable_count(); type s = selection.get_const(cap); for(int i = c + 1; i < cap; i ++) s += (selection.get_const(i) * get_variable(i)); _variables.set(c, -s / selection.get_const(c)); return true; } }; __gslib_end__ #endif
{ "alphanum_fraction": 0.5363972463, "avg_line_length": 29.2141527002, "ext": "h", "hexsha": "41f5107bd6e46a35286ec70a36f48b47319ccfd2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/gslib/linequ.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/gslib/linequ.h", "max_line_length": 117, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/gslib/linequ.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": 4187, "size": 15688 }
/*! \file allvars.h * \brief declares global variables. * * This file declares all global variables and structures. Further variables should be added here, and declared as * \e \b extern. The actual existence of these variables is provided by the file \ref allvars.cxx. To produce * \ref allvars.cxx from \ref allvars.h, do the following: * * \arg Erase all \#define's, typedef's, and enum's * \arg add \#include "allvars.h", delete the \#ifndef ALLVARS_H conditional * \arg delete all keywords 'extern' * \arg delete all struct definitions enclosed in {...}, e.g. * "extern struct global_data_all_processes {....} All;" * becomes "struct global_data_all_processes All;" */ #ifndef ALLVARS_H #define ALLVARS_H #include <cstdio> #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <cmath> #include <string> #include <vector> #include <set> #include <unordered_set> #include <algorithm> #include <map> #include <unordered_map> #include <bitset> #include <getopt.h> #include <sys/stat.h> #include <sys/timeb.h> #include <sys/time.h> #include <unistd.h> #include <gsl/gsl_heapsort.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> ///\name Include for NBodyFramework library. //@{ ///nbody code #include <NBody.h> ///Math code #include <NBodyMath.h> ///Binary KD-Tree code #include <KDTree.h> ///Extra routines that analyze a distribution of particles #include <Analysis.h> //@} // ///\name for checking the endian of floats //#include <endianutils.h> ///if using OpenMP API #ifdef USEOPENMP #include <omp.h> #endif #include "ompvar.h" ///if using HDF API #ifdef USEHDF #include "hdf5.h" #endif ///if using ADIOS API #ifdef USEADIOS #include "adios.h" #endif #include "git_revision.h" //#include "swiftinterface.h" // //using namespace Swift; using namespace std; using namespace Math; using namespace NBody; //-- Structures and external variables /// \defgroup PARTTYPES Particle types //@{ #define GASTYPE 0 #define DARKTYPE 1 #define DARK2TYPE 2 #define DARK3TYPE 3 #define STARTYPE 4 #define BHTYPE 5 #define WINDTYPE 6 #define NPARTTYPES 7 //number of baryon types +1, to store all baryons #define NBARYONTYPES 5 //@} /// \defgroup SEARCHTYPES Specify particle type to be searched, all, dm only, separate //@{ #define PSTALL 1 #define PSTDARK 2 #define PSTSTAR 3 #define PSTGAS 4 #define PSTBH 5 #define PSTNOBH 6 //@} /// \defgroup STRUCTURETYPES Specific structure type, allow for other types beside HALO //@{ /// \todo note that here I have set background group type to a halo structure type but that can be changed #define HALOSTYPE 10 #define HALOCORESTYPE 5 #define SUBSTYPE 10 #define WALLSTYPE 1 #define VOIDSTYPE 2 #define FILAMENTSTYPE 3 #define BGTYPE 10 #define GROUPNOPARENT -1 #define FOF3DTYPE 7 #define FOF3DGROUP -2 //@} /// \defgroup FOFTYPES FOF search types //@{ //subsets made ///call \ref FOFStreamwithprob #define FOFSTPROB 1 ///6D FOF search but only with outliers #define FOF6DSUBSET 7 ///like \ref FOFStreamwithprob search but search is limited to nearest physical neighbours #define FOFSTPROBNN 9 ///like \ref FOFStreamwithprob search but here linking length adjusted by velocity offset, smaller lengths for larger velocity offsets #define FOFSTPROBLX 10 ///like \ref FOFSTPROBLX but for NN search #define FOFSTPROBNNLX 11 ///like \ref FOFSTPROBNN but there is not linking length applied just use nearest neighbours #define FOFSTPROBNNNODIST 12 //for iterative method with FOFStreamwithprob //#define FOFSTPROBIT 13 #define FOFSTPROBSCALEELL 13 //#define FOFSTPROBIT 13 #define FOFSTPROBSCALEELLNN 14 //solely phase-space tensor core growth substructure search #define FOF6DCORE 6 ///phase-space FOF but no subset produced #define FOFSTNOSUBSET 2 ///no subsets made, just 6d (with each 6dfof search using 3d fof velocity dispersion,) #define FOF6DADAPTIVE 3 ///6d fof but only use single velocity dispersion from largest 3d fof object #define FOF6D 4 ///3d search #define FOF3D 5 ///baryon 6D FOF search #define FOFBARYON6D 0 ///baryon phase tensor search #define FOFBARYONPHASETENSOR 1 //@} /// \defgroup INTERATIVESEARCHPARAMS for iterative subsubstructure search //@{ /// this is minimum particle number size for a subsearch to proceed whereby substructure split up into CELLSPLITNUM new cells #define MINCELLSIZE 100 #define CELLSPLITNUM 8 #define MINSUBSIZE MINCELLSIZE*CELLSPLITNUM #define MAXSUBLEVEL 8 /// maximum fraction a cell can take of a halo #define MAXCELLFRACTION 0.1 //@} ///\defgroup GRIDTYPES Type of Grid structures //@{ #define PHYSENGRID 1 #define PHASEENGRID 2 #define PHYSGRID 3 //@} /// \name Max number of neighbouring cells used in interpolation of background velocity field. //@{ //if cells were cubes this would be all the neighbours that full enclose the cube, 6 faces+20 diagonals //using daganoals may not be ideal. Furthermore, code using adaptive grid that if effectively produces //cell that are rectangular prisms. Furthermore, not all cells will share a boundary with another cell. //So just consider "faces". #define MAXNGRID 6 //@} ///\defgroup INPUTTYPES defining types of input //@{ #define NUMINPUTS 5 #define IOGADGET 1 #define IOHDF 2 #define IOTIPSY 3 #define IORAMSES 4 #define IONCHILADA 5 //@} ///\defgroup OUTPUTTYPES defining format types of output //@{ #define OUTASCII 0 #define OUTBINARY 1 #define OUTHDF 2 #define OUTADIOS 3 //@} ///\defgroup CALCULATIONTYPES defining what is calculated //@{ #define CALCAVERAGE 1 #define CALCTOTAL 2 #define CALCSTD 3 #define CALCMEDIAN 4 #define CALCMIN 5 #define CALCMAX 6 #define CALCLOGAVERAGE 7 #define CALCLOGSTD 8 #define CALCQUANTITYMASSWEIGHT 10 #define CALCAVERAGEMASSWEIGHT 11 #define CALCTOTALMASSWEIGHT 12 #define CALCSTDMASSWEIGHT 13 #define CALCMEDIANMASSWEIGHT 14 #define CALCMINMASSWEIGHT 15 #define CALCMAXMASSWEIGHT 16 #define CALCLOGAVERAGEMASSWEIGHT 17 #define CALCLOGSTDMASSWEIGHT 18 #define CALCQUANTITYAPERTURETOTAL -1 #define CALCQUANTITYAPERTUREAVERAGE -2 typedef double (*ExtraPropFunc)(double, double, double&); //@} /// \name For Unbinding //@{ ///number below which just use PP calculation for potential, which occurs roughly at when n~2*log(n) (from scaling of n^2 vs n ln(n) for PP vs tree and factor of 2 is ///for extra overhead in producing tree. For reasonable values of n (>100) this occurs at ~100. Here to account for extra memory need for tree, we use n=3*log(n) or 150 #define UNBINDNUM 150 #define POTPPCALCNUM 150 #define POTOMPCALCNUM 1000 ///diferent methods for calculating approximate potential #define POTAPPROXMETHODTREE 0 #define POTAPPROXMETHODRAND 1 ///when unbinding check to see if system is bound and least bound particle is also bound #define USYSANDPART 0 ///when unbinding check to see if least bound particle is also bound #define UPART 1 ///use the bulk centre of mass velocity to define velocity reference frame when determining if particle bound #define CMVELREF 0 ///use the particle at potential minimum. Issues if too few particles used as particles will move in and out of deepest point of the potential well #define POTREF 1 ///use Centre-of-mass to caculate Properties #define PROPREFCM 0 ///use most bound particle to calculate properties #define PROPREFMBP 1 ///use minimum potential particle to calculat properties #define PROPREFMINPOT 2 //@} /// \name For Tree potential calculation //@{ ///leafflag indicating in tree-calculation of potential, reached a leaf node that does not satisfy mono-pole approx #define leafflag 1 ///split flag means node not used as subcells are searched #define splitflag -1 ///cellflag means a node that is not necessarily a leaf node can be approximated by mono-pole #define cellflag 0 //@} /// \defgroup PROPLIMS Particle limits for calculating properties //@{ #define PROPNFWMINNUM 100 #define PROPCMMINNUM 10 #define PROPROTMINNUM 10 #define PROPMORPHMINNUM 10 //@} /// \defgroup PROPERTYCONSTANTS Useful constants related to calculating properties //@{ /// if halo follows NFW profile, maximum ratio of half mass to virial mass one might /// expect for R200 (assuming the scale radius is inside this radius, giving a c>=1) #define NFWMAXRHALFRATIO 0.60668 #define NFWMINRHALFRATIO 0.05 #define NFWMINVMAXVVIRRATIO 36.0 //@} ///\name halo id modifers used with current snapshot value to make temporally unique halo identifiers #ifdef LONGINT #define HALOIDSNVAL 1000000000000L #else #define HALOIDSNVAL 1000000 #endif ///\defgroup radial profile parameters //@{ #define PROFILERNORMPHYS 0 #define PROFILERNORMR200CRIT 1 #define PROFILERBINTYPELOG 0 //@} ///\defgroup GASPARAMS Useful constants for gas //@{ ///mass of helium relative to hydrogen #define M_HetoM_H 4.0026 //@} ///\defgroup PhysConstants Useful physical constants //@{ #define Grav_in_kpc_kms_solarmasses 4.3022682e-6 //@} /// Structure stores unbinding information struct UnbindInfo { ///\name flag whether unbind groups, keep bg potential when unbinding, type of unbinding and reference frame //@{ int unbindflag,bgpot,unbindtype,cmvelreftype; //@} ///boolean as to whether code calculate potentials or potentials are externally provided bool icalculatepotential; ///fraction of potential energy that kinetic energy is allowed to be and consider particle bound Double_t Eratio; ///minimum bound mass fraction Double_t minEfrac; ///when to recalculate kinetic energies if cmvel has changed enough Double_t cmdelta; ///maximum fraction of particles to remove when unbinding in one given unbinding step Double_t maxunbindfrac; ///Maximum fraction of particles that can be considered unbound before group removed entirely Double_t maxunboundfracforiterativeunbind; ///Max allowed unbound fraction to speed up unbinding Double_t maxallowedunboundfrac; ///minimum number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame Int_t Npotref; ///fraction of number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame Double_t fracpotref; ///\name gravity and tree potential calculation; //@{ int BucketSize; Double_t TreeThetaOpen; ///softening length Double_t eps; ///whether to calculate approximate potential energy int iapproxpot; ///fraction of particles to subsample Double_t approxpotnumfrac; ///fraction of particles to subsample Double_t approxpotminnum; ///method of subsampling to calculate potential int approxpotmethod; //@} UnbindInfo(){ icalculatepotential=true; unbindflag=0; bgpot=1; unbindtype=UPART; cmvelreftype=CMVELREF; cmdelta=0.02; Eratio=1.0; minEfrac=1.0; BucketSize=8; TreeThetaOpen=0.5; eps=0.0; Npotref=20; fracpotref=1.0; maxunbindfrac=0.5; maxunboundfracforiterativeunbind=0.95; maxallowedunboundfrac=0.025; iapproxpot = 0; approxpotnumfrac = 0.1; approxpotminnum = 5000; approxpotmethod = POTAPPROXMETHODTREE; } }; /// Structure stores information used when calculating bulk (sub)structure properties /// which is used in \ref substructureproperties.cxx struct PropInfo { //interate till this much mass in contained in a spherical region to calculate cm quantities Double_t cmfrac,cmadjustfac; PropInfo(){ cmfrac=0.1; cmadjustfac=0.7; } }; /* Structure to hold the location of a top-level cell. */ struct cell_loc { /* Coordinates x,y,z */ double loc[3]; }; /// Options structure stores useful variables that have user determined values which are altered by \ref GetArgs in \ref ui.cxx struct Options { ///\name git related info //@{ string git_sha1; //@} ///\name filenames //@{ char *fname,*outname,*smname,*pname,*gname; char *ramsessnapname; //@} ///input format int inputtype; ///number of snapshots int num_files,snum; ///if parallel reading, number of files read in parallel int nsnapread; ///for output, specify the formats, ie. many separate files int iseparatefiles; ///for output specify the format HDF, binary or ascii \ref OUTHDF, \ref OUTBINARY, \ref OUTASCII int ibinaryout; ///for extended output allowing extraction of particles int iextendedoutput; /// output extra fields in halo properties int iextrahalooutput; /// calculate and output extra gas fields int iextragasoutput; /// calculate and output extra star fields int iextrastaroutput; /// calculate and output extra bh fields int iextrabhoutput; /// calculate and output extra interloper fields int iextrainterloperoutput; /// calculate subind like properties int isubfindproperties; ///for output, produce subfind like format int isubfindoutput; ///flag indicating that VR is running on the fly bool iontheflyfinding; ///disable particle id related output like fof.grp or catalog_group data. Useful if just want halo properties ///and not interested in tracking. Code writes halo properties catalog and exits. int inoidoutput; ///return propery data in in comoving little h units instead of standard physical units int icomoveunit; /// input is a cosmological simulation so can use box sizes, cosmological parameters, etc to set scales int icosmologicalin; /// input buffer size when reading data long long inputbufsize; /// mpi paritcle buffer size when sending input particle information long long mpiparticletotbufsize,mpiparticlebufsize; /// mpi factor by which to multiple the memory allocated, ie: buffer region /// to reduce likelihood of having to expand/allocate new memory Double_t mpipartfac; /// if using parallel output, number of mpi threads to group together int mpinprocswritesize; /// mpi number of top level cells used in decomposition /// could be integrated into metis/parmetis eventually /// here this is the number of cells in a singel dimension to total cells /// is this to ^3 int mpinumtoplevelcells; /// run FOF using OpenMP int iopenmpfof; /// size of openmp FOF region int openmpfofsize; ///\name length,m,v,grav conversion units //@{ Double_t lengthinputconversion, massinputconversion, energyinputconversion, internalenergyinputconversion, velocityinputconversion; Double_t SFRinputconversion, metallicityinputconversion, stellarageinputconversion; int istellaragescalefactor, isfrisssfr; Double_t G; Double_t lengthtokpc, velocitytokms, masstosolarmass, energyperunitmass, timetoseconds; Double_t SFRtosolarmassperyear, stellaragetoyrs, metallicitytosolar; //@} ///period (comove) Double_t p; ///\name scale factor, Hubunit, h, cosmology, virial density. These are used if linking lengths are scaled or trying to define virlevel using the cosmology //@{ Double_t a,H,h; Double_t Omega_m, Omega_b, Omega_cdm, Omega_Lambda, Omega_k, Omega_r, Omega_nu, Omega_de, w_de; Double_t rhocrit, rhobg, virlevel, virBN98; int comove; /// to store the internal code unit to kpc and the distance^2 of 30 kpc, and 50 kpc Double_t lengthtokpc30pow2, lengthtokpc50pow2; //@} ///to store number of each particle types so that if only searching one particle type, assumes order of gas, dark (halo, disk,bulge), star, special or sink for pfof tipsy style output Int_t numpart[NPARTTYPES]; ///\name parameters that control the local and average volumes used to calculate the local velocity density and the mean field, also the size of the leafnode in the kd-tree used when searching the tree for fof neighbours //@{ int iLocalVelDenApproxCalcFlag; int Nvel, Nsearch, Bsize; Int_t Ncell; Double_t Ncellfac; //@} ///minimum group size int MinSize; ///allows for field halos to have a different minimum size int HaloMinSize; ///Significance parameter for groups Double_t siglevel; ///whether to search for substructures at all int iSubSearch; ///type of search int foftype,fofbgtype; ///grid type, physical, physical+entropy splitting criterion, phase+entropy splitting criterion. Note that this parameter should not be changed from the default value int gridtype; ///flag indicating search all particle types or just dark matter int partsearchtype; ///flag indicating a separate baryonic search is run, looking for all particles that are associated in phase-space ///with dark matter particles that belong to a structure int iBaryonSearch; /// FOF search for baryons int ifofbaryonsearch; ///flag indicating if move to CM frame for substructure search int icmrefadjust; /// flag indicating if CM is interated shrinking spheres int iIterateCM; /// flag to sort output particle lists by binding energy (or potential if not on) int iSortByBindingEnergy; /// what reference position to use when calculating Properties int iPropertyReferencePosition; /// what particle type is used to define reference position int ParticleTypeForRefenceFrame; ///threshold on particle ELL value, normalized logarithmic distance from predicted maxwellian velocity density. Double_t ellthreshold; ///\name fofstream search parameters //@{ Double_t thetaopen,Vratio,ellphys; //@} ///fof6d search parameters Double_t ellvel; ///scaling for ellphs and ellvel Double_t ellxscale,ellvscale; ///flag to use iterative method int iiterflag; ///\name factors used to multiply the input values to find initial candidate particles and for mergering groups in interative search //@{ Double_t ellfac,ellxfac,vfac,thetafac,nminfac; Double_t fmerge; //@} ///factors to alter halo linking length search (related to substructure search) //@{ Double_t ellhalophysfac,ellhalovelfac; //@} ///\name parameters related to 3DFOF search & subsequent 6DFOF search //@{ Double_t ellhalo3dxfac; Double_t ellhalo6dxfac; Double_t ellhalo6dvfac; int iKeepFOF; Int_t num3dfof; //@} //@{ ///\name factors used to check for halo mergers, large background substructures and store the velocity scale when searching for associated baryon substructures //@{ Double_t HaloMergerSize,HaloMergerRatio,HaloSigmaV,HaloVelDispScale,HaloLocalSigmaV; Double_t fmergebg; //@} ///flag indicating a single halo is passed or must run search for FOF haloes Int_t iSingleHalo; ///flag indicating haloes are to be check for self-boundness after being searched for substructure Int_t iBoundHalos; /// store denv ratio statistics //@{ int idenvflag; Double_t denvstat[3]; //@} ///verbose output flag int iverbose; ///whether or not to write a fof.grp tipsy like array file int iwritefof; ///whether mass properties for field objects are inclusive int iInclusiveHalo; ///if no mass value stored then store global mass value Double_t MassValue; ///structure that contains variables for unbinding UnbindInfo uinfo; ///structure that contains variables for property calculation PropInfo pinfo; ///effective resolution for zoom simulations Int_t Neff; ///if during substructure search, want to also search for larger substructures //using the more time consuming local velocity calculations (partly in lieu of using the faster core search) int iLargerCellSearch; ///\name extra stuff for halo merger check and identification of multiple halo core and flag for fully adaptive linking length using number density of candidate objects //@{ /// run halo core search for mergers int iHaloCoreSearch; ///maximum sublevel at which we search for phase-space cores int maxnlevelcoresearch; ///parameters associated with phase-space search for cores of mergers Double_t halocorexfac, halocorevfac, halocorenfac, halocoresigmafac; ///x and v space linking lengths calculated for each object int iAdaptiveCoreLinking; ///use phase-space tensor core assignment int iPhaseCoreGrowth; ///number of iterations int halocorenumloops; ///factor by which one multiples the configuration space dispersion when looping for cores Double_t halocorexfaciter; ///factor by which one multiples the velocity space dispersion when looping for cores Double_t halocorevfaciter; ///factor by which one multiples the min num when looping for cores Double_t halocorenumfaciter; ///factor by which a core must be seperated from main core in phase-space in sigma units Double_t halocorephasedistsig; ///factor by which a substructure s must be closer than in phase-space to merger with another substructure in sigma units Double_t coresubmergemindist; ///whether substructure phase-space distance merge check is applied to background host halo as well. int icoresubmergewithbg; ///fraction of size a substructure must be of host to be considered a spurious dynamical substructure Double_t minfracsubsizeforremoval; ///Maximum allowed mean local velocity density ratio above which structure is considered highly unrelaxed. Double_t maxmeanlocalvelratio; //@} ///for storing a snapshot value to make halo ids unique across snapshots long long snapshotvalue; ///\name for reading gadget info with lots of extra sph, star and bh blocks //@{ int gnsphblocks,gnstarblocks,gnbhblocks; //@} /// \name Extra HDF flags indicating the existence of extra baryonic/dm particle types //@{ /// input naming convention int ihdfnameconvention; /// input contains dm particles int iusedmparticles; /// input contains hydro/gas particles int iusegasparticles; /// input contains star particles int iusestarparticles; /// input contains black hole/sink particles int iusesinkparticles; /// input contains wind particles int iusewindparticles; /// input contains tracer particles int iusetracerparticles; /// input contains extra dark type particles int iuseextradarkparticles; //@} /// if want full spherical overdensity, factor by which size is multiplied to get ///bucket of particles Double_t SphericalOverdensitySeachFac; ///if want to the particle IDs that are within the SO overdensity of a halo int iSphericalOverdensityPartList; /// if want to include more than just field objects (halos) in full SO calculations int SphericalOverdensitySeachMaxStructLevel; /// flag to store whether SO calculations need extra properties bool iSphericalOverdensityExtraFieldCalculations; /// \name Extra variables to store information useful in zoom simluations //@{ /// store the lowest dark matter particle mass Double_t zoomlowmassdm; //@} ///\name extra runtime flags //@{ ///scale lengths. Useful if searching single halo system and which to automatically scale linking lengths int iScaleLengths; /// \name Swift/Metis related quantitites //@{ //Swift::siminfo swiftsiminfo; double spacedimension[3]; /* Number of top-level cells. */ int numcells; /* Number of top-level cells in each dimension. */ int numcellsperdim; /// minimum number of top-level cells int minnumcellperdim; /* Locations of top-level cells. */ cell_loc *cellloc; /*! Top-level cell width. */ double cellwidth[3]; /*! Inverse of the top-level cell width. */ double icellwidth[3]; /*! Holds the node ID of each top-level cell. */ int *cellnodeids; /// holds the order of cells based on z-curve decomposition; vector<int> cellnodeorder; /// holds the number of particles in a given top-level cell vector<unsigned long long> cellnodenumparts; /// allowed mesh based mpi decomposition load imbalance float mpimeshimbalancelimit; ///whether using mesh decomposition bool impiusemesh; //@} /// \name options related to calculation of aperture/profile //@{ int iaperturecalc; int aperturenum,apertureprojnum; vector<Double_t> aperture_values_kpc; vector<string> aperture_names_kpc; vector<Double_t> aperture_proj_values_kpc; vector<string> aperture_proj_names_kpc; int iprofilecalc, iprofilenorm, iprofilebintype; int profilenbins; int iprofilecumulative; string profileradnormstring; vector<Double_t> profile_bin_edges; Int_t profileminsize, profileminFOFsize; //@} /// \name options related to calculation of arbitrary overdensities masses, radii, angular momentum //@{ int SOnum; vector<Double_t> SOthresholds_values_crit; vector<string> SOthresholds_names_crit; //@} /// \name options related to calculating star forming gas quantities //@{ Double_t gas_sfr_threshold; //@} /// \name options related to calculating detailed hydro/star/bh properties related to chemistry/feedbac, etc //@{ ///stores the name of the field vector<string> gas_internalprop_names; vector<string> star_internalprop_names; vector<string> bh_internalprop_names; ///can also store the dimensional index of the field, useful when single data ///set contains many related but different properties vector<unsigned int> gas_internalprop_index; vector<unsigned int> star_internalprop_index; vector<unsigned int> bh_internalprop_index; ///stores what is calculated ///(1 is mass weighted average, 2 mass weighted total, etc vector<int> gas_internalprop_function; vector<int> star_internalprop_function; vector<int> bh_internalprop_function; vector<string> gas_chem_names; vector<string> star_chem_names; vector<string> bh_chem_names; vector<unsigned int> gas_chem_index; vector<unsigned int> star_chem_index; vector<unsigned int> bh_chem_index; vector<int> gas_chem_function; vector<int> star_chem_function; vector<int> bh_chem_function; vector<string> gas_chemproduction_names; vector<string> star_chemproduction_names; vector<string> bh_chemproduction_names; vector<unsigned int> gas_chemproduction_index; vector<unsigned int> star_chemproduction_index; vector<unsigned int> bh_chemproduction_index; vector<int> gas_chemproduction_function; vector<int> star_chemproduction_function; vector<int> bh_chemproduction_function; vector<string> extra_dm_internalprop_names; vector<unsigned int> extra_dm_internalprop_index; vector<int> extra_dm_internalprop_function; ///store the output field name vector<string> gas_internalprop_output_names; vector<string> star_internalprop_output_names; vector<string> bh_internalprop_output_names; vector<string> gas_chem_output_names; vector<string> star_chem_output_names; vector<string> bh_chem_output_names; vector<string> gas_chemproduction_output_names; vector<string> star_chemproduction_output_names; vector<string> bh_chemproduction_output_names; vector<string> extra_dm_internalprop_output_names; ///store conversion factor from input unit to output unit vector<float> gas_internalprop_input_output_unit_conversion_factors; vector<float> star_internalprop_input_output_unit_conversion_factors; vector<float> bh_internalprop_input_output_unit_conversion_factors; vector<float> gas_chem_input_output_unit_conversion_factors; vector<float> star_chem_input_output_unit_conversion_factors; vector<float> bh_chem_input_output_unit_conversion_factors; vector<float> gas_chemproduction_input_output_unit_conversion_factors; vector<float> star_chemproduction_input_output_unit_conversion_factors; vector<float> bh_chemproduction_input_output_unit_conversion_factors; vector<float> extra_dm_internalprop_input_output_unit_conversion_factors; ///store output units vector<string> gas_internalprop_output_units; vector<string> star_internalprop_output_units; vector<string> bh_internalprop_output_units; vector<string> gas_chem_output_units; vector<string> star_chem_output_units; vector<string> bh_chem_output_units; vector<string> gas_chemproduction_output_units; vector<string> star_chemproduction_output_units; vector<string> bh_chemproduction_output_units; vector<string> extra_dm_internalprop_output_units; ///some calculations are multistage and must be paired with ///another calculation in the list. This is true of standard deviations vector<int> gas_internalprop_index_paired_calc; vector<int> star_internalprop_index_paired_calc; vector<int> bh_internalprop_index_paired_calc; vector<int> gas_chem_index_paired_calc; vector<int> star_chem_index_paired_calc; vector<int> bh_chem_index_paired_calc; vector<int> gas_chemproduction_index_paired_calc; vector<int> star_chemproduction_index_paired_calc; vector<int> bh_chemproduction_index_paired_calc; vector<int> extra_dm_internalprop_index_paired_calc; ///whether some calculations are for extra properties are aperture calculations bool gas_extraprop_aperture_calc; bool star_extraprop_aperture_calc; bool bh_extraprop_aperture_calc; bool extra_dm_extraprop_aperture_calc; ///easier to store information separately internally vector<string> gas_internalprop_names_aperture; vector<string> gas_chem_names_aperture; vector<string> gas_chemproduction_names_aperture; vector<string> star_internalprop_names_aperture; vector<string> star_chem_names_aperture; vector<string> star_chemproduction_names_aperture; vector<string> bh_internalprop_names_aperture; vector<string> bh_chem_names_aperture; vector<string> bh_chemproduction_names_aperture; vector<string> extra_dm_internalprop_names_aperture; vector<unsigned int> gas_internalprop_index_aperture; vector<unsigned int> gas_chem_index_aperture; vector<unsigned int> gas_chemproduction_index_aperture; vector<unsigned int> star_internalprop_index_aperture; vector<unsigned int> star_chem_index_aperture; vector<unsigned int> star_chemproduction_index_aperture; vector<unsigned int> bh_internalprop_index_aperture; vector<unsigned int> bh_chem_index_aperture; vector<unsigned int> bh_chemproduction_index_aperture; vector<unsigned int> extra_dm_internalprop_index_aperture; vector<int> gas_internalprop_function_aperture; vector<int> gas_chem_function_aperture; vector<int> gas_chemproduction_function_aperture; vector<int> star_internalprop_function_aperture; vector<int> star_chem_function_aperture; vector<int> star_chemproduction_function_aperture; vector<int> bh_internalprop_function_aperture; vector<int> bh_chem_function_aperture; vector<int> bh_chemproduction_function_aperture; vector<int> extra_dm_internalprop_function_aperture; vector<string> gas_internalprop_output_units_aperture; vector<string> star_internalprop_output_units_aperture; vector<string> bh_internalprop_output_units_aperture; vector<string> gas_chem_output_units_aperture; vector<string> star_chem_output_units_aperture; vector<string> bh_chem_output_units_aperture; vector<string> gas_chemproduction_output_units_aperture; vector<string> star_chemproduction_output_units_aperture; vector<string> bh_chemproduction_output_units_aperture; vector<string> extra_dm_internalprop_output_units_aperture; vector<float> gas_internalprop_input_output_unit_conversion_factors_aperture; vector<float> star_internalprop_input_output_unit_conversion_factors_aperture; vector<float> bh_internalprop_input_output_unit_conversion_factors_aperture; vector<float> gas_chem_input_output_unit_conversion_factors_aperture; vector<float> star_chem_input_output_unit_conversion_factors_aperture; vector<float> bh_chem_input_output_unit_conversion_factors_aperture; vector<float> gas_chemproduction_input_output_unit_conversion_factors_aperture; vector<float> star_chemproduction_input_output_unit_conversion_factors_aperture; vector<float> bh_chemproduction_input_output_unit_conversion_factors_aperture; vector<float> extra_dm_internalprop_input_output_unit_conversion_factors_aperture; vector<string> gas_internalprop_output_names_aperture; vector<string> gas_chem_output_names_aperture; vector<string> gas_chemproduction_output_names_aperture; vector<string> star_internalprop_output_names_aperture; vector<string> star_chem_output_names_aperture; vector<string> star_chemproduction_output_names_aperture; vector<string> bh_internalprop_output_names_aperture; vector<string> bh_chem_output_names_aperture; vector<string> bh_chemproduction_output_names_aperture; vector<string> extra_dm_internalprop_output_names_aperture; //to store the unique names that are going to be loaded from the input vector<string> gas_internalprop_unique_input_names; vector<string> gas_chem_unique_input_names; vector<string> gas_chemproduction_unique_input_names; vector<string> star_internalprop_unique_input_names; vector<string> star_chem_unique_input_names; vector<string> star_chemproduction_unique_input_names; vector<string> bh_internalprop_unique_input_names; vector<string> bh_chem_unique_input_names; vector<string> bh_chemproduction_unique_input_names; vector<string> extra_dm_internalprop_unique_input_names; vector<unsigned short> gas_internalprop_unique_input_indexlist; vector<unsigned short> gas_chem_unique_input_indexlist; vector<unsigned short> gas_chemproduction_unique_input_indexlist; vector<unsigned short> star_internalprop_unique_input_indexlist; vector<unsigned short> star_chem_unique_input_indexlist; vector<unsigned short> star_chemproduction_unique_input_indexlist; vector<unsigned short> bh_internalprop_unique_input_indexlist; vector<unsigned short> bh_chem_unique_input_indexlist; vector<unsigned short> bh_chemproduction_unique_input_indexlist; vector<unsigned short> extra_dm_internalprop_unique_input_indexlist; //@} /// \name memory related info //@{ unsigned long long memuse_peak; unsigned long long memuse_ave; int memuse_nsamples; bool memuse_log; //@} //silly flag to store whether input has little h's in it. bool inputcontainslittleh; Options() { lengthinputconversion = 1.0; massinputconversion = 1.0; velocityinputconversion = 1.0; SFRinputconversion = 1.0; metallicityinputconversion = 1.0; energyinputconversion = 1.0; stellarageinputconversion =1.0; istellaragescalefactor = 1; isfrisssfr = 0; G = 0.0; p = 0.0; a = 1.0; H = 0.; h = 1.0; Omega_m = 1.0; Omega_Lambda = 0.0; Omega_b = 0.0; Omega_cdm = Omega_m; Omega_k = 0; Omega_r = 0.0; Omega_nu = 0.0; Omega_de = 0.0; w_de = -1.0; rhobg = 1.0; virlevel = -1; comove=0; MassValue=-1.0; inputtype=IOGADGET; num_files=1; nsnapread=1; fname=outname=smname=pname=gname=outname=NULL; Bsize=32; Nvel=32; Nsearch=256; Ncellfac=0.01; iSubSearch=1; partsearchtype=PSTALL; for (int i=0;i<NPARTTYPES;i++)numpart[i]=0; foftype=FOFSTPROB; gridtype=PHYSENGRID; fofbgtype=FOF6D; idenvflag=0; iBaryonSearch=0; icmrefadjust=1; iIterateCM = 1; iLocalVelDenApproxCalcFlag = 2 ; Neff=-1; ellthreshold=1.5; thetaopen=0.05; Vratio=1.25; ellphys=0.2; MinSize=20; HaloMinSize=-1; siglevel=2.0; ellvel=0.5; ellxscale=ellvscale=1.0; ellhalophysfac=ellhalovelfac=1.0; ellhalo6dxfac=1.0; ellhalo6dvfac=1.25; ellhalo3dxfac=-1.0; iiterflag=0; ellfac=2.5; ellxfac=3.0; vfac=1.0; thetafac=1.0; nminfac=0.5; fmerge=0.25; HaloMergerSize=10000; HaloMergerRatio=0.2; HaloVelDispScale=0; fmergebg=0.5; iSingleHalo=0; iBoundHalos=0; iInclusiveHalo=0; iKeepFOF=0; iSortByBindingEnergy=1; iPropertyReferencePosition=PROPREFCM; ParticleTypeForRefenceFrame=-1; iLargerCellSearch=0; iHaloCoreSearch=0; iAdaptiveCoreLinking=0; iPhaseCoreGrowth=1; maxnlevelcoresearch=5; halocorexfac=0.5; halocorevfac=2.0; halocorenfac=0.1; halocoresigmafac=2.0; halocorenumloops=3; halocorexfaciter=0.75; halocorevfaciter=0.75; halocorenumfaciter=1.0; halocorephasedistsig=2.0; coresubmergemindist=0.0; icoresubmergewithbg=0; minfracsubsizeforremoval=0.75; maxmeanlocalvelratio=0.5; iverbose=0; iwritefof=0; iseparatefiles=0; ibinaryout=0; iextendedoutput=0; isubfindoutput=0; inoidoutput=0; icomoveunit=0; icosmologicalin=1; iextrahalooutput=0; iextragasoutput=0; iextrastaroutput=0; iextrainterloperoutput=0; isubfindproperties=0; iusedmparticles=1; iusegasparticles=1; iusestarparticles=1; iusesinkparticles=1; iusewindparticles=0; iusetracerparticles=0; #ifdef HIGHRES iuseextradarkparticles=1; #else iuseextradarkparticles=0; #endif snapshotvalue=0; gnsphblocks=4; gnstarblocks=2; gnbhblocks=2; iScaleLengths=0; inputbufsize=1000000; mpiparticletotbufsize=-1; mpiparticlebufsize=-1; mpinprocswritesize=1; #ifdef SWIFTINTERFACE impiusemesh = true; #else impiusemesh = true; mpimeshimbalancelimit = 0.1; minnumcellperdim = 8; #endif cellnodeids = NULL; lengthtokpc=-1.0; velocitytokms=-1.0; masstosolarmass=-1.0; #if defined(GASON) || defined(STARON) || defined(BHON) SFRtosolarmassperyear=-1.0; stellaragetoyrs=-1.0; metallicitytosolar=-1.0; #endif lengthtokpc30pow2=30.0*30.0; lengthtokpc50pow2=50.0*50.0; SphericalOverdensitySeachFac=2.5; iSphericalOverdensityPartList=0; SphericalOverdensitySeachMaxStructLevel = HALOSTYPE; iSphericalOverdensityExtraFieldCalculations = false; mpipartfac=0.1; #if USEHDF ihdfnameconvention=-1; #endif iaperturecalc=0; aperturenum=0; apertureprojnum=0; SOnum=0; iprofilecalc=0; iprofilenorm=PROFILERNORMR200CRIT; iprofilebintype=PROFILERBINTYPELOG; iprofilecumulative=0; profilenbins=0; profileminsize = profileminFOFsize = 0; #ifdef USEOPENMP iopenmpfof = 1; openmpfofsize = ompfofsearchnum; #endif iontheflyfinding = false; memuse_peak = 0; memuse_ave = 0; memuse_nsamples = 0; memuse_log = false; inputcontainslittleh = true; } Options(Options &opt) = default; Options& operator=(const Options&) = default; Options& operator=(Options&&) = default; }; struct ConfigInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; vector<string> datatype; string python_type_string(bool &x){return string("bool");} string python_type_string(int &x){return string("int32");} string python_type_string(unsigned int &x){return string("uint32");} string python_type_string(long long &x){return string("int64");} string python_type_string(unsigned long long &x){return string("uint64");} string python_type_string(float &x){return string("float32");} string python_type_string(double &x){return string("float64");} string python_type_string(string &x){return string("str");} void AddEntry(string entryname){ nameinfo.push_back(entryname); datainfo.push_back(""); datatype.push_back(""); } template<typename T> void AddEntry(string entryname, T entry){ nameinfo.push_back(entryname); datainfo.push_back(to_string(entry)); datatype.push_back(python_type_string(entry)); } template<typename T> void AddEntry(string entryname, vector<T> entries){ if (entries.size() == 0) return; T val = entries[0]; nameinfo.push_back(entryname); string datastring=string(""); for (auto &x:entries) {datastring+=to_string(x);datastring+=string(",");} datainfo.push_back(datastring); datatype.push_back(python_type_string(val)); } template<typename T> void AddEntry(string entryname, vector<T> entries1, vector<T> entries2){ if (entries1.size() + entries2.size() == 0) return; T val = entries1[0]; nameinfo.push_back(entryname); string datastring=string(""); for (auto &x:entries1) {datastring+=to_string(x);datastring+=string(",");} for (auto &x:entries2) {datastring+=to_string(x);datastring+=string(",");} datainfo.push_back(datastring); datatype.push_back(python_type_string(val)); } void AddEntry(string entryname, string entry){ nameinfo.push_back(entryname); datainfo.push_back(entry); datatype.push_back(python_type_string(entry)); } void AddEntry(string entryname, vector<string> entries){ if (entries.size() == 0) return; string val = entries[0]; nameinfo.push_back(entryname); string datastring=string(""); for (auto &x:entries) {datastring+=x;datastring+=string(",");} datainfo.push_back(datastring); datatype.push_back(python_type_string(val)); } void AddEntry(string entryname, vector<string> entries1, vector<string> entries2){ if (entries1.size() + entries2.size() == 0) return; string val = entries1[0]; nameinfo.push_back(entryname); string datastring=string(""); for (auto &x:entries1) {datastring+=x;datastring+=string(",");} for (auto &x:entries2) {datastring+=x;datastring+=string(",");} datainfo.push_back(datastring); datatype.push_back(python_type_string(val)); } ConfigInfo(Options &opt); }; struct SimInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; vector<string> datatype; string python_type_string(int &x){return string("int32");} string python_type_string(unsigned int &x){return string("uint32");} string python_type_string(long &x){return string("int64");} string python_type_string(unsigned long &x){return string("uint64");} string python_type_string(float &x){return string("float32");} string python_type_string(double &x){return string("float64");} SimInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER nameinfo.push_back("Cosmological_Sim"); datainfo.push_back(to_string(opt.icosmologicalin)); datatype.push_back(python_type_string(opt.icosmologicalin)); if (opt.icosmologicalin) { nameinfo.push_back("ScaleFactor"); datainfo.push_back(to_string(opt.a)); datatype.push_back(python_type_string(opt.a)); nameinfo.push_back("h_val"); datainfo.push_back(to_string(opt.h)); datatype.push_back(python_type_string(opt.h)); nameinfo.push_back("Omega_m"); datainfo.push_back(to_string(opt.Omega_m)); datatype.push_back(python_type_string(opt.Omega_m)); nameinfo.push_back("Omega_Lambda"); datainfo.push_back(to_string(opt.Omega_Lambda)); datatype.push_back(python_type_string(opt.Omega_Lambda)); nameinfo.push_back("Omega_cdm"); datainfo.push_back(to_string(opt.Omega_cdm)); datatype.push_back(python_type_string(opt.Omega_cdm)); nameinfo.push_back("Omega_b"); datainfo.push_back(to_string(opt.Omega_b)); datatype.push_back(python_type_string(opt.Omega_b)); nameinfo.push_back("w_of_DE"); datainfo.push_back(to_string(opt.w_de)); datatype.push_back(python_type_string(opt.w_de)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); datatype.push_back(python_type_string(opt.p)); nameinfo.push_back("Hubble_unit"); datainfo.push_back(to_string(opt.H)); datatype.push_back(python_type_string(opt.H)); } else{ nameinfo.push_back("Time"); datainfo.push_back(to_string(opt.a)); datatype.push_back(python_type_string(opt.a)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); datatype.push_back(python_type_string(opt.p)); } //units nameinfo.push_back("Length_unit"); datainfo.push_back(to_string(opt.lengthinputconversion)); datatype.push_back(python_type_string(opt.lengthinputconversion)); nameinfo.push_back("Velocity_unit"); datainfo.push_back(to_string(opt.velocityinputconversion)); datatype.push_back(python_type_string(opt.velocityinputconversion)); nameinfo.push_back("Mass_unit"); datainfo.push_back(to_string(opt.massinputconversion)); datatype.push_back(python_type_string(opt.massinputconversion)); nameinfo.push_back("Gravity"); datainfo.push_back(to_string(opt.G)); datatype.push_back(python_type_string(opt.G)); #ifdef NOMASS nameinfo.push_back("Mass_value"); datainfo.push_back(to_string(opt.MassValue)); datatype.push_back(python_type_string(opt.MassValue)); #endif #endif } }; struct UnitInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; vector<string> datatype; string python_type_string(int &x){return string("int32");} string python_type_string(unsigned int &x){return string("uint32");} string python_type_string(long &x){return string("int64");} string python_type_string(unsigned long &x){return string("uint64");} string python_type_string(float &x){return string("float32");} string python_type_string(double &x){return string("float64");} UnitInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER nameinfo.push_back("Cosmological_Sim"); datainfo.push_back(to_string(opt.icosmologicalin)); datatype.push_back(python_type_string(opt.icosmologicalin)); nameinfo.push_back("Comoving_or_Physical"); datainfo.push_back(to_string(opt.icomoveunit)); datatype.push_back(python_type_string(opt.icomoveunit)); //units nameinfo.push_back("Length_unit_to_kpc"); datainfo.push_back(to_string(opt.lengthtokpc)); datatype.push_back(python_type_string(opt.lengthtokpc)); nameinfo.push_back("Velocity_unit_to_kms"); datainfo.push_back(to_string(opt.velocitytokms)); datatype.push_back(python_type_string(opt.velocitytokms)); nameinfo.push_back("Mass_unit_to_solarmass"); datainfo.push_back(to_string(opt.masstosolarmass)); datatype.push_back(python_type_string(opt.masstosolarmass)); #if defined(GASON) || defined(STARON) || defined(BHON) nameinfo.push_back("Metallicity_unit_to_solar"); datainfo.push_back(to_string(opt.metallicitytosolar)); datatype.push_back(python_type_string(opt.metallicitytosolar)); nameinfo.push_back("SFR_unit_to_solarmassperyear"); datainfo.push_back(to_string(opt.SFRtosolarmassperyear)); datatype.push_back(python_type_string(opt.SFRtosolarmassperyear)); nameinfo.push_back("Stellar_age_unit_to_yr"); datainfo.push_back(to_string(opt.stellaragetoyrs)); datatype.push_back(python_type_string(opt.stellaragetoyrs)); #endif #endif } }; /// N-dim grid cell struct GridCell { int ndim; Int_t gid; //middle of cell, and boundaries of cell Double_t xm[6], xbl[6],xbu[6]; //mass, radial size of in cell Double_t mass, rsize; //number of particles in cell Int_t nparts,*nindex; //neighbouring grid cells and distance from cell centers Int_t nnidcells[MAXNGRID]; Double_t nndist[MAXNGRID]; Double_t den; GridCell(int N=3){ ndim=N; nparts=0; den=0; } ~GridCell(){ if (nparts>0)delete[] nindex; } }; /*! structure stores bulk properties like \f$ m,\ (x,y,z)_{\rm cm},\ (vx,vy,vz)_{\rm cm},\ V_{\rm max},\ R_{\rm max}, \f$ which is calculated in \ref substructureproperties.cxx */ struct PropData { ///\name order in structure hierarchy and number of subhaloes //@{ long long haloid,hostid,directhostid, hostfofid; Int_t numsubs; //@} ///\name properties of total object including DM, gas, stars, bh, etc //@{ ///number of particles Int_t num; ///number of particles in FOF envelop Int_t gNFOF,gN6DFOF; ///centre of mass Coordinate gcm, gcmvel; ///Position of most bound particle, and also of particle with min potential Coordinate gposmbp, gvelmbp, gposminpot, gvelminpot; ///\name physical properties regarding mass, size //@{ Double_t gmass,gsize,gMvir,gRvir,gRcm,gRmbp,gRminpot,gmaxvel,gRmaxvel,gMmaxvel,gRhalfmass,gMassTwiceRhalfmass; Double_t gM200c,gR200c,gM200m,gR200m,gMFOF,gM6DFOF,gM500c,gR500c,gMBN98,gRBN98; //to store exclusive masses of halo ignoring substructure Double_t gMvir_excl,gRvir_excl,gM200c_excl,gR200c_excl,gM200m_excl,gR200m_excl,gMBN98_excl,gRBN98_excl; //to store halfmass radii of overdensity masses Double_t gRhalf200c,gRhalf200m,gRhalfBN98; //@} ///\name physical properties for shape/mass distribution //@{ ///axis ratios Double_t gq,gs; ///eigenvector Matrix geigvec; //@} ///\name physical properties for velocity //@{ ///velocity dispersion Double_t gsigma_v; ///dispersion tensor Matrix gveldisp; //@} ///physical properties for dynamical state Double_t Efrac,Pot,T; ///physical properties for angular momentum Coordinate gJ; Coordinate gJ200m, gJ200c, gJBN98; ///physical properties for angular momentum exclusive Coordinate gJ200m_excl, gJ200c_excl, gJBN98_excl; ///Keep track of position of least unbound particle and most bound particle pid and minimum potential Int_t iunbound,ibound, iminpot; ///Type of structure int stype; ///concentration (and related quantity used to calculate a concentration) Double_t cNFW, VmaxVvir2; Double_t cNFW200c, cNFW200m, cNFWBN98; /// if fitting mass profiles with generalized NFW Double_t NFWfitrs, NFWfitalpha, NFWfitbeta; ///Bullock & Peebles spin parameters Double_t glambda_B,glambda_P; ///measure of rotational support Double_t Krot; //@} ///\name halo properties within RVmax //@{ Double_t RV_q,RV_s; Matrix RV_eigvec; Double_t RV_sigma_v; Matrix RV_veldisp; Coordinate RV_J; Double_t RV_lambda_B,RV_lambda_P; Double_t RV_Krot; //@} ///\name aperture quantities/ radial profiles //@{ vector<unsigned int> aperture_npart; vector<float> aperture_mass; vector<float> aperture_veldisp; vector<float> aperture_vrdisp; vector<float> aperture_rhalfmass; vector<Coordinate> aperture_mass_proj; vector<Coordinate> aperture_rhalfmass_proj; vector<Coordinate> aperture_L; vector<unsigned int> profile_npart; vector<unsigned int> profile_npart_inclusive; vector<float> profile_mass; vector<float> profile_mass_inclusive; vector<Coordinate> profile_L; #if defined(GASON) || defined(STARON) || defined(BHON) vector<unsigned int> aperture_npart_dm; vector<float> aperture_mass_dm; vector<float> aperture_veldisp_dm; vector<float> aperture_vrdisp_dm; vector<float> aperture_rhalfmass_dm; #endif //@} vector<Double_t> SO_mass, SO_radius; vector<Coordinate> SO_angularmomentum; #ifdef GASON ///\name gas specific quantities //@{ ///number of particles int n_gas; ///mass Double_t M_gas, M_gas_rvmax, M_gas_30kpc, M_gas_50kpc, M_gas_500c; ///mass in spherical overdensities Double_t M_200crit_gas, M_200mean_gas, M_BN98_gas; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_gas, M_200mean_excl_gas, M_BN98_excl_gas; ///pos/vel info Coordinate cm_gas,cmvel_gas; ///velocity/angular momentum info Double_t Krot_gas; Coordinate L_gas; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_gas, L_200mean_gas, L_BN98_gas; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_gas, L_200mean_excl_gas, L_BN98_excl_gas; //dispersion Matrix veldisp_gas; ///morphology Double_t MassTwiceRhalfmass_gas, Rhalfmass_gas, q_gas, s_gas; Matrix eigvec_gas; ///mass weighted sum of temperature, metallicty, star formation rate Double_t Temp_gas, Z_gas, SFR_gas; ///mean temperature,metallicty,star formation rate Double_t Temp_mean_gas, Z_mean_gas, SFR_mean_gas; ///physical properties for dynamical state Double_t Efrac_gas, Pot_gas, T_gas; //@} ///\name gas aperture quantities/ radial profiles //@{ vector<unsigned int> aperture_npart_gas; vector<float> aperture_mass_gas; vector<float> aperture_veldisp_gas; vector<float> aperture_vrdisp_gas; vector<float> aperture_SFR_gas; vector<float> aperture_Z_gas; vector<float> aperture_rhalfmass_gas; vector<Coordinate> aperture_L_gas; vector<Coordinate> aperture_mass_proj_gas; vector<Coordinate> aperture_rhalfmass_proj_gas; vector<Coordinate> aperture_SFR_proj_gas; vector<Coordinate> aperture_Z_proj_gas; vector<unsigned int> profile_npart_gas; vector<unsigned int> profile_npart_inclusive_gas; vector<float> profile_mass_gas; vector<float> profile_mass_inclusive_gas; vector<Coordinate> profile_L_gas; //@} vector<Double_t> SO_mass_gas; vector<Coordinate> SO_angularmomentum_gas; #ifdef STARON ///\name star forming gas specific quantities //@{ ///number of particles int n_gas_sf; ///mass Double_t M_gas_sf, M_gas_sf_rvmax,M_gas_sf_30kpc,M_gas_sf_50kpc, M_gas_sf_500c; ///mass in spherical overdensities Double_t M_200crit_gas_sf, M_200mean_gas_sf, M_BN98_gas_sf; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_gas_sf, M_200mean_excl_gas_sf, M_BN98_excl_gas_sf; ///velocity/angular momentum info Double_t Krot_gas_sf; Coordinate L_gas_sf; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_gas_sf, L_200mean_gas_sf, L_BN98_gas_sf; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_gas_sf, L_200mean_excl_gas_sf, L_BN98_excl_gas_sf; //dispersion Double_t sigV_gas_sf; ///morphology Double_t MassTwiceRhalfmass_gas_sf, Rhalfmass_gas_sf, q_gas_sf, s_gas_sf; ///mass weighted sum of temperature, metallicty, star formation rate Double_t Temp_gas_sf, Z_gas_sf, SFR_gas_sf; ///mean temperature,metallicty,star formation rate Double_t Temp_mean_gas_sf, Z_mean_gas_sf, SFR_mean_gas_sf; //@} ///\name gas star forming aperture quantities/ radial profiles //@{ vector<unsigned int> aperture_npart_gas_sf; vector<float> aperture_mass_gas_sf; vector<float> aperture_veldisp_gas_sf; vector<float> aperture_vrdisp_gas_sf; vector<float> aperture_rhalfmass_gas_sf; vector<float> aperture_Z_gas_sf; vector<Coordinate> aperture_L_gas_sf; vector<Coordinate> aperture_mass_proj_gas_sf; vector<Coordinate> aperture_rhalfmass_proj_gas_sf; vector<Coordinate> aperture_Z_proj_gas_sf; vector<unsigned int> profile_npart_gas_sf; vector<unsigned int> profile_npart_inclusive_gas_sf; vector<float> profile_mass_gas_sf; vector<float> profile_mass_inclusive_gas_sf; vector<Coordinate> profile_L_gas_sf; //@} vector<Double_t> SO_mass_gas_sf; vector<Coordinate> SO_angularmomentum_gas_sf; ///\name star forming gas specific quantities //@{ ///number of particles int n_gas_nsf; ///mass Double_t M_gas_nsf, M_gas_nsf_rvmax,M_gas_nsf_30kpc,M_gas_nsf_50kpc, M_gas_nsf_500c; ///mass in spherical overdensities Double_t M_200crit_gas_nsf, M_200mean_gas_nsf, M_BN98_gas_nsf; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_gas_nsf, M_200mean_excl_gas_nsf, M_BN98_excl_gas_nsf; ///velocity/angular momentum info Double_t Krot_gas_nsf; Coordinate L_gas_nsf; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_gas_nsf, L_200mean_gas_nsf, L_BN98_gas_nsf; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_gas_nsf, L_200mean_excl_gas_nsf, L_BN98_excl_gas_nsf; //dispersion Double_t sigV_gas_nsf; ///morphology Double_t MassTwiceRhalfmass_gas_nsf, Rhalfmass_gas_nsf, q_gas_nsf, s_gas_nsf; ///mass weighted sum of temperature, metallicty, star formation rate Double_t Temp_gas_nsf, Z_gas_nsf; ///mean temperature,metallicty,star formation rate Double_t Temp_mean_gas_nsf, Z_mean_gas_nsf; //@} ///\name gas star forming/non-star forming aperture quantities/radial profiles //@{ vector<unsigned int> aperture_npart_gas_nsf; vector<float> aperture_mass_gas_nsf; vector<float> aperture_veldisp_gas_nsf; vector<float> aperture_vrdisp_gas_nsf; vector<float> aperture_rhalfmass_gas_nsf; vector<float> aperture_Z_gas_nsf; vector<Coordinate> aperture_L_gas_nsf; vector<Coordinate> aperture_mass_proj_gas_nsf; vector<Coordinate> aperture_rhalfmass_proj_gas_nsf; vector<Coordinate> aperture_Z_proj_gas_nsf; vector<unsigned int> profile_npart_gas_nsf; vector<unsigned int> profile_npart_inclusive_gas_nsf; vector<float> profile_mass_gas_nsf; vector<float> profile_mass_inclusive_gas_nsf; vector<Coordinate> profile_L_gas_nsf; //@} vector<Double_t> SO_mass_gas_nsf; vector<Coordinate> SO_angularmomentum_gas_nsf; #endif #endif #ifdef STARON ///\name star specific quantities //@{ ///number of particles int n_star; ///mass Double_t M_star, M_star_rvmax, M_star_30kpc, M_star_50kpc, M_star_500c; ///mass in spherical overdensities Double_t M_200crit_star, M_200mean_star, M_BN98_star; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_star, M_200mean_excl_star, M_BN98_excl_star; ///pos/vel info Coordinate cm_star,cmvel_star; ///velocity/angular momentum info Double_t Krot_star; Coordinate L_star; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_star, L_200mean_star, L_BN98_star; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_star, L_200mean_excl_star, L_BN98_excl_star; Matrix veldisp_star; ///morphology Double_t MassTwiceRhalfmass_star, Rhalfmass_star,q_star,s_star; Matrix eigvec_star; ///mean age,metallicty Double_t t_star,Z_star; ///mean age,metallicty Double_t t_mean_star,Z_mean_star; ///physical properties for dynamical state Double_t Efrac_star,Pot_star,T_star; //@} ///\name stellar aperture quantities/radial profiles //@{ vector<unsigned int> aperture_npart_star; vector<float> aperture_mass_star; vector<float> aperture_veldisp_star; vector<float> aperture_vrdisp_star; vector<float> aperture_rhalfmass_star; vector<float> aperture_Z_star; vector<Coordinate> aperture_L_star; vector<Coordinate> aperture_mass_proj_star; vector<Coordinate> aperture_rhalfmass_proj_star; vector<Coordinate> aperture_Z_proj_star; vector<unsigned int> profile_npart_star; vector<unsigned int> profile_npart_inclusive_star; vector<float> profile_mass_star; vector<float> profile_mass_inclusive_star; vector<Coordinate> profile_L_star; //@} vector<Double_t> SO_mass_star; vector<Coordinate> SO_angularmomentum_star; #endif #ifdef BHON ///\name black hole specific quantities //@{ ///number of BH int n_bh; ///mass Double_t M_bh, M_bh_mostmassive; ///mean accretion rate, metallicty Double_t acc_bh, acc_bh_mostmassive; ///\name blackhole aperture quantities/radial profiles //@{ vector<int> aperture_npart_bh; vector<float> aperture_mass_bh; vector<Coordinate> aperture_mass_proj_bh; vector<Coordinate> aperture_L_bh; //@} vector<Double_t> SO_mass_bh; vector<Coordinate> SO_angularmomentum_bh; //@} #endif #ifdef HIGHRES ///\name low resolution interloper particle specific quantities //@{ ///number of interloper low res particles int n_interloper; ///mass Double_t M_interloper; ///mass in spherical overdensities Double_t M_200crit_interloper, M_200mean_interloper, M_BN98_interloper; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_interloper, M_200mean_excl_interloper, M_BN98_excl_interloper; vector<unsigned int> aperture_npart_interloper; vector<float> aperture_mass_interloper; vector<Coordinate> aperture_mass_proj_interloper; vector<unsigned int> profile_npart_interloper; vector<unsigned int> profile_npart_inclusive_interloper; vector<float> profile_mass_interloper; vector<float> profile_mass_inclusive_interloper; vector<Double_t> SO_mass_interloper; //@} #endif /// \name extra hydro/star/bh properties such as chemistry/feedback/metal production //@{ #if defined(GASON) HydroProperties hydroprop; vector<HydroProperties> aperture_properties_gas; #if defined(STARON) vector<HydroProperties> aperture_properties_gas_sf; vector<HydroProperties> aperture_properties_gas_nsf; #endif #endif #if defined(STARON) StarProperties starprop; vector<StarProperties> aperture_properties_star; #endif #if defined(BHON) BHProperties bhprop; vector<BHProperties> aperture_properties_bh; #endif #if defined(EXTRADMON) Int_t n_dm; ExtraDMProperties extradmprop; vector<ExtraDMProperties> aperture_properties_extra_dm; #endif //@} ///\name standard units of physical properties //@{ string massunit, velocityunit, lengthunit, energyunit; //@} PropData() { num=gNFOF=gN6DFOF=0; gmass=gsize=gRmbp=gmaxvel=gRmaxvel=gRvir=gR200m=gR200c=gRhalfmass=gMassTwiceRhalfmass=Efrac=Pot=T=0.; gMFOF=gM6DFOF=0; gM500c=gR500c=0; gMBN98=gRBN98=0; gRhalf200c = gRhalf200m = gRhalfBN98 = 0.; cNFW200c = cNFW200c = cNFWBN98 = 0; gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.; gJ[0]=gJ[1]=gJ[2]=0; gJ200m[0]=gJ200m[1]=gJ200m[2]=0; gJ200c[0]=gJ200c[1]=gJ200c[2]=0; gJBN98[0]=gJBN98[1]=gJBN98[2]=0; gveldisp=Matrix(0.); gq=gs=1.0; Krot=0.; gM200m_excl=gM200c_excl=gMBN98_excl=0; gR200m_excl=gR200c_excl=gRBN98_excl=0; gJ200m_excl[0]=gJ200m_excl[1]=gJ200m_excl[2]=0; gJ200c_excl[0]=gJ200c_excl[1]=gJ200c_excl[2]=0; gJBN98_excl[0]=gJBN98_excl[1]=gJBN98_excl[2]=0; RV_sigma_v=0; RV_q=RV_s=1.; RV_J[0]=RV_J[1]=RV_J[2]=0; RV_veldisp=Matrix(0.); RV_eigvec=Matrix(0.); RV_lambda_B=RV_lambda_P=RV_Krot=0; #ifdef GASON M_gas_rvmax=M_gas_30kpc=M_gas_50kpc=0; n_gas=M_gas=Efrac_gas=0; cm_gas[0]=cm_gas[1]=cm_gas[2]=cmvel_gas[0]=cmvel_gas[1]=cmvel_gas[2]=0.; L_gas[0]=L_gas[1]=L_gas[2]=0; q_gas=s_gas=1.0; MassTwiceRhalfmass_gas=Rhalfmass_gas=0; eigvec_gas=Matrix(1,0,0,0,1,0,0,0,1); Temp_gas=Z_gas=SFR_gas=0.0; Temp_mean_gas=Z_mean_gas=SFR_mean_gas=0.0; veldisp_gas=Matrix(0.); Krot_gas=T_gas=Pot_gas=0; M_200mean_gas=M_200crit_gas=M_BN98_gas=0; M_200mean_excl_gas=M_200crit_excl_gas=M_BN98_excl_gas=0; L_200crit_gas[0]=L_200crit_gas[1]=L_200crit_gas[2]=0; L_200mean_gas[0]=L_200mean_gas[1]=L_200mean_gas[2]=0; L_BN98_gas[0]=L_BN98_gas[1]=L_BN98_gas[2]=0; L_200crit_excl_gas[0]=L_200crit_excl_gas[1]=L_200crit_excl_gas[2]=0; L_200mean_excl_gas[0]=L_200mean_excl_gas[1]=L_200mean_excl_gas[2]=0; L_BN98_excl_gas[0]=L_BN98_excl_gas[1]=L_BN98_excl_gas[2]=0; #ifdef STARON n_gas_sf = n_gas_nsf = 0; M_gas_sf=M_gas_sf_rvmax=M_gas_sf_30kpc=M_gas_sf_50kpc=0; L_gas_sf[0]=L_gas_sf[1]=L_gas_sf[2]=0; q_gas_sf=s_gas_sf=1.0; MassTwiceRhalfmass_gas_sf=Rhalfmass_gas_sf=0; Temp_gas_sf=Z_gas_sf=0.0; Temp_mean_gas_sf=Z_mean_gas_sf=0.0; sigV_gas_sf=0; M_200mean_gas_sf=M_200crit_gas_sf=M_BN98_gas_sf=0; M_200mean_excl_gas_sf=M_200crit_excl_gas_sf=M_BN98_excl_gas_sf=0; L_200crit_gas_sf[0]=L_200crit_gas_sf[1]=L_200crit_gas_sf[2]=0; L_200mean_gas_sf[0]=L_200mean_gas_sf[1]=L_200mean_gas_sf[2]=0; L_BN98_gas_sf[0]=L_BN98_gas_sf[1]=L_BN98_gas_sf[2]=0; L_200crit_excl_gas_sf[0]=L_200crit_excl_gas_sf[1]=L_200crit_excl_gas_sf[2]=0; L_200mean_excl_gas_sf[0]=L_200mean_excl_gas_sf[1]=L_200mean_excl_gas_sf[2]=0; L_BN98_excl_gas_sf[0]=L_BN98_excl_gas_sf[1]=L_BN98_excl_gas_sf[2]=0; M_gas_nsf=M_gas_nsf_rvmax=M_gas_nsf_30kpc=M_gas_nsf_50kpc=0; L_gas_nsf[0]=L_gas_nsf[1]=L_gas_nsf[2]=0; q_gas_nsf=s_gas_nsf=1.0; MassTwiceRhalfmass_gas_nsf=Rhalfmass_gas_nsf=0; Temp_gas_nsf=Z_gas_nsf=0.0; Temp_mean_gas_nsf=Z_mean_gas_nsf=0.0; sigV_gas_nsf=0; M_200mean_gas_nsf=M_200crit_gas_nsf=M_BN98_gas_nsf=0; M_200mean_excl_gas_nsf=M_200crit_excl_gas_nsf=M_BN98_excl_gas_nsf=0; L_200crit_gas_nsf[0]=L_200crit_gas_nsf[1]=L_200crit_gas_nsf[2]=0; L_200mean_gas_nsf[0]=L_200mean_gas_nsf[1]=L_200mean_gas_nsf[2]=0; L_BN98_gas_nsf[0]=L_BN98_gas_nsf[1]=L_BN98_gas_nsf[2]=0; L_200crit_excl_gas_nsf[0]=L_200crit_excl_gas_nsf[1]=L_200crit_excl_gas_nsf[2]=0; L_200mean_excl_gas_nsf[0]=L_200mean_excl_gas_nsf[1]=L_200mean_excl_gas_nsf[2]=0; L_BN98_excl_gas_nsf[0]=L_BN98_excl_gas_nsf[1]=L_BN98_excl_gas_nsf[2]=0; #endif #endif #ifdef STARON M_star_rvmax=M_star_30kpc=M_star_50kpc=0; n_star=M_star=Efrac_star=0; cm_star[0]=cm_star[1]=cm_star[2]=cmvel_star[0]=cmvel_star[1]=cmvel_star[2]=0.; L_star[0]=L_star[1]=L_star[2]=0; q_star=s_star=1.0; MassTwiceRhalfmass_star=Rhalfmass_star=0; eigvec_star=Matrix(1,0,0,0,1,0,0,0,1); t_star=Z_star=0.; t_mean_star=Z_mean_star=0.; veldisp_star=Matrix(0.); Krot_star=T_star=Pot_star=0; M_200mean_star=M_200crit_star=M_BN98_star=0; M_200mean_excl_star=M_200crit_excl_star=M_BN98_excl_star=0; L_200crit_star[0]=L_200crit_star[1]=L_200crit_star[2]=0; L_200mean_star[0]=L_200mean_star[1]=L_200mean_star[2]=0; L_BN98_star[0]=L_BN98_star[1]=L_BN98_star[2]=0; L_200crit_excl_star[0]=L_200crit_excl_star[1]=L_200crit_excl_star[2]=0; L_200mean_excl_star[0]=L_200mean_excl_star[1]=L_200mean_excl_star[2]=0; L_BN98_excl_star[0]=L_BN98_excl_star[1]=L_BN98_excl_star[2]=0; #endif #ifdef BHON n_bh=M_bh=0; M_bh_mostmassive=0; acc_bh=0; acc_bh_mostmassive=0; #endif #ifdef HIGHRES n_interloper=M_interloper=0; #endif #ifdef EXTRADMON n_dm = 0; #endif } ///equals operator, useful if want inclusive information before substructure search PropData& operator=(const PropData &p) = default; /* PropData& operator=(const PropData &p) { num=p.num; gcm=p.gcm;gcmvel=p.gcmvel; gposmbp=p.gposmbp;gvelmbp=p.gvelmbp; gposminpot=p.gposminpot;gvelminpot=p.gvelminpot; gmass=p.gmass;gsize=p.gsize; gMvir=p.gMvir;gRvir=p.gRvir;gRmbp=p.gRmbp; gmaxvel=gmaxvel=p.gmaxvel;gRmaxvel=p.gRmaxvel;gMmaxvel=p.gMmaxvel; gM200c=p.gM200c;gR200c=p.gR200c; gM200m=p.gM200m;gR200m=p.gR200m; gM500c=p.gM500c;gR500c=p.gR500c; gMBN98=p.gMBN98;gRBN98=p.gRBN98; gNFOF=p.gNFOF; gMFOF=p.gMFOF; gM200c_excl=p.gM200c_excl;gR200c_excl=p.gR200c_excl; gM200m_excl=p.gM200m_excl;gR200m_excl=p.gR200m_excl; gMBN98_excl=p.gMBN98_excl;gRBN98_excl=p.gRBN98_excl; gJ=p.gJ; gJ200c=p.gJ200c; gJ200m=p.gJ200m; gJBN98=p.gJBN98; gJ200c_excl=p.gJ200c_excl; gJ200m_excl=p.gJ200m_excl; gJBN98_excl=p.gJBN98_excl; ///expand to copy all the gas, star, bh, stuff #ifdef GASON M_200mean_gas=p.M_200mean_gas; M_200crit_gas=p.M_200crit_gas; M_BN98_gas=p.M_BN98_gas; M_200mean_excl_gas=p.M_200mean_excl_gas; M_200crit_excl_gas=p.M_200crit_excl_gas; M_BN98_excl_gas=p.M_BN98_excl_gas; L_200mean_gas=p.L_200mean_gas; L_200crit_gas=p.L_200crit_gas; L_BN98_gas=p.L_BN98_gas; L_200mean_excl_gas=p.L_200mean_excl_gas; L_200crit_excl_gas=p.L_200crit_excl_gas; L_BN98_excl_gas=p.L_BN98_excl_gas; #ifdef STARON M_200mean_gas_sf=p.M_200mean_gas_sf; M_200crit_gas_sf=p.M_200crit_gas_sf; M_BN98_gas_sf=p.M_BN98_gas_sf; M_200mean_excl_gas_sf=p.M_200mean_excl_gas_sf; M_200crit_excl_gas_sf=p.M_200crit_excl_gas_sf; M_BN98_excl_gas_sf=p.M_BN98_excl_gas_sf; L_200mean_gas_sf=p.L_200mean_gas_sf; L_200crit_gas_sf=p.L_200crit_gas_sf; L_BN98_gas_sf=p.L_BN98_gas_sf; L_200mean_excl_gas_sf=p.L_200mean_excl_gas_sf; L_200crit_excl_gas_sf=p.L_200crit_excl_gas_sf; L_BN98_excl_gas_sf=p.L_BN98_excl_gas_sf; M_200mean_gas_nsf=p.M_200mean_gas_nsf; M_200crit_gas_nsf=p.M_200crit_gas_nsf; M_BN98_gas_nsf=p.M_BN98_gas_nsf; M_200mean_excl_gas_nsf=p.M_200mean_excl_gas_nsf; M_200crit_excl_gas_nsf=p.M_200crit_excl_gas_nsf; M_BN98_excl_gas_nsf=p.M_BN98_excl_gas_nsf; L_200mean_gas_nsf=p.L_200mean_gas_nsf; L_200crit_gas_nsf=p.L_200crit_gas_nsf; L_BN98_gas_nsf=p.L_BN98_gas_nsf; L_200mean_excl_gas_nsf=p.L_200mean_excl_gas_nsf; L_200crit_excl_gas_nsf=p.L_200crit_excl_gas_nsf; L_BN98_excl_gas_nsf=p.L_BN98_excl_gas_nsf; #endif #endif #ifdef STARON M_200mean_star=p.M_200mean_star; M_200crit_star=p.M_200crit_star; M_BN98_star=p.M_BN98_star; M_200mean_excl_star=p.M_200mean_excl_star; M_200crit_excl_star=p.M_200crit_excl_star; M_BN98_excl_star=p.M_BN98_excl_star; L_200mean_star=p.L_200mean_star; L_200crit_star=p.L_200crit_star; L_BN98_star=p.L_BN98_star; L_200mean_excl_star=p.L_200mean_excl_star; L_200crit_excl_star=p.L_200crit_excl_star; L_BN98_excl_star=p.L_BN98_excl_star; #endif aperture_npart=p.aperture_npart; aperture_mass=p.aperture_mass; aperture_veldisp=p.aperture_veldisp; aperture_vrdisp=p.aperture_vrdisp; aperture_rhalfmass=p.aperture_rhalfmass; #if defined(GASON) || defined(STARON) || defined(BHON) aperture_npart_dm=p.aperture_npart_dm; aperture_mass_dm=p.aperture_mass_dm; aperture_veldisp_dm=p.aperture_veldisp_dm; aperture_vrdisp_dm=p.aperture_vrdisp_dm; aperture_rhalfmass_dm=p.aperture_rhalfmass_dm; #endif #ifdef GASON aperture_npart_gas=p.aperture_npart_gas; aperture_mass_gas=p.aperture_mass_gas; aperture_veldisp_gas=p.aperture_veldisp_gas; aperture_rhalfmass_gas=p.aperture_rhalfmass_gas; #ifdef STARON aperture_SFR_gas=p.aperture_SFR_gas; aperture_Z_gas=p.aperture_Z_gas; aperture_npart_gas_sf=p.aperture_npart_gas_sf; aperture_npart_gas_nsf=p.aperture_npart_gas_nsf; aperture_mass_gas_sf=p.aperture_mass_gas_sf; aperture_mass_gas_nsf=p.aperture_mass_gas_nsf; aperture_veldisp_gas_sf=p.aperture_veldisp_gas_sf; aperture_veldisp_gas_nsf=p.aperture_veldisp_gas_nsf; aperture_vrdisp_gas_sf=p.aperture_vrdisp_gas_sf; aperture_vrdisp_gas_nsf=p.aperture_vrdisp_gas_nsf; aperture_rhalfmass_gas_sf=p.aperture_rhalfmass_gas_sf; aperture_rhalfmass_gas_nsf=p.aperture_rhalfmass_gas_nsf; aperture_Z_gas_sf=p.aperture_Z_gas_sf; aperture_Z_gas_nsf=p.aperture_Z_gas_nsf; #endif #endif #ifdef STARON aperture_npart_star=p.aperture_npart_star; aperture_mass_star=p.aperture_mass_star; aperture_veldisp_star=p.aperture_veldisp_star; aperture_vrdisp_star=p.aperture_vrdisp_star; aperture_rhalfmass_star=p.aperture_rhalfmass_star; aperture_Z_star=p.aperture_Z_star; #endif aperture_mass_proj=p.aperture_mass_proj; aperture_rhalfmass_proj=p.aperture_rhalfmass_proj; #ifdef GASON aperture_mass_proj_gas=p.aperture_mass_proj_gas; aperture_rhalfmass_proj_gas=p.aperture_rhalfmass_proj_gas; #ifdef STARON aperture_SFR_proj_gas=p.aperture_SFR_proj_gas; aperture_Z_proj_gas=p.aperture_Z_proj_gas; aperture_mass_proj_gas_sf=p.aperture_mass_proj_gas_sf; aperture_mass_proj_gas_nsf=p.aperture_mass_proj_gas_nsf; aperture_rhalfmass_proj_gas_sf=p.aperture_rhalfmass_proj_gas_sf; aperture_rhalfmass_proj_gas_nsf=p.aperture_rhalfmass_proj_gas_nsf; aperture_Z_proj_gas_sf=p.aperture_Z_proj_gas_sf; aperture_Z_proj_gas_nsf=p.aperture_Z_proj_gas_nsf; #endif #endif #ifdef STARON aperture_mass_proj_star=p.aperture_mass_proj_star; aperture_rhalfmass_proj_star=p.aperture_rhalfmass_proj_star; aperture_Z_proj_star=p.aperture_Z_proj_star; #endif profile_npart=p.profile_npart; profile_mass=p.profile_mass; profile_npart_inclusive=p.profile_npart_inclusive; profile_mass_inclusive=p.profile_mass_inclusive; #ifdef GASON profile_npart_gas=p.profile_npart_gas; profile_mass_gas=p.profile_mass_gas; profile_npart_inclusive_gas=p.profile_npart_inclusive_gas; profile_mass_inclusive_gas=p.profile_mass_inclusive_gas; #ifdef STARON profile_npart_gas_sf=p.profile_npart_gas_sf; profile_mass_gas_sf=p.profile_mass_gas_sf; profile_npart_inclusive_gas_sf=p.profile_npart_inclusive_gas_sf; profile_mass_inclusive_gas_sf=p.profile_mass_inclusive_gas_sf; profile_npart_gas_nsf=p.profile_npart_gas_nsf; profile_mass_gas_nsf=p.profile_mass_gas_nsf; profile_npart_inclusive_gas_nsf=p.profile_npart_inclusive_gas_nsf; profile_mass_inclusive_gas_nsf=p.profile_mass_inclusive_gas_nsf; #endif #endif #ifdef STARON profile_npart_star=p.profile_npart_star; profile_mass_star=p.profile_mass_star; profile_npart_inclusive_star=p.profile_npart_inclusive_star; profile_mass_inclusive_star=p.profile_mass_inclusive_star; #endif return *this; } */ //allocate memory for profiles void Allocate(Options &opt) { AllocateApertures(opt); AllocateProfiles(opt); AllocateSOs(opt); } void AllocateApertures(Options &opt) { if (opt.iaperturecalc && opt.aperturenum>0) { aperture_npart.resize(opt.aperturenum); aperture_mass.resize(opt.aperturenum); aperture_veldisp.resize(opt.aperturenum); aperture_vrdisp.resize(opt.aperturenum); aperture_rhalfmass.resize(opt.aperturenum); #ifdef GASON aperture_npart_gas.resize(opt.aperturenum); aperture_mass_gas.resize(opt.aperturenum); aperture_veldisp_gas.resize(opt.aperturenum); aperture_vrdisp_gas.resize(opt.aperturenum); aperture_rhalfmass_gas.resize(opt.aperturenum); if (opt.gas_extraprop_aperture_calc) aperture_properties_gas.resize(opt.aperturenum); #ifdef STARON aperture_SFR_gas.resize(opt.aperturenum); aperture_Z_gas.resize(opt.aperturenum); aperture_npart_gas_sf.resize(opt.aperturenum); aperture_npart_gas_nsf.resize(opt.aperturenum); aperture_mass_gas_sf.resize(opt.aperturenum); aperture_mass_gas_nsf.resize(opt.aperturenum); aperture_veldisp_gas_sf.resize(opt.aperturenum); aperture_veldisp_gas_nsf.resize(opt.aperturenum); aperture_vrdisp_gas_sf.resize(opt.aperturenum); aperture_vrdisp_gas_nsf.resize(opt.aperturenum); aperture_rhalfmass_gas_sf.resize(opt.aperturenum); aperture_rhalfmass_gas_nsf.resize(opt.aperturenum); aperture_Z_gas_sf.resize(opt.aperturenum); aperture_Z_gas_nsf.resize(opt.aperturenum); if (opt.gas_extraprop_aperture_calc) aperture_properties_gas_sf.resize(opt.aperturenum); if (opt.gas_extraprop_aperture_calc) aperture_properties_gas_nsf.resize(opt.aperturenum); #endif #endif #ifdef STARON aperture_npart_star.resize(opt.aperturenum); aperture_mass_star.resize(opt.aperturenum); aperture_veldisp_star.resize(opt.aperturenum); aperture_vrdisp_star.resize(opt.aperturenum); aperture_rhalfmass_star.resize(opt.aperturenum); aperture_Z_star.resize(opt.aperturenum); if (opt.star_extraprop_aperture_calc) aperture_properties_star.resize(opt.aperturenum); #endif #ifdef BHON aperture_npart_bh.resize(opt.aperturenum); aperture_mass_bh.resize(opt.aperturenum); if (opt.bh_extraprop_aperture_calc) aperture_properties_bh.resize(opt.aperturenum); #endif #ifdef HIGHRES aperture_npart_interloper.resize(opt.aperturenum); aperture_mass_interloper.resize(opt.aperturenum); #endif #ifdef EXTRADMON if (opt.extra_dm_extraprop_aperture_calc) aperture_properties_extra_dm.resize(opt.aperturenum); #endif #if defined(GASON) || defined(STARON) || defined(BHON) //if searching all types, also store dm only aperture quantities if (opt.partsearchtype==PSTALL) { aperture_npart_dm.resize(opt.aperturenum); aperture_mass_dm.resize(opt.aperturenum); aperture_veldisp_dm.resize(opt.aperturenum); aperture_vrdisp_dm.resize(opt.aperturenum); aperture_rhalfmass_dm.resize(opt.aperturenum); } #endif for (auto &x:aperture_npart) x=0; for (auto &x:aperture_mass) x=-1; for (auto &x:aperture_veldisp) x=0; for (auto &x:aperture_rhalfmass) x=-1; #ifdef GASON for (auto &x:aperture_npart_gas) x=0; for (auto &x:aperture_mass_gas) x=-1; for (auto &x:aperture_veldisp_gas) x=0; for (auto &x:aperture_rhalfmass_gas) x=-1; #ifdef STARON for (auto &x:aperture_SFR_gas) x=0; for (auto &x:aperture_Z_gas) x=0; for (auto &x:aperture_npart_gas_sf) x=0; for (auto &x:aperture_mass_gas_sf) x=-1; for (auto &x:aperture_npart_gas_nsf) x=0; for (auto &x:aperture_mass_gas_nsf) x=-1; for (auto &x:aperture_veldisp_gas_sf) x=0; for (auto &x:aperture_veldisp_gas_nsf) x=0; for (auto &x:aperture_rhalfmass_gas_sf) x=-1; for (auto &x:aperture_rhalfmass_gas_nsf) x=-1; for (auto &x:aperture_Z_gas_sf) x=0; for (auto &x:aperture_Z_gas_nsf) x=0; #endif #endif #ifdef STARON for (auto &x:aperture_npart_star) x=0; for (auto &x:aperture_mass_star) x=-1; for (auto &x:aperture_veldisp_star) x=0; for (auto &x:aperture_rhalfmass_star) x=-1; for (auto &x:aperture_Z_star) x=0; #endif #ifdef HIGHRES for (auto &x:aperture_npart_interloper) x=0; for (auto &x:aperture_mass_interloper) x=-1; #endif #if defined(GASON) || defined(STARON) || defined(BHON) if (opt.partsearchtype==PSTALL) { for (auto &x:aperture_npart_dm) x=0; for (auto &x:aperture_mass_dm) x=-1; for (auto &x:aperture_veldisp_dm) x=0; for (auto &x:aperture_rhalfmass_dm) x=0; } #endif } if (opt.iaperturecalc && opt.apertureprojnum>0) { aperture_mass_proj.resize(opt.apertureprojnum); aperture_rhalfmass_proj.resize(opt.apertureprojnum); #ifdef GASON aperture_mass_proj_gas.resize(opt.apertureprojnum); aperture_rhalfmass_proj_gas.resize(opt.apertureprojnum); #ifdef STARON aperture_SFR_proj_gas.resize(opt.apertureprojnum); aperture_Z_proj_gas.resize(opt.apertureprojnum); aperture_mass_proj_gas_sf.resize(opt.apertureprojnum); aperture_mass_proj_gas_nsf.resize(opt.apertureprojnum); aperture_rhalfmass_proj_gas_sf.resize(opt.apertureprojnum); aperture_rhalfmass_proj_gas_nsf.resize(opt.apertureprojnum); aperture_Z_proj_gas_sf.resize(opt.apertureprojnum); aperture_Z_proj_gas_nsf.resize(opt.apertureprojnum); #endif #endif #ifdef STARON aperture_mass_proj_star.resize(opt.apertureprojnum); aperture_rhalfmass_proj_star.resize(opt.apertureprojnum); aperture_Z_proj_star.resize(opt.apertureprojnum); #endif #ifdef BHON aperture_mass_proj_bh.resize(opt.apertureprojnum); #endif #ifdef HIGHRES aperture_mass_proj_interloper.resize(opt.apertureprojnum); #endif for (auto &x:aperture_mass_proj) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj) x[0]=x[1]=x[2]=-1; #ifdef GASON for (auto &x:aperture_mass_proj_gas) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_gas) x[0]=x[1]=x[2]=-1; #ifdef STARON for (auto &x:aperture_SFR_proj_gas) x[0]=x[1]=x[2]=0; for (auto &x:aperture_Z_proj_gas) x[0]=x[1]=x[2]=0; for (auto &x:aperture_mass_proj_gas_sf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_gas_sf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_mass_proj_gas_nsf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_gas_nsf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_Z_proj_gas_sf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_Z_proj_gas_nsf) x[0]=x[1]=x[2]=-1; #endif #endif #ifdef STARON for (auto &x:aperture_mass_proj_star) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_star) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_Z_proj_star) x[0]=x[1]=x[2]=-1; #endif #ifdef BHON for (auto &x:aperture_mass_proj_bh) x[0]=x[1]=x[2]=-1; #endif #ifdef HIGHRES for (auto &x:aperture_mass_proj_interloper) x[0]=x[1]=x[2]=-1; #endif } } void AllocateProfiles(Options &opt) { if (opt.iprofilecalc && gNFOF>=opt.profileminFOFsize && num>=opt.profileminsize) { profile_npart.resize(opt.profilenbins); profile_mass.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart[i]=profile_mass[i]=0; #ifdef GASON profile_npart_gas.resize(opt.profilenbins); profile_mass_gas.resize(opt.profilenbins); #ifdef STARON profile_npart_gas_sf.resize(opt.profilenbins); profile_mass_gas_sf.resize(opt.profilenbins); profile_npart_gas_nsf.resize(opt.profilenbins); profile_mass_gas_nsf.resize(opt.profilenbins); #endif for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas[i]=profile_mass_gas[i]=0; #ifdef STARON for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0; #endif #endif #ifdef STARON profile_npart_star.resize(opt.profilenbins); profile_mass_star.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart_star[i]=profile_mass_star[i]=0; #endif if (opt.iInclusiveHalo>0) { profile_npart_inclusive.resize(opt.profilenbins); profile_mass_inclusive.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive[i]=profile_mass_inclusive[i]=0; #ifdef GASON profile_npart_inclusive_gas.resize(opt.profilenbins); profile_mass_inclusive_gas.resize(opt.profilenbins); #ifdef STARON profile_npart_inclusive_gas_sf.resize(opt.profilenbins); profile_mass_inclusive_gas_sf.resize(opt.profilenbins); profile_npart_inclusive_gas_nsf.resize(opt.profilenbins); profile_mass_inclusive_gas_nsf.resize(opt.profilenbins); #endif for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas[i]=profile_mass_inclusive_gas[i]=0; #ifdef STARON for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas_sf[i]=profile_mass_inclusive_gas_sf[i]=profile_npart_inclusive_gas_nsf[i]=profile_mass_inclusive_gas_nsf[i]=0; #endif #endif #ifdef STARON profile_npart_inclusive_star.resize(opt.profilenbins); profile_mass_inclusive_star.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_star[i]=profile_mass_inclusive_star[i]=0; #endif } } } void AllocateSOs(Options &opt) { if (opt.SOnum>0) { SO_mass.resize(opt.SOnum); SO_radius.resize(opt.SOnum); for (auto &x:SO_mass) x=0; for (auto &x:SO_radius) x=0; if (opt.iextrahalooutput) { SO_angularmomentum.resize(opt.SOnum); for (auto &x:SO_angularmomentum) {x[0]=x[1]=x[2]=0;} #ifdef GASON if (opt.iextragasoutput) { SO_mass_gas.resize(opt.SOnum); for (auto &x:SO_mass_gas) x=0; SO_angularmomentum_gas.resize(opt.SOnum); for (auto &x:SO_angularmomentum_gas) {x[0]=x[1]=x[2]=0;} #ifdef STARON #endif } #endif #ifdef STARON if (opt.iextrastaroutput) { SO_mass_star.resize(opt.SOnum); for (auto &x:SO_mass_star) x=0; SO_angularmomentum_star.resize(opt.SOnum); for (auto &x:SO_angularmomentum_star) {x[0]=x[1]=x[2]=0;} } #endif #ifdef HIGHRES if (opt.iextrainterloperoutput) { SO_mass_interloper.resize(opt.SOnum); for (auto &x:SO_mass_interloper) x=0; } #endif } } } void CopyProfileToInclusive(Options &opt) { for (auto i=0;i<opt.profilenbins;i++) { profile_npart_inclusive[i]=profile_npart[i]; profile_mass_inclusive[i]=profile_mass[i]; profile_npart[i]=profile_mass[i]=0; #ifdef GASON profile_npart_inclusive_gas[i]=profile_npart_gas[i]; profile_mass_inclusive_gas[i]=profile_mass_gas[i]; profile_npart_gas[i]=profile_mass_gas[i]=0; #ifdef STARON profile_npart_inclusive_gas_sf[i]=profile_npart_gas_sf[i]; profile_mass_inclusive_gas_sf[i]=profile_mass_gas_sf[i]; profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=0; profile_npart_inclusive_gas_nsf[i]=profile_npart_gas_nsf[i]; profile_mass_inclusive_gas_nsf[i]=profile_mass_gas_nsf[i]; profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0; #endif #endif #ifdef STARON profile_npart_inclusive_star[i]=profile_npart_star[i]; profile_mass_inclusive_star[i]=profile_mass_star[i]; profile_npart_star[i]=profile_mass_star[i]=0; #endif } } ///converts the properties data into comoving little h values ///so masses, positions have little h values and positions are comoving void ConverttoComove(Options &opt){ gcm=gcm*opt.h/opt.a; gposmbp=gposmbp*opt.h/opt.a; gposminpot=gposminpot*opt.h/opt.a; gmass*=opt.h; gMvir*=opt.h; gM200c*=opt.h; gM200m*=opt.h; gM500c*=opt.h; gMBN98*=opt.h; gMFOF*=opt.h; gsize*=opt.h/opt.a; gRmbp*=opt.h/opt.a; gRmaxvel*=opt.h/opt.a; gRvir*=opt.h/opt.a; gR200c*=opt.h/opt.a; gR200m*=opt.h/opt.a; gR500c*=opt.h/opt.a; gRBN98*=opt.h/opt.a; gRhalf200m*=opt.h/opt.a; gRhalf200c*=opt.h/opt.a; gRhalfBN98*=opt.h/opt.a; gMassTwiceRhalfmass*=opt.h; gRhalfmass*=opt.h/opt.a; gJ=gJ*opt.h*opt.h/opt.a; gJ200m=gJ200m*opt.h*opt.h/opt.a; gJ200c=gJ200c*opt.h*opt.h/opt.a; gJBN98=gJBN98*opt.h*opt.h/opt.a; RV_J=RV_J*opt.h*opt.h/opt.a; if (opt.iextrahalooutput) { gM200c_excl*=opt.h; gM200m_excl*=opt.h; gMBN98_excl*=opt.h; gR200c_excl*=opt.h/opt.a; gR200m_excl*=opt.h/opt.a; gRBN98_excl*=opt.h/opt.a; gJ200m_excl=gJ200m_excl*opt.h*opt.h/opt.a; gJ200c_excl=gJ200c_excl*opt.h*opt.h/opt.a; gJBN98_excl=gJBN98_excl*opt.h*opt.h/opt.a; } #ifdef GASON M_gas*=opt.h; M_gas_rvmax*=opt.h; M_gas_30kpc*=opt.h; M_gas_50kpc*=opt.h; M_gas_500c*=opt.h; cm_gas=cm_gas*opt.h/opt.a; L_gas=L_gas*opt.h*opt.h/opt.a; MassTwiceRhalfmass_gas*=opt.h; Rhalfmass_gas*=opt.h/opt.a; if (opt.iextragasoutput) { M_200mean_gas*=opt.h; M_200crit_gas*=opt.h; M_BN98_gas*=opt.h; M_200mean_excl_gas*=opt.h; M_200crit_excl_gas*=opt.h; M_BN98_excl_gas*=opt.h; L_200crit_gas=L_200crit_gas*opt.h*opt.h/opt.a; L_200mean_gas=L_200mean_gas*opt.h*opt.h/opt.a; L_BN98_gas=L_BN98_gas*opt.h*opt.h/opt.a; L_200crit_excl_gas=L_200crit_excl_gas*opt.h*opt.h/opt.a; L_200mean_excl_gas=L_200mean_excl_gas*opt.h*opt.h/opt.a; L_BN98_excl_gas=L_BN98_excl_gas*opt.h*opt.h/opt.a; } #ifdef STARON M_gas_sf*=opt.h; L_gas_sf*=opt.h*opt.h/opt.a; MassTwiceRhalfmass_gas_sf*=opt.h; Rhalfmass_gas_sf*=opt.h/opt.a; M_gas_nsf*=opt.h; L_gas_nsf*=opt.h*opt.h/opt.a; MassTwiceRhalfmass_gas_nsf*=opt.h; Rhalfmass_gas_nsf*=opt.h/opt.a; if (opt.iextragasoutput) { M_200mean_gas_sf*=opt.h; M_200crit_gas_sf*=opt.h; M_BN98_gas_sf*=opt.h; M_200mean_excl_gas_sf*=opt.h; M_200crit_excl_gas_sf*=opt.h; M_BN98_excl_gas_sf*=opt.h; L_200crit_gas_sf*=opt.h*opt.h/opt.a; L_200mean_gas_sf*=opt.h*opt.h/opt.a; L_BN98_gas_sf*=opt.h*opt.h/opt.a; L_200crit_excl_gas_sf*=opt.h*opt.h/opt.a; L_200mean_excl_gas_sf*=opt.h*opt.h/opt.a; L_BN98_excl_gas_sf*=opt.h*opt.h/opt.a; M_200mean_gas_nsf*=opt.h; M_200crit_gas_nsf*=opt.h; M_BN98_gas_nsf*=opt.h; M_200mean_excl_gas_nsf*=opt.h; M_200crit_excl_gas_nsf*=opt.h; M_BN98_excl_gas_nsf*=opt.h; L_200crit_gas_nsf*=opt.h*opt.h/opt.a; L_200mean_gas_nsf*=opt.h*opt.h/opt.a; L_BN98_gas_nsf*=opt.h*opt.h/opt.a; L_200crit_excl_gas_nsf*=opt.h*opt.h/opt.a; L_200mean_excl_gas_nsf*=opt.h*opt.h/opt.a; L_BN98_excl_gas_nsf*=opt.h*opt.h/opt.a; } #endif #endif #ifdef STARON M_star*=opt.h; M_star_rvmax*=opt.h; M_star_30kpc*=opt.h; M_star_50kpc*=opt.h; M_star_500c*=opt.h; cm_star=cm_star*opt.h/opt.a; MassTwiceRhalfmass_star*=opt.h/opt.a; Rhalfmass_star*=opt.h/opt.a; L_star=L_star*opt.h*opt.h/opt.a; #endif #ifdef BHON M_bh*=opt.h; #endif #ifdef HIGHRES M_interloper*=opt.h; #endif if (opt.iaperturecalc) { for (auto i=0;i<opt.iaperturecalc;i++) { aperture_mass[i]*=opt.h; #ifdef GASON aperture_mass_gas[i]*=opt.h; #ifdef STARON aperture_mass_gas_sf[i]*=opt.h; aperture_mass_gas_nsf[i]*=opt.h; #endif #endif #ifdef STARON aperture_mass_star[i]*=opt.h; #endif } } if (opt.SOnum>0) { for (auto i=0;i<opt.SOnum;i++) { SO_mass[i] *= opt.h; SO_radius[i] *= opt.h/opt.a; if (opt.iextrahalooutput) { SO_angularmomentum[i]*=(opt.h*opt.h/opt.a); #ifdef GASON SO_mass_gas[i] *= opt.h; SO_angularmomentum_gas[i]*=(opt.h*opt.h/opt.a); #ifdef STARON #endif #endif #ifdef STARON SO_mass_star[i] *= opt.h; SO_angularmomentum_star[i]*=(opt.h*opt.h/opt.a); #endif } } } } void ConvertProfilestoComove(Options &opt){ for (auto i=0;i<opt.profilenbins;i++) { profile_mass[i]*=opt.h; #ifdef GASON profile_mass_gas[i]*=opt.h; #ifdef STARON profile_mass_gas_sf[i]*=opt.h; profile_mass_gas_nsf[i]*=opt.h; #endif #endif #ifdef STARON profile_mass_star[i]*=opt.h; #endif } if (opt.iInclusiveHalo) { for (auto i=0;i<opt.profilenbins;i++) { profile_mass_inclusive[i]*=opt.h; #ifdef GASON profile_mass_inclusive_gas[i]*=opt.h; #ifdef STARON profile_mass_inclusive_gas_sf[i]*=opt.h; profile_mass_inclusive_gas_nsf[i]*=opt.h; #endif #endif #ifdef STARON profile_mass_inclusive_star[i]*=opt.h; #endif } } } void WriteBinary(fstream &Fout, Options &opt); void WriteAscii(fstream &Fout, Options &opt); ///write (append) the properties data to an already open ascii file #ifdef USEHDF ///write (append) the properties data to an already open hdf file //void WriteHDF(H5File &Fhdf, DataSpace *&dataspaces, DataSet *&datasets, Options&opt){}; #endif }; //for storing the units of known fields struct HeaderUnitInfo{ float massdim, lengthdim, velocitydim, timedim, energydim; string extrainfo; HeaderUnitInfo(float md = 0, float ld = 0, float vd = 0, float td = 0, string s = ""){ massdim = md; lengthdim = ld; velocitydim = vd; timedim = td; extrainfo = s; }; //Parse the string in the format massdim:lengthdim:velocitydim:timedim:energydim if only a string is passed //if format does not match this then just store string HeaderUnitInfo(string s); }; /*! Structures stores header info of the data writen by the \ref PropData data structure, specifically the \ref PropData::WriteBinary, \ref PropData::WriteAscii, \ref PropData::WriteHDF routines Must ensure that these routines are all altered together so that the io makes sense. */ struct PropDataHeader{ //list the header info vector<string> headerdatainfo; vector<HeaderUnitInfo> unitdatainfo; #ifdef USEHDF // vector<PredType> predtypeinfo; vector<hid_t> hdfpredtypeinfo; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospredtypeinfo; #endif PropDataHeader(Options&opt); }; /*! Structures stores profile info of the data writen by the \ref PropData profiles data structures, specifically the \ref PropData::WriteProfileBinary, \ref PropData::WriteProfileAscii, \ref PropData::WriteProfileHDF routines */ struct ProfileDataHeader{ //list the header info vector<string> headerdatainfo; #ifdef USEHDF vector<hid_t> hdfpredtypeinfo; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospredtypeinfo; #endif int numberscalarentries, numberarrayallgroupentries, numberarrayhaloentries; int offsetscalarentries, offsetarrayallgroupentries, offsetarrayhaloentries; ProfileDataHeader(Options&opt){ int sizeval; #ifdef USEHDF vector<hid_t> hdfdesiredproprealtype; if (sizeof(Double_t)==sizeof(double)) hdfdesiredproprealtype.push_back(H5T_NATIVE_DOUBLE); else hdfdesiredproprealtype.push_back(H5T_NATIVE_FLOAT); #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> desiredadiosproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double); else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real); #endif offsetscalarentries=0; headerdatainfo.push_back("ID"); #ifdef USEHDF hdfpredtypeinfo.push_back(H5T_NATIVE_ULONG); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif //if normalisation is phys then no need for writing normalisation block if (opt.iprofilenorm != PROFILERNORMPHYS) { headerdatainfo.push_back(opt.profileradnormstring); #ifdef USEHDF hdfpredtypeinfo.push_back(hdfdesiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } numberscalarentries=headerdatainfo.size(); offsetarrayallgroupentries=headerdatainfo.size(); headerdatainfo.push_back("Npart_profile"); #ifdef GASON headerdatainfo.push_back("Npart_profile_gas"); #ifdef STARON headerdatainfo.push_back("Npart_profile_gas_sf"); headerdatainfo.push_back("Npart_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Npart_profile_star"); #endif #ifdef USEHDF sizeval=hdfpredtypeinfo.size(); // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE); for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_UINT); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer); #endif headerdatainfo.push_back("Mass_profile"); #ifdef GASON headerdatainfo.push_back("Mass_profile_gas"); #ifdef STARON headerdatainfo.push_back("Mass_profile_gas_sf"); headerdatainfo.push_back("Mass_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Mass_profile_star"); #endif #ifdef USEHDF sizeval=hdfpredtypeinfo.size(); // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT); for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_FLOAT); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real); #endif numberarrayallgroupentries=headerdatainfo.size()-offsetarrayallgroupentries; //stuff for inclusive halo/SO profiles if (opt.iInclusiveHalo >0) { offsetarrayhaloentries=headerdatainfo.size(); headerdatainfo.push_back("Npart_inclusive_profile"); #ifdef GASON headerdatainfo.push_back("Npart_inclusive_profile_gas"); #ifdef STARON headerdatainfo.push_back("Npart_inclusive_profile_gas_sf"); headerdatainfo.push_back("Npart_inclusive_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Npart_inclusive_profile_star"); #endif #ifdef USEHDF sizeval=hdfpredtypeinfo.size(); // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE); for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_UINT); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer); #endif headerdatainfo.push_back("Mass_inclusive_profile"); #ifdef GASON headerdatainfo.push_back("Mass_inclusive_profile_gas"); #ifdef STARON headerdatainfo.push_back("Mass_inclusive_profile_gas_sf"); headerdatainfo.push_back("Mass_inclusive_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Mass_inclusive_profile_star"); #endif #ifdef USEHDF sizeval=hdfpredtypeinfo.size(); // for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT); for (int i=sizeval;i<headerdatainfo.size();i++) hdfpredtypeinfo.push_back(H5T_NATIVE_FLOAT); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real); #endif numberarrayhaloentries=headerdatainfo.size()-offsetarrayhaloentries; } } }; /*! Structure used to keep track of a structure's parent structure note that level could be sim->halo->subhalo->subsubhalo or even sim->wall/void/filament->halo->substructure->subsubstructure here sim is stype=0,gid=0, and the other structure types are to be defined. The data structure is meant to be traversed from - level 0 structures ("field" objects) - level 0 pointer to nextlevel - nextlevel containing nginlevel objects */ struct StrucLevelData { ///structure type and number in current level of hierarchy Int_t stype,nsinlevel; ///points to the the head pfof address of the group and parent Particle **Phead; Int_t **gidhead; ///parent pointers point to the address of the parents gidhead and Phead Particle **Pparenthead; Int_t **gidparenthead; ///add uber parent pointer (that is pointer to field halo) Int_t **giduberparenthead; ///allowing for multiple structure types at a given level in the hierarchy Int_t *stypeinlevel; StrucLevelData *nextlevel; StrucLevelData(Int_t numgroups=-1){ if (numgroups<=0) { Phead=NULL; Pparenthead=NULL; gidhead=NULL; gidparenthead=NULL; giduberparenthead=NULL; nextlevel=NULL; stypeinlevel=NULL; nsinlevel=0; } else Allocate(numgroups); } ///just allocate memory void Allocate(Int_t numgroups){ nsinlevel=numgroups; Phead=new Particle*[numgroups+1]; Pparenthead=new Particle*[numgroups+1]; gidhead=new Int_t*[numgroups+1]; gidparenthead=new Int_t*[numgroups+1]; giduberparenthead=new Int_t*[numgroups+1]; stypeinlevel=new Int_t[numgroups+1]; nextlevel=NULL; } ///initialize void Initialize(){ for (Int_t i=1;i<=nsinlevel;i++) {gidhead[i]=NULL;gidparenthead[i]=NULL;giduberparenthead[i]=NULL;} } ~StrucLevelData(){ if (nextlevel!=NULL) delete nextlevel; nextlevel=NULL; delete[] Phead; delete[] Pparenthead; delete[] gidhead; delete[] gidparenthead; delete[] giduberparenthead; delete[] stypeinlevel; } }; #if defined(USEHDF)||defined(USEADIOS) ///store the names of datasets in catalog output struct DataGroupNames { ///store names of catalog group files vector<string> prop; #ifdef USEHDF //store the data type // vector<PredType> propdatatype; vector<hid_t> hdfpropdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospropdatatype; #endif ///store names of catalog group files vector<string> group; #ifdef USEHDF // vector<PredType> groupdatatype; vector<hid_t> hdfgroupdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiosgroupdatatype; #endif ///store the names of catalog particle files vector<string> part; #ifdef USEHDF // vector<PredType> partdatatype; vector<hid_t> hdfpartdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospartdatatype; #endif ///store the names of catalog particle type files vector<string> types; #ifdef USEHDF // vector<PredType> typesdatatype; vector<hid_t> hdftypesdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiostypesdatatype; #endif ///store the names of hierarchy files vector<string> hierarchy; #ifdef USEHDF // vector<PredType> hierarchydatatype; vector<hid_t> hdfhierarchydatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adioshierarchydatatype; #endif ///store names of SO files vector<string> SO; #ifdef USEHDF // vector<PredType> SOdatatype; vector<hid_t> hdfSOdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> SOdatatype; #endif //store names of profile files vector<string> profile; #ifdef USEHDF //store the data type // vector<PredType> profiledatatype; vector<hid_t> hdfprofiledatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiosprofiledatatype; #endif DataGroupNames(){ #ifdef USEHDF vector<hid_t> hdfdesiredproprealtype; if (sizeof(Double_t)==sizeof(double)) hdfdesiredproprealtype.push_back(H5T_NATIVE_DOUBLE); else hdfdesiredproprealtype.push_back(H5T_NATIVE_FLOAT); #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> desiredadiosproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double); else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real); #endif prop.push_back("File_id"); prop.push_back("Num_of_files"); prop.push_back("Num_of_groups"); prop.push_back("Total_num_of_groups"); prop.push_back("Cosmological_Sim"); prop.push_back("Comoving_or_Physical"); prop.push_back("Period"); prop.push_back("Time"); prop.push_back("Length_unit_to_kpc"); prop.push_back("Velocity_to_kms"); prop.push_back("Mass_unit_to_solarmass"); #if defined(GASON) || defined(STARON) || defined(BHON) prop.push_back("Metallicity_unit_to_solar"); prop.push_back("SFR_unit_to_solarmassperyear"); prop.push_back("Stellar_age_unit_to_yr"); #endif #ifdef USEHDF hdfpropdatatype.push_back(H5T_NATIVE_INT); hdfpropdatatype.push_back(H5T_NATIVE_INT); hdfpropdatatype.push_back(H5T_NATIVE_ULONG); hdfpropdatatype.push_back(H5T_NATIVE_ULONG); hdfpropdatatype.push_back(H5T_NATIVE_UINT); hdfpropdatatype.push_back(H5T_NATIVE_UINT); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); #if defined(GASON) || defined(STARON) || defined(BHON) hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); hdfpropdatatype.push_back(hdfdesiredproprealtype[0]); #endif #endif #ifdef USEADIOS adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); #if defined(GASON) || defined(STARON) || defined(BHON) adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); #endif #endif group.push_back("File_id"); group.push_back("Num_of_files"); group.push_back("Num_of_groups"); group.push_back("Total_num_of_groups"); group.push_back("Group_Size"); group.push_back("Offset"); group.push_back("Offset_unbound"); #ifdef USEHDF hdfgroupdatatype.push_back(H5T_NATIVE_INT); hdfgroupdatatype.push_back(H5T_NATIVE_INT); hdfgroupdatatype.push_back(H5T_NATIVE_ULONG); hdfgroupdatatype.push_back(H5T_NATIVE_ULONG); hdfgroupdatatype.push_back(H5T_NATIVE_ULONG); hdfgroupdatatype.push_back(H5T_NATIVE_ULONG); hdfgroupdatatype.push_back(H5T_NATIVE_ULONG); #endif #ifdef USEADIOS adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif part.push_back("File_id"); part.push_back("Num_of_files"); part.push_back("Num_of_particles_in_groups"); part.push_back("Total_num_of_particles_in_all_groups"); part.push_back("Particle_IDs"); #ifdef USEHDF hdfpartdatatype.push_back(H5T_NATIVE_INT); hdfpartdatatype.push_back(H5T_NATIVE_INT); hdfpartdatatype.push_back(H5T_NATIVE_ULONG); hdfpartdatatype.push_back(H5T_NATIVE_ULONG); hdfpartdatatype.push_back(H5T_NATIVE_LONG); #endif #ifdef USEADIOS adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_long); #endif types.push_back("File_id"); types.push_back("Num_of_files"); types.push_back("Num_of_particles_in_groups"); types.push_back("Total_num_of_particles_in_all_groups"); types.push_back("Particle_types"); #ifdef USEHDF hdftypesdatatype.push_back(H5T_NATIVE_INT); hdftypesdatatype.push_back(H5T_NATIVE_INT); hdftypesdatatype.push_back(H5T_NATIVE_ULONG); hdftypesdatatype.push_back(H5T_NATIVE_ULONG); hdftypesdatatype.push_back(H5T_NATIVE_USHORT); #endif #ifdef USEADIOS adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_short); #endif hierarchy.push_back("File_id"); hierarchy.push_back("Num_of_files"); hierarchy.push_back("Num_of_groups"); hierarchy.push_back("Total_num_of_groups"); hierarchy.push_back("Number_of_substructures_in_halo"); hierarchy.push_back("Parent_halo_ID"); #ifdef USEHDF hdfhierarchydatatype.push_back(H5T_NATIVE_INT); hdfhierarchydatatype.push_back(H5T_NATIVE_INT); hdfhierarchydatatype.push_back(H5T_NATIVE_ULONG); hdfhierarchydatatype.push_back(H5T_NATIVE_ULONG); hdfhierarchydatatype.push_back(H5T_NATIVE_UINT); hdfhierarchydatatype.push_back(H5T_NATIVE_LONG); #endif #ifdef USEADIOS adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif SO.push_back("File_id"); SO.push_back("Num_of_files"); SO.push_back("Num_of_SO_regions"); SO.push_back("Total_num_of_SO_regions"); SO.push_back("Num_of_particles_in_SO_regions"); SO.push_back("Total_num_of_particles_in_SO_regions"); SO.push_back("SO_size"); SO.push_back("Offset"); SO.push_back("Particle_IDs"); #if defined(GASON) || defined(STARON) || defined(BHON) SO.push_back("Particle_types"); #endif #ifdef USEHDF hdfSOdatatype.push_back(H5T_NATIVE_INT); hdfSOdatatype.push_back(H5T_NATIVE_INT); hdfSOdatatype.push_back(H5T_NATIVE_ULONG); hdfSOdatatype.push_back(H5T_NATIVE_ULONG); hdfSOdatatype.push_back(H5T_NATIVE_ULONG); hdfSOdatatype.push_back(H5T_NATIVE_ULONG); hdfSOdatatype.push_back(H5T_NATIVE_UINT); hdfSOdatatype.push_back(H5T_NATIVE_ULONG); hdfSOdatatype.push_back(H5T_NATIVE_LONG); #if defined(GASON) || defined(STARON) || defined(BHON) hdfSOdatatype.push_back(H5T_NATIVE_INT); #endif #endif #ifdef USEADIOS adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_long); #if defined(GASON) || defined(STARON) || defined(BHON) adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); #endif #endif profile.push_back("File_id"); profile.push_back("Num_of_files"); profile.push_back("Num_of_groups"); profile.push_back("Total_num_of_groups"); profile.push_back("Num_of_halos"); profile.push_back("Total_num_of_halos"); profile.push_back("Radial_norm"); profile.push_back("Inclusive_profiles_flag"); profile.push_back("Num_of_bin_edges"); profile.push_back("Radial_bin_edges"); #ifdef USEHDF hdfprofiledatatype.push_back(H5T_NATIVE_INT); hdfprofiledatatype.push_back(H5T_NATIVE_INT); hdfprofiledatatype.push_back(H5T_NATIVE_ULONG); hdfprofiledatatype.push_back(H5T_NATIVE_ULONG); hdfprofiledatatype.push_back(H5T_NATIVE_ULONG); hdfprofiledatatype.push_back(H5T_NATIVE_ULONG); hdfprofiledatatype.push_back(H5T_C_S1); hdfprofiledatatype.push_back(H5T_NATIVE_INT); hdfprofiledatatype.push_back(H5T_NATIVE_INT); hdfprofiledatatype.push_back(hdfdesiredproprealtype[0]); #endif #ifdef USEADIOS adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_string); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(desiredadiosproprealtype[0]); #endif } }; #endif ///Useful structore to store information of leaf nodes in the tree struct leaf_node_info{ int num, numtot; Int_t id, istart, iend; Coordinate cm; Double_t size; #ifdef USEMPI Double_t searchdist; #endif }; ///if using MPI API #ifdef USEMPI #include <mpi.h> ///Includes external global variables used for MPI version of code #include "mpivar.h" #endif extern StrucLevelData *psldata; #endif
{ "alphanum_fraction": 0.7077574072, "avg_line_length": 37.259399684, "ext": "h", "hexsha": "4399334b85ceeafea581c9c3d64107d52b19391c", "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": "deb674aedf0885ecfc82c0b6fe3b2ef45966907c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "EthTay/VELOCIraptor-STF", "max_forks_repo_path": "src/allvars.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "deb674aedf0885ecfc82c0b6fe3b2ef45966907c", "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": "EthTay/VELOCIraptor-STF", "max_issues_repo_path": "src/allvars.h", "max_line_length": 224, "max_stars_count": null, "max_stars_repo_head_hexsha": "deb674aedf0885ecfc82c0b6fe3b2ef45966907c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "EthTay/VELOCIraptor-STF", "max_stars_repo_path": "src/allvars.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 31644, "size": 117926 }
/* LODO library: laser-stabilized odometry Copyright (C) 2004 Andrew Howard ahoward@usc.edu 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. */ /** @file lodo.h @brief The lodo library provides laser-stabilizied odometric pose estimates: the inputs are raw odometry and laser scans, the output is a corrected pose estimate. The drift in this corrected estimate is much lower than that seen with odometry alone. See, for example, the figure below: this plot shows the trajectory of a robot that has travelled 125m and executed 19 complete rotations before returning to the starting location. The final cumulative orientation error is less than 5 degrees (versus 110 degrees for pure odometry). @image html lodo_comparison.gif "Odometry versus laser-stabilized odometry" @par How it works The lodo library uses an incremental SLAM algorithm to correct drift in the robot's orientation. The algorithm has three key data structures: - The current laser scan (a list of range values). - The local map (a ring buffer containing recent laser scans). - The <i>polar error function</i> (a grid generated from the local map). The algorithm applied to each new laser scan is as follows: -# Generate the polar error function: - For each scan in the local map: - For each point on the polygonal boundary of the map scan: - Project point into the local coordinate frame of the new scan. - Convert to polar coordinates and mark the corresponding cell in the polar error function as "occupied". - For each cell in the polar error function, compute the distance to the nearest occupied cell with the same radial value. -# Find orientation correction: - For each possible correction: - Apply correction to each point in the new scan and convert into polar coordinates. - Look up error value in the polar error function. - Add to the todal error for this correction value. - Select correction value with the lowest total error. -# Build map: - If the new scan has a signficant number of "outlier" points (large error values), add this scan to the current map. The map is a ring buffer, so adding a new scan will necessarily lead to an old one being discarded. The intuition behind this algorithm is best explained in diagrams (below). Figure (a) shows a map scan in global carestian coordinates; the map scan is projected into the coordinate frame of the new scan and converted to polar coordinates (b); using dynamic programming, we compute the error function (c). This polar error function can be used to test possible orientation corrections very efficiently: changes in the orientation of the new scan correspond the translations of the polar error function. <table align="center"> <tr> <td> @image html lodo_map.gif "(a) Original map scan (cartesian coordinates)." <td> @image html lodo_map_polar.gif "(b) Map scan in local polar coordinates." <tr><td colspan=2> @image html lodo_map_pef.gif "(c) Calculated polar error function." </table> @par lodo_caveats The current version of the library takes about 15ms to process each scan on a 2.8 GHz P4, so expect it to use lots of cycles on your robot. There is still lots of optimization to do, however, so expect future releases to clock in around the 5ms mark. @todo Accuracy, reliability and performance */ #ifndef LODO_H #define LODO_H #include <gsl/gsl_min.h> #include "slap.h" #ifdef __cplusplus extern "C" { #endif /// Limits #define LODO_MAX_RANGES 1024 /// @brief Data pertaining to an individual scan typedef struct { /// Odometric pose (x, y, theta) pose2_t opose; /// Corrected pose (x, y, theta) pose2_t cpose; /// Range values double ranges[LODO_MAX_RANGES]; } lodo_scan_t; /// @brief Working data for a map point typedef struct { /// Local cartesian position vector3_t local; /// Local polar position vector3_t polar; } lodo_map_point_t; /// @brief Working data for scan point typedef struct { /// Range bin in PEF int ni; } lodo_scan_point_t; /// @brief Laser odometry module data typedef struct { /// Number of points in each scan int num_ranges; /// Maximum accepted range double range_max; /// Start angle for scans double range_start; /// Angular resolution of scans double range_step; /// Laser pose relative to robot pose2_t laser_pose; /// Maximum error value on a single point (m) double max_error; /// Number of bins in polar error function int pef_num_ranges, pef_num_bearings; /// Range bin starting value and resolution in polar error function. double pef_range_start, pef_range_step; /// Bearing bin starting value and resolution in polar error /// function. Note that the pef_bearing_step measures a distance, /// not an angle. double pef_bearing_start, pef_bearing_step; /// Polar error function (map) int pef_size; int *pef; /// Search interval for fitting (fitting will check interval /// [-fit_interval, +fit_interval] radians). double fit_interval; /// Error threshold for good fits (error must be less than this /// value for a good fit). double fit_err_thresh; /// Error value for outlier points (points with error values larger /// than this are labeled as outliers). double fit_outlier_dist; /// Outlier fraction threshold (used to decide when scans should be /// added to the map). double fit_outlier_frac; /// Cumulative odometric distance and rotation double odom_dist, odom_turn; /// Odometer interval for adding scans. double map_dist_interval, map_turn_interval; /// Odometer value of last scan in map double map_last_dist, map_last_turn; /// Map (ring buffer of scans) int map_scan_count, max_map_scans; lodo_scan_t *map_scans; /// Current scan int scan_count; lodo_scan_t scan; /// Working space for current scan (useful pre-computed values). lodo_scan_point_t scan_points[LODO_MAX_RANGES]; /// Working space for projected map points int num_map_points, max_map_points; lodo_map_point_t *map_points; /// Minimizer gsl_min_fminimizer *mini; /// Fit correction double fit_correct; /// True if last scan fitted int fit_valid; /// True if the last scan should be added to the map int fit_add; } lodo_t; /// @brief Allocate object /// @param num_ranges Number of range readings in each scan (should be 181). /// @param range_max Maximum useable range value (e.g., 8.00 or 16.00). /// @param range_res Resolution for comparing range values (i.e., range bin width). /// @param range_start Starting angle for range readings (should be -M_PI / 2). /// @param range_step Angular step size for each successive range reading /// (should be M_PI / 180). /// @returns Object handle. lodo_t *lodo_alloc(int num_ranges, double range_max, double range_res, double range_start, double range_step); /// @brief Free object void lodo_free(lodo_t *self); /// @brief Add a scan, compute correction, update map /// @param self Object handle. /// @param odom_pose Raw odometric pose of the robot. /// @param num_ranges Number of range readings. /// @param ranges Array of laser range readings. /// @returns Returns the corrected robot pose. pose2_t lodo_add_scan(lodo_t *self, pose2_t odom_pose, int num_ranges, double *ranges); /// @brief Project map points into scan polar coordinates /// @internal void lodo_project_map(lodo_t *self); /// @brief Project map free space into the scan polar frame /// @internal void lodo_project_map_free(lodo_t *self, lodo_scan_t *scan_m, matrix33_t Pd, matrix33_t Pm); /// @brief Compute correction for a scan /// @internal double lodo_correct(lodo_t *self); /// @brief Test a scan offset /// @internal double lodo_test_offset(lodo_t *self, double offset, double *outliers); /// @brief Print projected map points void lodo_print_map(lodo_t *self); /// @brief Print a polar error functions for scan and map void lodo_print_pef(lodo_t *self); /// @brief Print error histograms void lodo_print_err(lodo_t *self); /// @brief Draw a scan void lodo_draw_scan(lodo_t *self, lodo_scan_t *scan); /// @brief Draw the current map (hits) void lodo_draw_map(lodo_t *self); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7364584502, "avg_line_length": 30.0235690236, "ext": "h", "hexsha": "21bd37474a8d2c9368b23530c0fe103fd62ede74", "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": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_path": "physicalrobots/player/utils/pmap/lodo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "parasol-ppl/PPL_utils", "max_issues_repo_path": "physicalrobots/player/utils/pmap/lodo.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "physicalrobots/player/utils/pmap/lodo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2181, "size": 8917 }
/* ode-initval/rk4.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Runge-Kutta 4, Classical */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "odeiv_util.h" typedef struct { double *k; double *y0; double *ytmp; } rk4_state_t; static void * rk4_alloc (size_t dim) { rk4_state_t *state = (rk4_state_t *) malloc (sizeof (rk4_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for rk4_state", GSL_ENOMEM); } state->k = (double *) malloc (dim * sizeof (double)); if (state->k == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for k", GSL_ENOMEM); } state->y0 = (double *) malloc (dim * sizeof (double)); if (state->y0 == 0) { free (state->k); free (state); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } state->ytmp = (double *) malloc (dim * sizeof (double)); if (state->ytmp == 0) { free (state->y0); free (state->k); free (state); GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM); } return state; } static int rk4_apply (void *vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * sys) { rk4_state_t *state = (rk4_state_t *) vstate; size_t i; int status = 0; double *const k = state->k; double *const y0 = state->y0; double *const ytmp = state->ytmp; /* Copy the starting value. We will write over * the y[] vector, using it for scratch and * then filling it with the final result. */ DBL_MEMCPY (y0, y, dim); if (dydt_in != NULL) { DBL_MEMCPY (k, dydt_in, dim); } else { int s = GSL_ODEIV_FN_EVAL (sys, t, y0, k); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) { y[i] = h / 6.0 * k[i]; /* use y[] to store delta_y */ ytmp[i] = y0[i] + 0.5 * h * k[i]; } /* k2 step */ { int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) { y[i] += h / 3.0 * k[i]; ytmp[i] = y0[i] + 0.5 * h * k[i]; } /* k3 step */ { int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) { y[i] += h / 3.0 * k[i]; ytmp[i] = y0[i] + h * k[i]; } /* k4 step, error estimate, and final sum */ { int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k); GSL_STATUS_UPDATE (&status, s); } for (i = 0; i < dim; i++) { y[i] += h / 6.0 * k[i]; yerr[i] = h * y[i]; y[i] += y0[i]; if (dydt_out != NULL) dydt_out[i] = k[i]; } return status; } static int rk4_reset (void *vstate, size_t dim) { rk4_state_t *state = (rk4_state_t *) vstate; DBL_ZERO_MEMSET (state->k, dim); DBL_ZERO_MEMSET (state->y0, dim); DBL_ZERO_MEMSET (state->ytmp, dim); return GSL_SUCCESS; } static unsigned int rk4_order (void *vstate) { rk4_state_t *state = (rk4_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 4; } static void rk4_free (void *vstate) { rk4_state_t *state = (rk4_state_t *) vstate; free (state->k); free (state->y0); free (state->ytmp); free (state); } static const gsl_odeiv_step_type rk4_type = { "rk4", /* name */ 1, /* can use dydt_in */ 0, /* gives exact dydt_out */ &rk4_alloc, &rk4_apply, &rk4_reset, &rk4_order, &rk4_free }; const gsl_odeiv_step_type *gsl_odeiv_step_rk4 = &rk4_type;
{ "alphanum_fraction": 0.5824514991, "avg_line_length": 21.8076923077, "ext": "c", "hexsha": "ae944e7a20e5650d14a69272dc74e3c4e66181aa", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_path": "gsl_subset/ode-initval/rk4.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_path": "gsl_subset/ode-initval/rk4.c", "max_line_length": 76, "max_stars_count": 30, "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_path": "gsl_subset/ode-initval/rk4.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "num_tokens": 1450, "size": 4536 }
///////////////// //example25.5.c ///////////////// #include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv.h> #include <math.h> typedef struct{ double *a; //y=a[0]x[0]+a[1]x[1]+...a[ka]y[ka]+b[0]u[0]+b[1]u[1]+...+b[kb]u[kb] // double *a; //y[t+1]=a[0]y[t]+a[1]y[t-1]+...a[ka]y[t-ka]+b[0]u[t]+b[1]u[t-1]+...+b[kb]u[t-kb] double *b; double *x; double *u; int k,kx,ku; double xmax; double umax; double y; int _dim; double *_y; double *_y_err; double *_dydt_in; double *_dydt_out; double _t; } CRANE; #define dim_crane 4 int cranefunc (double t, const double y[], double f[], void *params) { CRANE *c = (CRANE *)params; f[0] = y[1]; f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; f[2] = y[3]; f[3] = (c->F+c->T*sin(y[0]))/c->M; return GSL_SUCCESS; } //////////////// #define square(x) ((x)*(x)) CRANE crane; int initialize() { crane.kx=3; crane.ku=1; crane.k=crane.kx+ku; double *a=(double*)malloc(sizeof(double)*ka); double *b=&a[kx]; double *x=(double*)malloc(sizeof(double)*k+1); double *u=&x[kx]; crane.umax=20.0;//check// crane.Fmax=30;//check #ifdef CRANESUB // crane.Fmax=_crane_Fmax;//check// crane.Fmax=30;//check // crane.xmax=20.0;//check// crane.Fmax=30;//check if(_AP_umax>0) AP_u_max=crane.umax=_AP_umax; else AP_u_max=crane.umax; AP_u_min=-AP_u_max; rr=AP_r=_AP_r;//10 rr_kyoyou=_rr_kyoyou; C_MODE=11; #else crane.h=0.01; #endif crane._t=0; int i;for(i=0;i<crane._dim;i++) crane._dydt_in[i]=0; return(0); } #ifndef CRANESUB char *fn="crane2io.dat"; FILE *fp; #endif//#ifndef CRANESUB double plant(double uu) { //store previous x and u int i,kx_1=crane.kx-1; for(i=0;i<kx_1;i++) crane.x[i+1]=crane.x[i]; int ku_1=crane.ku-1; for(i=0;i<ku_1;i++) crane.u[i+1]=crane.u[i]; //store former output crane.x[0]=crane.y; //current input if(uu>crane.umax) crane.u[0]=crane.umax; else if(uu<-crane.umax) crane.u[0]=-crane.umax; // current output crane.y=0; for(i=0;i<crane.k;i++) crane.y+=crane.a[i]*crane.x[i]; crane._t++; #ifndef CRANESUB fprintf(fp,"%.7e %.7e %.7e %.7e", crane._t,crane.u[0],crane.x[0],crane.y);//crane.a,crane.da fprintf(fp,"\n"); #endif return(crane.x); // return(crane.X); } #ifndef CRANESUB int main() { //////////////////////////////////////////////////// /// method 1 /// /// input ddX /// /// output a,x,y,F /// //////////////////////////////////////////////////// // double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1; double t0=5; //stationary double t1=5.0+t0;//accelerate(speed up) double t2=2.0+t1;//free run double t3=5.0+t2;//decelerate(slow down) double t4=20+t3; //free run initialize(); int M=(t4/crane.h)+1; double *ddX=(double*)malloc(sizeof(double)*M); // double *F =(double*)malloc(sizeof(double)*M); double Vmax=1;//dX/dt=1[m/s] int n; double t; //////////////////////////////////////////////////// /// set ddX /// //////////////////////////////////////////////////// int n0 =t0/crane.h+0.5, n4=t4/crane.h+0.5; for(t=0;t<t4;t+=crane.h){ n=t/crane.h; if(t<=t0) ddX[n]=0; //zero else if(t<=t1) ddX[n]=Vmax/(t1-t0); //accelerate else if(t<=t2) ddX[n]=0; //free move else if(t<=t3) ddX[n]=-Vmax/(t3-t2);//decelerate else ddX[n]=0; //free move } //////////////////////////////////////////////////// /// Solve by the Runge Kutta Method of GSL /// //////////////////////////////////////////////////// fp=fopen(fn,"w"); fprintf(fp,"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\n",crane.h,n0,n4,crane.M,crane.m,crane.r,crane.C); // double dx0=0,dy0=0,da0=0; // for(n=0;n<n4;){ for(t=0;t<t4;t+=crane.h){ n=t/crane.h; plant(ddX[n]); } fclose(fp); fprintf(stdout,"Results are stored in '%s'.\n",fn); gsl_odeiv_step_free (crane._s); return 0; } #ifndef CRANESUB int main() { //////////////////////////////////////////////////// /// method 1 /// /// input ddX /// /// output a,x,y,F /// //////////////////////////////////////////////////// // double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1; double t0=5; //stationary double t1=5.0+t0;//accelerate(speed up) double t2=2.0+t1;//free run double t3=5.0+t2;//decelerate(slow down) double t4=20+t3; //free run initialize(); int M=(t4/crane.h)+1; double *ddX=(double*)malloc(sizeof(double)*M); // double *F =(double*)malloc(sizeof(double)*M); double Vmax=1;//dX/dt=1[m/s] int n; double t; //////////////////////////////////////////////////// /// set ddX /// //////////////////////////////////////////////////// int n0 =t0/crane.h+0.5, n4=t4/crane.h+0.5; for(t=0;t<t4;t+=crane.h){ n=t/crane.h; if(t<=t0) ddX[n]=0; //zero else if(t<=t1) ddX[n]=Vmax/(t1-t0); //accelerate else if(t<=t2) ddX[n]=0; //free move else if(t<=t3) ddX[n]=-Vmax/(t3-t2);//decelerate else ddX[n]=0; //free move } //////////////////////////////////////////////////// /// Solve by the Runge Kutta Method of GSL /// //////////////////////////////////////////////////// fp=fopen(fn,"w"); fprintf(fp,"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\n",crane.h,n0,n4,crane.M,crane.m,crane.r,crane.C); // double dx0=0,dy0=0,da0=0; // for(n=0;n<n4;){ for(t=0;t<t4;t+=crane.h){ n=t/crane.h; plant(ddX[n]); } fclose(fp); fprintf(stdout,"Results are stored in '%s'.\n",fn); gsl_odeiv_step_free (crane._s); return 0; } #endif //#ifndef SUB
{ "alphanum_fraction": 0.478868439, "avg_line_length": 28.6243902439, "ext": "c", "hexsha": "7c249549c414946aa8c96a53ab8088c7ebb042f7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": [ "CECILL-B" ], "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_path": "1021/mspc/linear2sub.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CECILL-B" ], "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_path": "1021/mspc/linear2sub.c", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": [ "CECILL-B" ], "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_path": "1021/mspc/linear2sub.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2112, "size": 5868 }
#ifndef OPT_H #define OPT_H #include <gsl/gsl_vector.h> void optimize_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, gsl_vector* opt_x); double f_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, const gsl_vector* opt_x); void df_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, const gsl_vector* opt_x, gsl_vector* g); bool is_feasible(const gsl_vector* x); void simplex_projection(const gsl_vector* x, gsl_vector* x_proj, double z=1.0); #endif // OPT_H
{ "alphanum_fraction": 0.7822736031, "avg_line_length": 39.9230769231, "ext": "h", "hexsha": "01897849382f8a9040b5a3ddae1a71323d78b0f1", "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": "780f9e6824804a273829bdb28baa888bcd8e2bc5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bit-jmm/cctr", "max_forks_repo_path": "baseline/ctr/opt.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "780f9e6824804a273829bdb28baa888bcd8e2bc5", "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": "bit-jmm/cctr", "max_issues_repo_path": "baseline/ctr/opt.h", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "780f9e6824804a273829bdb28baa888bcd8e2bc5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bit-jmm/cctr", "max_stars_repo_path": "baseline/ctr/opt.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 137, "size": 519 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C header for functions manipulating waveforms. * */ #ifndef _WAVEFORM_H #define _WAVEFORM_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" #include "struct.h" #include "EOBNRv2HMROM.h" #if defined(__cplusplus) extern "C" { #define complex _Complex #elif 0 } /* so that editors will match preceding brace */ #endif /* NOTE: uses the list of modes of EOBNRv2HMROM (listmode), to be extended when more waveform models are added */ /***************** Function estimating frequency corresponding to a given time to coalescence ****************/ /* Functions computing relations between chirp mass, eta, m1, m2*/ double Mchirpofm1m2( const double m1, /* Mass 1 */ const double m2); /* Mass 2 */ double etaofm1m2( const double m1, /* Mass 1 */ const double m2); /* Mass 2 */ double m1ofMchirpeta( const double Mchirp, /* Chirp mass */ const double eta); /* Symmetric mass ratio */ double m2ofMchirpeta( const double Mchirp, /* Chirp mass */ const double eta); /* Symmetric mass ratio */ /* Newtonian estimate of the relation Mf(deltat/M) (for the 22 mode) - gives the starting geometric frequency for a given mass ratio and a given geometric duration of the observations */ double NewtonianfoftGeom(const double q, const double t); /* t here is t/M */ /* Newtonian estimate of the relation f(deltat) (for the 22 mode) - gives the starting frequency in Hz for a given mass ratio and a given geometric duration of the observations */ double Newtonianfoft(const double m1, const double m2, const double t); /* t here is in years, m1-m2 in solar masses */ /* Newtonian estimate of the relation f(deltat) (for the 22 mode freq) - gives the starting geometric frequency for a given time to merger and chirp mass - output in Hz */ double Newtonianfoftchirp( const double mchirp, /* Chirp mass (solar masses) */ const double t); /* Time in years */ /* Newtonian estimate of the relation deltat(f) (for the 22 mode freq) - gives the time to merger from a starting frequency for a given chirp mass - output in years */ double Newtoniantoffchirp( const double mchirp, /* Chirp mass (solar masses) */ const double t); /* Freq in Hz */ /***************** Function estimating time to coalescence and min/max frequency ****************/ /* Functions reading from a list of modes the minimal and maximal frequencies */ double ListmodesCAmpPhaseFrequencySeries_maxf(ListmodesCAmpPhaseFrequencySeries* listhlm); double ListmodesCAmpPhaseFrequencySeries_minf(ListmodesCAmpPhaseFrequencySeries* listhlm); /* Function estimating initial time from Psi22, according to tf_SPA = -1/(2pi)dPsi/df */ double EstimateInitialTime(ListmodesCAmpPhaseFrequencySeries* listhlm, double fLow); /***************** Functions to manipulate ReImFrequencySeries structure ****************/ void ReImFrequencySeries_AddCAmpPhaseFrequencySeries( struct tagReImFrequencySeries* freqseriesReIm, /* Output Re/Im frequency series */ struct tagCAmpPhaseFrequencySeries* freqseriesCAmpPhase, /* Input CAmp/Phase frequency series, to be interpolated and added to the output */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobsmode); /* Starting frequency in case of limited duration of observations- assumed to have been scaled with the proper factor m/2 for this mode - set to 0 to ignore */ /* Function evaluating a ReImFrequencySeries by interpolating wach mode of a ListmodesCAmpPhaseFrequencySeries and summing them, given a set of frequencies */ void ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries( struct tagReImFrequencySeries* freqseriesReIm, /* Output Re/Im frequency series - already initialized */ struct tagListmodesCAmpPhaseFrequencySeries* listmodesCAmpPhase, /* Input CAmp/Phase frequency series, to be interpolated */ gsl_vector* freq, /* Input set of frequencies on which evaluating */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobs); /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */ /* Helper function to add a mode to hplus, hcross in Fourier domain * - copies the function XLALSimAddMode, which was done only for TD structures */ int FDAddMode( ReImFrequencySeries* hptilde, /* Output: frequency series for hplus */ ReImFrequencySeries* hctilde, /* Output: frequency series for hcross */ ReImFrequencySeries* hlmtilde, /* Input: frequency series for the mode hlm */ double theta, /* First angle for position in the sky of observer */ double phi, /* Second angle for position in the sky of observer */ int l, /* First mode number l */ int m, /* Second mode number m */ int sym); /* If 1, assume planar symmetry and add also mode l,-m. Do not if set to 0. */ /* Function evaluating the FD frequency series for hplus, hcross from the modes hlm */ int GeneratehphcFDReImFrequencySeries( ReImFrequencySeries** hptilde, /* Output: frequency series for hplus */ ReImFrequencySeries** hctilde, /* Output: frequency series for hcross */ ListmodesCAmpPhaseFrequencySeries* listhlm, /* Input: frequency series for the mode hlm */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobs, /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */ double deltaf, /* Frequency step */ int nbpt, /* Number of points of output - if 0, determined from deltaF and maximal frequency in input */ int nbmode, /* Number of modes to add */ double theta, /* First angle for position in the sky of observer */ double phi, /* Second angle for position in the sky of observer */ int sym); /* If 1, assume planar symmetry and add also mode l,-m. Do not if set to 0. */ /* Function evaluating the FD frequency series by summing mode contributions from each hlm */ int GenerateFDReImFrequencySeries( ReImFrequencySeries** freqseries, /* Output: frequency series */ ListmodesCAmpPhaseFrequencySeries* listhlm, /* Input: FD modes hlm in the form AmpReal/AmpIm/Phase */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobs, /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */ double deltaf, /* Frequency step */ int nbpt); /* Number of points of output - if 0, determined from deltaf and maximal frequency in input */ /* Function evaluating the FD frequency series for a single mode contribution (l,m) */ int GenerateFDReImFrequencySeriesSingleMode( ReImFrequencySeries** freqseries, /* Output: frequency series */ ListmodesCAmpPhaseFrequencySeries* listhlm, /* Input: FD modes hlm in the form AmpReal/AmpIm/Phase */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobs, /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */ double deltaf, /* Frequency step */ int nbpt, /* Number of points of output - if 0, determined from deltaf and maximal frequency in input */ int l, /* Mode index l */ int m); /* Mode index m */ /* Function to restrict a frequency series (typically output of a FFT) to a given frequency range */ int RestrictFDReImFrequencySeries( ReImFrequencySeries** freqseriesout, /* Output: truncated frequency series */ ReImFrequencySeries* freqseriesin, /* Input: frequency series */ double fLow, /* Minimal frequency */ double fHigh); /* Maximal frequency */ /* Function for getting a phase mod 2pi (between -pi and pi) */ double mod2pi(double phase); /* Function for getting a phase mod pi (between 0 and pi, e.g. polarization) */ double modpi(double phase); /* Function to unwrap the phase mod 2pi - acts directly on the gsl_vector representing the phase */ int UnwrapPhase( gsl_vector* phaseout, /* Output: unwrapped phase vector - already allocated */ gsl_vector* phasein); /* Input: phase vector */ /* Function to convert a time series from Re/Im form to Amp/Phase form - unwrapping the phase */ int ReImTimeSeries_ToAmpPhase( AmpPhaseTimeSeries** timeseriesout, /* Output: Amp/Phase time series */ ReImTimeSeries* timeseriesin); /* Input: Re/Im time series */ /* Function to convert a time series from Amp/Phase form to Re/Im form */ int AmpPhaseTimeSeries_ToReIm( ReImTimeSeries** timeseriesout, /* Output: Re/Im time series */ AmpPhaseTimeSeries* timeseriesin); /* Input: Amp/Phase time series */ /* Function to compute a linear resampling at high frequencies to enforce a maximal deltaf */ /* NOTE: Assumes input frequencies are logarithmic (except maybe first interval) to evaluate when to resample */ int SetMaxdeltafResampledFrequencies( gsl_vector** freqr, /* Output: resampled frequencies */ gsl_vector* freq, /* Input: original frequencies */ const double maxf, /* Input: maximal frequency - set to 0. to ignore */ const double deltaf); /* Input: maximal deltaf aimed for - 0.002Hz appropriate for LISA */ /* Function to compute a linear-in-time resampling at low frequencies to enforce a maximal deltat */ int SetMaxdeltatResampledFrequencies( gsl_vector** freqr, /* Output: resampled frequencies */ gsl_vector* freq, /* Input: original frequencies */ const double deltat, /* Input: maximal deltat aimed for - fraction of a year, 1/24 (half month) appropriate for 1e-4 interpolation errors */ const double mchirp, /* Input: chirp mass, used for approximate t-f correspondence */ const int m); /* Input: chirp mass, used for approximate t-f correspondence */ /* Function to resample a CAmp/Phase frequency series on the specified frequencies */ int CAmpPhaseFrequencySeries_Resample( CAmpPhaseFrequencySeries** freqseriesout, /* Output: CAmp/Phase freq series */ CAmpPhaseFrequencySeries* freqseriesin, /* Input: CAmp/Phase freq series */ gsl_vector* freqr); /* Input: freq vector to resample on */ /***************** Spin weighted spherical harmonics ****************/ /* Additional function reproducing XLALSpinWeightedSphericalHarmonic */ double complex SpinWeightedSphericalHarmonic(double theta, double phi, int s, int l, int m); /* Currently only supports s=-2, l=2,3,4,5 modes */ #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _WAVEFORM_H */
{ "alphanum_fraction": 0.6380847204, "avg_line_length": 62.4482758621, "ext": "h", "hexsha": "bd07a483f7deca91b139b32ce8c58af501b8d839", "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": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_path": "tools/waveform.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "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": "JohnGBaker/flare", "max_issues_repo_path": "tools/waveform.h", "max_line_length": 221, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_path": "tools/waveform.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": 2815, "size": 12677 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #pragma once #ifndef COMMON_H #define COMMON_H // Since we call cblas_dgemm in openmp for loop, // we call "extension" APIs for setting the number of threads. #ifdef USE_INTEL_MKL #include <mkl.h> #if INTEL_MKL_VERSION < 20170000 // Will throw an error at development time in non-standard settings PLEASE DONOT COMPILE SHARED LIBRARIES WITH OLDER MKL VERSIONS #endif #include <mkl_service.h> extern "C" void mkl_set_num_threads(int numThreads); #else #include <cblas.h> extern "C" void openblas_set_num_threads(int numThreads); #endif template<class FP> size_t computeNNZ(FP* arr, int limit) { size_t nnz = 0; #ifndef USE_INTEL_MKL #pragma omp parallel for reduction(+: nnz) #endif for(int i=0; i<limit; i++) nnz += (arr[i]!=0) ? 1 : 0; return nnz; } static int SYSDS_CURRENT_NUM_THREADS = -1; static void setNumThreadsForBLAS(int numThreads) { if (SYSDS_CURRENT_NUM_THREADS != numThreads) { #ifdef USE_OPEN_BLAS openblas_set_num_threads(numThreads); #else mkl_set_num_threads(numThreads); #endif SYSDS_CURRENT_NUM_THREADS = numThreads; } } #endif // COMMON_H
{ "alphanum_fraction": 0.7477713686, "avg_line_length": 30.2698412698, "ext": "h", "hexsha": "34f98017655cb56730cc24264ba412d49ac3c3ef", "lang": "C", "max_forks_count": 190, "max_forks_repo_forks_event_max_datetime": "2020-06-15T12:26:12.000Z", "max_forks_repo_forks_event_min_datetime": "2017-06-08T19:32:54.000Z", "max_forks_repo_head_hexsha": "5cc523971854cdf4f22e6199987a86e213fae4e2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ywcb00/systemds", "max_forks_repo_path": "src/main/cpp/common.h", "max_issues_count": 418, "max_issues_repo_head_hexsha": "5cc523971854cdf4f22e6199987a86e213fae4e2", "max_issues_repo_issues_event_max_datetime": "2020-06-25T12:15:54.000Z", "max_issues_repo_issues_event_min_datetime": "2017-06-08T16:27:44.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ywcb00/systemds", "max_issues_repo_path": "src/main/cpp/common.h", "max_line_length": 69, "max_stars_count": 372, "max_stars_repo_head_hexsha": "eca11c6fe9cff88df2e1960caf1b0cff9bf2b2b6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Shafaq-Siddiqi/systemml", "max_stars_repo_path": "src/main/cpp/common.h", "max_stars_repo_stars_event_max_datetime": "2020-06-24T05:45:00.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-09T01:02:53.000Z", "num_tokens": 493, "size": 1907 }
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "xform.h" #include "imgfeatures.h" #include "utils.h" //#include "cxcore.h" //#include <highgui.h> // Universal include for all versions of OpenCV #include <mrpt/otherlibs/do_opencv_includes.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> /************************* Local Function Prototypes *************************/ static __inline struct feature* get_match( struct feature*, int ); int get_matched_features( struct feature*, int, int, struct feature*** ); int calc_min_inliers( int, int, double, double ); struct feature** draw_ransac_sample( struct feature**, int, int, gsl_rng* ); void extract_corresp_pts( struct feature**, int, int, CvPoint2D64f**, CvPoint2D64f** ); int find_consensus( struct feature**, int, int, CvMat*, ransac_err_fn, double, struct feature*** ); static __inline void release_mem( CvPoint2D64f*, CvPoint2D64f*, struct feature** ); /********************** Functions prototyped in xform.h **********************/ /* Calculates a best-fit image transform from image feature correspondences using RANSAC. For more information refer to: Fischler, M. A. and Bolles, R. C. Random sample consensus: a paradigm for model fitting with applications to image analysis and automated cartography. <EM>Communications of the ACM, 24</EM>, 6 (1981), pp. 381--395. @param features an array of features; only features with a non-NULL match of type mtype are used in homography computation @param n number of features in feat @param mtype determines which of each feature's match fields to use for model computation; should be one of FEATURE_FWD_MATCH, FEATURE_BCK_MATCH, or FEATURE_MDL_MATCH; if this is FEATURE_MDL_MATCH, correspondences are assumed to be between a feature's img_pt field and its match's mdl_pt field, otherwise correspondences are assumed to be between the the feature's img_pt field and its match's img_pt field @param xform_fn pointer to the function used to compute the desired transformation from feature correspondences @param m minimum number of correspondences necessary to instantiate the model computed by xform_fn @param p_badxform desired probability that the final transformation returned by RANSAC is corrupted by outliers (i.e. the probability that no samples of all inliers were drawn) @param err_fn pointer to the function used to compute a measure of error between putative correspondences and a computed model @param err_tol correspondences within this distance of a computed model are considered as inliers @param inliers if not NULL, output as an array of pointers to the final set of inliers @param n_in if not NULL and \a inliers is not NULL, output as the final number of inliers @return Returns a transformation matrix computed using RANSAC or NULL on error or if an acceptable transform could not be computed. */ CvMat* ransac_xform( struct feature* features, int n, int mtype, ransac_xform_fn xform_fn, int m, double p_badxform, ransac_err_fn err_fn, double err_tol, struct feature*** inliers, int* n_in ) { struct feature** matched, ** sample, ** consensus, ** consensus_max = NULL; struct ransac_data* rdata; CvPoint2D64f* pts, * mpts; CvMat* M = NULL; gsl_rng* rng; double p, in_frac = RANSAC_INLIER_FRAC_EST; int i, nm, in, in_min, in_max = 0, k = 0; nm = get_matched_features( features, n, mtype, &matched ); if( nm < m ) { fprintf( stderr, "Warning: not enough matches to compute xform, %s" \ " line %d\n", __FILE__, __LINE__ ); goto end; } /* initialize random number generator */ rng = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( rng, time(NULL) ); in_min = calc_min_inliers( nm, m, RANSAC_PROB_BAD_SUPP, p_badxform ); p = pow( 1.0 - pow( in_frac, m ), k ); i = 0; while( p > p_badxform ) { sample = draw_ransac_sample( matched, nm, m, rng ); extract_corresp_pts( sample, m, mtype, &pts, &mpts ); M = xform_fn( pts, mpts, m ); if( ! M ) goto iteration_end; in = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus); if( in > in_max ) { if( consensus_max ) free( consensus_max ); consensus_max = consensus; in_max = in; in_frac = (double)in_max / nm; } else free( consensus ); cvReleaseMat( &M ); iteration_end: release_mem( pts, mpts, sample ); p = pow( 1.0 - pow( in_frac, m ), ++k ); } /* calculate final transform based on best consensus set */ if( in_max >= in_min ) { extract_corresp_pts( consensus_max, in_max, mtype, &pts, &mpts ); M = xform_fn( pts, mpts, in_max ); in = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus); cvReleaseMat( &M ); release_mem( pts, mpts, consensus_max ); extract_corresp_pts( consensus, in, mtype, &pts, &mpts ); M = xform_fn( pts, mpts, in ); if( inliers ) { *inliers = consensus; consensus = NULL; } if( n_in ) *n_in = in; release_mem( pts, mpts, consensus ); } else if( consensus_max ) { if( inliers ) *inliers = NULL; if( n_in ) *n_in = 0; free( consensus_max ); } gsl_rng_free( rng ); end: for( i = 0; i < nm; i++ ) { rdata = feat_ransac_data( matched[i] ); matched[i]->feature_data = rdata->orig_feat_data; free( rdata ); } free( matched ); return M; } /* Calculates a least-squares planar homography from point correspondeces. @param pts array of points @param mpts array of corresponding points; each pts[i], i=0..n-1, corresponds to mpts[i] @param n number of points in both pts and mpts; must be at least 4 @return Returns the 3 x 3 least-squares planar homography matrix that transforms points in pts to their corresponding points in mpts or NULL if fewer than 4 correspondences were provided */ CvMat* lsq_homog( CvPoint2D64f* pts, CvPoint2D64f* mpts, int n ) { CvMat* H, * A, * B, X; double x[9]; int i; if( n < 4 ) { fprintf( stderr, "Warning: too few points in lsq_homog(), %s line %d\n", __FILE__, __LINE__ ); return NULL; } /* set up matrices so we can unstack homography into X; AX = B */ A = cvCreateMat( 2*n, 8, CV_64FC1 ); B = cvCreateMat( 2*n, 1, CV_64FC1 ); X = cvMat( 8, 1, CV_64FC1, x ); H = cvCreateMat(3, 3, CV_64FC1); cvZero( A ); for( i = 0; i < n; i++ ) { cvmSet( A, i, 0, pts[i].x ); cvmSet( A, i+n, 3, pts[i].x ); cvmSet( A, i, 1, pts[i].y ); cvmSet( A, i+n, 4, pts[i].y ); cvmSet( A, i, 2, 1.0 ); cvmSet( A, i+n, 5, 1.0 ); cvmSet( A, i, 6, -pts[i].x * mpts[i].x ); cvmSet( A, i, 7, -pts[i].y * mpts[i].x ); cvmSet( A, i+n, 6, -pts[i].x * mpts[i].y ); cvmSet( A, i+n, 7, -pts[i].y * mpts[i].y ); cvmSet( B, i, 0, mpts[i].x ); cvmSet( B, i+n, 0, mpts[i].y ); } cvSolve( A, B, &X, CV_SVD ); x[8] = 1.0; X = cvMat( 3, 3, CV_64FC1, x ); cvConvert( &X, H ); cvReleaseMat( &A ); cvReleaseMat( &B ); return H; } /* Calculates the transfer error between a point and its correspondence for a given homography, i.e. for a point x, it's correspondence x', and homography H, computes d(x', Hx)^2. @param pt a point @param mpt pt's correspondence @param H a homography matrix @return Returns the transfer error between pt and mpt given H */ double homog_xfer_err( CvPoint2D64f pt, CvPoint2D64f mpt, CvMat* H ) { CvPoint2D64f xpt = persp_xform_pt( pt, H ); return sqrt( dist_sq_2D( xpt, mpt ) ); } /* Performs a perspective transformation on a single point. That is, for a point (x, y) and a 3 x 3 matrix T this function returns the point (u, v), where [x' y' w']^T = T * [x y 1]^T, and (u, v) = (x'/w', y'/w'). Note that affine transforms are a subset of perspective transforms. @param pt a 2D point @param T a perspective transformation matrix @return Returns the point (u, v) as above. */ CvPoint2D64f persp_xform_pt( CvPoint2D64f pt, CvMat* T ) { CvMat XY, UV; double xy[3] = { pt.x, pt.y, 1.0 }, uv[3] = { 0 }; CvPoint2D64f rslt; cvInitMatHeader( &XY, 3, 1, CV_64FC1, xy, CV_AUTOSTEP ); cvInitMatHeader( &UV, 3, 1, CV_64FC1, uv, CV_AUTOSTEP ); cvMatMul( T, &XY, &UV ); rslt = cvPoint2D64f( uv[0] / uv[2], uv[1] / uv[2] ); return rslt; } /************************ Local funciton definitions *************************/ /* Returns a feature's match according to a specified match type @param feat feature @param mtype match type, one of FEATURE_FWD_MATCH, FEATURE_BCK_MATCH, or FEATURE_MDL_MATCH @return Returns feat's match corresponding to mtype or NULL for bad mtype */ static __inline struct feature* get_match( struct feature* feat, int mtype ) { if( mtype == FEATURE_MDL_MATCH ) return feat->mdl_match; if( mtype == FEATURE_BCK_MATCH ) return feat->bck_match; if( mtype == FEATURE_FWD_MATCH ) return feat->fwd_match; return NULL; } /* Finds all features with a match of a specified type and stores pointers to them in an array. Additionally initializes each matched feature's feature_data field with a ransac_data structure. @param features array of features @param n number of features in features @param mtype match type, one of FEATURE_{FWD,BCK,MDL}_MATCH @param matched output as an array of pointers to features with a match of the specified type @return Returns the number of features output in matched. */ int get_matched_features( struct feature* features, int n, int mtype, struct feature*** matched ) { struct feature** _matched; struct ransac_data* rdata; int i, m = 0; _matched = calloc( n, sizeof( struct feature* ) ); for( i = 0; i < n; i++ ) if( get_match( features + i, mtype ) ) { rdata = malloc( sizeof( struct ransac_data ) ); memset( rdata, 0, sizeof( struct ransac_data ) ); rdata->orig_feat_data = features[i].feature_data; _matched[m] = features + i; _matched[m]->feature_data = rdata; m++; } *matched = _matched; return m; } /* Calculates the minimum number of inliers as a function of the number of putative correspondences. Based on equation (7) in Chum, O. and Matas, J. Matching with PROSAC -- Progressive Sample Consensus. In <EM>Conference on Computer Vision and Pattern Recognition (CVPR)</EM>, (2005), pp. 220--226. @param n number of putative correspondences @param m min number of correspondences to compute the model in question @param p_badsupp prob. that a bad model is supported by a correspondence @param p_badxform desired prob. that the final transformation returned is bad @return Returns the minimum number of inliers required to guarantee, based on p_badsupp, that the probability that the final transformation returned by RANSAC is less than p_badxform */ int calc_min_inliers( int n, int m, double p_badsupp, double p_badxform ) { double pi, sum; int i, j; for( j = m+1; j <= n; j++ ) { sum = 0; for( i = j; i <= n; i++ ) { pi = ( i - m ) * log( p_badsupp ) + ( n - i + m ) * log( 1.0 - p_badsupp ) + gsl_sf_lnchoose( n - m, i - m ); sum += exp( pi ); } if( sum < p_badxform ) break; } return j; } /* Draws a RANSAC sample from a set of features. @param features array of pointers to features from which to sample @param n number of features in features @param m size of the sample @param rng random number generator used to sample @return Returns an array of pointers to the sampled features; the sampled field of each sampled feature's ransac_data is set to 1 */ struct feature** draw_ransac_sample( struct feature** features, int n, int m, gsl_rng* rng ) { struct feature** sample, * feat; struct ransac_data* rdata; int i, x; for( i = 0; i < n; i++ ) { rdata = feat_ransac_data( features[i] ); rdata->sampled = 0; } sample = calloc( m, sizeof( struct feature* ) ); for( i = 0; i < m; i++ ) { do { x = gsl_rng_uniform_int( rng, n ); feat = features[x]; rdata = feat_ransac_data( feat ); } while( rdata->sampled ); sample[i] = feat; rdata->sampled = 1; } return sample; } /* Extrancs raw point correspondence locations from a set of features @param features array of features from which to extract points and match points; each of these is assumed to have a match of type mtype @param n number of features @param mtype match type; if FEATURE_MDL_MATCH correspondences are assumed to be between each feature's img_pt field and it's match's mdl_pt field, otherwise, correspondences are assumed to be between img_pt and img_pt @param pts output as an array of raw point locations from features @param mpts output as an array of raw point locations from features' matches */ void extract_corresp_pts( struct feature** features, int n, int mtype, CvPoint2D64f** pts, CvPoint2D64f** mpts ) { struct feature* match; CvPoint2D64f* _pts, * _mpts; int i; _pts = calloc( n, sizeof( CvPoint2D64f ) ); _mpts = calloc( n, sizeof( CvPoint2D64f ) ); if( mtype == FEATURE_MDL_MATCH ) for( i = 0; i < n; i++ ) { match = get_match( features[i], mtype ); if( ! match ) fatal_error( "feature does not have match of type %d, %s line %d", mtype, __FILE__, __LINE__ ); _pts[i] = features[i]->img_pt; _mpts[i] = match->mdl_pt; } else for( i = 0; i < n; i++ ) { match = get_match( features[i], mtype ); if( ! match ) fatal_error( "feature does not have match of type %d, %s line %d", mtype, __FILE__, __LINE__ ); _pts[i] = features[i]->img_pt; _mpts[i] = match->img_pt; } *pts = _pts; *mpts = _mpts; } /* For a given model and error function, finds a consensus from a set of feature correspondences. @param features set of pointers to features; every feature is assumed to have a match of type mtype @param n number of features in features @param mtype determines the match field of each feature against which to measure error; if this is FEATURE_MDL_MATCH, correspondences are assumed to be between the feature's img_pt field and the match's mdl_pt field; otherwise matches are assumed to be between img_pt and img_pt @param M model for which a consensus set is being found @param err_fn error function used to measure distance from M @param err_tol correspondences within this distance of M are added to the consensus set @param consensus output as an array of pointers to features in the consensus set @return Returns the number of points in the consensus set */ int find_consensus( struct feature** features, int n, int mtype, CvMat* M, ransac_err_fn err_fn, double err_tol, struct feature*** consensus ) { struct feature** _consensus; struct feature* match; CvPoint2D64f pt, mpt; double err; int i, in = 0; _consensus = calloc( n, sizeof( struct feature* ) ); if( mtype == FEATURE_MDL_MATCH ) for( i = 0; i < n; i++ ) { match = get_match( features[i], mtype ); if( ! match ) fatal_error( "feature does not have match of type %d, %s line %d", mtype, __FILE__, __LINE__ ); pt = features[i]->img_pt; mpt = match->mdl_pt; err = err_fn( pt, mpt, M ); if( err <= err_tol ) _consensus[in++] = features[i]; } else for( i = 0; i < n; i++ ) { match = get_match( features[i], mtype ); if( ! match ) fatal_error( "feature does not have match of type %d, %s line %d", mtype, __FILE__, __LINE__ ); pt = features[i]->img_pt; mpt = match->img_pt; err = err_fn( pt, mpt, M ); if( err <= err_tol ) _consensus[in++] = features[i]; } *consensus = _consensus; return in; } /* Releases memory and reduces code size above @param pts1 an array of points @param pts2 an array of points @param features an array of pointers to features; can be NULL */ static __inline void release_mem( CvPoint2D64f* pts1, CvPoint2D64f* pts2, struct feature** features ) { free( pts1 ); free( pts2 ); if( features ) free( features ); }
{ "alphanum_fraction": 0.6689858999, "avg_line_length": 29.105734767, "ext": "c", "hexsha": "a144d6b8b5439240aebe3db6da58f9bb9a859eb1", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2022-02-22T08:56:28.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-08T07:55:51.000Z", "max_forks_repo_head_hexsha": "451480f9815cc029ae427ed8067732606bcfbb43", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "amitsingh19975/mrpt", "max_forks_repo_path": "libs/vision/src/sift-hess/xform.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "451480f9815cc029ae427ed8067732606bcfbb43", "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": "amitsingh19975/mrpt", "max_issues_repo_path": "libs/vision/src/sift-hess/xform.c", "max_line_length": 83, "max_stars_count": 9, "max_stars_repo_head_hexsha": "451480f9815cc029ae427ed8067732606bcfbb43", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "amitsingh19975/mrpt", "max_stars_repo_path": "libs/vision/src/sift-hess/xform.c", "max_stars_repo_stars_event_max_datetime": "2020-07-16T02:13:43.000Z", "max_stars_repo_stars_event_min_datetime": "2017-11-19T16:18:09.000Z", "num_tokens": 4805, "size": 16241 }
#ifndef _COMMON_ #define _COMMON_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_roots.h> #include "params.h" //#include "dam_utils.h" #include "cosmo_mad.h" #define DTOR 0.01745329251 typedef struct { gsl_interp_accel *intacc; gsl_spline *spline; double x0,xf; double y0,yf; } SplPar; typedef struct { double om,ol,ob; double w0,wa,h0; double ns,s8; char **fname_window; char fname_bias[256]; char fname_sbias[256]; char fname_pk[256]; char prefix_out[256]; int lmax; Csm_params *cpar; double chi_horizon; double chi_LSS; double prefac_lensing; double dchi; int do_nc; int do_shear; int do_cmblens; int do_isw; int has_bg; int has_dens; int has_rsd; int has_lensing; SplPar *aofchi; SplPar *zofchi; SplPar *hofchi; SplPar *gfofchi; SplPar *fgofchi; SplPar **wind_0; SplPar **wind_M; SplPar **wind_L; SplPar *bias; SplPar *sbias; double *cl_dd; double *cl_d1l2; double *cl_d2l1; double *cl_dc; double *cl_di; double *cl_ll; double *cl_lc; double *cl_li; double *cl_cc; double *cl_ci; double *cl_ii; int do_w_theta; int do_w_theta_logbin; double th_min; double th_max; int n_th; int n_th_logint; double *wt_dd; double *wt_d1l2; double *wt_d2l1; double *wt_dc; double *wt_di; double *wt_ll_pp; double *wt_ll_mm; double *wt_lc; double *wt_li; double *wt_cc; double *wt_ci; double *wt_ii; } RunParams; //Defined in common.c void dam_report_error(int level,char *fmt,...); void *dam_malloc(size_t size); void *dam_calloc(size_t nmemb,size_t size); FILE *dam_fopen(const char *path,const char *mode); int dam_linecount(FILE *f); SplPar *spline_init(int n,double *x,double *y,double y0,double yf); double spline_eval(double x,SplPar *spl); void spline_free(SplPar *spl); RunParams *param_new(void); void param_free(RunParams *par); //Defined in cosmo.c RunParams *init_params(char *fname_ini); //Defined in transfers.c double transfer_wrap(int l,double k,RunParams *par,char *trtype,int ibin); //Defined in spectra.c void compute_spectra(RunParams *par); void compute_w_theta(RunParams *par); //Defined in io.c int read_parameter_file(char *fname,RunParams *par); void write_output(RunParams *par); #endif //_COMMON_
{ "alphanum_fraction": 0.7158211522, "avg_line_length": 20.4035087719, "ext": "h", "hexsha": "405a29ad7fff5f172fbea368d9499f6f41d333eb", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "benchmarks/data/codes/cl_corr_bm/src/common.h", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "benchmarks/data/codes/cl_corr_bm/src/common.h", "max_line_length": 74, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "benchmarks/data/codes/cl_corr_bm/src/common.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 749, "size": 2326 }
// Authors: David Blei (blei@cs.princeton.edu) // Sean Gerrish (sgerrish@cs.princeton.edu) // // Copyright 2011 Sean Gerrish and David Blei // All Rights Reserved. // // See the README for this package for details about modifying or // distributing this software. #include "lda-seq.h" #include "gflags.h" #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector_double.h> extern int LDA_INFERENCE_MAX_ITER; static double* scaled_influence = NULL; // const int TIME = 61; const int TIME = -3; const double PI = 3.141592654; DEFINE_int32(lda_sequence_max_iter, 20, "The maximum number of iterations."); DEFINE_int32(lda_sequence_min_iter, 1, "The maximum number of iterations."); DEFINE_int32(forward_window, 1, "The forward window for deltas. " "If negative, we use a beta with mean " "5."); DEFINE_string(normalize_docs, "normalize", "Describes how documents's wordcounts " "are considered for finding influence. " "Options are \"normalize\", \"none\", " "\"occurrence\", \"log\", or \"log_norm\"."); DEFINE_int32(save_time, 1e20, "Save a specific time. If -1, save all times."); DEFINE_int32(fix_topics, 0, "Fix a set of this many topics. This amounts " "to fixing these topics' variance at 1e-10."); DECLARE_string(model); DECLARE_int32(max_number_time_points); DECLARE_double(sigma_d); DECLARE_double(sigma_l); DECLARE_double(sigma_c); DECLARE_double(sigma_cv); /* * populate an LDA model at a particular time point * */ inf_var* inf_var_alloc(int number_topics, corpus_seq_t* corpus_seq) { // Hate to do this, but I had trouble using it before. This should // be the first place we use it; otherwise we'll get a sigsev nil. if (scaled_influence == NULL) { scaled_influence = NewScaledInfluence(FLAGS_max_number_time_points); } inf_var* inf_var_ptr = (inf_var*) malloc(sizeof(inf_var)); inf_var_ptr->doc_weights = (gsl_matrix**) malloc(sizeof(gsl_matrix*) * corpus_seq->len); inf_var_ptr->renormalized_doc_weights = (gsl_matrix**) malloc( sizeof(gsl_matrix*) * corpus_seq->len); inf_var_ptr->ntime = corpus_seq->len; int i=0; for (i=0; i < corpus_seq->len; ++i) { corpus_t* corpus = corpus_seq->corpus[i]; outlog("creating matrix. %d %d", corpus->ndocs, number_topics); if (corpus->ndocs == 0) { inf_var_ptr->doc_weights[i] = (gsl_matrix*) malloc(sizeof(gsl_matrix)); inf_var_ptr->doc_weights[i]->size1 = 0; inf_var_ptr->doc_weights[i]->size2 = number_topics; inf_var_ptr->renormalized_doc_weights[i] = (gsl_matrix*) malloc(sizeof(gsl_matrix)); inf_var_ptr->renormalized_doc_weights[i]->size1 = 0; inf_var_ptr->renormalized_doc_weights[i]->size2 = number_topics; } else { inf_var_ptr->doc_weights[i] = gsl_matrix_calloc(corpus->ndocs, number_topics); inf_var_ptr->renormalized_doc_weights[i] = gsl_matrix_calloc(corpus->ndocs, number_topics); } } return inf_var_ptr; } void inf_var_free(inf_var* ptr) { // TODO. } // Solves the linear system Ax = b for x. // Assumes that x is already allocated. void Solve(gsl_matrix* A, const gsl_vector* b, gsl_vector* x) { int permutation_sign; gsl_permutation* permutation = gsl_permutation_alloc(b->size); gsl_linalg_LU_decomp(A, permutation, &permutation_sign); gsl_linalg_LU_solve(A, permutation, b, x); gsl_permutation_free(permutation); } // Find the sums of influence of all documents in advance. // g has scores for everything *up to but not including* g. void InfluenceTotalFixed(lda_seq* seq, const corpus_seq_t* data) { gsl_vector* exp_tmp = gsl_vector_alloc(seq->nterms); for (int k=0; k < seq->ntopics; ++k) { for (int s=0; s < seq->nseq; ++s) { // Pull out elements of g, and make sure to set them to 0! gsl_vector_view g = gsl_matrix_column( seq->influence_sum_lgl[k], s); gsl_vector_set_zero(&g.vector); for (int t=0; t <= s; ++t) { gsl_vector_view w_phi_l = gsl_matrix_column(seq->topic[k]->w_phi_l, t); gsl_vector_memcpy(exp_tmp, &w_phi_l.vector); gsl_vector_scale(exp_tmp, scaled_influence[s - t]); gsl_vector_add(&g.vector, exp_tmp); } } } gsl_vector_free(exp_tmp); } void DumpTimeDocTopicStats(const char* root, size_t t, corpus_t* corpus, gsl_matrix** phi) { // For all documents, dump the top topics. char name[400]; // Dump the top topics for each word. sprintf(name, "%s%ld_doc_term_topics.dat", root, t); FILE* f = fopen(name, "w"); for (unsigned int d=0; d < corpus->ndocs; ++d) { gsl_matrix* phi_d = phi[d]; doc_t* doc = corpus->doc[d]; for (unsigned int n=0; n < doc->nterms; ++n) { unsigned int w = doc->word[n]; // First, find the max topic weight. unsigned int max_topic_index = 0; double max_topic_weight = gsl_matrix_get(phi_d, n, 0); for (unsigned int k=0; k < phi_d->size2; ++k) { double phi_d_n_k = gsl_matrix_get(phi_d, n, k); if (phi_d_n_k > max_topic_weight) { max_topic_weight = phi_d_n_k; max_topic_index = k; } } fprintf(f, "%d:%d:%.3f", w, max_topic_index, max_topic_weight); if (n < doc->nterms - 1) { fprintf(f, " "); } } fprintf(f, "\n"); } fclose(f); } void PrepareRegressionComponents( corpus_t* corpus, lda_seq* seq, unsigned int k, gsl_matrix* W_phi, gsl_matrix* W_phi_var, gsl_vector* d_phi_var_tmp, gsl_vector* response, gsl_vector* d_tmp, gsl_matrix* dd_tmp, gsl_vector* document_weights, gsl_matrix* W_phi_tmp, gsl_vector* exp_h_tmp) { // Then left-multiply this by W_phi: gsl_blas_dgemv(CblasTrans, 1.0, W_phi, response, 0.0, d_tmp); // Set up the transformation matrix. // First, set up W_phi^T \Lambda W_phi. gsl_matrix_memcpy(W_phi_tmp, W_phi); for (unsigned int d=0; d < corpus->ndocs; ++d) { gsl_vector_view col = gsl_matrix_column(W_phi_tmp, d); gsl_vector_mul(&col.vector, exp_h_tmp); } // Yuck. Maybe we should do this sparsely? // Probably won't be too bad, at least for now. gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, W_phi_tmp, W_phi, 0.0, dd_tmp); gsl_blas_dgemv(CblasTrans, 1.0, W_phi_var, exp_h_tmp, 0.0, d_phi_var_tmp); // Next, add elements to the diagonal of dd_tmp. for (unsigned int d=0; d < corpus->ndocs; ++d) { double value = gsl_matrix_get(dd_tmp, d, d); value += (seq->topic[k]->chain_variance / (FLAGS_sigma_d * FLAGS_sigma_d)); // sgerrish: Is this supposed to be multiplied by anything? value += gsl_vector_get(d_phi_var_tmp, d); gsl_matrix_set(dd_tmp, d, d, value); } } void SetExpHTmp(lda_seq* seq, const corpus_seq_t* data, unsigned int t, unsigned int k, unsigned int n, gsl_vector* exp_h_tmp, gsl_vector* zw_tmp, gsl_vector** exp_i_tmp) { gsl_vector_set_zero(exp_h_tmp); for (int i = t; i < seq->nseq; ++i) { gsl_vector_view mean_i_current = gsl_matrix_column(seq->topic[k]->e_log_prob, i); gsl_vector_view var_i_current = gsl_matrix_column(seq->topic[k]->variance, i + 1); // Set up exp_h_tmp. gsl_vector_memcpy(zw_tmp, &var_i_current.vector); gsl_vector_sub(zw_tmp, &mean_i_current.vector); gsl_vector_scale(zw_tmp, 2.0); for (n=0; n < data->nterms; ++n) { gsl_vector_set(zw_tmp, n, exp(gsl_vector_get(zw_tmp, n))); } gsl_vector_scale(zw_tmp, scaled_influence[i - t] * scaled_influence[i - t]); gsl_vector_add(exp_h_tmp, zw_tmp); // Set up exp_i_tmp. gsl_vector_memcpy(exp_i_tmp[i], &var_i_current.vector); gsl_vector_scale(exp_i_tmp[i], 0.5); gsl_vector_sub(exp_i_tmp[i], &mean_i_current.vector); for (n=0; n < data->nterms; ++n) { gsl_vector_set(exp_i_tmp[i], n, exp(gsl_vector_get(exp_i_tmp[i], n))); } } } double update_inf_var_fixed(lda_seq* seq, const corpus_seq_t* data, gsl_matrix** phi, size_t t, const char* root, int dump_doc_stats) { double lhood = 0.0; // Note that we're missing a suspicious factor of -2 on the document // weights currently. We won't worry about that for now (since // we're still experimenting), but it should soon be fixed. corpus_t* corpus = data->corpus[t]; if (!corpus->ndocs) { return lhood; } inf_var* influence = seq->influence; if (t != TIME && 0) { return lhood; } // We need access to the following: gsl_matrix* documents_topics_t = influence->doc_weights[t]; gsl_matrix* renormalized_documents_topics_t = influence->renormalized_doc_weights[t]; size_t k; gsl_matrix* W_phi = gsl_matrix_calloc( seq->nterms, corpus->ndocs); gsl_matrix* W2_phi2 = gsl_matrix_calloc( seq->nterms, corpus->ndocs); gsl_matrix* W_phi_var = gsl_matrix_calloc(seq->nterms, corpus->ndocs); gsl_matrix* W_phi_tmp = gsl_matrix_alloc( seq->nterms, corpus->ndocs); gsl_matrix* dd_tmp = gsl_matrix_alloc( corpus->ndocs, corpus->ndocs); gsl_vector* xd_tmp = gsl_vector_calloc( corpus->ndocs); gsl_vector* yw_tmp = gsl_vector_calloc( seq->nterms); gsl_vector* zw_tmp = gsl_vector_calloc( seq->nterms); gsl_vector* terms_inc_tmp = gsl_vector_calloc( seq->nterms); gsl_vector** exp_i_tmp = new gsl_vector*[seq->nseq]; for (int i=0; i < seq->nseq; ++i) { exp_i_tmp[i] = gsl_vector_calloc(seq->nterms); } int n; gsl_vector* response = gsl_vector_calloc(seq->nterms); gsl_vector* exp_h_tmp = gsl_vector_calloc(seq->nterms); gsl_vector* d_tmp = gsl_vector_calloc(corpus->ndocs); gsl_vector* d_phi_var_tmp = gsl_vector_calloc(corpus->ndocs); // assert(post->phi->size2 == documents_topics_t->size2); double* total_terms = (double*) malloc(sizeof(double) * corpus->ndocs); double* renormalization_totals = (double*) malloc(sizeof(double) * corpus->ndocs); for (k=0; k < documents_topics_t->size2; ++k) { // Set up W_phi and W_phi_var. for (int d=0; d < corpus->ndocs; ++d) { doc_t* doc = corpus->doc[d]; total_terms[d] = 0.0; renormalization_totals[d] = 0.0; double log_norm_sum = 0.0; for (n=0; n < doc->nterms; ++n) { total_terms[d] += doc->count[n]; if (FLAGS_normalize_docs == "normalize") { renormalization_totals[d] = 1.0; } else if (FLAGS_normalize_docs == "log") { renormalization_totals[d] += log(doc->count[n] + 1); } else if (FLAGS_normalize_docs == "log_norm") { double weight = log(doc->count[n] / doc->total); renormalization_totals[d] += weight; } else if (FLAGS_normalize_docs == "identity") { renormalization_totals[d] += doc->count[n]; } else if (FLAGS_normalize_docs == "occurrence") { renormalization_totals[d] = 1.0; } } assert(doc->total == total_terms[d]); for (n=0; n < doc->nterms; ++n) { // Phi, for the doc's term n and topic k. double phi_d_n_k = gsl_matrix_get(phi[d], n, k); // This cast should happen automatically because total_terms is a double, // but we make the cast here to be explicit and to avoid bugs later. double number_terms; if (FLAGS_normalize_docs == "normalize") { number_terms = ((double) doc->count[n] / (double) total_terms[d]); } else if (FLAGS_normalize_docs == "log") { number_terms = log(doc->count[n] + 1.0); } else if (FLAGS_normalize_docs == "log_norm") { number_terms = log(doc->count[n] / total_terms[d]); renormalization_totals[d] += log(doc->count[n] / total_terms[d]); } else if (FLAGS_normalize_docs == "identity") { number_terms = doc->count[n]; } else if (FLAGS_normalize_docs == "occurrence") { number_terms = ((double) doc->count[n] / (double) total_terms[d]); assert(doc->count[n] == 1); } else { assert(0); } gsl_matrix_set(W_phi, doc->word[n], d, number_terms * phi_d_n_k); gsl_matrix_set(W2_phi2, doc->word[n], d, number_terms * number_terms * phi_d_n_k * phi_d_n_k); gsl_matrix_set(W_phi_var, doc->word[n], d, number_terms * number_terms * (phi_d_n_k - phi_d_n_k * phi_d_n_k)); } } gsl_vector_view document_weights = gsl_matrix_column( documents_topics_t, k); gsl_vector_view renormalized_document_weights = gsl_matrix_column( renormalized_documents_topics_t, k); assert(seq->topic[k]->e_log_prob->size2 == data->len); // Now, with w_phi_var, etc. set, determine // \sum_{i=t}^{T-1} r(...) h(t, i) SetExpHTmp(seq, data, t, k, n, exp_h_tmp, zw_tmp, exp_i_tmp); // Next, set up the weighted response, // \exp_{-m + v / 2) \circ (m_{t+1} - m_t + v_t}). // Here we also subtract the current l's contribution to influence_sum_lgl. gsl_vector_view w_phi_l_t = gsl_matrix_column(seq->topic[k]->w_phi_l, t); gsl_vector_set_zero(response); for (int i = t; i < seq->nseq - 1; ++i) { gsl_vector_view total_influence_time_i = gsl_matrix_column(seq->influence_sum_lgl[k], i); gsl_vector_memcpy(zw_tmp, &w_phi_l_t.vector); gsl_vector_scale(zw_tmp, scaled_influence[i - t]); gsl_vector_sub(&total_influence_time_i.vector, zw_tmp); // Now, copy this total influence at time i back into zw_tmp. gsl_vector_memcpy(zw_tmp, &total_influence_time_i.vector); gsl_vector_mul(zw_tmp, exp_i_tmp[i]); gsl_vector_view mean_i_current = gsl_matrix_column(seq->topic[k]->e_log_prob, i); gsl_vector_view mean_i_next = gsl_matrix_column(seq->topic[k]->e_log_prob, i + 1); gsl_vector_view var_i_current = gsl_matrix_column(seq->topic[k]->variance, i + 1); gsl_vector_memcpy(terms_inc_tmp, &mean_i_next.vector); gsl_vector_sub(terms_inc_tmp, &mean_i_current.vector); gsl_vector_add(terms_inc_tmp, &var_i_current.vector); gsl_vector_sub(terms_inc_tmp, zw_tmp); assert(data->nterms == terms_inc_tmp->size); gsl_vector_mul(terms_inc_tmp, exp_i_tmp[i]); gsl_vector_scale(terms_inc_tmp, scaled_influence[i - t]); gsl_vector_add(response, terms_inc_tmp); } PrepareRegressionComponents(corpus, seq, k, W_phi, W_phi_var, d_phi_var_tmp, response, d_tmp, dd_tmp, &document_weights.vector, W_phi_tmp, exp_h_tmp); // Finally, solve for the document weights d! Solve(dd_tmp, d_tmp, &document_weights.vector); // Keep track of the iteration so we can dump certain stats // occasionally (but not always). static int dump_count = 0; ++dump_count; if (FLAGS_save_time == t) { outlog("Updating topic %ld, time %ld.", k, t); char name[400]; sprintf(name, "%s%ld_%ld_weighted_document_terms.dat", root, k, t); FILE* f = fopen(name, "w"); params_write_sparse_gsl_matrix(f, "W_phi", W_phi); fclose(f); sprintf(name, "%s%ld_%ld_weighted_document_terms_var.dat", root, k, t); f = fopen(name, "w"); params_write_sparse_gsl_matrix(f, "W_phi_var", W_phi_var); fclose(f); sprintf(name, "%s%ld_%ld_phi.dat", root, k, t); f = fopen(name, "w"); params_write_gsl_matrix(f, "phi 0", phi[0]); // params_write_gsl_matrix(f, "phi 2", phi[1]); // params_write_gsl_matrix(f, "phi 2", phi[7]); fclose(f); sprintf(name, "%s%ld_%ld_weighted_document_terms_sq.dat", root, k, t); f = fopen(name, "w"); params_write_sparse_gsl_matrix(f, "W2_phi2", W2_phi2); fclose(f); sprintf(name, "%s%ld_%ld_weighted_response.dat", root, k, t); f = fopen(name, "w"); params_write_gsl_vector_multiline(f, "weighted_response", d_tmp); fclose(f); sprintf(name, "%s%ld_%ld_response.dat", root, k, t); f = fopen(name, "w"); params_write_gsl_vector_multiline(f, "response", response); fclose(f); sprintf(name, "%s%ld_%ld_exp_h.dat", root, k, t); f = fopen(name, "w"); params_write_gsl_vector_multiline(f, "exp_h", exp_h_tmp); fclose(f); if (dump_doc_stats || dump_count % 4 == 0) { sprintf(name, "%s%ld_%ld_document_document_matrix.dat", root, k, t); f = fopen(name, "w"); params_write_gsl_matrix(f, "document_document_matrix", dd_tmp); fclose(f); sprintf(name, "%s%ld_%ld_exp_h.dat", root, k, t); f = fopen(name, "w"); params_write_gsl_vector_multiline(f, "exp_h", exp_h_tmp); fclose(f); } } if (FLAGS_save_time == -1) { // First, dump phi's for the top topics. DumpTimeDocTopicStats(root, t, corpus, phi); } outlog("Done updating topic %ld, time %ld.", k, t); for (int d = 0; d < document_weights.vector.size; ++d) { gsl_vector_set(&renormalized_document_weights.vector, d, vget(&document_weights.vector, d) * renormalization_totals[d]); } // Now copy this and several products to // the sslm_var object. gsl_vector_view w_phi_l = gsl_matrix_column(seq->topic[k]->w_phi_l, t); gsl_blas_dgemv(CblasNoTrans, 1.0, W_phi, &document_weights.vector, 0.0, &w_phi_l.vector); // Copy this value back into lgl. for (int i=t; i < seq->nseq - 1; ++i) { gsl_vector_view total_influence_time_i = gsl_matrix_column(seq->influence_sum_lgl[k], i); gsl_vector_memcpy(zw_tmp, &w_phi_l.vector); gsl_vector_scale(zw_tmp, scaled_influence[i - t]); gsl_vector_add(&total_influence_time_i.vector, zw_tmp); } // Keep track of the term we need to add to m_update_coeff. gsl_vector_memcpy(terms_inc_tmp, &w_phi_l.vector); gsl_vector_mul(terms_inc_tmp, &w_phi_l.vector); // Copy and square the document weights vector. for (int i = 0; i < xd_tmp->size; ++i) { double value = gsl_vector_get(&document_weights.vector, i); value = value * value + FLAGS_sigma_l * FLAGS_sigma_l; gsl_vector_set(xd_tmp, i, value); } gsl_blas_dgemv(CblasNoTrans, 1.0, W_phi_var, xd_tmp, 0.0, yw_tmp); gsl_vector_add(terms_inc_tmp, yw_tmp); for (int i = 0; i < xd_tmp->size; ++i) { gsl_vector_set(xd_tmp, i, FLAGS_sigma_l * FLAGS_sigma_l); } gsl_blas_dgemv(CblasNoTrans, 1.0, W2_phi2, xd_tmp, 0.0, yw_tmp); gsl_vector_add(terms_inc_tmp, yw_tmp); // Store an update coefficient for the beta updates. for (int i = t; i < seq->nseq; ++i) { gsl_vector_view m_update_coeff_h = gsl_matrix_column(seq->topic[k]->m_update_coeff, i); if (t == 0) { gsl_vector_set_zero(&m_update_coeff_h.vector); } gsl_vector_memcpy(yw_tmp, terms_inc_tmp); gsl_vector_scale(yw_tmp, scaled_influence[i - t]); gsl_vector_add(&m_update_coeff_h.vector, yw_tmp); } for (int i = t; i < seq->nseq; ++i) { gsl_vector_view m_update_coeff_g = gsl_matrix_column(seq->topic[k]->m_update_coeff_g, i); if (t == 0) { gsl_vector_set_zero(&m_update_coeff_g.vector); } gsl_vector_memcpy(yw_tmp, &w_phi_l.vector); gsl_vector_scale(yw_tmp, scaled_influence[i - t]); gsl_vector_add(&m_update_coeff_g.vector, yw_tmp); } for (int i = 0; i < corpus->ndocs; ++i) { double value = gsl_vector_get(&document_weights.vector, i); // While we're here, increment the likelihood. lhood += (-(value * value + FLAGS_sigma_l * FLAGS_sigma_l) / (2.0 * FLAGS_sigma_d * FLAGS_sigma_d) - 0.5 * log(2 * PI) - log(FLAGS_sigma_d * FLAGS_sigma_d)); } } free(total_terms); free(renormalization_totals); gsl_matrix_free(W_phi); gsl_matrix_free(W_phi_tmp); gsl_matrix_free(W2_phi2); gsl_matrix_free(W_phi_var); gsl_matrix_free(dd_tmp); gsl_vector_free(exp_h_tmp); gsl_vector_free(response); gsl_vector_free(terms_inc_tmp); for (int i=0; i < seq->nseq; ++i) { gsl_vector_free(exp_i_tmp[i]); } delete[] exp_i_tmp; gsl_vector_free(d_tmp); gsl_vector_free(d_phi_var_tmp); gsl_vector_free(xd_tmp); gsl_vector_free(yw_tmp); gsl_vector_free(zw_tmp); return lhood; } void make_lda_from_seq_slice(lda* lda_m, lda_seq* lda_seq_m, int time) { // set lda model topics // !!! note: we should be able to point to the view... int k; for (k = 0; k < lda_seq_m->ntopics; k++) { // get topic gsl_vector s = gsl_matrix_column(lda_seq_m->topic[k]->e_log_prob, time).vector; gsl_vector d = gsl_matrix_column(lda_m->topics, k).vector; gsl_blas_dcopy(&s, &d); } gsl_blas_dcopy(lda_seq_m->alpha, lda_m->alpha); } static gsl_matrix* g_alloc(lda_seq* model, const corpus_seq_t* data, int time) { gsl_matrix* g = gsl_matrix_calloc(model->nterms, model->ntopics); double exp_m, m, m_next; for (int k = 0; k < model->ntopics; ++k) { for (int w=0; w < model->nterms; ++w) { double variance_first = mget(model->topic[k]->variance, w, time); double m = mget(model->topic[k]->e_log_prob, w, time); double m_next; exp_m = exp(-m + variance_first / 2.0); gsl_matrix_set(g, w, k, (scaled_influence[0] * -variance_first * exp_m)); for (int i=time; i < model->nseq - 1; ++i) { // This loop is kind of going overboard, but at least we // do this once per E-M iteration. double influence_other_times = 0.0; for (int j = 0; j < i; ++j) { exp_m = exp(-mget(model->topic[k]->e_log_prob, w, j) + mget(model->topic[k]->variance, w, j) / 2.0); // Note that we skip the other docs in this time period. // Those get special treatment below. if (j != time) { influence_other_times += ( mget(model->topic[k]->w_phi_l, w, j) * scaled_influence[i - j] * exp_m); } } m = mget(model->topic[k]->e_log_prob, w, i); m_next = mget(model->topic[k]->e_log_prob, w, i + 1); // Increment the current count by this value. gsl_matrix_set(g, w, k, mget(g, w, k) + (scaled_influence[i - time] * (m_next - m - influence_other_times))); } exp_m = exp(-m + mget(model->topic[k]->variance, w, time) / 2.0); gsl_matrix_set(g, w, k, mget(g, w, k) * exp_m); } } return g; } static gsl_matrix* g3_alloc(lda_seq* model, const corpus_seq_t* data, int time) { gsl_matrix* g = gsl_matrix_calloc(model->nterms, model->ntopics); double exp_m, m, m_next, variance, total; for (int k = 0; k < model->ntopics; ++k) { for (int w=0; w < model->nterms; ++w) { total = 0.0; for (int i=time; i < model->nseq - 1; ++i) { // This loop is kind of going overboard, but at least we // do this once per E-M iteration. variance = mget(model->topic[k]->variance, w, i + 1); m = mget(model->topic[k]->e_log_prob, w, i); m_next = mget(model->topic[k]->e_log_prob, w, i + 1); exp_m = exp(-m + variance / 2.0); total += (scaled_influence[i - time] * exp_m * (m_next - m + variance)); } gsl_matrix_set(g, w, k, total); } } return g; } static gsl_matrix* g4_alloc(lda_seq* model, const corpus_seq_t* data, int time) { gsl_matrix* g = gsl_matrix_calloc(model->nterms, model->ntopics); double exp_m, exp_m_scaled, m, total, variance, w_phi_l; for (int k = 0; k < model->ntopics; ++k) { for (int w=0; w < model->nterms; ++w) { total = 0.0; for (int i=time; i < model->nseq - 1; ++i) { // This loop is kind of going overboard, but at least we // do this once per E-M iteration. variance = mget(model->topic[k]->variance, w, i + 1); m = mget(model->topic[k]->e_log_prob, w, i); exp_m = exp(-2.0 * m + 2.0 * variance); exp_m_scaled = exp_m * scaled_influence[i - time]; for (int j=0; j <= i; ++j) { w_phi_l = mget(model->topic[k]->w_phi_l, w, j); total += exp_m_scaled * w_phi_l * scaled_influence[i - j]; } } gsl_matrix_set(g, w, k, total); } } return g; } static gsl_matrix* g5_alloc(lda_seq* model, const corpus_seq_t* data, int time) { gsl_matrix* g = gsl_matrix_calloc(model->nterms, model->ntopics); double exp_m, m, total, variance; for (int k = 0; k < model->ntopics; ++k) { for (int w=0; w < model->nterms; ++w) { total = 0.0; for (int i=time; i < model->nseq - 1; ++i) { // This loop is kind of going overboard, but at least we // do this once per E-M iteration. variance = mget(model->topic[k]->variance, w, i + 1); m = mget(model->topic[k]->e_log_prob, w, i); exp_m = exp(-2.0 * m + 2.0 * variance); total += exp_m * (scaled_influence[i - time] * scaled_influence[i - time]); } gsl_matrix_set(g, w, k, total); } } return g; } /* * compute the likelihood of a sequential corpus under an LDA seq * model. return the likelihood bound. * */ static void InferDTMSeq(const int K, unsigned int iter, unsigned int last_iter, const corpus_seq_t* data, gsl_matrix* gammas, gsl_matrix* lhoods, lda* lda_model, lda_post* post, lda_seq* model, gsl_matrix** suffstats, double* bound) { int doc_index = 0; for (int t = 0; t < data->len; t++) { // Prepare coefficients for the phi updates. This change is // relatively painless. make_lda_from_seq_slice(lda_model, model, t); int ndocs = data->corpus[t]->ndocs; for (int d = 0; d < ndocs; d++) { gsl_vector gam = gsl_matrix_row(gammas, doc_index).vector; gsl_vector lhood = gsl_matrix_row(lhoods, doc_index).vector; post->gamma = &gam; post->doc = data->corpus[t]->doc[d]; post->lhood = &lhood; double doc_lhood; // For now, only do the standard, phi-based update. if (iter == 0) { doc_lhood = fit_lda_post(d, t, post, NULL, NULL, NULL, NULL, NULL); } else { doc_lhood = fit_lda_post(d, t, post, model, NULL, NULL, NULL, NULL); } if (suffstats != NULL) { update_lda_seq_ss(t, data->corpus[t]->doc[d], post, suffstats); } *bound += doc_lhood; doc_index++; } } } static void InferDIMSeq(const int K, unsigned int iter, unsigned int last_iter, const char* file_root, const corpus_seq_t* data, gsl_matrix* gammas, gsl_matrix* lhoods, lda* lda_model, lda_post* post, lda_seq* model, gsl_matrix** suffstats, double* bound) { int doc_index = 0; for (int t = 0; t < data->len; t++) { // Prepare coefficients for the phi updates. This change is // relatively painless. gsl_matrix* g = g_alloc(model, data, t); gsl_matrix* g3_matrix = g3_alloc(model, data, t); gsl_matrix* g4_matrix = g4_alloc(model, data, t); gsl_matrix* g5_matrix = g5_alloc(model, data, t); make_lda_from_seq_slice(lda_model, model, t); int ndocs = data->corpus[t]->ndocs; gsl_matrix** phi_t = (gsl_matrix**) malloc(ndocs * sizeof(gsl_matrix*)); for (int d = 0; d < ndocs; d++) { gsl_vector gam = gsl_matrix_row(gammas, doc_index).vector; gsl_vector lhood = gsl_matrix_row(lhoods, doc_index).vector; post->gamma = &gam; post->doc = data->corpus[t]->doc[d]; post->lhood = &lhood; double doc_lhood; // For now, only do the standard, phi-based update. if (iter == 0) { doc_lhood = fit_lda_post(d, t, post, NULL, NULL, NULL, NULL, NULL); } else { doc_lhood = fit_lda_post(d, t, post, model, g, g3_matrix, g4_matrix, g5_matrix); } if (suffstats != NULL) { update_lda_seq_ss(t, data->corpus[t]->doc[d], post, suffstats); } phi_t[d] = gsl_matrix_alloc(post->doc->nterms, K); gsl_matrix_view phi_view = gsl_matrix_submatrix( post->phi, 0, 0, post->doc->nterms, K); gsl_matrix_memcpy(phi_t[d], &phi_view.matrix); *bound += doc_lhood; doc_index++; } if (t < data->len - 1) { if (FLAGS_model == "fixed") { double l_bound = update_inf_var_fixed( model, data, // Also want a copy of phi for each doc. // Can keep this as a vector for now. phi_t, t, file_root, last_iter || iter >= FLAGS_lda_sequence_min_iter); *bound += l_bound; } } for (int d=0; d < ndocs; ++d) { gsl_matrix_free(phi_t[d]); } free(phi_t); gsl_matrix_free(g); gsl_matrix_free(g3_matrix); gsl_matrix_free(g4_matrix); gsl_matrix_free(g5_matrix); } } double lda_seq_infer(lda_seq* model, const corpus_seq_t* data, gsl_matrix** suffstats, gsl_matrix* gammas, gsl_matrix* lhoods, unsigned int iter, unsigned int last_iter, const char* file_root) { int K = model->ntopics; int W = model->nterms; double bound = 0.0; lda* lda_model = new_lda_model(K, W); lda_post post; post.phi = gsl_matrix_calloc(data->max_nterms, K); post.log_phi = gsl_matrix_calloc(data->max_nterms, K); post.model = lda_model; if (FLAGS_model == "fixed") { // First, pre-compute the functions f and g. InfluenceTotalFixed(model, data); InferDIMSeq(K, iter, last_iter, file_root, data, gammas, lhoods, lda_model, &post, model, suffstats, &bound); } else if (FLAGS_model == "dtm") { InferDTMSeq(K, iter, last_iter, data, gammas, lhoods, lda_model, &post, model, suffstats, &bound); } else { printf("Error. Unknown model.\n"); exit(1); } gsl_matrix_free(post.phi); gsl_matrix_free(post.log_phi); free_lda_model(lda_model); return(bound); } /* * fit an lda sequence model: * * . for each time period * . set up lda model with E[log p(w|z)] and \alpha * . for each document * . perform posterior inference * . update sufficient statistics/likelihood * . * . maximize topics * */ double fit_lda_seq(lda_seq* m, const corpus_seq_t* data, const corpus_seq_t* heldout, const char* file_root) { int K = m->ntopics, W = m->nterms; int k; // initialize sufficient statistics gsl_matrix* topic_suffstats[K]; for (k = 0; k < K; k++) { topic_suffstats[k] = gsl_matrix_calloc(W, data->len); } // set up variables char name[400]; gsl_matrix* gammas = gsl_matrix_calloc(data->ndocs, K); gsl_matrix* lhoods = gsl_matrix_calloc(data->ndocs, K+1); gsl_matrix* heldout_gammas = NULL; gsl_matrix* heldout_lhoods = NULL; if (heldout != NULL) { heldout_gammas = gsl_matrix_calloc(heldout->ndocs, K); heldout_lhoods = gsl_matrix_calloc(heldout->ndocs, K+1); } double bound = 0, heldout_bound = 0, old_bound; double convergence = LDA_SEQ_EM_THRESH + 1; char root[400]; sprintf(root, "%s/lda-seq/", file_root); make_directory(root); char em_log_filename[400]; sprintf(em_log_filename, "%s/em_log.dat", file_root); FILE* em_log = fopen(em_log_filename, "w"); // run EM int iter = 0; // LDA_INFERENCE_MAX_ITER = 1; short final_iters_flag = 0; unsigned int last_iter = 0; while (iter < FLAGS_lda_sequence_min_iter || ((final_iters_flag == 0 || convergence > LDA_SEQ_EM_THRESH) && iter <= FLAGS_lda_sequence_max_iter) && !last_iter) { if (!(iter < FLAGS_lda_sequence_min_iter || ((final_iters_flag == 0 || convergence > LDA_SEQ_EM_THRESH) && iter <= FLAGS_lda_sequence_max_iter))) { last_iter = 1; } outlog("\nEM iter %3d\n", iter); outlog("%s", "E step\n"); fprintf(em_log, "%17.14e %5.3e\n", bound, convergence); old_bound = bound; gsl_matrix_set_zero(gammas); gsl_matrix_set_zero(lhoods); if (heldout != NULL) { gsl_matrix_set_zero(heldout_gammas); gsl_matrix_set_zero(heldout_lhoods); } for (k = 0; k < K; k++) { gsl_matrix_set_zero(topic_suffstats[k]); } // compute the likelihood of a sequential corpus under an LDA // seq model and find the evidence lower bound. bound = lda_seq_infer(m, data, topic_suffstats, gammas, lhoods, iter, last_iter, file_root); if (heldout != NULL) { heldout_bound = lda_seq_infer(m, heldout, NULL, heldout_gammas, heldout_lhoods, iter, last_iter, file_root); } // print out the gammas and likelihoods. sprintf(name, "%s/gam.dat", root); mtx_fprintf(name, gammas); sprintf(name, "%s/lhoods.dat", root); mtx_fprintf(name, lhoods); if (heldout != NULL) { sprintf(name, "%s/heldout_lhoods.dat", root); mtx_fprintf(name, heldout_lhoods); sprintf(name, "%s/heldout_gam.dat", root); mtx_fprintf(name, heldout_gammas); } outlog("%s", "\nM step"); // fit the variational distribution double topic_bnd = fit_lda_seq_topics(m, topic_suffstats); bound += topic_bnd; write_lda_seq(m, root); if ((bound - old_bound) < 0) { if (LDA_INFERENCE_MAX_ITER == 1) LDA_INFERENCE_MAX_ITER = 2; if (LDA_INFERENCE_MAX_ITER == 2) LDA_INFERENCE_MAX_ITER = 5; if (LDA_INFERENCE_MAX_ITER == 5) LDA_INFERENCE_MAX_ITER = 10; if (LDA_INFERENCE_MAX_ITER == 10) LDA_INFERENCE_MAX_ITER = 20; outlog( "\nWARNING: bound went down %18.14f; " "increasing var iter to %d\n", bound-old_bound, LDA_INFERENCE_MAX_ITER); } // check for convergence convergence = fabs((bound - old_bound) / old_bound); if (convergence < LDA_SEQ_EM_THRESH) { final_iters_flag = 1; LDA_INFERENCE_MAX_ITER = 500; outlog("starting final iterations : max iter = %d\n", LDA_INFERENCE_MAX_ITER); convergence = 1.0; } outlog("\n(%02d) lda seq bound=% 15.7f; " "heldout bound=% 15.7f, conv=% 15.7e\n", iter, bound, heldout_bound, convergence); iter++; } return(bound); } /* * read and write lda sequence variational distribution * */ void write_lda_seq(const lda_seq* model, const char* root) { char name[400]; sprintf(name, "%sinfo.dat", root); FILE* f = fopen(name, "w"); params_write_int(f, "NUM_TOPICS", model->ntopics); params_write_int(f, "NUM_TERMS", model->nterms); params_write_int(f, "SEQ_LENGTH", model->nseq); params_write_gsl_vector(f, "ALPHA", model->alpha); fclose(f); int k; for (k = 0; k < model->ntopics; k++) { const int tmp = k; outlog("\nwriting topic %03d", tmp); sprintf(name, "%stopic-%03d", root, tmp); write_sslm_var(model->topic[tmp], name); } if (FLAGS_model == "fixed") { for (int t=0; t < model->influence->ntime; ++t) { sprintf(name, "%sinfluence_time-%03d", root, t); outlog("\nwriting influence weights for time %d to %s", t, name); gsl_matrix* influence_t = model->influence->doc_weights[t]; assert(model->ntopics == influence_t->size2); mtx_fprintf(name, influence_t); sprintf(name, "%srenormalized_influence_time-%03d", root, t); outlog("\nwriting influence weights for time %d to %s", t, name); influence_t = model->influence->renormalized_doc_weights[t]; assert(model->ntopics == influence_t->size2); mtx_fprintf(name, influence_t); } } } // Read information about a particular model. // This model should be named "{root}info.dat" // and should contain the following rows: // number_topics // number_times // alpha, as a gsl vector lda_seq* read_lda_seq(const char* root, corpus_seq_t* data) { char name[400]; lda_seq* model = (lda_seq*) malloc(sizeof(lda_seq)); sprintf(name, "%sinfo.dat", root); FILE* f = fopen(name, "r"); if (f == NULL) { outlog("Unable to open file %s. Failing.", name); exit(1); } params_read_int(f, "NUM_TOPICS", &(model->ntopics)); params_read_int(f, "NUM_TERMS", &(model->nterms)); params_read_int(f, "SEQ_LENGTH", &(model->nseq)); params_read_gsl_vector(f, "ALPHA", &(model->alpha)); fclose(f); model->topic = (sslm_var**) malloc(sizeof(sslm_var*) * model->ntopics); for (int k = 0; k < model->ntopics; k++) { outlog( "reading topic %d", k); sprintf(name, "%stopic-%03d", root, k); model->topic[k] = read_sslm_var(name); model->topic[k]->w_phi_l = gsl_matrix_alloc(model->nterms, model->nseq); model->topic[k]->w_phi_sum = gsl_matrix_alloc(model->nterms, model->nseq); model->topic[k]->w_phi_l_sq = gsl_matrix_alloc(model->nterms, model->nseq); if (FLAGS_model == "dim" || FLAGS_model == "regression") { sprintf(name, "%sw_phi_l-%d", root, k); mtx_fscanf(name, model->topic[k]->w_phi_l); sprintf(name, "%sw_phi_sum-%d", root, k); mtx_fscanf(name, model->topic[k]->w_phi_sum); sprintf(name, "%sw_phi_l_sq-%d", root, k); mtx_fscanf(name, model->topic[k]->w_phi_l_sq); } } if (FLAGS_model == "dim" || FLAGS_model == "regression" && data != NULL) { model->influence = (inf_var*) malloc(sizeof(inf_var)); model->influence->doc_weights = (gsl_matrix**) malloc(sizeof(gsl_matrix*)); int t; model->influence->ntime = model->nseq; for (t=0; t < model->nseq; ++t) { // outlog("%d %d", t, model->influence->ntime); sprintf(name, "%sinfluence_time-%03d", root, t); outlog("\n reading influence weights for time %d from %s", t, name); model->influence->doc_weights[t] = gsl_matrix_alloc(data->corpus[t]->ndocs, model->ntopics); mtx_fscanf(name, model->influence->doc_weights[t]); } } else { model->influence = NULL; } return(model); } /* * update lda sequence sufficient statistics from an lda posterior * */ void update_lda_seq_ss(int time, const doc_t* doc, const lda_post* post, gsl_matrix** ss) { int K = post->phi->size2, N = doc->nterms; int k, n; for (k = 0; k < K; k++) { gsl_matrix* topic_ss = ss[k]; for (n = 0; n < N; n++) { int w = doc->word[n]; int c = doc->count[n]; minc(topic_ss, w, time, c * mget(post->phi, n, k)); } } } /* * fit lda sequence * */ double fit_lda_seq_topics(lda_seq* model, gsl_matrix** ss) { double lhood = 0, lhood_term = 0; int k; for (k = 0; k < model->ntopics; k++) { outlog( "\nfitting topic %02d", k); lhood_term = fit_sslm(model->topic[k], ss[k]); lhood += lhood_term; } return(lhood); } /* * allocate lda seq * */ lda_seq* new_lda_seq(corpus_seq_t* data, int W, int T, int K) { lda_seq* model = (lda_seq*) malloc(sizeof(lda_seq)); model->ntopics = K; model->nterms = W; model->nseq = T; model->alpha = gsl_vector_alloc(K); model->topic = (sslm_var**) malloc(sizeof(sslm_var*) * K); // Create the vectors of total counts for each time. model->influence_sum_lgl = (gsl_matrix**) malloc(sizeof(gsl_matrix*) * K); for (int k = 0; k < K; k++) { // model->w_phi_l = (gsl_matrix*) malloc(sizeof(gsl_matrix)); // model->w_phi_l_sq = (gsl_matrix*) malloc(sizeof(gsl_matrix*)); model->influence_sum_lgl[k] = gsl_matrix_calloc(W, T); model->topic[k] = sslm_var_alloc(W, T); if (k < FLAGS_fix_topics) { model->topic[k]->chain_variance = 1e-10; } model->topic[k]->w_phi_l = gsl_matrix_calloc(W, T); model->topic[k]->w_phi_sum = gsl_matrix_calloc(W, T); model->topic[k]->w_phi_l_sq = gsl_matrix_calloc(W, T); } model->influence = inf_var_alloc(K, data); return(model); } /* * initialize from sufficient statistics (expected counts). * */ void init_lda_seq_from_ss(lda_seq* model, double topic_chain_variance, double topic_obs_variance, double alpha, gsl_matrix* init_suffstats) { gsl_vector_set_all(model->alpha, alpha); for (int k = 0; k < model->ntopics; k++) { gsl_vector slice = gsl_matrix_column(init_suffstats, k).vector; sslm_counts_init(model->topic[k], topic_obs_variance, topic_chain_variance, &slice); if (k < FLAGS_fix_topics) { model->topic[k]->chain_variance = 1e-10; } model->topic[k]->w_phi_l = gsl_matrix_calloc(model->nterms, model->nseq); model->topic[k]->w_phi_sum = gsl_matrix_calloc(model->nterms, model->nseq); model->topic[k]->w_phi_l_sq = gsl_matrix_calloc(model->nterms, model->nseq); } }
{ "alphanum_fraction": 0.6232351361, "avg_line_length": 29.8599562363, "ext": "c", "hexsha": "256d320a4727041030c9af457f58117b4f84ca46", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_path": "scripts/lib/DTM/dtm/lda-seq.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "iwangjian/topic-extractor", "max_issues_repo_path": "scripts/lib/DTM/dtm/lda-seq.c", "max_line_length": 90, "max_stars_count": 11, "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_path": "scripts/lib/DTM/dtm/lda-seq.c", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "num_tokens": 12058, "size": 40938 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include <class.h> /* from extern/ */ #include "ccl.h" #include "ccl_params.h" #include "ccl_emu17.h" #include "ccl_emu17_params.h" /*------ ROUTINE: ccl_cosmology_compute_power_class ----- INPUT: ccl_cosmology * cosmo */ static void ccl_free_class_structs(ccl_cosmology *cosmo, struct background *ba, struct thermo *th, struct perturbs *pt, struct transfers *tr, struct primordial *pm, struct spectra *sp, struct nonlinear *nl, struct lensing *le, int *init_arr, int * status) { int i_init=6; if(init_arr[i_init--]) { if (spectra_free(sp) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS spectra:%s\n", sp->error_message); return; } } if(init_arr[i_init--]) { if (transfer_free(tr) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS transfer:%s\n", tr->error_message); return; } } if(init_arr[i_init--]) { if (nonlinear_free(nl) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS nonlinear:%s\n", nl->error_message); return; } } if(init_arr[i_init--]) { if (primordial_free(pm) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS pm:%s\n", pm->error_message); return; } } if(init_arr[i_init--]) { if (perturb_free(pt) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS pt:%s\n", pt->error_message); return; } } if(init_arr[i_init--]) { if (thermodynamics_free(th) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS thermo:%s\n", th->error_message); return; } } if(init_arr[i_init--]) { if (background_free(ba) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_free_class_structs(): Error freeing CLASS bg:%s\n", ba->error_message); return; } } return; } static void ccl_class_preinit(struct background *ba, struct thermo *th, struct perturbs *pt, struct transfers *tr, struct primordial *pm, struct spectra *sp, struct nonlinear *nl, struct lensing *le) { //pre-initialize all fields that are freed by *_free() routine //prevents crashes if *_init()failed and did not initialize all tables freed by *_free() //init for background_free ba->tau_table = NULL; ba->z_table = NULL; ba->d2tau_dz2_table = NULL; ba->background_table = NULL; ba->d2background_dtau2_table = NULL; //init for thermodynamics_free th->z_table = NULL; th->thermodynamics_table = NULL; th->d2thermodynamics_dz2_table = NULL; //init for perturb_free pt->tau_sampling = NULL; pt->tp_size = NULL; pt->ic_size = NULL; pt->k = NULL; pt->k_size_cmb = NULL; pt->k_size_cl = NULL; pt->k_size = NULL; pt->sources = NULL; //init for primordial_free pm->amplitude = NULL; pm->tilt = NULL; pm->running = NULL; pm->lnpk = NULL; pm->ddlnpk = NULL; pm->is_non_zero = NULL; pm->ic_size = NULL; pm->ic_ic_size = NULL; pm->lnk = NULL; //init for nonlinear_free nl->k = NULL; nl->tau = NULL; nl->nl_corr_density = NULL; nl->k_nl = NULL; //init for transfer_free tr->tt_size = NULL; tr->l_size_tt = NULL; tr->l_size = NULL; tr->l = NULL; tr->q = NULL; tr->k = NULL; tr->transfer = NULL; //init for spectra_free //spectra_free checks all other data fields before freeing sp->is_non_zero = NULL; sp->ic_size = NULL; sp->ic_ic_size = NULL; } static void ccl_run_class(ccl_cosmology *cosmo, struct file_content *fc, struct precision* pr, struct background* ba, struct thermo* th, struct perturbs* pt, struct transfers* tr, struct primordial* pm, struct spectra* sp, struct nonlinear* nl, struct lensing* le, struct output* op, int *init_arr, int * status) { ErrorMsg errmsg; // for error messages int i_init=0; ccl_class_preinit(ba,th,pt,tr,pm,sp,nl,le); if(input_init(fc,pr,ba,th,pt,tr,pm,sp,nl,le,op,errmsg) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS input:%s\n", errmsg); return; } if (background_init(pr,ba) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS background:%s\n", ba->error_message); return; } init_arr[i_init++]=1; if (thermodynamics_init(pr,ba,th) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS thermodynamics:%s\n", th->error_message); return; } init_arr[i_init++]=1; if (perturb_init(pr,ba,th,pt) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS pertubations:%s\n", pt->error_message); return; } init_arr[i_init++]=1; if (primordial_init(pr,pt,pm) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS primordial:%s\n", pm->error_message); return; } init_arr[i_init++]=1; if (nonlinear_init(pr,ba,th,pt,pm,nl) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS nonlinear:%s\n", nl->error_message); return; } init_arr[i_init++]=1; if (transfer_init(pr,ba,th,pt,nl,tr) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS transfer:%s\n", tr->error_message); return; } init_arr[i_init++]=1; if (spectra_init(pr,ba,pt,pm,nl,tr,sp) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS spectra:%s\n", sp->error_message); return; } init_arr[i_init++]=1; } static double ccl_get_class_As(ccl_cosmology *cosmo, struct file_content *fc, int position_As, double sigma8, int * status) { //structures for class test run struct precision pr; // for precision parameters struct background ba; // for cosmological background struct thermo th; // for thermodynamics struct perturbs pt; // for source functions struct transfers tr; // for transfer functions struct primordial pm; // for primordial spectra struct spectra sp; // for output spectra struct nonlinear nl; // for non-linear spectra struct lensing le; struct output op; //temporarily overwrite P_k_max_1/Mpc to speed up sigma8 calculation double k_max_old = 0.; int position_kmax =2; double A_s_guess; int init_arr[7]={0,0,0,0,0,0,0}; if (strcmp(fc->name[position_kmax],"P_k_max_1/Mpc")) { k_max_old = strtof(fc->value[position_kmax],NULL); sprintf(fc->value[position_kmax],"%.15e",10.); } A_s_guess = 2.43e-9/0.87659*sigma8; sprintf(fc->value[position_As],"%.15e",A_s_guess); ccl_run_class(cosmo, fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status); if (cosmo->status != CCL_ERROR_CLASS) A_s_guess*=pow(sigma8/sp.sigma8,2.); ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); if (k_max_old >0) { sprintf(fc->value[position_kmax],"%.15e",k_max_old); } return A_s_guess; } static void ccl_fill_class_parameters(ccl_cosmology * cosmo, struct file_content * fc, int parser_length, int * status) { // initialize fc fields //silences Valgrind's "Conditional jump or move depends on uninitialised value" warning for (int i = 0; i< parser_length; i++){ strcpy(fc->name[i]," "); strcpy(fc->value[i]," "); } strcpy(fc->name[0],"output"); strcpy(fc->value[0],"mPk"); strcpy(fc->name[1],"non linear"); if (cosmo->config.matter_power_spectrum_method == ccl_halofit) strcpy(fc->value[1],"Halofit"); else strcpy(fc->value[1],"none"); strcpy(fc->name[2],"P_k_max_1/Mpc"); sprintf(fc->value[2],"%.15e",ccl_splines->K_MAX_SPLINE); //in units of 1/Mpc, corroborated with ccl_constants.h strcpy(fc->name[3],"z_max_pk"); sprintf(fc->value[3],"%.15e",1./ccl_splines->A_SPLINE_MINLOG_PK-1.); strcpy(fc->name[4],"modes"); strcpy(fc->value[4],"s"); strcpy(fc->name[5],"lensing"); strcpy(fc->value[5],"no"); // now, copy over cosmology parameters strcpy(fc->name[6],"h"); sprintf(fc->value[6],"%.15e",cosmo->params.h); strcpy(fc->name[7],"Omega_cdm"); sprintf(fc->value[7],"%.15e",cosmo->params.Omega_c); strcpy(fc->name[8],"Omega_b"); sprintf(fc->value[8],"%.15e",cosmo->params.Omega_b); strcpy(fc->name[9],"Omega_k"); sprintf(fc->value[9],"%.15e",cosmo->params.Omega_k); strcpy(fc->name[10],"n_s"); sprintf(fc->value[10],"%.15e",cosmo->params.n_s); //cosmological constant? // set Omega_Lambda = 0.0 if w !=-1 if ((cosmo->params.w0 !=-1.0) || (cosmo->params.wa !=0)) { strcpy(fc->name[11],"Omega_Lambda"); sprintf(fc->value[11],"%.15e",0.0); strcpy(fc->name[12],"w0_fld"); sprintf(fc->value[12],"%.15e",cosmo->params.w0); strcpy(fc->name[13],"wa_fld"); sprintf(fc->value[13],"%.15e",cosmo->params.wa); } //neutrino parameters //massless neutrinos if (cosmo->params.N_nu_rel > 1.e-4) { strcpy(fc->name[14],"N_ur"); sprintf(fc->value[14],"%.15e",cosmo->params.N_nu_rel); } else { strcpy(fc->name[14],"N_ur"); sprintf(fc->value[14],"%.15e", 0.); } if (cosmo->params.N_nu_mass > 0) { strcpy(fc->name[15],"N_ncdm"); sprintf(fc->value[15],"%d",cosmo->params.N_nu_mass); strcpy(fc->name[16],"m_ncdm"); sprintf(fc->value[16],"%f", (cosmo->params.mnu)[0]); if (cosmo->params.N_nu_mass >=1){ for (int i = 1; i < cosmo->params.N_nu_mass; i++) { char tmp[20]; sprintf(tmp,", %f",(cosmo->params.mnu)[i]); strcat(fc->value[16],tmp); } } } strcpy(fc->name[17],"T_cmb"); sprintf(fc->value[17],"%.15e",cosmo->params.T_CMB); //normalization comes last, so that all other parameters are filled in for determining A_s if sigma8 is specified if (isfinite(cosmo->params.sigma8) && isfinite(cosmo->params.A_s)){ *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: class_parameters(): Error initializing CLASS parameters: both sigma8 and A_s defined\n"); return; } if (isfinite(cosmo->params.sigma8)) { strcpy(fc->name[parser_length-1],"A_s"); sprintf(fc->value[parser_length-1],"%.15e",ccl_get_class_As(cosmo,fc,parser_length-1,cosmo->params.sigma8, status)); } else if (isfinite(cosmo->params.A_s)) { strcpy(fc->name[parser_length-1],"A_s"); sprintf(fc->value[parser_length-1],"%.15e",cosmo->params.A_s); } else { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: class_parameters(): Error initializing CLASS pararmeters: neither sigma8 nor A_s defined\n"); return; } } static void ccl_cosmology_compute_power_class(ccl_cosmology * cosmo, int * status) { struct precision pr; // for precision parameters struct background ba; // for cosmological background struct thermo th; // for thermodynamics struct perturbs pt; // for source functions struct transfers tr; // for transfer functions struct primordial pm; // for primordial spectra struct spectra sp; // for output spectra struct nonlinear nl; // for non-linear spectra struct lensing le; struct output op; struct file_content fc; ErrorMsg errmsg; // for error messages // generate file_content structure // CLASS configuration parameters will be passed through this structure, // to avoid writing and reading .ini files for every call int parser_length = 20; int init_arr[7]={0,0,0,0,0,0,0}; if (parser_init(&fc,parser_length,"none",errmsg) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): parser init error:%s\n", errmsg); return; } ccl_fill_class_parameters(cosmo,&fc,parser_length, status); if (*status != CCL_ERROR_CLASS) ccl_run_class(cosmo, &fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status); if (*status == CCL_ERROR_CLASS) { //printed error message while running CLASS ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); return; } if (parser_free(&fc)== _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error freeing CLASS parser\n"); ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); return; } //These are the limits of the splining range cosmo->data.k_min_lin=2*exp(sp.ln_k[0]); cosmo->data.k_max_lin=ccl_splines->K_MAX_SPLINE; //CLASS calculations done - now allocate CCL splines double kmin = cosmo->data.k_min_lin; double kmax = ccl_splines->K_MAX_SPLINE; //Compute nk from number of decades and N_K = # k per decade double ndecades = log10(kmax) - log10(kmin); int nk = (int)ceil(ndecades*ccl_splines->N_K); double amin = ccl_splines->A_SPLINE_MINLOG_PK; double amax = ccl_splines->A_SPLINE_MAX; int na = ccl_splines->A_SPLINE_NA_PK+ccl_splines->A_SPLINE_NLOG_PK-1; // The x array is initially k, but will later // be overwritten with log(k) double * x = ccl_log_spacing(kmin, kmax, nk); double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK); double * y2d_lin = malloc(nk * na * sizeof(double)); double * y2d_nl = malloc(nk * na * sizeof(double)); //If error, store status, we will free later if (a==NULL|| x==NULL || y2d_lin==NULL || y2d_nl==NULL) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): memory allocation error\n"); } //Status flags int newstatus=0; int pwstatus=0; //If not, proceed if(!*status){ // After this loop x will contain log(k) // all in Mpc, not Mpc/h units! double psout_l,ic; for (int i=0; i<nk; i++) { for (int j = 0; j < na; j++) { //The 2D interpolation routines access the function values y_{k_ia_j} with the following ordering: //y_ij = y2d[j*N_k + i] //with i = 0,...,N_k-1 and j = 0,...,N_a-1. newstatus |= spectra_pk_at_k_and_z(&ba, &pm, &sp,x[i],1./a[j]-1., &psout_l,&ic); y2d_lin[j*nk+i] = log(psout_l); } x[i] = log(x[i]); } //If error, store status, we will free later if(newstatus) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error computing CLASS power spectrum\n"); } } //If no error, proceed if(!*status) { gsl_spline2d * log_power = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na); pwstatus = gsl_spline2d_init(log_power, x, a, y2d_lin,nk,na); //If not, proceed if(!pwstatus){ cosmo->data.p_lin = log_power; } else { gsl_spline2d_free(log_power); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error creating log_power spline\n"); } } if(*status){ //Linear power spec failed, so we return without proceeding to nonlinear. free(x); free(a); free(y2d_nl); free(y2d_lin); ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); return; } //Non-linear power //At the moment KMIN can't be less than CLASS's kmin in the nonlinear case. //If error, store status, we will free later if (kmin<(exp(sp.ln_k[0]))) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): K_MIN is less than CLASS's kmin. Not yet supported for nonlinear P(k).\n"); } //If not, proceed if(!*status){ //These are the limits of the splining range cosmo->data.k_min_nl=2*exp(sp.ln_k[0]); cosmo->data.k_max_nl=ccl_splines->K_MAX_SPLINE; if(cosmo->config.matter_power_spectrum_method==ccl_halofit) { double psout_nl; for (int i=0; i<nk; i++) { for (int j = 0; j < na; j++) { newstatus |= spectra_pk_nl_at_k_and_z(&ba, &pm, &sp,exp(x[i]),1./a[j]-1.,&psout_nl); y2d_nl[j*nk+i] = log(psout_nl); } } } if(newstatus){ *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error computing CLASS power spectrum\n"); } } if(!*status){ gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PNL_SPLINE_TYPE, nk,na); pwstatus = gsl_spline2d_init(log_power_nl, x, a, y2d_nl,nk,na); if(!pwstatus){ cosmo->data.p_nl = log_power_nl; } else { gsl_spline2d_free(log_power_nl); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error creating log_power_nl spline\n"); } } ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); free(x); free(a); free(y2d_nl); free(y2d_lin); return; } /* BCM correction See Schneider & Teyssier (2015) for details of the model. The equations inside this function correspond to those in that work for: gf -> G(k) scomp -> S(k) */ double ccl_bcm_model_fka(ccl_cosmology * cosmo, double k, double a, int *status){ double fka; double b0; double bfunc, bfunc4; double kg; double gf,scomp; double kh; double z; z=1./a-1.; kh = k/cosmo->params.h; //convert to h/Mpc b0 = 0.105*cosmo->params.bcm_log10Mc-1.27; //Eq. 4.4 bfunc = b0/(1.+pow(z/2.3,2.5)); //Eq. 4.3 bfunc4 = (1-bfunc)*(1-bfunc)*(1-bfunc)*(1-bfunc); //B^4(z) kg = 0.7*bfunc4*pow(cosmo->params.bcm_etab,-1.6); //Eq. 4.3 gf = bfunc/(1+pow(kh/kg,3.))+1.-bfunc; //Eq. 4.2, k in h/Mpc scomp = 1+(kh/cosmo->params.bcm_ks)*(kh/cosmo->params.bcm_ks); //Eq 4.5, k in h/Mpc fka = gf*scomp; return fka; } void ccl_cosmology_write_power_class_z(char *filename, ccl_cosmology * cosmo, double z, int * status) { struct precision pr; // for precision parameters struct background ba; // for cosmological background struct thermo th; // for thermodynamics struct perturbs pt; // for source functions struct transfers tr; // for transfer functions struct primordial pm; // for primordial spectra struct spectra sp; // for output spectra struct nonlinear nl; // for non-linear spectra struct lensing le; struct output op; struct file_content fc; ErrorMsg errmsg; // for error messages // generate file_content structure // CLASS configuration parameters will be passed through this structure, // to avoid writing and reading .ini files for every call int parser_length = 20; int init_arr[7]={0,0,0,0,0,0,0}; if (parser_init(&fc,parser_length,"none",errmsg) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: write_power_class_z(): parser init error:%s\n", errmsg); return; } ccl_fill_class_parameters(cosmo,&fc,parser_length, status); if (*status != CCL_ERROR_CLASS) ccl_run_class(cosmo, &fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status); if (*status == CCL_ERROR_CLASS) { //printed error message while running CLASS ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); return; } if (parser_free(&fc)== _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: write_power_class_z(): Error freeing CLASS parser\n"); ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); return; } FILE *f; f = fopen(filename,"w"); if (!f){ *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: write_power_class_z(): Error opening output file\n"); ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); fclose(f); return; } double psout_l,ic; int s=0; for (int i=0; i<sp.ln_k_size; i++) { s |= spectra_pk_at_k_and_z(&ba, &pm, &sp,exp(sp.ln_k[i]),z, &psout_l,&ic); fprintf(f,"%e %e\n",exp(sp.ln_k[i]),psout_l); } fclose(f); if(s) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: write_power_class_z(): Error writing CLASS power spectrum\n"); } ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); } typedef struct { double rsound; double zeq; double keq; double zdrag; double kSilk; double rsound_approx; double th2p7; double alphac; double alphab; double betac; double betab; double bnode; } eh_struct; static eh_struct *eh_struct_new(ccl_parameters *params) { ////// // Computes Eisenstein & Hu parameters for // P_k and r_sound // see astro-ph/9709112 for the relevant equations double OMh2,OBh2; double th2p7; eh_struct *eh=malloc(sizeof(eh_struct)); if(eh==NULL) return NULL; OMh2=params->Omega_m*params->h*params->h; //Cosmo params scaled by h^2 OBh2=params->Omega_b*params->h*params->h; th2p7=params->T_CMB/2.7; //This is Theta_{2.7} in E&Hu notation eh->th2p7=th2p7; //This is Theta_{2.7} in E&Hu notation eh->zeq=2.5E4*OMh2/pow(th2p7,4);// Eq 2 eh->keq=0.0746*OMh2/(params->h*th2p7*th2p7);//Eq. 3 //These group corresponds to Eq. 4 double b1,b2; b1=0.313*pow(OMh2,-0.419)*(1+0.607*pow(OMh2,0.674)); b2=0.238*pow(OMh2,0.223); eh->zdrag=1291*pow(OMh2,0.251)*(1+b1*pow(OBh2,b2))/(1+0.659*pow(OMh2,0.828)); //These are the baryon-to-photon ratios //at equality (Req) and drag (Rd) epochs //Eq. 5 double Req,Rd; Req=31.5*OBh2*1000./(eh->zeq*pow(th2p7,4)); Rd=31.5*OBh2*1000./((1+eh->zdrag)*pow(th2p7,4)); eh->rsound=2/(3*eh->keq)*sqrt(6/Req)* log((sqrt(1+Rd)+sqrt(Rd+Req))/(1+sqrt(Req))); //This is Eq. 7 (but in h/Mpc) eh->kSilk=1.6*pow(OBh2,0.52)*pow(OMh2,0.73)*(1+pow(10.4*OMh2,-0.95))/params->h; //These are Eqs. 11 double a1,a2,b_frac; a1=pow(46.9*OMh2,0.670)*(1+pow(32.1*OMh2,-0.532)); a2=pow(12.0*OMh2,0.424)*(1+pow(45.0*OMh2,-0.582)); b_frac=OBh2/OMh2; eh->alphac=pow(a1,-b_frac)*pow(a2,-b_frac*b_frac*b_frac); //These are Eqs. 12 double bb1,bb2; bb1=0.944/(1+pow(458*OMh2,-0.708)); bb2=pow(0.395*OMh2,-0.0266); eh->betac=1/(1+bb1*(pow(1-b_frac,bb2)-1)); double y=eh->zeq/(1+eh->zdrag); double sqy=sqrt(1+y); double gy=y*(-6*sqy+(2+3*y)*log((sqy+1)/(sqy-1))); //Eq 15 //Baryon suppression Eq. 14 eh->alphab=2.07*eh->keq*eh->rsound*pow(1+Rd,-0.75)*gy; //Baryon envelope shift Eq. 24 eh->betab=0.5+b_frac+(3-2*b_frac)*sqrt(pow(17.2*OMh2,2)+1); //Node shift parameter Eq. 23 eh->bnode=8.41*pow(OMh2,0.435); //Approx for the sound horizon, Eq. 26 eh->rsound_approx=params->h*44.5*log(9.83/OMh2)/ sqrt(1+10*pow(OBh2,0.75)); return eh; } static double tkEH_0(double keq,double k,double a,double b) { ////// // Eisentstein & Hu's Tk_0 // see astro-ph/9709112 for the relevant equations double q=k/(13.41*keq); //Eq 10 double c=14.2/a+386./(1+69.9*pow(q,1.08)); //Eq 20 double l=log(M_E+1.8*b*q); //Change of var for Eq 19 return l/(l+c*q*q); //Returns Eq 19 } static double tkEH_c(eh_struct *eh,double k) { ////// // Eisenstein & Hu's Tk_c // see astro-ph/9709112 for the relevant equations double f=1/(1+pow(k*eh->rsound/5.4,4)); //Eq 18 return f*tkEH_0(eh->keq,k,1,eh->betac)+ (1-f)*tkEH_0(eh->keq,k,eh->alphac,eh->betac); //Returns Eq 17 } static double jbes0(double x) { double jl; double ax2=x*x; if(ax2<1e-4) jl=1-ax2*(1-ax2/20.)/6.; else jl=sin(x)/x; return jl; } static double tkEH_b(eh_struct *eh,double k) { ////// // Eisenstein & Hu's Tk_b (Eq 21) // see astro-ph/9709112 for the relevant equations double x_bessel,part1,part2,jbes; double x=k*eh->rsound; //First term of Eq. 21 if(k==0) x_bessel=0; else { x_bessel=x*pow(1+eh->bnode*eh->bnode*eh->bnode/(x*x*x),-1./3.); } part1=tkEH_0(eh->keq,k,1,1)/(1+pow(x/5.2,2)); //Second term of Eq. 21 if(k==0) part2=0; else part2=eh->alphab/(1+pow(eh->betab/x,3))*exp(-pow(k/eh->kSilk,1.4)); return jbes0(x_bessel)*(part1+part2); } static double tsqr_EH(ccl_parameters *params,eh_struct * eh,double k,int wiggled) { ////// // Eisenstein & Hu's Tk_c // see astro-ph/9709112 for the relevant equations // Notice the last parameter in eh_power controls // whether to introduce wiggles (BAO) in the power spectrum. // We do this by default when obtaining the power spectrum. double tk; double b_frac=params->Omega_b/params->Omega_m; if(wiggled) //Case with baryons (Eq 8) tk=b_frac*tkEH_b(eh,k)+(1-b_frac)*tkEH_c(eh,k); else { //Zero baryon case (sec 4.2) double OMh2=params->Omega_m*params->h*params->h; // Compute Eq. 31 double alpha_gamma=1-0.328*log(431*OMh2)*b_frac+0.38*log(22.3*OMh2)*b_frac*b_frac; // Compute Eq. 30 double gamma_eff=params->Omega_m*params->h*(alpha_gamma+(1-alpha_gamma)/ (1+pow(0.43*k*eh->rsound_approx,4))); // Compute Eq. 28 (assume k in h/Mpc) double q=k*eh->th2p7*eh->th2p7/gamma_eff; // Compute Eqs. 29 double l0=log(2*M_E+1.8*q); double c0=14.2+731/(1+62.5*q); tk=l0/(l0+c0*q*q); //T_0 of Eq. 29 } return tk*tk; //Return T_0^2 } static double eh_power(ccl_parameters *params,eh_struct *eh,double k,int wiggled) { //Wavenumber in units of Mpc^-1 double kinvh=k/params->h; //Changed to h/Mpc return pow(k,params->n_s)*tsqr_EH(params,eh,kinvh,wiggled); } static void ccl_cosmology_compute_power_eh(ccl_cosmology * cosmo, int * status) { //These are the limits of the splining range cosmo->data.k_min_lin = ccl_splines->K_MIN; cosmo->data.k_min_nl = ccl_splines->K_MIN; cosmo->data.k_max_lin = ccl_splines->K_MAX; cosmo->data.k_max_nl = ccl_splines->K_MAX; double kmin = cosmo->data.k_min_lin; double kmax = ccl_splines->K_MAX; // Compute nk from number of decades and N_K = # k per decade double ndecades = log10(kmax) - log10(kmin); int nk = (int)ceil(ndecades*ccl_splines->N_K); // Compute na using predefined spline spacing double amin = ccl_splines->A_SPLINE_MINLOG_PK; double amax = ccl_splines->A_SPLINE_MAX; int na = ccl_splines->A_SPLINE_NA_PK + ccl_splines->A_SPLINE_NLOG_PK - 1; // Exit if sigma8 wasn't specified if (isnan(cosmo->params.sigma8)) { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_eh(): sigma8 was not set, but is required for E&H method\n"); return; } // New struct for EH parameters eh_struct *eh = eh_struct_new(&(cosmo->params)); if (eh == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_eh(): memory allocation error\n"); return; } // Build grids in k and a that P(k, a) will be evaluated on // NB: The x array is initially k, but will later be overwritten with log(k) double * x = ccl_log_spacing(kmin, kmax, nk); double * y = malloc(sizeof(double)*nk); double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK); double * y2d = malloc(nk * na * sizeof(double)); if (a==NULL || y==NULL || x==NULL || y2d==NULL) { free(eh);free(x);free(y); free(a);free(y2d); *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_eh(): memory allocation error\n"); return; } // Calculate P(k) on k grid. After this loop, x will contain log(k) and y // will contain log(pk) [which has not yet been normalized] // Notice the last parameter in eh_power controls // whether to introduce wiggles (BAO) in the power spectrum. // We do this by default. for (int i=0; i<nk; i++) { y[i] = log(eh_power(&cosmo->params, eh, x[i], 1)); x[i] = log(x[i]); } // Apply growth factor, D(a), to P(k) and store in 2D (k, a) array double gfac, g2; gsl_spline2d *log_power_lin = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na); for (int j = 0; j < na; j++) { gfac = ccl_growth_factor(cosmo, a[j], status); g2 = 2.*log(gfac); for (int i=0; i<nk; i++) { y2d[j*nk+i] = y[i]+g2; } // end loop over k } // end loop over a // Check that ccl_growth_factor didn't fail if (*status) { free(eh); free(x); free(y); free(a); free(y2d); gsl_spline2d_free(log_power_lin); return; } // Initialize a 2D spline over P(k, a) [which is still unnormalized by sigma8] int splinstatus = gsl_spline2d_init(log_power_lin, x, a, y2d,nk,na); if (splinstatus) { free(eh); free(x); free(y); free(a); free(y2d); gsl_spline2d_free(log_power_lin); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_eh(): Error creating log_power_lin spline\n"); return; } // Calculate sigma8 for the unnormalized P(k), using the standard // ccl_sigma8() function cosmo->data.p_lin = log_power_lin; cosmo->computed_power = true; // Temporarily set this to true double sigma8 = ccl_sigma8(cosmo, status); cosmo->computed_power = false; // Check that ccl_sigma8 didn't fail if (*status) { free(eh); free(x); free(y); free(a); free(y2d); gsl_spline2d_free(log_power_lin); return; } // Calculate normalization factor using computed value of sigma8, then // recompute P(k, a) using this normalization double log_normalization_factor = 2*(log(cosmo->params.sigma8) - log(sigma8)); for (int i=0; i < nk; i++) { y[i] += log_normalization_factor; } for (int j = 0; j < na; j++) { gfac = ccl_growth_factor(cosmo, a[j], status); g2 = 2.*log(gfac); for (int i=0; i<nk; i++) { y2d[j*nk+i] = y[i]+g2; // Replace previous values } // end k loop } // end a loop splinstatus = gsl_spline2d_init(log_power_lin, x, a, y2d, nk, na); if (splinstatus) { free(eh); free(x); free(y); free(a); free(y2d); gsl_spline2d_free(log_power_lin); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_eh(): Error creating log_power_lin spline\n"); return; } else cosmo->data.p_lin = log_power_lin; // Allocate a 2D spline for the nonlinear P(k) [which is just a copy of the // linear one for E&H] gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PNL_SPLINE_TYPE, nk, na); splinstatus = gsl_spline2d_init(log_power_nl, x, a, y2d, nk, na); if (splinstatus) { free(eh); free(x); free(y); free(a); free(y2d); gsl_spline2d_free(log_power_lin); gsl_spline2d_free(log_power_nl); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_eh(): Error creating log_power_nl spline\n"); return; } else cosmo->data.p_nl = log_power_nl; // Free temporary arrays free(eh); free(x); free(y); free(a); free(y2d); } /*------ ROUTINE: tsqr_BBKS ----- INPUT: ccl_parameters and k wavenumber in 1/Mpc TASK: provide the square of the BBKS transfer function with baryonic correction NOTE: Bardeen et al. (1986) as implemented in Sugiyama (1995) */ static double tsqr_BBKS(ccl_parameters * params, double k) { double q = k/(params->Omega_m*params->h*params->h*exp(-params->Omega_b*(1.0+pow(2.*params->h,.5)/params->Omega_m))); return pow(log(1.+2.34*q)/(2.34*q),2.0)/pow(1.+3.89*q+pow(16.1*q,2.0)+pow(5.46*q,3.0)+pow(6.71*q,4.0),0.5); } /*------ ROUTINE: bbks_power ----- INPUT: ccl_parameters and k wavenumber in 1/Mpc TASK: provide the BBKS power spectrum with baryonic correction at single k */ //Calculate Normalization see Cosmology Notes 8.105 (TODO: whose comment is this?) static double bbks_power(ccl_parameters * params, double k) { return pow(k,params->n_s)*tsqr_BBKS(params, k); } /*------ ROUTINE: ccl_cosmology_compute_bbks_power ----- INPUT: cosmology TASK: provide spline for the BBKS power spectrum with baryonic correction */ static void ccl_cosmology_compute_power_bbks(ccl_cosmology * cosmo, int * status) { //These are the limits of the splining range cosmo->data.k_min_lin=ccl_splines->K_MIN; cosmo->data.k_min_nl=ccl_splines->K_MIN; cosmo->data.k_max_lin=ccl_splines->K_MAX; cosmo->data.k_max_nl=ccl_splines->K_MAX; double kmin = cosmo->data.k_min_lin; double kmax = ccl_splines->K_MAX; //Compute nk from number of decades and N_K = # k per decade double ndecades = log10(kmax) - log10(kmin); int nk = (int)ceil(ndecades*ccl_splines->N_K); double amin = ccl_splines->A_SPLINE_MINLOG_PK; double amax = ccl_splines->A_SPLINE_MAX; int na = ccl_splines->A_SPLINE_NA_PK+ccl_splines->A_SPLINE_NLOG_PK-1; // Exit if sigma8 wasn't specified if (isnan(cosmo->params.sigma8)) { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_bbks(): sigma8 not set, required for BBKS\n"); return; //Return without anything to free } // The x array is initially k, but will later // be overwritten with log(k) double * x = ccl_log_spacing(kmin, kmax, nk); double * y = malloc(sizeof(double)*nk); double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK); double * y2d = malloc(nk * na * sizeof(double)); //If error, store status, we will free later if (a==NULL||y==NULL|| x==NULL || y2d==0) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_bbks(): memory allocation error\n"); } //Status flags int splinstatus=0; if(!*status){ // After this loop x will contain log(k) for (int i=0; i<nk; i++) { y[i] = log(bbks_power(&cosmo->params, x[i])); x[i] = log(x[i]); } for (int j = 0; j < na; j++) { double gfac = ccl_growth_factor(cosmo,a[j], status); double g2 = 2.*log(gfac); for (int i=0; i<nk; i++) { y2d[j*nk+i] = y[i]+g2; } } } if(!*status){ // Initialize a 2D spline over P(k, a) [which is still unnormalized by sigma8] gsl_spline2d * log_power_lin_unnorm = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na); splinstatus = gsl_spline2d_init(log_power_lin_unnorm, x, a, y2d,nk,na); //If not, proceed if (!splinstatus) { cosmo->data.p_lin=log_power_lin_unnorm; cosmo->computed_power=true; } else { gsl_spline2d_free(log_power_lin_unnorm); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo,"ccl_power.c: ccl_cosmology_compute_power_bbks(): Error creating log_power_lin spline\n"); } } if(*status){ free(x); free(y); free(a); free(y2d); return; } // Calculate sigma8 for the unnormalized P(k), using the standard // ccl_sigma8() function double sigma8 = ccl_sigma8(cosmo,status); cosmo->computed_power=false; // Check that ccl_sigma8 didn't fail if (!*status) { // Calculate normalization factor using computed value of sigma8, then // recompute P(k, a) using this normalization double log_normalization_factor = 2*(log(cosmo->params.sigma8) - log(sigma8)); for (int i=0; i<nk; i++) { y[i] += log_normalization_factor; } for (int j = 0; j < na; j++) { double gfac = ccl_growth_factor(cosmo,a[j], status); double g2 = 2.*log(gfac); for (int i=0; i<nk; i++) { y2d[j*nk+i] = y[i]+g2; } } } //Check growth didn't fail if (!*status) { gsl_spline2d * log_power_lin = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na); splinstatus = gsl_spline2d_init(log_power_lin, x, a, y2d,nk,na); if (!splinstatus) { cosmo->data.p_lin=log_power_lin; } else { gsl_spline2d_free(log_power_lin); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo,"ccl_power.c: ccl_cosmology_compute_power_bbks(): Error creating log_power_lin spline\n"); } } if(!*status){ // Allocate a 2D spline for the nonlinear P(k) //[which is just a copy of the linear one for BBKS] gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PNL_SPLINE_TYPE, nk,na); splinstatus = gsl_spline2d_init(log_power_nl, x, a, y2d,nk,na); if (!splinstatus) { cosmo->data.p_nl = log_power_nl; } else { gsl_spline2d_free(log_power_nl); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_bbks(): Error creating log_power_nl spline\n"); } } free(x); free(y); free(a); free(y2d); return; } /*------ ROUTINE: ccl_cosmology_compute_power_emu ----- INPUT: cosmology TASK: provide spline for the emulated power spectrum from Cosmic EMU */ static void ccl_cosmology_compute_power_emu(ccl_cosmology * cosmo, int * status) { struct precision pr; // for precision parameters struct background ba; // for cosmological background struct thermo th; // for thermodynamics struct perturbs pt; // for source functions struct transfers tr; // for transfer functions struct primordial pm; // for primordial spectra struct spectra sp; // for output spectra struct nonlinear nl; // for non-linear spectra struct lensing le; struct output op; struct file_content fc; double Omeganuh2_eq; double w0wacomb = -cosmo->params.w0 - cosmo->params.wa; ErrorMsg errmsg; // for error messages // generate file_content structure // Configuration parameters will be passed through this structure, // to avoid writing and reading .ini files for every call int parser_length = 20; int init_arr[7]={0,0,0,0,0,0,0}; //Check initialization if (parser_init(&fc,parser_length,"none",errmsg) == _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): parser init error:%s\n", errmsg); } // Check ranges to see if the cosmology is valid if((cosmo->params.h<0.55) || (cosmo->params.h>0.85)){ *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): h is outside allowed range\n"); } if(w0wacomb<8.1e-3){ //0.3^4 *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): w0 and wa do not satisfy the emulator bound\n"); } if(cosmo->params.Omega_n_mass*cosmo->params.h*cosmo->params.h>0.01){ *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): Omega_nu does not satisfy the emulator bound\n"); } // Check to see if sigma8 was defined if(isnan(cosmo->params.sigma8)){ *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): sigma8 is not defined; specify sigma8 instead of A_s\n"); } //If one of the previous test was unsuccessful, quit: if(*status) return; // Check if the cosmology has been set up with equal neutrino masses for the emulator // If not, check if the user has forced redistribution of masses and if so do this. if(cosmo->params.N_nu_mass>0) { if (cosmo->config.emulator_neutrinos_method == ccl_emu_strict){ if (cosmo->params.N_nu_mass==3){ //double diff1 = pow((cosmo->params.mnu[0] - cosmo->params.mnu[1]) * (cosmo->params.mnu[0] - cosmo->params.mnu[1]), 0.5); //double diff2 = pow((cosmo->params.mnu[1] - cosmo->params.mnu[2]) * (cosmo->params.mnu[1] - cosmo->params.mnu[2]), 0.5); //double diff3 = pow((cosmo->params.mnu[2] - cosmo->params.mnu[0]) * (cosmo->params.mnu[2] - cosmo->params.mnu[0]), 0.5); //if (diff1>1e-12 || diff2>1e-12 || diff3>1e-12){ if (cosmo->params.mnu[0] != cosmo->params.mnu[1] || cosmo->params.mnu[0] != cosmo->params.mnu[2] || cosmo->params.mnu[1] != cosmo->params.mnu[2]){ *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): In the default configuration, you must pass a list of 3 equal neutrino masses or pass a sum and set mnu_type = ccl_mnu_sum_equal. If you wish to over-ride this, set config->emulator_neutrinos_method = 'ccl_emu_equalize'. This will force the neutrinos to be of equal mass but will result in internal inconsistencies.\n"); } } else if (cosmo->params.N_nu_mass!=3){ *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): In the default configuration, you must pass a list of 3 equal neutrino masses or pass a sum and set mnu_type = ccl_mnu_sum_equal. If you wish to over-ride this, set config->emulator_neutrinos_method = 'ccl_emu_equalize'. This will force the neutrinos to be of equal mass but will result in internal inconsistencies.\n"); } } else if (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize){ // Reset the masses to equal double mnu_eq[3] = {cosmo->params.sum_nu_masses / 3., cosmo->params.sum_nu_masses / 3., cosmo->params.sum_nu_masses / 3.}; Omeganuh2_eq = ccl_Omeganuh2(1.0, 3, mnu_eq, cosmo->params.T_CMB, cosmo->data.accelerator, status); } } else { if(fabs(cosmo->params.N_nu_rel - 3.04)>1.e-6){ *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): Set Neff = 3.04 for cosmic emulator predictions in absence of massive neutrinos.\n"); } } if(!*status){ // Prepare to run CLASS for linear scales ccl_fill_class_parameters(cosmo,&fc,parser_length, status); } if (!*status){ ccl_run_class(cosmo, &fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status); } if (*status){ ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); if (parser_free(&fc)== _FAILURE_) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): Error freeing CLASS parser\n"); } return; } //These are the limits of the splining range cosmo->data.k_min_lin=2*exp(sp.ln_k[0]); cosmo->data.k_max_lin=ccl_splines->K_MAX_SPLINE; //CLASS calculations done - now allocate CCL splines double kmin = cosmo->data.k_min_lin; double kmax = ccl_splines->K_MAX_SPLINE; //Compute nk from number of decades and N_K = # k per decade double ndecades = log10(kmax) - log10(kmin); int nk = (int)ceil(ndecades*ccl_splines->N_K); double amin = ccl_splines->A_SPLINE_MINLOG_PK; double amax = ccl_splines->A_SPLINE_MAX; int na = ccl_splines->A_SPLINE_NA_PK+ccl_splines->A_SPLINE_NLOG_PK-1; // The x array is initially k, but will later // be overwritten with log(k) double * x = ccl_log_spacing(kmin, kmax, nk); double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK); double * y2d_lin = malloc(nk * na * sizeof(double)); if (a==NULL|| x==NULL || y2d_lin==NULL) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_class(): memory allocation error\n"); } if(!*status){ // After this loop x will contain log(k), y will contain log(P_nl), z will contain log(P_lin) // all in Mpc, not Mpc/h units! double psout_l,ic; int s=0; for (int i=0; i<nk; i++) { for (int j = 0; j < na; j++) { //The 2D interpolation routines access the function values y_{k_ia_j} with the following ordering: //y_ij = y2d[j*N_k + i] //with i = 0,...,N_k-1 and j = 0,...,N_a-1. s |= spectra_pk_at_k_and_z(&ba, &pm, &sp,x[i],1./a[j]-1., &psout_l,&ic); y2d_lin[j*nk+i] = log(psout_l); } x[i] = log(x[i]); } if(s) { *status = CCL_ERROR_CLASS; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): Error computing CLASS power spectrum\n"); } } if(!*status){ gsl_spline2d * log_power = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na); int pwstatus = gsl_spline2d_init(log_power, x, a, y2d_lin,nk,na); if (!pwstatus) { cosmo->data.p_lin = log_power; } else { gsl_spline2d_free(log_power); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): Error creating log_power spline\n"); } } if(*status){ //Linear power spectrum failed, so quit. free(x); free(a); free(y2d_lin); ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status); return; } //Now start the NL computation with the emulator //These are the limits of the splining range cosmo->data.k_min_nl=K_MIN_EMU; cosmo->data.k_max_nl=K_MAX_EMU; amin = A_MIN_EMU; //limit of the emulator amax = ccl_splines->A_SPLINE_MAX; na = ccl_splines->A_SPLINE_NA_PK; // The x array is initially k, but will later // be overwritten with log(k) double * logx= malloc(NK_EMU*sizeof(double)); double * y; double * xstar = malloc(9 * sizeof(double)); double * aemu = ccl_linear_spacing(amin,amax, na); double * y2d = malloc(NK_EMU * na * sizeof(double)); if (aemu==NULL || y2d==NULL || logx==NULL || xstar==NULL){ *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): memory allocation error\n"); } if(!*status){ //For each redshift: for (int j = 0; j < na; j++){ //Turn cosmology into xstar: xstar[0] = (cosmo->params.Omega_c+cosmo->params.Omega_b)*cosmo->params.h*cosmo->params.h; xstar[1] = cosmo->params.Omega_b*cosmo->params.h*cosmo->params.h; xstar[2] = cosmo->params.sigma8; xstar[3] = cosmo->params.h; xstar[4] = cosmo->params.n_s; xstar[5] = cosmo->params.w0; xstar[6] = cosmo->params.wa; if ((cosmo->params.N_nu_mass>0) && (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize)){ xstar[7] = Omeganuh2_eq; } else { xstar[7] = cosmo->params.Omega_n_mass*cosmo->params.h*cosmo->params.h; } xstar[8] = 1./aemu[j]-1; //Need to have this here because otherwise overwritten by emu in each loop //Call emulator at this redshift ccl_pkemu(xstar,&y, status, cosmo); if (y == NULL){ *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): Error obtaining emulator predictions\n"); } for (int i=0; i<NK_EMU; i++){ logx[i] = log(mode[i]); y2d[j*NK_EMU+i] = log(y[i]); } } } if(!*status){ gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, NK_EMU,na); int splinstatus = gsl_spline2d_init(log_power_nl, logx, aemu, y2d,NK_EMU,na); //Note the minimum k of the spline is different from the linear one. if (!splinstatus){ cosmo->data.p_nl = log_power_nl; } else { gsl_spline2d_free(log_power_nl); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power_emu(): Error creating log_power spline\n"); } } free(x); free(a); free(y); free(xstar); free(logx); free(aemu); free(y2d_lin); free(y2d); } /*------ ROUTINE: ccl_cosmology_compute_power ----- INPUT: ccl_cosmology * cosmo TASK: compute power spectrum */ void ccl_cosmology_compute_power(ccl_cosmology * cosmo, int * status) { if (cosmo->computed_power) return; switch(cosmo->config.transfer_function_method){ case ccl_bbks: ccl_cosmology_compute_power_bbks(cosmo,status); break; case ccl_eisenstein_hu: ccl_cosmology_compute_power_eh(cosmo,status); break; case ccl_boltzmann_class: ccl_cosmology_compute_power_class(cosmo,status); break; case ccl_emulator: ccl_cosmology_compute_power_emu(cosmo,status); break; default: *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_cosmology_compute_power(): Unknown or non-implemented transfer function method: %d \n", cosmo->config.transfer_function_method); } ccl_check_status(cosmo,status); if (*status==0){ cosmo->computed_power = true; } return; } /*------ ROUTINE: ccl_power_extrapol_highk ----- INPUT: ccl_cosmology * cosmo, a, k [1/Mpc] TASK: extrapolate power spectrum at high k */ static double ccl_power_extrapol_highk(ccl_cosmology * cosmo, double k, double a, gsl_spline2d * powerspl, double kmax_spline, int * status) { double log_p_1; double deltak=1e-2; //step for numerical derivative; double deriv_pk_kmid,deriv2_pk_kmid; double lkmid; double lpk_kmid; lkmid = log(kmax_spline)-2*deltak; int gslstatus = gsl_spline2d_eval_e(powerspl, lkmid,a,NULL ,NULL ,&lpk_kmid); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_power_extrapol_highk():"); *status = CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_power_extrapol_highk(): Spline evaluation error\n"); return NAN; } //GSL derivatives gslstatus = gsl_spline2d_eval_deriv_x_e (powerspl, lkmid, a, NULL,NULL,&deriv_pk_kmid); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_power_extrapol_highk():"); *status = CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_power_extrapol_highk(): Spline evaluation error\n"); return NAN; } gslstatus = gsl_spline2d_eval_deriv_xx_e (powerspl, lkmid, a, NULL,NULL,&deriv2_pk_kmid); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_power_extrapol_highk():"); *status = CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_power_extrapol_highk(): Spline evaluation error\n"); return NAN; } log_p_1=lpk_kmid+deriv_pk_kmid*(log(k)-lkmid)+deriv2_pk_kmid/2.*(log(k)-lkmid)*(log(k)-lkmid); return log_p_1; } /*------ ROUTINE: ccl_power_extrapol_lowk ----- INPUT: ccl_cosmology * cosmo, a, k [1/Mpc] TASK: extrapolate power spectrum at low k */ static double ccl_power_extrapol_lowk(ccl_cosmology * cosmo, double k, double a, gsl_spline2d * powerspl, double kmin_spline, int * status) { double log_p_1; double deltak=1e-2; //safety step double lkmin=log(kmin_spline)+deltak; double lpk_kmin; int gslstatus = gsl_spline2d_eval_e(powerspl,lkmin,a,NULL,NULL,&lpk_kmin); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_power_extrapol_lowk():"); *status=CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo,"ccl_power.c: ccl_power_extrapol_lowk(): Spline evaluation error\n"); return NAN; } return lpk_kmin+cosmo->params.n_s*(log(k)-lkmin); } /*------ ROUTINE: ccl_linear_matter_power ----- INPUT: ccl_cosmology * cosmo, k [1/Mpc],a TASK: compute the linear power spectrum at a given redshift by rescaling using the growth function */ double ccl_linear_matter_power(ccl_cosmology * cosmo, double k, double a, int * status) { if ((cosmo->config.transfer_function_method == ccl_emulator) && (a<A_MIN_EMU)){ *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: the cosmic emulator cannot be used above a=%f\n",A_MIN_EMU); return NAN; } if (!cosmo->computed_power) ccl_cosmology_compute_power(cosmo, status); // Return if compilation failed //if (cosmo->data.p_lin == NULL) return NAN; if (!cosmo->computed_power) return NAN; double log_p_1; int gslstatus; if(a<ccl_splines->A_SPLINE_MINLOG_PK) { //Extrapolate linearly at high redshift double pk0=ccl_linear_matter_power(cosmo,k,ccl_splines->A_SPLINE_MINLOG_PK,status); double gf=ccl_growth_factor(cosmo,a,status)/ccl_growth_factor(cosmo,ccl_splines->A_SPLINE_MINLOG_PK,status); return pk0*gf*gf; } if (*status!=CCL_ERROR_INCONSISTENT){ if(k<=cosmo->data.k_min_lin) { log_p_1=ccl_power_extrapol_lowk(cosmo,k,a,cosmo->data.p_lin,cosmo->data.k_min_lin,status); return exp(log_p_1); } else if(k<cosmo->data.k_max_lin){ gslstatus = gsl_spline2d_eval_e(cosmo->data.p_lin, log(k), a,NULL,NULL,&log_p_1); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_linear_matter_power():"); *status = CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_linear_matter_power(): Spline evaluation error\n"); return NAN; } else { return exp(log_p_1); } } else { //Extrapolate using log derivative log_p_1 = ccl_power_extrapol_highk(cosmo,k,a,cosmo->data.p_lin,cosmo->data.k_max_lin,status); return exp(log_p_1); } } return exp(log_p_1); } /*------ ROUTINE: ccl_nonlin_matter_power ----- INPUT: ccl_cosmology * cosmo, a, k [1/Mpc] TASK: compute the nonlinear power spectrum at a given redshift */ double ccl_nonlin_matter_power(ccl_cosmology * cosmo, double k, double a, int *status) { double log_p_1, pk; switch(cosmo->config.matter_power_spectrum_method) { //If the matter PS specified was linear, then do the linear compuation case ccl_linear: return ccl_linear_matter_power(cosmo,k,a,status); case ccl_halofit: if (!cosmo->computed_power) ccl_cosmology_compute_power(cosmo, status); if (cosmo->data.p_nl == NULL) return NAN; // Return if computation failed if(a<ccl_splines->A_SPLINE_MINLOG_PK) { //Extrapolate linearly at high redshift double pk0=ccl_nonlin_matter_power(cosmo,k,ccl_splines->A_SPLINE_MINLOG_PK,status); double gf=ccl_growth_factor(cosmo,a,status)/ccl_growth_factor(cosmo,ccl_splines->A_SPLINE_MINLOG_PK,status); return pk0*gf*gf; } break; case ccl_emu: if ((cosmo->config.transfer_function_method == ccl_emulator) && (a<A_MIN_EMU)){ *status = CCL_ERROR_EMULATOR_BOUND; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: the cosmic emulator cannot be used above z=2\n"); return NAN; } // Compute power spectrum if needed; return if computation failed if (!cosmo->computed_power){ ccl_cosmology_compute_power(cosmo,status); } if (cosmo->data.p_nl == NULL) return NAN; break; default: ccl_raise_warning( CCL_ERROR_NOT_IMPLEMENTED, "config.matter_power_spectrum_method = %d not yet supported " "continuing with linear power spectrum\n", cosmo->config.matter_power_spectrum_method); cosmo->config.matter_power_spectrum_method=ccl_linear; return ccl_linear_matter_power(cosmo,k,a,status); } // end switch // if we get here, try to evaluate the power spectrum // we need to account for bounds below and above if (k <= cosmo->data.k_min_nl) { // we assume no baryonic effects below k_min_nl log_p_1 = ccl_power_extrapol_lowk(cosmo, k, a, cosmo->data.p_nl, cosmo->data.k_min_nl, status); return exp(log_p_1); } if (k < cosmo->data.k_max_nl) { int gslstatus = gsl_spline2d_eval_e(cosmo->data.p_nl, log(k), a, NULL ,NULL, &log_p_1); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_nonlin_matter_power():"); *status = CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_nonlin_matter_power(): Spline evaluation error\n"); return NAN; } else { pk = exp(log_p_1); } } else { // Extrapolate NL regime using log derivative log_p_1 = ccl_power_extrapol_highk(cosmo, k, a, cosmo->data.p_nl, cosmo->data.k_max_nl, status); pk = exp(log_p_1); } // Add baryonic correction if (cosmo->config.baryons_power_spectrum_method == ccl_bcm) { int pwstatus = 0; double fbcm = ccl_bcm_model_fka(cosmo, k, a, &pwstatus); pk *= fbcm; if (pwstatus) { *status = CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_power.c: ccl_nonlin_matter_power(): Error in BCM correction\n"); return NAN; } } return pk; } // Params for sigma(R) integrand typedef struct { ccl_cosmology *cosmo; double R; int* status; } SigmaR_pars; typedef struct { ccl_cosmology *cosmo; double R; int* status; } SigmaV_pars; /* --------- ROUTINE: w_tophat --------- INPUT: kR, ususally a wavenumber multiplied by a smoothing radius TASK: Output W(x)=[sin(x)-x*cos(x)]*(3/x)^3 */ static double w_tophat(double kR) { double w; double kR2 = kR*kR; // This is the Maclaurin expansion of W(x)=[sin(x)-xcos(x)]*(3/x)**3 to O(x^7), with x=kR. // Necessary numerically because at low x W(x) relies on the fine cancellation of two terms if(kR<0.1) { w = 1. + kR2*(-0.1 + kR2*(0.003561429 + kR2*(-6.61376e-5 + kR2*(7.51563e-7)))); /*w =1.-0.1*kR*kR+0.003571429*kR*kR*kR*kR -6.61376E-5*kR*kR*kR*kR*kR*kR +7.51563E-7*kR*kR*kR*kR*kR*kR*kR*kR;*/ } else w = 3.*(sin(kR) - kR*cos(kR))/(kR2*kR); return w; } // Integrand for sigmaR integral static double sigmaR_integrand(double lk,void *params) { SigmaR_pars *par=(SigmaR_pars *)params; double k=pow(10.,lk); double pk=ccl_linear_matter_power(par->cosmo,k, 1.,par->status); double kR=k*par->R; double w = w_tophat(kR); return pk*k*k*k*w*w; } // Integrand for sigmaV integral static double sigmaV_integrand(double lk,void *params) { SigmaV_pars *par=(SigmaV_pars *)params; double k=pow(10.,lk); double pk=ccl_linear_matter_power(par->cosmo,k, 1.,par->status); double kR=k*par->R; double w = w_tophat(kR); return pk*k*w*w/3.0; } /* --------- ROUTINE: ccl_sigmaR --------- INPUT: cosmology, comoving smoothing radius, scale factor TASK: compute sigmaR, the variance in the *linear* density field smoothed with a tophat filter of comoving size R */ double ccl_sigmaR(ccl_cosmology *cosmo,double R,double a,int *status) { SigmaR_pars par; par.status = status; par.cosmo=cosmo; par.R=R; gsl_integration_cquad_workspace *workspace=gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION); gsl_function F; F.function=&sigmaR_integrand; F.params=&par; double sigma_R; int gslstatus = gsl_integration_cquad(&F, log10(ccl_splines->K_MIN), log10(ccl_splines->K_MAX), 0.0, ccl_gsl->INTEGRATION_SIGMAR_EPSREL, workspace,&sigma_R,NULL,NULL); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_sigmaR():"); *status |= gslstatus; } gsl_integration_cquad_workspace_free(workspace); return sqrt(sigma_R*M_LN10/(2*M_PI*M_PI))*ccl_growth_factor(cosmo, a, status); } /* --------- ROUTINE: ccl_sigmaV --------- INPUT: cosmology, comoving smoothing radius, scale factor TASK: compute sigmaV, the variance in the *linear* displacement field smoothed with a tophat filter of comoving size R The linear displacement field is the gradient of the linear density field */ double ccl_sigmaV(ccl_cosmology *cosmo,double R,double a,int *status) { SigmaV_pars par; par.status = status; par.cosmo=cosmo; par.R=R; gsl_integration_cquad_workspace *workspace=gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION); gsl_function F; F.function=&sigmaV_integrand; F.params=&par; double sigma_V; int gslstatus = gsl_integration_cquad(&F, log10(ccl_splines->K_MIN), log10(ccl_splines->K_MAX), 0.0, ccl_gsl->INTEGRATION_SIGMAR_EPSREL, workspace,&sigma_V,NULL,NULL); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_power.c: ccl_sigmaV():"); *status |= gslstatus; } gsl_integration_cquad_workspace_free(workspace); return sqrt(sigma_V*M_LN10/(2*M_PI*M_PI))*ccl_growth_factor(cosmo, a, status); } /* --------- ROUTINE: ccl_sigma8 --------- INPUT: cosmology TASK: compute sigma8, the variance in the *linear* density field at a=1 smoothed with a tophat filter of comoving size 8 Mpc/h */ double ccl_sigma8(ccl_cosmology *cosmo, int *status) { return ccl_sigmaR(cosmo,8/cosmo->params.h, 1.,status); }
{ "alphanum_fraction": 0.6798442794, "avg_line_length": 34.4705221786, "ext": "c", "hexsha": "dc94d25ad58a1729b94c81c6c1638c3c9b2caaeb", "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": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_path": "src/ccl_power.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "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": "vrastil/CCL", "max_issues_repo_path": "src/ccl_power.c", "max_line_length": 412, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_path": "src/ccl_power.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 19808, "size": 61392 }
/** * @file matrix.i * @brief Wrapper for GSL matrix objects. * @author John McDonough, Kenichi Kumatani */ #ifndef GSLMATRIX_H #define GSLMATRIX_H #include <gsl/gsl_matrix.h> #define GSL_MATRIX_NROWS(x) ((x)->size2) #define GSL_MATRIX_NCOLS(x) ((x)->size2) gsl_matrix_float* gsl_matrix_float_resize(gsl_matrix_float* m, size_t size1, size_t size2); void gsl_matrix_float_set_cosine(gsl_matrix_float* m, size_t i, size_t j, int type); gsl_matrix_float* gsl_matrix_float_load(gsl_matrix_float* m, const char* filename, bool old = false); gsl_vector_float* gsl_vector_float_load(gsl_vector_float* m, const char* filename, bool old = false); #endif
{ "alphanum_fraction": 0.7705167173, "avg_line_length": 27.4166666667, "ext": "h", "hexsha": "1fafaf1d67dc9a5867daff2a853536be54a8634f", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/matrix/gslmatrix.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/matrix/gslmatrix.h", "max_line_length": 101, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/matrix/gslmatrix.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 181, "size": 658 }
// Copyright 2011-2021 GameParadiso, Inc. All Rights Reserved. #pragma once #include <map> #include <unordered_map> #include <ranges> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/ext/matrix_transform.hpp> #include <glm/ext/matrix_clip_space.hpp> #include <glm/ext/scalar_constants.hpp> #include <gsl/gsl> using namespace std::string_literals;
{ "alphanum_fraction": 0.76, "avg_line_length": 21.25, "ext": "h", "hexsha": "704bd572205d273c6ffd942c467acd9b46fa4a86", "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": "81d620e95fa677bde0dcc5f8e562500157402aa1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "noirhero/MemoryChunk", "max_forks_repo_path": "pch.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "81d620e95fa677bde0dcc5f8e562500157402aa1", "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": "noirhero/MemoryChunk", "max_issues_repo_path": "pch.h", "max_line_length": 62, "max_stars_count": null, "max_stars_repo_head_hexsha": "81d620e95fa677bde0dcc5f8e562500157402aa1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "noirhero/MemoryChunk", "max_stars_repo_path": "pch.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 111, "size": 425 }
/// /// @file /// /// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University /// @author Lars Karlsson (larsk@cs.umu.se), Umeå University /// /// @internal LICENSE /// /// Copyright (c) 2019-2020, Umeå Universitet /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// 1. Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// /// 2. Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// 3. Neither the name of the copyright holder nor the names of its /// contributors may be used to endorse or promote products derived from this /// software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE /// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE /// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR /// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF /// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN /// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) /// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// #include <starneig_config.h> #include <starneig/configuration.h> #include "node_internal.h" #ifdef STARNEIG_ENABLE_MPI #include "../mpi/node_internal.h" #include "../mpi/distr_matrix_internal.h" #endif #include "common.h" #include "scratch.h" #include <starneig/node.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <hwloc.h> #include <starpu.h> #ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND #include <mkl.h> #endif #if defined(OPENBLAS_SET_NUM_THREADS_FOUND) || \ defined(GOTO_SET_NUM_THREADS_FOUND) #include <cblas.h> #endif static struct { /// initialization flag bool is_init; // initialization flags starneig_flag_t flags; /// library mode enum starneig_mode mode; /// blas mode enum starneig_blas_mode blas_mode; // original blas thread count int blas_threads_original; // StarPU worker bind mask unsigned starpu_workers_bindid[STARPU_NMAXWORKERS]; // total number of available cpu cores int avail_cores; // total number of available gpus int avail_gpus; // number of used cpu cores int used_cores; // total number of used gpus int used_gpus; } state = { .is_init = false, .flags = STARNEIG_DEFAULT, .mode = STARNEIG_MODE_OFF, .blas_mode = STARNEIG_BLAS_MODE_ORIGINAL, .blas_threads_original = -1, .avail_cores = 0, .avail_gpus = 0, .used_cores = 0, .used_gpus = 0 }; /// /// @brief Sets the number of BLAS threads. /// /// @param[in] threads /// Number of BLAS threads. /// /// @return Previous BLAS thread count (can be 0). /// static int set_blas_threads(int threads) { starneig_verbose("Setting BLAS thread count to %d.", threads); #ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND return mkl_set_num_threads_local(threads); #elif defined(OPENBLAS_SET_NUM_THREADS_FOUND) int old = openblas_get_num_threads(); openblas_set_num_threads(threads); return old; #elif defined(GOTO_SET_NUM_THREADS_FOUND) goto_set_num_threads(threads); return 1; #else return 1; #endif } /// /// @brief Sets the BLAS mode. /// /// @param[in] mode /// BLAS mode. /// static void set_blas_mode(enum starneig_blas_mode mode) { int old = -1; switch (mode) { case STARNEIG_BLAS_MODE_PARALLEL: starneig_verbose("Switching to parallel BLAS."); old = set_blas_threads(state.used_cores); break; case STARNEIG_BLAS_MODE_SEQUENTIAL: starneig_verbose("Switching to sequential BLAS."); old = set_blas_threads(1); break; default: starneig_verbose("Restoring BLAS mode."); if (0 <= state.blas_threads_original) set_blas_threads(state.blas_threads_original); state.blas_threads_original = -1; } if (state.blas_mode == STARNEIG_BLAS_MODE_ORIGINAL && 0 <= old) state.blas_threads_original = old; state.blas_mode = mode; } #ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND /// /// @brief Sets the per thread BLAS thread count to 1. /// /// @param[in] arg /// An unused argument. /// static void set_worker_blas_mode(void *arg) { mkl_set_num_threads_local(1); } #endif /// /// @brief Reconfigures the node. /// /// @param[in] cores /// Number of CPU cores to use. /// /// @param[in] gpus /// Number of GPUs to use. /// /// @param[in] mode /// Library mode. /// /// @param[in] blas_mode /// BLAS mode. /// #define CONFIGURE(cores, gpus, mode, blas_mode) \ node_configure(cores, gpus, mode, blas_mode, __func__) /// /// @brief Reconfigures the node. /// /// @param[in] cores /// Number of CPU cores to use. /// /// @param[in] gpus /// Number of GPUs to use. /// /// @param[in] mode /// Library mode. /// /// @param[in] blas_mode /// BLAS mode /// /// @param[in] func /// Name of the calling function. /// static void node_configure( int cores, int gpus, enum starneig_mode mode, enum starneig_blas_mode blas_mode, char const *func) { #ifndef STARNEIG_ENABLE_MPI if (mode == STARNEIG_MODE_DM) starneig_fatal_error("StarPU was compiled without MPI support."); #endif if (cores == state.used_cores && gpus == state.used_gpus && mode == state.mode && blas_mode == state.blas_mode) return; starneig_verbose("Reconfiguring the library."); if (cores == state.used_cores && gpus == state.used_gpus && mode == state.mode) { set_blas_mode(blas_mode); return; } // // shutdown StarPU // if (state.mode != STARNEIG_MODE_OFF) { starneig_node_resume_starpu(); #ifdef STARNEIG_ENABLE_CUDA if (0 < state.used_gpus) { starneig_verbose("Shutting down cuBLAS."); starpu_cublas_shutdown(); } #endif starneig_verbose("Shutting down StarPU."); starneig_scratch_unregister(); #ifdef STARNEIG_ENABLE_MPI starneig_mpi_cache_clear(); if (state.mode == STARNEIG_MODE_DM && state.flags & STARNEIG_AWAKE_MPI_WORKER) starneig_mpi_stop_persistent_starpumpi(); #endif starpu_task_wait_for_all(); starpu_shutdown(); } // // set the number of CPU cores // if (cores == 0) starneig_fatal_error("At least one CPU core must be selected."); if (cores < 0) { state.used_cores = state.avail_cores; } else { state.used_cores = MIN(cores, state.avail_cores); if (state.avail_cores < cores) starneig_warning( "Failed to acquire the desired number of CPU cores. " "Acquired %d.", state.used_cores); } // // set the number of GPUs // if (gpus < 0) { state.used_gpus = state.avail_gpus; } else { #ifdef STARNEIG_ENABLE_CUDA state.used_gpus = MIN(gpus, state.avail_gpus); if (state.avail_gpus < gpus) starneig_warning( "Failed to acquire the desired number of CUDA devices. " "Acquired %d.", state.used_gpus); #else if (0 < gpus) starneig_warning("StarPU was compiled without CUDA support."); #endif } // // set BLAS threads // set_blas_mode(blas_mode); // // set mode // state.mode = mode; if (state.mode == STARNEIG_MODE_OFF) return; // // create StarPU configuration // starneig_verbose("Configuring StarPU."); struct starpu_conf conf; starpu_conf_init(&conf); int cpu_workers = state.used_cores; if (0 < state.used_gpus) cpu_workers -= state.used_gpus; if (state.mode == STARNEIG_MODE_DM) cpu_workers--; conf.ncpus = MAX(1, cpu_workers); conf.ncuda = state.used_gpus; conf.nopencl = 0; //#if 1 < STARPU_MAJOR_VERSION || 2 < STARPU_MINOR_VERSION if (getenv("STARPU_WORKERS_CPUID") == NULL) conf.use_explicit_workers_bindid = 1; //#endif memcpy(conf.workers_bindid, state.starpu_workers_bindid, sizeof(state.starpu_workers_bindid)); #ifdef STARNEIG_ENABLE_CUDA if (0 < state.used_gpus) conf.sched_policy_name = "dmdas"; else #endif conf.sched_policy_name = "prio"; // // setup FXT // if (state.flags & STARNEIG_FXT_DISABLE) { starneig_verbose("Disabling FXT traces."); starpu_fxt_autostart_profiling(0); } else { char const *starpu_fxt_trace = getenv("STARPU_FXT_TRACE"); if (starpu_fxt_trace == NULL || atoi(starpu_fxt_trace) != 0) { starneig_verbose("Keeping FXT traces enabled."); starpu_fxt_autostart_profiling(1); } } // // initialize StarPU // starneig_verbose("Starting StarPU."); unsigned seed = rand(); int ret = starpu_init(&conf); srand(seed); if (ret != 0) starneig_fatal_error("Failed to initialize StarPU."); starpu_profiling_status_set(STARPU_PROFILING_ENABLE); starpu_malloc_set_align(64); // // initialize persistent StarPU-MPI // #ifdef STARNEIG_ENABLE_MPI if (state.mode == STARNEIG_MODE_DM && state.flags & STARNEIG_AWAKE_MPI_WORKER) starneig_mpi_start_persistent_starpumpi(); #endif // // cuBLAS // if (0 < state.used_gpus) { starneig_verbose("Initializing cuBLAS."); starpu_cublas_init(); } // // configure workers // #ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND starneig_verbose( "MKL detected. Setting StarPU worker BLAS thread count to 1."); starpu_execute_on_each_worker( &set_worker_blas_mode, NULL, STARPU_CPU | STARPU_CUDA); #endif starneig_node_pause_starpu(); } void starneig_node_pause_starpu() { if (state.flags & STARNEIG_AWAKE_WORKERS) return; starneig_verbose("Pausing StarPU workers."); starpu_pause(); } void starneig_node_resume_starpu() { if (state.flags & STARNEIG_AWAKE_WORKERS) return; starneig_verbose("Waking up StarPU workers."); starpu_resume(); } void starneig_node_pause_awake_starpu() { if (!(state.flags & STARNEIG_AWAKE_WORKERS)) return; starneig_verbose("Pausing \"awake\" StarPU workers."); starpu_pause(); } void starneig_node_resume_awake_starpu() { if (!(state.flags & STARNEIG_AWAKE_WORKERS)) return; starneig_verbose("Waking up \"awake\" StarPU workers."); starpu_resume(); } __attribute__ ((visibility ("default"))) void starneig_node_init(int cores, int gpus, starneig_flag_t flags) { starneig_set_message_mode( !(flags & STARNEIG_NO_MESSAGES), !(flags & STARNEIG_NO_VERBOSE)); starneig_verbose("Initializing node."); if (state.is_init) starneig_fatal_error("The node is already initialized."); state.flags = flags; // // set up CUDA // state.avail_gpus = 0; state.used_gpus = 0; #ifdef STARNEIG_ENABLE_CUDA // query the number of available CUDA devices if (cudaGetDeviceCount(&state.avail_gpus) != cudaSuccess) { starneig_warning("Failed to acquire CUDA device count."); state.avail_gpus = 0; } #endif // query STARPU_NCUDA environment char *starpu_ncuda = getenv("STARPU_NCUDA"); int num_starpu_gpus = (starpu_ncuda ? atoi(starpu_ncuda) : -1); if (num_starpu_gpus != -1) { if (state.avail_gpus < num_starpu_gpus) starneig_warning( "A conflict between STARPU_NCUDA and cudaGetDeviceCount()."); state.avail_gpus = MIN(state.avail_gpus, num_starpu_gpus); } // // set up CPU cores // state.avail_cores = 0; state.used_cores = 0; // query the SLURM environment char *slurm = getenv("SLURM_CPUS_PER_TASK"); const int num_slurm_cpus = (slurm ? atoi(slurm) : -1); // query STARPU_NCPUS environment char *starpu_ncpus = getenv("STARPU_NCPUS"); int num_starpu_cpus = -1; if (starpu_ncpus) { if (0 < state.avail_gpus) num_starpu_cpus = atoi(starpu_ncpus) + 1; else num_starpu_cpus = atoi(starpu_ncpus); } // query hardware topology and CPU core binding mask hwloc_topology_t topology; hwloc_topology_init(&topology); hwloc_topology_load(topology); hwloc_cpuset_t res = hwloc_bitmap_alloc(); hwloc_cpuset_t mask = hwloc_bitmap_alloc(); hwloc_get_cpubind(topology, mask, HWLOC_CPUBIND_THREAD); int depth_cores = hwloc_get_type_depth(topology, HWLOC_OBJ_CORE); int num_cores = hwloc_get_nbobjs_by_depth(topology, depth_cores); int num_hwloc_cpus = 0; // iterate over all COREs for (int i = 0; i < num_cores && num_hwloc_cpus < STARPU_NMAXWORKERS; i++) { hwloc_obj_t core = hwloc_get_obj_by_depth(topology, depth_cores, i); // if the CORE has PUs inside it, ... if (core->first_child && core->first_child->type == HWLOC_OBJ_PU) { // iterate over them hwloc_obj_t pu = core->first_child; while (pu) { // if the PU is in the binding mask, ... hwloc_bitmap_and(res, mask, pu->cpuset); if (!hwloc_bitmap_iszero(res)) { // add it to the worker list state.starpu_workers_bindid[num_hwloc_cpus++] = pu->logical_index; break; } pu = pu->next_sibling; } } else { // if the CORE is in the binding mask, ... hwloc_bitmap_and(res, mask, core->cpuset); if (!hwloc_bitmap_iszero(res)) { // add it to the worker list state.starpu_workers_bindid[num_hwloc_cpus++] = core->logical_index; } } } hwloc_bitmap_free(mask); hwloc_bitmap_free(res); hwloc_topology_destroy(topology); starneig_verbose_begin("Attached CPU cores"); for (int i = 0; i < num_hwloc_cpus; i++) starneig_verbose_cont(" %d", state.starpu_workers_bindid[i]); starneig_verbose_cont(".\n"); // set avail_cores state.avail_cores = num_hwloc_cpus; if (0 < num_starpu_cpus) { if (num_hwloc_cpus < num_starpu_cpus) starneig_warning( "A conflict between STARPU_NCPUS/STARPU_NCUDA and hwloc core " "binding mask."); state.avail_cores = MIN(state.avail_cores, num_starpu_cpus); if (0 < num_slurm_cpus) { if (num_slurm_cpus < num_starpu_cpus) starneig_warning( "A conflict between STARPU_NCPUS/STARPU_NCUDA and " "SLURM_CPUS_PER_TASK."); state.avail_cores = MIN(state.avail_cores, num_slurm_cpus); } } if (0 < num_slurm_cpus) { if (num_hwloc_cpus < num_slurm_cpus) starneig_warning( "A conflict between SLURM_CPUS_PER_TASK and hwloc core " "binding mask."); state.avail_cores = MIN(state.avail_cores, num_slurm_cpus); } if (state.avail_cores <= 0) starneig_fatal_error("Something unexpected happened."); state.is_init = true; if (state.flags & STARNEIG_HINT_DM) CONFIGURE(cores, gpus, STARNEIG_MODE_DM, STARNEIG_BLAS_MODE_SEQUENTIAL); else CONFIGURE(cores, gpus, STARNEIG_MODE_SM, STARNEIG_BLAS_MODE_SEQUENTIAL); } __attribute__ ((visibility ("default"))) int starneig_node_initialized() { return state.is_init; } __attribute__ ((visibility ("default"))) void starneig_node_finalize(void) { CHECK_INIT(); starneig_verbose("De-initializing node."); CONFIGURE(-1, -1, STARNEIG_MODE_OFF, STARNEIG_BLAS_MODE_ORIGINAL); starneig_set_message_mode(0, 0); state.avail_cores = 0; state.avail_gpus = 0; state.is_init = false; } __attribute__ ((visibility ("default"))) int starneig_node_get_cores(void) { CHECK_INIT(); return state.used_cores; } __attribute__ ((visibility ("default"))) void starneig_node_set_cores(int cores) { CHECK_INIT(); CONFIGURE(cores, starneig_node_get_gpus(), state.mode, state.blas_mode); } __attribute__ ((visibility ("default"))) int starneig_node_get_gpus(void) { CHECK_INIT(); return state.used_gpus; } __attribute__ ((visibility ("default"))) void starneig_node_set_gpus(int gpus) { CHECK_INIT(); CONFIGURE(starneig_node_get_cores(), gpus, state.mode, state.blas_mode); } __attribute__ ((visibility ("default"))) void starneig_node_set_mode(enum starneig_mode mode) { CHECK_INIT(); CONFIGURE(starneig_node_get_cores(), starneig_node_get_gpus(), mode, state.blas_mode); } void starneig_node_set_blas_mode(enum starneig_blas_mode blas_mode) { CHECK_INIT(); CONFIGURE(starneig_node_get_cores(), starneig_node_get_gpus(), state.mode, blas_mode); }
{ "alphanum_fraction": 0.6506592407, "avg_line_length": 27.0291858679, "ext": "c", "hexsha": "68f61733a7a549282ce9d54fc13897f21269c69c", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_path": "src/common/node.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_path": "src/common/node.c", "max_line_length": 80, "max_stars_count": 12, "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_path": "src/common/node.c", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "num_tokens": 4486, "size": 17596 }
#include <gsl/gsl_sf_erf.h> #include <gsl/gsl_cdf.h> #include <stdio.h> void evaluate(double x) { double probability = gsl_sf_erf(x); printf( "The probability that Normal(0, 1) random variable has a value " "between %g and %g is: %g\n", -x, x, probability ); double area = 1 - 2 * gsl_cdf_gaussian_P(-x, 1); printf( "The integral of a Normal(0, 1) distribution " "between %g and %g is: %g\n", -x, x, area ); } int main() { evaluate(0.25); evaluate(1.96); }
{ "alphanum_fraction": 0.6194331984, "avg_line_length": 19.76, "ext": "c", "hexsha": "4e5748d489872be88b504747411a943d30235e7b", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-01-09T02:51:16.000Z", "max_forks_repo_forks_event_min_datetime": "2016-06-15T10:13:12.000Z", "max_forks_repo_head_hexsha": "25f37f2a422d1f63a7d03b25a7876d6fa707cf7a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tardate/LittleCodingKata", "max_forks_repo_path": "c/error_function/erf_gsl.c", "max_issues_count": 34, "max_issues_repo_head_hexsha": "25f37f2a422d1f63a7d03b25a7876d6fa707cf7a", "max_issues_repo_issues_event_max_datetime": "2022-03-29T05:54:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-09T00:55:40.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tardate/LittleCodingKata", "max_issues_repo_path": "c/error_function/erf_gsl.c", "max_line_length": 68, "max_stars_count": 8, "max_stars_repo_head_hexsha": "25f37f2a422d1f63a7d03b25a7876d6fa707cf7a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tardate/LittleCodingKata", "max_stars_repo_path": "c/error_function/erf_gsl.c", "max_stars_repo_stars_event_max_datetime": "2022-01-09T02:50:55.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-02T05:12:11.000Z", "num_tokens": 169, "size": 494 }
/** * author: Jochen K"upper * created: Jan 2002 * file: pygsl/src/statistics/longmodule.c * $Id: longmodule.c,v 1.10 2004/03/24 08:40:45 schnizer Exp $ * * optional usage of Numeric module, available at http://numpy.sourceforge.net *" */ #include <Python.h> #include <pygsl/error_helpers.h> #include <pygsl/block_helpers.h> #include <gsl/gsl_statistics.h> /* include real functions for different data-types */ #define STATMOD_APPEND_PY_TYPE(X) X ## Int #define STATMOD_APPEND_PYC_TYPE(X) X ## LONG #define STATMOD_FUNC_EXT(X, Y) X ## _long ## Y #define STATMOD_PY_AS_C PyInt_AsLong #define STATMOD_C_TYPE long int #include "functions.c" /* initialization */ PyGSL_STATISTICS_INIT(long, "long") /* * Local Variables: * mode: c * c-file-style: "Stroustrup" * End: */
{ "alphanum_fraction": 0.7122940431, "avg_line_length": 20.2307692308, "ext": "c", "hexsha": "8c2a3ed02e2eea51367675fb23fcaa930b2a1d72", "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/src/statistics/longmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/longmodule.c", "max_line_length": 78, "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/src/statistics/longmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 224, "size": 789 }
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef MATHFUNCTIONS_H_ #define MATHFUNCTIONS_H_ #ifdef PADDLE_USE_MKL #include <mkl.h> #include <mkl_lapacke.h> #else extern "C" { #include <cblas.h> } #ifdef PADDLE_USE_ATLAS extern "C" { #include <clapack.h> } #else #include <lapacke.h> #endif #endif #include <cmath> namespace paddle { template <class T> void gemm(const CBLAS_TRANSPOSE transA, const CBLAS_TRANSPOSE transB, const int M, const int N, const int K, const T alpha, const T* A, const int lda, const T* B, const int ldb, const T beta, T* C, const int ldc); template <class T> int getrf(const CBLAS_ORDER Order, const int M, const int N, T* A, const int lda, int* ipiv); template <class T> int getri( const CBLAS_ORDER Order, const int N, T* A, const int lda, const int* ipiv); template <class T> void axpy(const int n, const T alpha, const T* x, T* y); template <class T> T dotProduct(const int n, const T* x, const T* y); template <class T> void vExp(const int n, const T* a, T* r); template <class T> void vPow(const int n, const T* a, const T b, T* r); template <class T> void vLog(const int n, const T* a, T* r); template <class T> void vAdd(const int n, const T* a, const T* b, T* r); template <class T> void vInvSqrt(const int n, const T* a, T* r); template <class T> void vLog1p(const int n, const T* a, T* r); template <class T> void vTanh(const int n, const T* a, T* r); } // namespace paddle #endif // MATHFUNCTIONS_H_
{ "alphanum_fraction": 0.6626947754, "avg_line_length": 22.9684210526, "ext": "h", "hexsha": "c8559eefd8378450fc18c2ba821c65b39c8cc046", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-07T00:50:53.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-07T00:50:53.000Z", "max_forks_repo_head_hexsha": "21fa3eb0688459d3b71141d316e8358d31882b8d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "anuranrc/Paddle", "max_forks_repo_path": "paddle/math/MathFunctions.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "21fa3eb0688459d3b71141d316e8358d31882b8d", "max_issues_repo_issues_event_max_datetime": "2017-05-26T18:33:00.000Z", "max_issues_repo_issues_event_min_datetime": "2017-05-26T18:33:00.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "anuranrc/Paddle", "max_issues_repo_path": "paddle/math/MathFunctions.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "7b67f9863e4af535835bf3012b3192db42362308", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "emailweixu/Paddle", "max_stars_repo_path": "paddle/math/MathFunctions.h", "max_stars_repo_stars_event_max_datetime": "2016-10-07T20:40:11.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-07T20:40:11.000Z", "num_tokens": 603, "size": 2182 }
/* spdgemv.c * * Copyright (C) 2012-2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_spblas.h> #include <gsl/gsl_blas.h> /* gsl_spblas_dgemv() Multiply a sparse matrix and a vector Inputs: alpha - scalar factor A - sparse matrix x - dense vector beta - scalar factor y - (input/output) dense vector Return: y = alpha*op(A)*x + beta*y */ int gsl_spblas_dgemv(const CBLAS_TRANSPOSE_t TransA, const double alpha, const gsl_spmatrix *A, const gsl_vector *x, const double beta, gsl_vector *y) { const size_t M = A->size1; const size_t N = A->size2; if ((TransA == CblasNoTrans && N != x->size) || (TransA == CblasTrans && M != x->size)) { GSL_ERROR("invalid length of x vector", GSL_EBADLEN); } else if ((TransA == CblasNoTrans && M != y->size) || (TransA == CblasTrans && N != y->size)) { GSL_ERROR("invalid length of y vector", GSL_EBADLEN); } else { size_t j, p; size_t incX, incY; size_t lenX, lenY; double *X, *Y; double *Ad; size_t *Ap, *Ai, *Aj; if (TransA == CblasNoTrans) { lenX = N; lenY = M; } else { lenX = M; lenY = N; } /* form y := beta*y */ Y = y->data; incY = y->stride; if (beta == 0.0) { size_t jy = 0; for (j = 0; j < lenY; ++j) { Y[jy] = 0.0; jy += incY; } } else if (beta != 1.0) { size_t jy = 0; for (j = 0; j < lenY; ++j) { Y[jy] *= beta; jy += incY; } } if (alpha == 0.0) return GSL_SUCCESS; /* form y := alpha*op(A)*x + y */ Ap = A->p; Ad = A->data; X = x->data; incX = x->stride; if ((GSL_SPMATRIX_ISCCS(A) && (TransA == CblasNoTrans)) || (GSL_SPMATRIX_ISCRS(A) && (TransA == CblasTrans))) { Ai = A->i; for (j = 0; j < lenX; ++j) { for (p = Ap[j]; p < Ap[j + 1]; ++p) { Y[Ai[p] * incY] += alpha * Ad[p] * X[j * incX]; } } } else if ((GSL_SPMATRIX_ISCCS(A) && (TransA == CblasTrans)) || (GSL_SPMATRIX_ISCRS(A) && (TransA == CblasNoTrans))) { Ai = A->i; for (j = 0; j < lenY; ++j) { for (p = Ap[j]; p < Ap[j + 1]; ++p) { Y[j * incY] += alpha * Ad[p] * X[Ai[p] * incX]; } } } else if (GSL_SPMATRIX_ISTRIPLET(A)) { if (TransA == CblasNoTrans) { Ai = A->i; Aj = A->p; } else { Ai = A->p; Aj = A->i; } for (p = 0; p < A->nz; ++p) { Y[Ai[p] * incY] += alpha * Ad[p] * X[Aj[p] * incX]; } } else { GSL_ERROR("unsupported matrix type", GSL_EINVAL); } return GSL_SUCCESS; } } /* gsl_spblas_dgemv() */
{ "alphanum_fraction": 0.4738491203, "avg_line_length": 24.8443113772, "ext": "c", "hexsha": "cadb57c31df873752b130de3610c213a74862dca", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spblas/spdgemv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spblas/spdgemv.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spblas/spdgemv.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 1210, "size": 4149 }
/* multiroots/broyden.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multiroots.h> #include <gsl/gsl_linalg.h> #include "enorm.c" /* Broyden's method. It is not an efficient or modern algorithm but gives an example of a rank-1 update. C.G. Broyden, "A Class of Methods for Solving Nonlinear Simultaneous Equations", Mathematics of Computation, vol 19 (1965), p 577-593 */ typedef struct { gsl_matrix *H; gsl_matrix *lu; gsl_permutation *permutation; gsl_vector *v; gsl_vector *w; gsl_vector *y; gsl_vector *p; gsl_vector *fnew; gsl_vector *x_trial; double phi; } broyden_state_t; static int broyden_alloc (void *vstate, size_t n); static int broyden_set (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); static int broyden_iterate (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); static void broyden_free (void *vstate); static int broyden_alloc (void *vstate, size_t n) { broyden_state_t *state = (broyden_state_t *) vstate; gsl_vector *v, *w, *y, *fnew, *x_trial, *p; gsl_permutation *perm; gsl_matrix *m, *H; m = gsl_matrix_calloc (n, n); if (m == 0) { GSL_ERROR ("failed to allocate space for lu", GSL_ENOMEM); } state->lu = m; perm = gsl_permutation_calloc (n); if (perm == 0) { gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for permutation", GSL_ENOMEM); } state->permutation = perm; H = gsl_matrix_calloc (n, n); if (H == 0) { gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for d", GSL_ENOMEM); } state->H = H; v = gsl_vector_calloc (n); if (v == 0) { gsl_matrix_free (H); gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for v", GSL_ENOMEM); } state->v = v; w = gsl_vector_calloc (n); if (w == 0) { gsl_vector_free (v); gsl_matrix_free (H); gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for w", GSL_ENOMEM); } state->w = w; y = gsl_vector_calloc (n); if (y == 0) { gsl_vector_free (w); gsl_vector_free (v); gsl_matrix_free (H); gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for y", GSL_ENOMEM); } state->y = y; fnew = gsl_vector_calloc (n); if (fnew == 0) { gsl_vector_free (y); gsl_vector_free (w); gsl_vector_free (v); gsl_matrix_free (H); gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for fnew", GSL_ENOMEM); } state->fnew = fnew; x_trial = gsl_vector_calloc (n); if (x_trial == 0) { gsl_vector_free (fnew); gsl_vector_free (y); gsl_vector_free (w); gsl_vector_free (v); gsl_matrix_free (H); gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for x_trial", GSL_ENOMEM); } state->x_trial = x_trial; p = gsl_vector_calloc (n); if (p == 0) { gsl_vector_free (x_trial); gsl_vector_free (fnew); gsl_vector_free (y); gsl_vector_free (w); gsl_vector_free (v); gsl_matrix_free (H); gsl_permutation_free (perm); gsl_matrix_free (m); GSL_ERROR ("failed to allocate space for p", GSL_ENOMEM); } state->p = p; return GSL_SUCCESS; } static int broyden_set (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx) { broyden_state_t *state = (broyden_state_t *) vstate; size_t i, j, n = function->n; int signum = 0; GSL_MULTIROOT_FN_EVAL (function, x, f); gsl_multiroot_fdjacobian (function, x, f, GSL_SQRT_DBL_EPSILON, state->lu); gsl_linalg_LU_decomp (state->lu, state->permutation, &signum); gsl_linalg_LU_invert (state->lu, state->permutation, state->H); for (i = 0; i < n; i++) for (j = 0; j < n; j++) gsl_matrix_set(state->H,i,j,-gsl_matrix_get(state->H,i,j)); for (i = 0; i < n; i++) { gsl_vector_set (dx, i, 0.0); } state->phi = enorm (f); return GSL_SUCCESS; } static int broyden_iterate (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx) { broyden_state_t *state = (broyden_state_t *) vstate; double phi0, phi1, t, lambda; gsl_matrix *H = state->H; gsl_vector *p = state->p; gsl_vector *y = state->y; gsl_vector *v = state->v; gsl_vector *w = state->w; gsl_vector *fnew = state->fnew; gsl_vector *x_trial = state->x_trial; gsl_matrix *lu = state->lu; gsl_permutation *perm = state->permutation; size_t i, j, iter; size_t n = function->n; /* p = H f */ for (i = 0; i < n; i++) { double sum = 0; for (j = 0; j < n; j++) { sum += gsl_matrix_get (H, i, j) * gsl_vector_get (f, j); } gsl_vector_set (p, i, sum); } t = 1; iter = 0; phi0 = state->phi; new_step: for (i = 0; i < n; i++) { double pi = gsl_vector_get (p, i); double xi = gsl_vector_get (x, i); gsl_vector_set (x_trial, i, xi + t * pi); } { int status = GSL_MULTIROOT_FN_EVAL (function, x_trial, fnew); if (status != GSL_SUCCESS) { return GSL_EBADFUNC; } } phi1 = enorm (fnew); iter++ ; if (phi1 > phi0 && iter < 10 && t > 0.1) { /* full step goes uphill, take a reduced step instead */ double theta = phi1 / phi0; t *= (sqrt (1.0 + 6.0 * theta) - 1.0) / (3.0 * theta); goto new_step; } if (phi1 > phi0) { /* need to recompute Jacobian */ int signum = 0; gsl_multiroot_fdjacobian (function, x, f, GSL_SQRT_DBL_EPSILON, lu); for (i = 0; i < n; i++) for (j = 0; j < n; j++) gsl_matrix_set(lu,i,j,-gsl_matrix_get(lu,i,j)); gsl_linalg_LU_decomp (lu, perm, &signum); gsl_linalg_LU_invert (lu, perm, H); gsl_linalg_LU_solve (lu, perm, f, p); t = 1; for (i = 0; i < n; i++) { double pi = gsl_vector_get (p, i); double xi = gsl_vector_get (x, i); gsl_vector_set (x_trial, i, xi + t * pi); } { int status = GSL_MULTIROOT_FN_EVAL (function, x_trial, fnew); if (status != GSL_SUCCESS) { return GSL_EBADFUNC; } } phi1 = enorm (fnew); } /* y = f' - f */ for (i = 0; i < n; i++) { double yi = gsl_vector_get (fnew, i) - gsl_vector_get (f, i); gsl_vector_set (y, i, yi); } /* v = H y */ for (i = 0; i < n; i++) { double sum = 0; for (j = 0; j < n; j++) { sum += gsl_matrix_get (H, i, j) * gsl_vector_get (y, j); } gsl_vector_set (v, i, sum); } /* lambda = p . v */ lambda = 0; for (i = 0; i < n; i++) { lambda += gsl_vector_get (p, i) * gsl_vector_get (v, i); } if (lambda == 0) { GSL_ERROR ("approximation to Jacobian has collapsed", GSL_EZERODIV) ; } /* v' = v + t * p */ for (i = 0; i < n; i++) { double vi = gsl_vector_get (v, i) + t * gsl_vector_get (p, i); gsl_vector_set (v, i, vi); } /* w^T = p^T H */ for (i = 0; i < n; i++) { double sum = 0; for (j = 0; j < n; j++) { sum += gsl_matrix_get (H, j, i) * gsl_vector_get (p, j); } gsl_vector_set (w, i, sum); } /* Hij -> Hij - (vi wj / lambda) */ for (i = 0; i < n; i++) { double vi = gsl_vector_get (v, i); for (j = 0; j < n; j++) { double wj = gsl_vector_get (w, j); double Hij = gsl_matrix_get (H, i, j) - vi * wj / lambda; gsl_matrix_set (H, i, j, Hij); } } /* copy fnew into f */ gsl_vector_memcpy (f, fnew); /* copy x_trial into x */ gsl_vector_memcpy (x, x_trial); for (i = 0; i < n; i++) { double pi = gsl_vector_get (p, i); gsl_vector_set (dx, i, t * pi); } state->phi = phi1; return GSL_SUCCESS; } static void broyden_free (void *vstate) { broyden_state_t *state = (broyden_state_t *) vstate; gsl_matrix_free (state->H); gsl_matrix_free (state->lu); gsl_permutation_free (state->permutation); gsl_vector_free (state->v); gsl_vector_free (state->w); gsl_vector_free (state->y); gsl_vector_free (state->p); gsl_vector_free (state->fnew); gsl_vector_free (state->x_trial); } static const gsl_multiroot_fsolver_type broyden_type = {"broyden", /* name */ sizeof (broyden_state_t), &broyden_alloc, &broyden_set, &broyden_iterate, &broyden_free}; const gsl_multiroot_fsolver_type *gsl_multiroot_fsolver_broyden = &broyden_type;
{ "alphanum_fraction": 0.5881405416, "avg_line_length": 21.7352297593, "ext": "c", "hexsha": "65c96478d7ef7296a84752bb2c703f624b46bce1", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/multiroots/broyden.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/multiroots/broyden.c", "max_line_length": 126, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/multiroots/broyden.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 3081, "size": 9933 }
#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_trsv (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.349749f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1150)"); } }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.348f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1151)"); } }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.349749f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1152)"); } }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.348f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1153)"); } }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.349749f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1154)"); } }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.348f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1155)"); } }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.349749f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1156)"); } }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.995f }; float X[] = { 0.348f }; int incX = -1; float x_expected[] = { 0.348f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1157)"); } }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.42623f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1158)"); } }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.338f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1159)"); } }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.42623f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1160)"); } }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.338f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1161)"); } }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.42623f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1162)"); } }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.338f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1163)"); } }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.42623f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1164)"); } }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.793f }; float X[] = { 0.338f }; int incX = -1; float x_expected[] = { 0.338f }; cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], flteps, "strsv(case 1165)"); } }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { -2.25238095238 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1166)"); } }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { 0.473 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1167)"); } }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { -2.25238095238 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1168)"); } }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { 0.473 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1169)"); } }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { -2.25238095238 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1170)"); } }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { 0.473 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1171)"); } }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { -2.25238095238 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1172)"); } }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { -0.21 }; double X[] = { 0.473 }; int incX = -1; double x_expected[] = { 0.473 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1173)"); } }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 1.30882352941 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1174)"); } }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 0.979 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1175)"); } }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 1.30882352941 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1176)"); } }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 0.979 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1177)"); } }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 1.30882352941 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1178)"); } }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 0.979 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1179)"); } }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 1.30882352941 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1180)"); } }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.748 }; double X[] = { 0.979 }; int incX = -1; double x_expected[] = { 0.979 }; cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], x_expected[i], dbleps, "dtrsv(case 1181)"); } }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -1.55112f, -0.372004f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1182) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1182) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -0.95f, 0.343f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1183) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1183) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -1.55112f, -0.372004f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1184) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1184) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -0.95f, 0.343f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1185) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1185) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -1.55112f, -0.372004f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1186) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1186) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -0.95f, 0.343f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1187) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1187) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -1.55112f, -0.372004f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1188) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1188) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.529f, -0.348f }; float X[] = { -0.95f, 0.343f }; int incX = -1; float x_expected[] = { -0.95f, 0.343f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1189) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1189) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 1.43572f, -0.843108f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1190) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1190) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 0.896f, -0.447f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1191) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1191) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 1.43572f, -0.843108f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1192) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1192) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 0.896f, -0.447f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1193) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1193) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 1.43572f, -0.843108f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1194) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1194) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 0.896f, -0.447f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1195) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1195) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 1.43572f, -0.843108f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1196) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1196) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.6f, 0.041f }; float X[] = { 0.896f, -0.447f }; int incX = -1; float x_expected[] = { 0.896f, -0.447f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1197) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1197) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.289642f, 0.951701f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1198) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1198) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.765f, 0.18f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1199) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1199) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.289642f, 0.951701f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1200) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1200) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.765f, 0.18f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1201) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1201) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 121; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.289642f, 0.951701f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1202) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1202) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 121; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.765f, 0.18f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1203) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1203) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 122; int diag = 131; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.289642f, 0.951701f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1204) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1204) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 122; int diag = 132; int N = 1; int lda = 1; float A[] = { 0.397f, 0.683f }; float X[] = { 0.765f, 0.18f }; int incX = -1; float x_expected[] = { 0.765f, 0.18f }; cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrsv(case 1205) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrsv(case 1205) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.471957414573, -0.173714770642 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1206) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1206) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.627, 0.281 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1207) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1207) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.471957414573, -0.173714770642 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1208) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1208) imag"); }; }; }; { int order = 101; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.627, 0.281 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1209) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1209) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.471957414573, -0.173714770642 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1210) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1210) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.627, 0.281 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1211) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1211) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.471957414573, -0.173714770642 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1212) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1212) imag"); }; }; }; { int order = 102; int trans = 111; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.977, -0.955 }; double X[] = { -0.627, 0.281 }; int incX = -1; double x_expected[] = { -0.627, 0.281 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1213) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1213) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 5.18357980622, -0.587200407955 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1214) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1214) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 0.3, -0.874 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1215) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1215) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 5.18357980622, -0.587200407955 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1216) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1216) imag"); }; }; }; { int order = 101; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 0.3, -0.874 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1217) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1217) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 5.18357980622, -0.587200407955 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1218) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1218) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 0.3, -0.874 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1219) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1219) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 5.18357980622, -0.587200407955 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1220) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1220) imag"); }; }; }; { int order = 102; int trans = 112; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.076, -0.16 }; double X[] = { 0.3, -0.874 }; int incX = -1; double x_expected[] = { 0.3, -0.874 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1221) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1221) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.371144591432, -0.0712292456544 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1222) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1222) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.085, -0.303 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1223) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1223) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.371144591432, -0.0712292456544 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1224) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1224) imag"); }; }; }; { int order = 101; int trans = 113; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.085, -0.303 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1225) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1225) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 121; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.371144591432, -0.0712292456544 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1226) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1226) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 121; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.085, -0.303 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1227) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1227) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 122; int diag = 131; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.371144591432, -0.0712292456544 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1228) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1228) imag"); }; }; }; { int order = 102; int trans = 113; int uplo = 122; int diag = 132; int N = 1; int lda = 1; double A[] = { 0.372, -0.745 }; double X[] = { -0.085, -0.303 }; int incX = -1; double x_expected[] = { -0.085, -0.303 }; cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrsv(case 1229) real"); gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrsv(case 1229) imag"); }; }; }; }
{ "alphanum_fraction": 0.4972220127, "avg_line_length": 22.8603448276, "ext": "c", "hexsha": "39f5083b3c9feff9c8000ab65afca9d6baadefcc", "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_trsv.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_trsv.c", "max_line_length": 82, "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_trsv.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": 16136, "size": 39777 }
#include <config.h> #include <math.h> #include <gsl/gsl_statistics.h> #define BASE_LONG_DOUBLE #include "templates_on.h" #include "wskew_source.c" #include "templates_off.h" #undef BASE_LONG_DOUBLE #define BASE_DOUBLE #include "templates_on.h" #include "wskew_source.c" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "wskew_source.c" #include "templates_off.h" #undef BASE_FLOAT
{ "alphanum_fraction": 0.7767653759, "avg_line_length": 19.0869565217, "ext": "c", "hexsha": "9e747c6cdc594d0cbc15597fbcd0e836a2ebcabb", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/statistics/wskew.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/statistics/wskew.c", "max_line_length": 31, "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/statistics/wskew.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": 108, "size": 439 }
#ifndef SPECTRALFUNCTIONS #define SPECTRALFUNCTIONS #include <string> #include <iostream> #include <vector> #include <gsl/gsl_complex.h> #include <tuple> #include "Constants.h" #include "NuclearUtilities.h" namespace bsg { /** * Namespace containing all correction factors to the allowed beta spectrum shape * as described by Hayen et al., Rev. Mod. Phys. 90 (2018) 015008 */ namespace SpectralFunctions { /// type of beta decay, negative or positive enum BetaType { BETA_PLUS = -1, BETA_MINUS = 1 }; enum DecayType { FERMI, GAMOW_TELLER, MIXED }; // the different corrections double PhaseSpace(double W, double W0, int motherSpinParity, int daughterSpinParity); /** * @brief Fermi function * @param W total energy in units of electron mass * @param Z the proton number of the daughter * @param R the nuclear radius of the daughter * @param betaType the BetaType of the transition * @return the value * * The point charge Fermi function @f$ F_0(Z, W) @f$ * \f[ F_0(Z,W) = 2(\gamma+1) \Gamma(2\gamma+1)^{-2} (2pR)^{2(\gamma-1)} *e^{\pi\alpha Z W /p} |\Gamma(\gamma + i \alpha Z W /p) |^2\f] * the last factor \f$ |\Gamma(\gamma + i \alpha Z W /p) |^2 \f$ is calculated *using GSL. The GSL function returns the magnitude and phase, and here, as we *are interested in the absolute value of the result we just use the *magnitude. * The calculation of the 2nd factor \f$ \Gamma(2\gamma+1)^{-2} \f$ and the *last factor \f$ |\Gamma(\gamma + i \alpha Z W /p) |^2 \f$ is combined, i.e. * \f[ \ln\frac{a^2}{b^2} = 2\ln\frac{a}{b} = 2(\ln a - \ln b) \f] * */ double FermiFunction(double W, int Z, double R, int betaType); /** * @brief C correction * @param W total energy in units of electron mass * @param W0 the total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param R nuclear radius in natural units * @param betaType the BetaType of the transition * @param decayType the DecayType of the transition * @param gA the axial vector coupling constant * @param gP the induced pseudoscalar coupling constant * @param fc1 the c1 form factor as per Holstein (@f$ g_A M_{GT} @f$) * @param fb the b form factor as per Holstein * @param fd the d form factor as per Holstein * @param ratioM121 the ratio of the @f$^AM_{121}@f$ and @f$ ^AM_{101}@f$ matrix elements in the Behrens-Buehring formalism * @param addCI boolean to decide whether or not to include the isovector correction to the shape part of C * @param NSShape string, says which charge distribution to use in the C correction * @param hoFit the fitted A value for the Modified Gaussian distribution * @param spsi NuclearStructure::SingleParticleState object denoting the initial nucleon state * @param spsf NuclearStructure::SingleParticleState object denoting the final nucleon state * * The C correction describing effects of finite nuclear size and induced currents when the connection to the NME library has been made and actual single-particle wave functions will be used in C_I */ double CCorrection(double W, double W0, int Z, int A, double R, int betaType, int decayType, double gA, double gP, double fc1, double fb, double fd, double ratioM121, bool addCI, std::string NSShape, double hoFit, nme::NuclearStructure::SingleParticleState& spsi, nme::NuclearStructure::SingleParticleState& spsf); /** * @brief C correction * @param W total energy in units of electron mass * @param W0 the total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param R nuclear radius in natural units * @param betaType the BetaType of the transition * @param decayType the DecayType of the transition * @param gA the axial vector coupling constant * @param gP the induced pseudoscalar coupling constant * @param fc1 the c1 form factor as per Holstein (@f$ g_A M_{GT} @f$) * @param fb the b form factor as per Holstein * @param fd the d form factor as per Holstein * @param ratioM121 the ratio of the @f$^AM_{121}@f$ and @f$ ^AM_{101}@f$ matrix elements in the Behrens-Buehring formalism * @param addCI boolean to decide whether or not to include the isovector correction to the shape part of C * @param NSShape string, says which charge distribution to use in the C correction * @param hoFit the fitted A value for the Modified Gaussian distribution * * The C correction describing effects of finite nuclear size and induced currents. */ double CCorrection(double W, double W0, int Z, int A, double R, int betaType, int decayType, double gA, double gP, double fc1, double fb, double fd, double ratioM121, bool addCI, std::string NSShape, double hoFit); /** * @brief C correction * @param W total energy in units of electron mass * @param W0 the total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param R nuclear radius in natural units * @param betaType the BetaType of the transition * @param hoFit the fitted A value for the Modified Gaussian distribution * @param decayType the DecayType of the transition * @param gA the axial vector coupling constant * @param gP the induced pseudoscalar coupling constant * @param fc1 the c1 form factor as per Holstein (@f$ g_A M_{GT} @f$) * @param fb the b form factor as per Holstein * @param fd the d form factor as per Holstein * @param ratioM121 the ratio of the @f$^AM_{121}@f$ and @f$ ^AM_{101}@f$ matrix elements in the Behrens-Buehring formalism * @param NSShape string, says which charge distribution to use in the C correction * @param hoFit the fitted A value for the Modified Gaussian distribution * @return the value * * The C correction describing effects of finite nuclear size and induced currents. Return the shape and nuclear-sensitive parts separately in a tuple. */ std::tuple<double, double> CCorrectionComponents(double W, double W0, int Z, int A, double R, int betaType, int decayType, double gA, double gP, double fc1, double fb, double fd, double ratioM121, std::string NSShape, double hoFit); /** * Isovector correction to the charge density-calculated C correction * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param R nuclear radius in natural units * @param betaType BetaType of the transition * @param decayType DecayType of the transition */ double CICorrection(double W, double W0, int Z, int A, double R, int betaType); /** * Isovector correction to the charge density-calculated C correction * Gets called when connection with NME is turned on, thereby using actual * single particle wave functions from a (deformed) Woods-Saxon potential * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy i units of the electron rest mass * @param Z proton number * @param R nuclear radius in natural units * @betaType beta type of the transition * @param spsi NuclearStructure::SingleParticleState object denoting the initial state * @param spsf NuclearStructure::SingleParticleState object denoting the final state */ double CICorrection(double W, double W0, double Z, double R, int betaType, nme::NuclearStructure::SingleParticleState& spsi, nme::NuclearStructure::SingleParticleState& spsf); /** * Relativistic matrix element correction to the vector pahe "black hole girl" right now, and how she's being given too much credit for her role in the historic first image of a black hole. Because this is too important, I want to set the record straight. Once Katie Bouman became the "face" of the black hole photo, and articles began to call her "the woman behind the black hole photo", an assortment of people that I'm strongly inclined to callrt of the C correction * as per Wilkinson. * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param R nuclear radius in natural units * @param betaType BetaType of the transition * @param decayType DecayType of the transition */ double RelativisticCorrection(double W, double W0, int Z, int A, double R, int betaType, int decayType); /** * Deformation correction to L0 * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param R nuclear radius in natural units * @param beta2 quadrupole deformation * @param betaType BetaType of the transition * @param aPos array of fitted constants for beta+ decay * @param aNeg array of fitted constants for beta- decay */ double DeformationCorrection(double W, double W0, int Z, double R, double beta2, int betaType, double aPos[], double aNeg[]); /** * Electrostatic finite size correction to the point charge Fermi function * written as @f$L_0(Z, W) @f$ * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param r radius in natural units * @param betaType BetaType of the transition * @param aPos array of fitted constants for beta+ decay * @param aNeg array of fitted constants for beta- decay */ double L0Correction(double W, int Z, double r, int betaType, double aPos[], double aNeg[]); /** * Correction to L0 by moving from a uniformly charged sphere to a more elaborate nuclear shape * * @param W electron total energy in units of its rest mass * @param Z proton number * @param R nuclear radius in natural units * @param betaType BetaType of the transition * @param ESShape string denoting the name of the base shape. Currently only Fermi is implemented * @param v vector representing the first 3 terms in an even-r power expansion of the base shape * @param vp vector representing the first 3 terms in an even-r power expansion of the new shape */ double UCorrection(double W, int Z, double R, int betaType, std::string ESShape, std::vector<double>& v, std::vector<double>& vp); /** * Correction to L0 by calculating @f$ \frac{L_0'}{L_0} @f$ using a power expansion of the potentials * * @param W electron total energy in units of its rest mass * @param Z proton number * @param R nuclear radius in natural units * @param betaType BetaType of the transition * @param v vector representing the first 3 terms in an even-r power expansion of the base shape * @param vp vector representing the first 3 terms in an even-r power expansion of the new shape * @see UCorrection */ double UCorrection(double W, int Z, double R, int betaType, std::vector<double>& v, std::vector<double>& vp); /** * Electromagnetic correction to the Fermi function due to the change in the * electromagnetic field of the recoiling nucleus compared to it standing still * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param betaType BetaType of the transition * @param decayType decsay type of the transition * @double mixingRatio mixing ratio of Fermi versus Gamow-Teller */ double QCorrection(double W, double W0, int Z, int A, int betaType, int decayType, double mixingRatio); /** * The radiative correction up to order @f$ \alpha^3Z^2 @f$ as per Sirlin * * @param W total electron energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param R nuclear radius in natural units * @param betaType BetaType of the transition * @param gA axial vector coupling constant @f$ g_A @f$ * @param gM nucleon isovector moment @f$ g_M = 4.706 @f$ * * The first order correction is \f$ \delta_1=\frac{\alpha}{2\pi}g(W_0,W) \f$, *where \f$ g \f$ is defined by Sirlin (1967). * \f{eqnarray*} g(W_0,W) = & 3 \ln{\frac{m_p}{m_e}} - \frac{3}{4} + *\frac{4}{\beta}\rm{Spence}{\frac{2\beta}{1+\beta}} + 4 \left( *\frac{\tanh^{-1}{\beta}}{\beta}-1 \right) \\ * & \times \left[ \frac{W_0-W}{3W} - \frac{3}{2} + \ln{2(W_0-W)} \right] \\ * & + \frac{\tanh^{-1}{\beta}}{\beta} \left[ 2(1+\beta^2) + *\frac{(W_0-W)^2}{6W^2} -4\tanh^{-1}{\beta}\right] * \f} * * where \f$ \tanh^{-1} \f$ is the inverse hyperbolic tangent function, \f$ *\beta = \sqrt{W^2-1} \f$ and the Spence function is defined elsewhere. * @see Spence() */ double RadiativeCorrection(double W, double W0, int Z, double R, int betaType, double gA, double gM); /** * Radiative correction to the neutrino spectrum by Sirlin and Marciano * * @param Wv neutrino total energy in units of the electron rest mass */ double NeutrinoRadiativeCorrection(double Wv); /** * Kinematic recoil correction to the beta spectrum due to the enlargement of the phase space * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param A mass number * @param decayType decsay type of the transition * @double mixingRatio mixing ratio of Fermi versus Gamow-Teller */ double RecoilCorrection(double W, double W0, int A, int decayType, double mixingRatio); /** * Correction due to atomic screening calculated using the Salvat potential * * @param W electron total energy in units of its rest mass * @param Z proton number * @param betaType the BetaType of the transition */ double AtomicScreeningCorrection(double W, int Z, int betaType); /** * The atomic exchange correction where an electron decays into a bound state of the daughter atom * and its corresponding interference with the direct process * * @param W electron total energy in units of its rest mass * @param exPars array containing the 9 fit parameters required for the analytical parametrisation */ double AtomicExchangeCorrection(double W, double exPars[9]); /** * Correction due to the mismatch between initial and final atomic states, causing the * endpoint of the transition to get smaller * * @param W electron total energy in units of its rest mass * @param W0 total endpoint energy in units of the electron rest mass * @param Z proton number * @param A mass number * @param betaType BetaType of the transition */ double AtomicMismatchCorrection(double W, double W0, int Z, int A, int betaType); /** * @brief Spence function * @param x * @return -gs_sf_dilog(x) * * The Spence function is included here because the Wilkinson article refers *to it. It's value is actually equal (with a sign change) to the DiLogarithm, *which is used from GSL. * \f[ \rm{Spence} = \int_0^x\frac{\ln{(1-t)}}{t}\mathrm{d}t \equiv - *\sum_{k=1}^{k=\infty}\frac{x^k}{k^2} \equiv -\mathrm{Li}_2(x) \f] */ double Spence(double x); } } #endif // SPECTRALFUNCTIONS
{ "alphanum_fraction": 0.7169724469, "avg_line_length": 44.4649122807, "ext": "h", "hexsha": "772f9387dcacd0e346a28cc4dd135465d03f2bdd", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-08-24T00:55:59.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-29T16:49:09.000Z", "max_forks_repo_head_hexsha": "d02d9c6b6bb5dddffbf55bfa5762cda0ec97ad54", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MorisRand/BSG", "max_forks_repo_path": "source/bsg/include/SpectralFunctions.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "d02d9c6b6bb5dddffbf55bfa5762cda0ec97ad54", "max_issues_repo_issues_event_max_datetime": "2020-08-07T16:49:10.000Z", "max_issues_repo_issues_event_min_datetime": "2019-03-26T09:07:03.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MorisRand/BSG", "max_issues_repo_path": "source/bsg/include/SpectralFunctions.h", "max_line_length": 255, "max_stars_count": 10, "max_stars_repo_head_hexsha": "d02d9c6b6bb5dddffbf55bfa5762cda0ec97ad54", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MorisRand/BSG", "max_stars_repo_path": "source/bsg/include/SpectralFunctions.h", "max_stars_repo_stars_event_max_datetime": "2021-09-02T09:54:30.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-02T02:33:58.000Z", "num_tokens": 3973, "size": 15207 }
#include <stdio.h> #include <gsl/gsl_vector.h> int sum(double* arr, int size) { for (int i=0; i<size ; i++) { arr[i] += 10; } return 0; } gsl_vector* get_vector( int size ) { int i; gsl_vector * v = gsl_vector_alloc (size); for (i = 0; i < size; i++) { gsl_vector_set (v, i, 1.23 + i); } return v; } double * get_vector_pointer(gsl_vector* v){ return gsl_vector_ptr(v, 0); } int print_array_data(double* arr, int size){ for(int i=0; i<size; i++) { printf("%f\n", arr[i]); } return 0; } int free_vector(gsl_vector * v) { gsl_vector_free(v); return 0; } int main(int argc, char *argv[]) { gsl_vector* vec = get_vector(1); double* darry = get_vector_pointer(vec); //incd(darry,1); printf("printing darry\n"); print_array_data(darry, 1); free_vector(vec); } double* get_double_array(int size) { double* arr = (double*) malloc(size*sizeof(double)); for (int i=0; i<size; i++ ) { arr[i] = i; } return arr; } int free_double_array(double* arr) { free(arr); return 0; } gsl_vector_view make_vector(double* arr, int size) { return gsl_vector_view_array(arr, size); }
{ "alphanum_fraction": 0.5863486842, "avg_line_length": 17.6231884058, "ext": "c", "hexsha": "e0e840f6723afb80cdf3946a3ffe3bcd1f84b9b7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "subramon/qlu", "max_forks_repo_path": "experimental/c_files/gsl_test/vec.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "subramon/qlu", "max_issues_repo_path": "experimental/c_files/gsl_test/vec.c", "max_line_length": 56, "max_stars_count": null, "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "subramon/qlu", "max_stars_repo_path": "experimental/c_files/gsl_test/vec.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 365, "size": 1216 }
#ifndef LOGSUMEXP_INCLUDED #define LOGSUMEXP_INCLUDED #include <limits> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <cmath> #include "vguard.h" /* uncomment to disable lookup table */ /* #define LOG_SUM_EXP_SLOW */ /* uncomment to catch NaN errors */ /* #define NAN_DEBUG */ #define LOG_SUM_EXP_LOOKUP_MAX 10 #define LOG_SUM_EXP_LOOKUP_PRECISION .0001 #define LOG_SUM_EXP_LOOKUP_ENTRIES (((int) (LOG_SUM_EXP_LOOKUP_MAX / LOG_SUM_EXP_LOOKUP_PRECISION)) + 1) /* comment to disable interpolation */ #define LOG_SUM_EXP_INTERPOLATE namespace MachineBoss { using namespace std; typedef double LogProb; double log_sum_exp_unary_slow (double x); /* does not use lookup table */ struct LogSumExpLookupTable { double *lookup; LogSumExpLookupTable(); ~LogSumExpLookupTable(); }; extern LogSumExpLookupTable logSumExpLookupTable; inline double log_sum_exp_unary (double x) { /* returns log(1 + exp(-x)) for nonnegative x */ #ifdef LOG_SUM_EXP_SLOW return log_sum_exp_unary_slow(x); #else /* LOG_SUM_EXP_SLOW */ if (x >= LOG_SUM_EXP_LOOKUP_MAX || std::isnan(x) || std::isinf(x)) return 0; if (x < 0) { /* really dumb approximation for x < 0. Should never be encountered, so issue a warning */ cerr << "Called log_sum_exp_unary(x) for negative x = " << x << endl; return -x; } const int n = (int) (x / LOG_SUM_EXP_LOOKUP_PRECISION); const double f0 = logSumExpLookupTable.lookup[n]; #ifdef LOG_SUM_EXP_INTERPOLATE const double dx = x - (n * LOG_SUM_EXP_LOOKUP_PRECISION); const double f1 = logSumExpLookupTable.lookup[n+1]; const double df = f1 - f0; return f0 + df * (dx / LOG_SUM_EXP_LOOKUP_PRECISION); #else /* LOG_SUM_EXP_INTERPOLATE */ return f0; #endif /* LOG_SUM_EXP_INTERPOLATE */ #endif /* LOG_SUM_EXP_SLOW */ } inline double log_sum_exp (double a, double b) { /* returns log(exp(a) + exp(b)) */ double max, diff, ret; // Note: Infinity plus or minus a finite quantity is still Infinity, // but Infinity - Infinity = NaN. // Thus, we are susceptible to NaN errors when trying to add 0+0 in log-space. // To work around this, we explicitly test for a==b. if (a == b) { max = a; diff = 0; } else if (a < b) { max = b; diff = b - a; } else { max = a; diff = a - b; } ret = max + log_sum_exp_unary (diff); #if defined(NAN_DEBUG) if (std::isnan(ret)) { cerr << "NaN error in log_sum_exp" << endl; throw; } #endif return ret; } inline double log_sum_exp (double a, double b, double c) { return log_sum_exp (log_sum_exp (a, b), c); } inline double log_sum_exp (double a, double b, double c, double d) { return log_sum_exp (log_sum_exp (log_sum_exp (a, b), c), d); } inline double log_accum_exp (double& a, double b) { a = log_sum_exp (a, b); return a; } inline double log_sum_exp (double a, double b, double c, double d, double e) { return log_sum_exp (log_sum_exp (log_sum_exp (log_sum_exp (a, b), c), d), e); } inline double log_sum_exp (const vguard<double>& v) { double lpTot = -numeric_limits<double>::infinity(); for (auto lp : v) (void) log_accum_exp (lpTot, lp); return lpTot; } inline double log_sum_exp (const vguard<vguard<double> >& v) { double lpTot = -numeric_limits<double>::infinity(); for (auto lp : v) (void) log_accum_exp (lpTot, log_sum_exp (lp)); return lpTot; } double log_sum_exp_slow (double a, double b); /* does not use lookup table */ double log_sum_exp_slow (double a, double b, double c); double log_sum_exp_slow (double a, double b, double c, double d); double log_accum_exp_slow (double& a, double b); inline double log_subtract_exp (double a, double b) { if (a < b) { cerr << "Sign error in log_subtract_exp" << endl; throw; } return a + log (1. - exp(b-a)); } vguard<LogProb> log_vector (const vguard<double>& v); vguard<vguard<LogProb> > log_matrix (const vguard<vguard<double> >& m); vguard<LogProb> log_gsl_vector (const gsl_vector* v); vguard<double> gsl_vector_to_stl (const gsl_vector* v); vguard<vguard<LogProb> > log_vector_gsl_vector (const vguard<const gsl_vector*>& v); vguard<vguard<double> > gsl_matrix_to_stl (const gsl_matrix* m); gsl_matrix* stl_to_gsl_matrix (const vguard<vguard<double> >& m); inline LogProb logInnerProduct (const vguard<LogProb>& v1, const vguard<LogProb>& v2) { LogProb lip = -numeric_limits<double>::infinity(); for (vguard<LogProb>::const_iterator iter1 = v1.begin(), iter2 = v2.begin(); iter1 != v1.end(); ++iter1, ++iter2) lip = log_sum_exp (lip, *iter1 + *iter2); return lip; } inline LogProb logInnerProduct (const vguard<LogProb>& v1, const vguard<LogProb>& v2, const vguard<LogProb>& v3) { LogProb lip = -numeric_limits<double>::infinity(); for (vguard<LogProb>::const_iterator iter1 = v1.begin(), iter2 = v2.begin(), iter3 = v3.begin(); iter1 != v1.end(); ++iter1, ++iter2, ++iter3) lip = log_sum_exp (lip, *iter1 + *iter2 + *iter3); return lip; } inline LogProb logInnerProduct (const vguard<vguard<LogProb> >& v1, const vguard<vguard<LogProb> >& v2) { LogProb lip = -numeric_limits<double>::infinity(); for (vguard<vguard<LogProb> >::const_iterator iter1 = v1.begin(), iter2 = v2.begin(); iter1 != v1.end(); ++iter1, ++iter2) lip = log_sum_exp (lip, logInnerProduct (*iter1, *iter2)); return lip; } double logBetaPdf (double prob, double yesCount, double noCount); // alpha = yesCount+1, beta = noCount+1 double logGammaPdf (double rate, double eventCount, double waitTime); // alpha = shape = eventCount+1, beta = rate = 1/scale = 1/theta = waitTime double logDirichletPdf (const vguard<double>& prob, const vguard<double>& count); // alpha[n] = count[n] + 1 double logGaussianPdf (double x, double mu, double sigma); } // end namespace #endif /* LOGSUMEXP_INCLUDED */
{ "alphanum_fraction": 0.698159083, "avg_line_length": 33.2832369942, "ext": "h", "hexsha": "8b50bf0641ca8ddcacbf5b3458e8592ab8134e72", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:24:48.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-05T01:39:50.000Z", "max_forks_repo_head_hexsha": "4af653f38821f621a2cdf141dc27dc8d62841667", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "evoldoers/bossmachine", "max_forks_repo_path": "src/logsumexp.h", "max_issues_count": 58, "max_issues_repo_head_hexsha": "4af653f38821f621a2cdf141dc27dc8d62841667", "max_issues_repo_issues_event_max_datetime": "2018-10-19T16:52:06.000Z", "max_issues_repo_issues_event_min_datetime": "2018-07-20T17:19:04.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "evoldoers/bossmachine", "max_issues_repo_path": "src/logsumexp.h", "max_line_length": 146, "max_stars_count": 32, "max_stars_repo_head_hexsha": "4af653f38821f621a2cdf141dc27dc8d62841667", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ihh/acidbot", "max_stars_repo_path": "src/logsumexp.h", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:16:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-30T00:09:52.000Z", "num_tokens": 1695, "size": 5758 }
/** * This file is part of the Contour terminal project * Copyright (c) 2019-2021 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 <gsl/span> #include <gsl/span_ext> #include <algorithm> #include <cassert> #include <iterator> #include <stdexcept> #include <vector> namespace crispy { template <typename T, typename Vector> struct RingIterator; template <typename T, typename Vector> struct RingReverseIterator; /** * Implements an efficient ring buffer over type T * and the underlying storage Vector. */ template <typename T, typename Vector = std::vector<T>> class basic_ring { public: using value_type = T; using iterator = RingIterator<value_type, Vector>; using const_iterator = RingIterator<value_type const, Vector>; using reverse_iterator = RingReverseIterator<value_type, Vector>; using const_reverse_iterator = RingReverseIterator<value_type const, Vector>; using difference_type = long; using offset_type = long; basic_ring() = default; basic_ring(basic_ring const&) = default; basic_ring& operator=(basic_ring const&) = default; basic_ring(basic_ring&&) noexcept = default; basic_ring& operator=(basic_ring&&) noexcept = default; virtual ~basic_ring() = default; explicit basic_ring(Vector storage): _storage(std::move(storage)) {} value_type const& operator[](offset_type i) const noexcept { return _storage[size_t(offset_type(_zero + size()) + i) % size()]; } value_type& operator[](offset_type i) noexcept { return _storage[size_t(offset_type(_zero + size()) + i) % size()]; } value_type const& at(offset_type i) const noexcept { return _storage[size_t(_zero + size() + i) % size()]; } value_type& at(offset_type i) noexcept { return _storage[size_t(offset_type(_zero + size()) + i) % size()]; } Vector& storage() noexcept { return _storage; } Vector const& storage() const noexcept { return _storage; } std::size_t zero_index() const noexcept { return _zero; } void rezero(iterator i); void rezero(); std::size_t size() const noexcept { return _storage.size(); } // positvie count rotates right, negative count rotates left void rotate(int count) noexcept { _zero = size_t(offset_type(_zero + size()) - count) % size(); } void rotate_left(std::size_t count) noexcept { _zero = (_zero + size() + count) % size(); } void rotate_right(std::size_t count) noexcept { _zero = (_zero + size() - count) % size(); } void unrotate() { _zero = 0; } value_type& front() noexcept { return at(0); } value_type const& front() const noexcept { return at(0); } value_type& back() { if (size() == 0) throw std::length_error("empty"); return at(static_cast<offset_type>(size()) - 1); } value_type const& back() const { if (size() == 0) throw std::length_error("empty"); return at(static_cast<offset_type>(size()) - 1); } iterator begin() noexcept { return iterator { this, 0 }; } iterator end() noexcept { return iterator { this, static_cast<difference_type>(size()) }; } const_iterator cbegin() const noexcept { return const_iterator { (basic_ring<value_type const, Vector>*) this, 0 }; } const_iterator cend() const noexcept { return const_iterator { (basic_ring<value_type const, Vector>*) this, static_cast<difference_type>(size()) }; } const_iterator begin() const noexcept { return cbegin(); } const_iterator end() const noexcept { return cend(); } reverse_iterator rbegin() noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rbegin() const noexcept; const_reverse_iterator rend() const noexcept; gsl::span<value_type> span(offset_type start, size_t count) noexcept { auto a = std::next(begin(), start); auto b = std::next(a, count); return gsl::make_span(a, b); } gsl::span<value_type const> span(offset_type start, size_t count) const noexcept { auto a = std::next(begin(), start); auto b = std::next(a, count); return gsl::make_span(a, b); } protected: Vector _storage; std::size_t _zero = 0; }; /** * Implements an efficient ring buffer over type T * and the underlying dynamic storage type Vector<T, Allocator>. */ template <typename T, template <typename, typename> class Container = std::vector, typename Allocator = std::allocator<T>> class ring: public basic_ring<T, Container<T, Allocator>> { public: using basic_ring<T, Container<T, Allocator>>::basic_ring; ring(size_t capacity, T value): ring(Container<T, Allocator>(capacity, value)) {} explicit ring(size_t capacity): ring(capacity, T {}) {} size_t size() const noexcept { return this->_storage.size(); } void reserve(size_t capacity) { this->_storage.reserve(capacity); } void resize(size_t newSize) { this->rezero(); this->_storage.resize(newSize); } void clear() { this->_storage.clear(); this->_zero = 0; } void push_back(T const& _value) { this->_storage.push_back(_value); } void push_back(T&& _value) { this->emplace_back(std::move(_value)); } template <typename... Args> void emplace_back(Args&&... args) { this->_storage.emplace_back(std::forward<Args>(args)...); } void pop_front() { this->_storage.erase(this->_storage.begin()); } }; /// Fixed-size basic_ring<T> implementation template <typename T, std::size_t N> using fixed_size_ring = basic_ring<T, std::array<T, N>>; // {{{ iterator template <typename T, typename Vector> struct RingIterator { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = long; using pointer = T*; using reference = T&; basic_ring<T, Vector>* ring {}; difference_type current {}; RingIterator(basic_ring<T, Vector>* aRing, difference_type aCurrent): ring { aRing }, current { aCurrent } { } RingIterator() = default; RingIterator(RingIterator const&) = default; RingIterator& operator=(RingIterator const&) = default; RingIterator(RingIterator&&) noexcept = default; RingIterator& operator=(RingIterator&&) noexcept = default; RingIterator& operator++() noexcept { ++current; return *this; } RingIterator operator++(int) noexcept { auto old = *this; ++(*this); return old; } RingIterator& operator--() noexcept { --current; return *this; } RingIterator operator--(int) noexcept { auto old = *this; --(*this); return old; } RingIterator& operator+=(int n) noexcept { current += n; return *this; } RingIterator& operator-=(int n) noexcept { current -= n; return *this; } RingIterator operator+(difference_type n) noexcept { return RingIterator { ring, current + n }; } RingIterator operator-(difference_type n) noexcept { return RingIterator { ring, current - n }; } RingIterator operator+(RingIterator const& rhs) const noexcept { return RingIterator { ring, current + rhs.current }; } difference_type operator-(RingIterator const& rhs) const noexcept { return current - rhs.current; } friend RingIterator operator+(difference_type n, RingIterator a) { return RingIterator { a.ring, n + a.current }; } friend RingIterator operator-(difference_type n, RingIterator a) { return RingIterator { a.ring, n - a.current }; } bool operator==(RingIterator const& rhs) const noexcept { return current == rhs.current; } bool operator!=(RingIterator const& rhs) const noexcept { return current != rhs.current; } T& operator*() noexcept { return (*ring)[current]; } T const& operator*() const noexcept { return (*ring)[current]; } T* operator->() noexcept { return &(*ring)[current]; } T* operator->() const noexcept { return &(*ring)[current]; } }; // }}} // {{{ reverse iterator template <typename T, typename Vector> struct RingReverseIterator { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = long; using pointer = T*; using reference = T&; basic_ring<T, Vector>* ring; difference_type current; RingReverseIterator(basic_ring<T, Vector>* _ring, difference_type _current): ring { _ring }, current { _current } { } RingReverseIterator(RingReverseIterator const&) = default; RingReverseIterator& operator=(RingReverseIterator const&) = default; RingReverseIterator(RingReverseIterator&&) noexcept = default; RingReverseIterator& operator=(RingReverseIterator&&) noexcept = default; RingReverseIterator& operator++() noexcept { ++current; return *this; } RingReverseIterator& operator++(int) noexcept { return ++(*this); } RingReverseIterator& operator--() noexcept { --current; return *this; } RingReverseIterator& operator--(int) noexcept { return --(*this); } RingReverseIterator& operator+=(int n) noexcept { current += n; return *this; } RingReverseIterator& operator-=(int n) noexcept { current -= n; return *this; } RingReverseIterator operator+(difference_type n) noexcept { return RingReverseIterator { ring, current + n }; } RingReverseIterator operator-(difference_type n) noexcept { return RingReverseIterator { ring, current - n }; } RingReverseIterator operator+(RingReverseIterator const& rhs) const noexcept { return RingReverseIterator { ring, current + rhs.current }; } difference_type operator-(RingReverseIterator const& rhs) const noexcept { return current - rhs.current; } friend RingReverseIterator operator+(difference_type n, RingReverseIterator a) { return RingReverseIterator { a.ring, n + a.current }; } friend RingReverseIterator operator-(difference_type n, RingReverseIterator a) { return RingReverseIterator { a.ring, n - a.current }; } bool operator==(RingReverseIterator const& rhs) const noexcept { return current == rhs.current; } bool operator!=(RingReverseIterator const& rhs) const noexcept { return current != rhs.current; } T& operator*() noexcept { return (*ring)[ring->size() - current - 1]; } T const& operator*() const noexcept { return (*ring)[ring->size() - current - 1]; } T* operator->() noexcept { return &(*ring)[static_cast<difference_type>(ring->size()) - current - 1]; } T* operator->() const noexcept { return &(*ring)[static_cast<difference_type>(ring->size()) - current - 1]; } }; // }}} // {{{ basic_ring<T> impl template <typename T, typename Vector> typename basic_ring<T, Vector>::reverse_iterator basic_ring<T, Vector>::rbegin() noexcept { return reverse_iterator { this, 0 }; } template <typename T, typename Vector> typename basic_ring<T, Vector>::reverse_iterator basic_ring<T, Vector>::rend() noexcept { return reverse_iterator { this, size() }; } template <typename T, typename Vector> typename basic_ring<T, Vector>::const_reverse_iterator basic_ring<T, Vector>::rbegin() const noexcept { return const_reverse_iterator { (basic_ring<T const, Vector>*) this, 0 }; } template <typename T, typename Vector> typename basic_ring<T, Vector>::const_reverse_iterator basic_ring<T, Vector>::rend() const noexcept { return const_reverse_iterator { (basic_ring<T const, Vector>*) this, static_cast<difference_type>(size()) }; } template <typename T, typename Vector> void basic_ring<T, Vector>::rezero() { std::rotate(begin(), std::next(begin(), static_cast<difference_type>(_zero)), end()); // shift-left _zero = 0; } template <typename T, typename Vector> void basic_ring<T, Vector>::rezero(iterator i) { std::rotate(begin(), std::next(begin(), i.current), end()); // shift-left _zero = 0; } // }}} } // namespace crispy
{ "alphanum_fraction": 0.6558543067, "avg_line_length": 30.6076555024, "ext": "h", "hexsha": "162bdf592babbc636b8c2efebc8c5f2956c9bd0c", "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": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_path": "src/crispy/ring.h", "max_issues_count": 69, "max_issues_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "sebastianrakel/contour", "max_issues_repo_path": "src/crispy/ring.h", "max_line_length": 110, "max_stars_count": 4, "max_stars_repo_head_hexsha": "f0004230be75bb99fc899851a216f41d1dca2a81", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sebastianrakel/contour", "max_stars_repo_path": "src/crispy/ring.h", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "num_tokens": 2989, "size": 12794 }
#include "ui/detail/ui_helpers_native.h" #include <gsl/gsl> struct Tcl_Interp; namespace cws80 { class TkUI : public NativeUI { public: std::string choose_file(gsl::span<const FileChooserFilter> filters, const std::string &directory, const std::string &title, FileChooserMode mode) override; cxx::optional<std::string> edit_line(const std::string &title, const std::string &initial_value) override; uint select_by_menu(gsl::span<const std::string> choices, uint initial_selection) override; private: static Tcl_Interp *create_tk_interp(); static std::string quote(gsl::cstring_span str); }; } // namespace cws80
{ "alphanum_fraction": 0.7519623234, "avg_line_length": 33.5263157895, "ext": "h", "hexsha": "cf622d674424d715a99afab86243632c6eaa4aba", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_path": "sources/ui/detail/ui_helpers_tk.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_path": "sources/ui/detail/ui_helpers_tk.h", "max_line_length": 159, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_path": "sources/ui/detail/ui_helpers_tk.h", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "num_tokens": 159, "size": 637 }
/* Copyright 2015 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. ==============================================================================*/ // Portions Copyright (c) Microsoft Corporation #pragma once #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <gsl/gsl> #include "core/common/common.h" #include "core/common/path_string.h" #include "core/framework/callback.h" #include "core/platform/env_time.h" #include "core/platform/telemetry.h" #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #endif namespace Eigen { class ThreadPoolInterface; } namespace onnxruntime { #ifdef _WIN32 using PIDType = unsigned long; using FileOffsetType = int64_t; #else using PIDType = pid_t; using FileOffsetType = off_t; #endif class EnvThread { public: virtual void OnCancel() = 0; virtual ~EnvThread() = default; }; // Parameters that are required to create a set of threads for a thread pool struct ThreadOptions { // Stack size for a new thread. If it is 0, the operating system uses the same value as the stack that's specified for // the main thread, which is usually set in the main executable(not controlled by onnxruntime.dll). unsigned int stack_size = 0; // Thread affinity means a thread can only run on the logical processors that the thread is allowed to run on. // If the vector is not empty, set the affinity of each thread to just one CPU. // Index is thread index, value is CPU ID, starting from zero. For example, the first thread in the pool will be bound // to the logical processor with id of affinity[0]. If the vector is empty, the thread can run on all the processors // its process can run on. NOTE: When hyperthreading is enabled, for example, on a 4 cores 8 physical threads CPU, // processor group [0,1,2,3] may only contain half of the physical cores. std::vector<size_t> affinity; // Set or unset denormal as zero. bool set_denormal_as_zero = false; }; /// \brief An interface used by the onnxruntime implementation to /// access operating system functionality like the filesystem etc. /// /// Callers may wish to provide a custom Env object to get fine grain /// control. /// /// All Env implementations are safe for concurrent access from /// multiple threads without any external synchronization. class Env { public: using EnvThread = onnxruntime::EnvThread; virtual ~Env() = default; // clang-format off /** * Start a new thread for a thread pool * \param name_prefix A human-readable string for debugging purpose, can be NULL * \param index The index value of the thread, for each thread pool instance, the index should start from 0 and be continuous. * \param start_address The entry point of thread * \param threadpool The thread pool that the new thread belongs to * \param thread_options options to create the thread * * Caller is responsible for deleting the returned value */ // clang-format on virtual EnvThread* CreateThread(_In_opt_z_ const ORTCHAR_T* name_prefix, int index, _In_ unsigned (*start_address)(int id, Eigen::ThreadPoolInterface* param), Eigen::ThreadPoolInterface* threadpool, const ThreadOptions& thread_options) = 0; /// \brief Returns a default environment suitable for the current operating /// system. /// /// Sophisticated users may wish to provide their own Env /// implementation instead of relying on this default environment. /// /// The result of Default() belongs to this library and must never be deleted. static Env& Default(); virtual int GetNumCpuCores() const = 0; // This function doesn't support systems with more than 64 logical processors virtual std::vector<size_t> GetThreadAffinityMasks() const = 0; /// \brief Returns the number of micro-seconds since the Unix epoch. virtual uint64_t NowMicros() const { return env_time_->NowMicros(); } /// \brief Returns the number of seconds since the Unix epoch. virtual uint64_t NowSeconds() const { return env_time_->NowSeconds(); } /// Sleeps/delays the thread for the prescribed number of micro-seconds. /// On Windows, it's the min time to sleep, not the actual one. virtual void SleepForMicroseconds(int64_t micros) const = 0; /** * Gets the length of the specified file. */ virtual common::Status GetFileLength(_In_z_ const ORTCHAR_T* file_path, size_t& length) const = 0; virtual common::Status GetFileLength(int fd, /*out*/ size_t& file_size) const = 0; /** * Copies the content of the file into the provided buffer. * @param file_path The path to the file. * @param offset The file offset from which to start reading. * @param length The length in bytes to read. * @param buffer The buffer in which to write. */ virtual common::Status ReadFileIntoBuffer(_In_z_ const ORTCHAR_T* file_path, FileOffsetType offset, size_t length, gsl::span<char> buffer) const = 0; using MappedMemoryPtr = std::unique_ptr<char[], OrtCallbackInvoker>; /** * Maps the content of the file into memory. * This is a copy-on-write mapping, so any changes are not written to the * actual file. * @param file_path The path to the file. * @param offset The file offset from which to start the mapping. * @param length The length in bytes of the mapping. * @param[out] mapped_memory A smart pointer to the mapped memory which * unmaps the memory (unless release()'d) when destroyed. */ virtual common::Status MapFileIntoMemory(_In_z_ const ORTCHAR_T* file_path, FileOffsetType offset, size_t length, MappedMemoryPtr& mapped_memory) const = 0; #ifdef _WIN32 /// \brief Returns true if the directory exists. virtual bool FolderExists(const std::wstring& path) const = 0; /// \brief Recursively creates the directory, if it doesn't exist. virtual common::Status CreateFolder(const std::wstring& path) const = 0; // Mainly for use with protobuf library virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0; // Mainly for use with protobuf library virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0; #endif /// \brief Returns true if the directory exists. virtual bool FolderExists(const std::string& path) const = 0; /// \brief Recursively creates the directory, if it doesn't exist. virtual common::Status CreateFolder(const std::string& path) const = 0; // Recursively deletes the directory and its contents. // Note: This function is not thread safe! virtual common::Status DeleteFolder(const PathString& path) const = 0; // Mainly for use with protobuf library virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0; // Mainly for use with protobuf library virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0; // Mainly for use with protobuf library virtual common::Status FileClose(int fd) const = 0; /** Gets the canonical form of a file path (symlinks resolved). */ virtual common::Status GetCanonicalPath( const PathString& path, PathString& canonical_path) const = 0; // This functions is always successful. It can't fail. virtual PIDType GetSelfPid() const = 0; // \brief Load a dynamic library. // // Pass "library_filename" to a platform-specific mechanism for dynamically // loading a library. The rules for determining the exact location of the // library are platform-specific and are not documented here. // // On success, returns a handle to the library in "*handle" and returns // OK from the function. // Otherwise returns nullptr in "*handle" and an error status from the // function. virtual common::Status LoadDynamicLibrary(const std::string& library_filename, void** handle) const = 0; virtual common::Status UnloadDynamicLibrary(void* handle) const = 0; // \brief Gets the file path of the onnx runtime code // // Used to help load other shared libraries that live in the same folder as the core code, for example // The DNNL provider shared library. Without this path, the module won't be found on windows in all cases. virtual std::string GetRuntimePath() const { return ""; } // \brief Get a pointer to a symbol from a dynamic library. // // "handle" should be a pointer returned from a previous call to LoadDynamicLibrary. // On success, store a pointer to the located symbol in "*symbol" and return // OK from the function. Otherwise, returns nullptr in "*symbol" and an error // status from the function. virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0; // \brief build the name of dynamic library. // // "name" should be name of the library. // "version" should be the version of the library or NULL // returns the name that LoadDynamicLibrary() can use virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0; // \brief returns a provider that will handle telemetry on the current platform virtual const Telemetry& GetTelemetryProvider() const = 0; // \brief returns a value for the queried variable name (var_name) // // Returns the corresponding value stored in the environment variable if available // Returns empty string if there is no such environment variable available virtual std::string GetEnvironmentVar(const std::string& var_name) const = 0; protected: Env(); private: ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env); EnvTime* env_time_ = EnvTime::Default(); }; } // namespace onnxruntime
{ "alphanum_fraction": 0.7176321928, "avg_line_length": 42.1639344262, "ext": "h", "hexsha": "268f729acf811a4de7512ee055e79d3e29095e7c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-03-09T19:15:20.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-20T12:10:05.000Z", "max_forks_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dennyac/onnxruntime", "max_forks_repo_path": "onnxruntime/core/platform/env.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_issues_repo_issues_event_max_datetime": "2022-03-09T05:38:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-01T21:35:50.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dennyac/onnxruntime", "max_issues_repo_path": "onnxruntime/core/platform/env.h", "max_line_length": 128, "max_stars_count": 5, "max_stars_repo_head_hexsha": "d5175795d2b7f2db18b0390f394a49238f814668", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dennyac/onnxruntime", "max_stars_repo_path": "onnxruntime/core/platform/env.h", "max_stars_repo_stars_event_max_datetime": "2021-03-09T19:29:27.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-20T04:53:48.000Z", "num_tokens": 2421, "size": 10288 }
/* * 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 sysop_eb634adc_cca3_4f8f_853c_7852abe06d2d_h #define sysop_eb634adc_cca3_4f8f_853c_7852abe06d2d_h #include <gslib/type.h> #include <gslib/std.h> #include <ariel/type.h> #include <ariel/image.h> __ariel_begin__ enum unimask { declare_mask(um_shift, 0), declare_mask(um_sshift, 1), declare_mask(um_control, 2), declare_mask(um_scontrol, 3), declare_mask(um_reserve, 4), declare_mask(um_alter, 6), declare_mask(um_salter, 7), declare_mask(um_lmouse, 8), declare_mask(um_rmouse, 9), }; enum stylemask { declare_mask(sm_hitable, 0), declare_mask(sm_visible, 1), }; /* * part1. ascii codes * part2. reserved * part3. mouse keys * part4. joystick keys * part5. keyboard controls */ enum unikey { uk_null = 0, /* null */ uk_soh, /* start of heading */ uk_stx, /* start of text */ uk_etx, /* end of text */ uk_eot, /* end of transmission */ uk_enq, /* enquiry */ uk_ack, /* acknowledge */ uk_bel, /* bell */ uk_bs, /* backspace */ uk_tab, /* horizontal tab */ uk_lf, /* nl line feed, new line */ uk_vt, /* vertical tab */ uk_ff, /* np form feed, new page */ uk_cr, /* carriage return */ uk_so, /* shift out */ uk_si, /* shift in */ uk_dle, /* data link escape */ uk_dc1, /* device control 1 */ uk_dc2, /* device control 2 */ uk_dc3, /* device control 3 */ uk_dc4, /* device control 4 */ uk_nak, /* negative acknowledge */ uk_syn, /* synchronous idle */ uk_etb, /* end of trans. block */ uk_can, /* cancel */ uk_em, /* end of medium */ uk_sub, /* substitute */ uk_esc, /* escape */ uk_fs, /* file separator */ uk_gs, /* group separator */ uk_rs, /* record separator */ uk_us, /* unit separator */ uk_sp, /* space, blank */ /* ! - ~ */ uk_del = 0x7f, /* delete */ mk_left, mk_center, mk_right, vk_insert, /* insert */ vk_caps, /* caps lock */ vk_pscr, /* print screen */ vk_numlock, /* number lock */ vk_home, /* home */ vk_end, /* end */ vk_pageup, /* page up */ vk_pagedown, /* page down */ vk_left, /* left arrow */ vk_up, /* up arrow */ vk_right, /* right arrow */ vk_down, /* down arrow */ vk_shift, vk_control, vk_alter, vk_f1, /* f1 - f12 */ vk_f2, vk_f3, vk_f4, vk_f5, vk_f6, vk_f7, vk_f8, vk_f9, vk_f10, vk_f11, vk_f12, }; enum cursor_type { cur_arrow, cur_beam, cur_cross, cur_up_arrow, cur_size_nwse, cur_size_nesw, cur_size_we, cur_size_ns, cur_size_all, cur_hand, cur_help, }; class system_driver; typedef render_texture2d texture2d; class __gs_novtable system_notify abstract { public: virtual void on_show(bool b) = 0; virtual void on_create(system_driver* ptr, const rect& rc) = 0; virtual void on_close() = 0; virtual void on_resize(const rect& rc) = 0; virtual void on_paint(const rect& rc) = 0; virtual void on_halt() = 0; virtual void on_resume() = 0; virtual bool on_mouse_down(uint um, unikey uk, const point& pt) = 0; virtual bool on_mouse_up(uint um, unikey uk, const point& pt) = 0; virtual bool on_mouse_move(uint um, const point& pt) = 0; virtual bool on_key_down(uint um, unikey uk) = 0; virtual bool on_key_up(uint um, unikey uk) = 0; virtual bool on_char(uint um, uint ch) = 0; virtual void on_timer(uint tid) = 0; }; enum clipfmt { cf_text, cf_bitmap, }; class __gs_novtable clipboard_data abstract { public: virtual ~clipboard_data() {} virtual clipfmt get_format() const = 0; virtual void* get_ptr() = 0; virtual int get_size() const = 0; template<class _tdata> _tdata* get_data() { return (_tdata*)get_ptr(); } }; class clipboard_list: public list<clipboard_data*> { public: ~clipboard_list() { for(auto* p : *this) { assert(p); delete p; } clear(); } }; struct clipboard_text: public clipboard_data, public string { virtual clipfmt get_format() const { return cf_text; } virtual void* get_ptr() { return (void*)static_cast<string*>(this); } virtual int get_size() const { return string::length(); } }; struct clipboard_bitmap: public clipboard_data, public image { virtual clipfmt get_format() const { return cf_bitmap; } virtual void* get_ptr() { return (void*)static_cast<image*>(this); } virtual int get_size() const { return -1; } }; struct system_context { enum { sct_notify = 0x01, sct_painter = 0x02, sct_rectangle = 0x04, sct_hwnd = 0x08, sct_hinst = 0x10, sct_everything = 0xffffffff, }; uint mask; system_notify* notify; void* painter; rect rectangle; uint hwnd; uint hinst; }; class __gs_novtable system_driver abstract { public: virtual ~system_driver() {} virtual void initialize(const system_context& ctx) = 0; virtual void setup() = 0; virtual void close() = 0; virtual void set_timer(uint tid, int t) = 0; virtual void kill_timer(uint tid) = 0; virtual void update() = 0; virtual void emit(int msgid, void* msg, int size) = 0; virtual void set_ime(point pt, const font& ft) = 0; virtual void set_cursor(cursor_type curty) = 0; //virtual void set_clipboard(const gchar* fmt, const void* ptr, int size) = 0; //virtual int get_clipboard(const gchar* fmt, const void*& ptr) = 0; //virtual int get_clipboard(clipboard_list& cl, int c) = 0; }; class __gs_novtable fontsys abstract { public: virtual ~fontsys() {} virtual void initialize() = 0; virtual void set_font(const font& f) = 0; virtual bool query_size(const gchar* str, int& w, int& h, int len = -1) = 0; virtual bool create_text_image(image& img, const gchar* str, int x, int y, const color& cr, int len = -1) = 0; virtual bool create_text_texture(texture2d** tex, const gchar* str, int margin, const color& cr, int len = -1) = 0; virtual void draw(image& img, const gchar* str, int x, int y, const color& cr, int len = -1) = 0; }; __ariel_end__ #endif
{ "alphanum_fraction": 0.57239819, "avg_line_length": 30.6496350365, "ext": "h", "hexsha": "7c8b9a0bd42850685a998d1a0808e13d41606f52", "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/sysop.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/sysop.h", "max_line_length": 120, "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/sysop.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": 2168, "size": 8398 }
/* multimin/vector_bfgs.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi * * 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. */ /* vector_bfgs.c -- Limited memory Broyden-Fletcher-Goldfarb-Shanno conjugate gradient method */ /* Modified by Brian Gough to use single iteration structure */ #include <config.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_blas.h> #include "directional_minimize.c" typedef struct { int iter; double step; double max_step; double tol; gsl_vector *x1; gsl_vector *dx1; gsl_vector *x2; double g0norm; double pnorm; gsl_vector *p; gsl_vector *x0; gsl_vector *g0; gsl_vector *dx0; gsl_vector *dg0; } vector_bfgs_state_t; static int vector_bfgs_alloc (void *vstate, size_t n) { vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate; state->x1 = gsl_vector_calloc (n); if (state->x1 == 0) { GSL_ERROR ("failed to allocate space for x1", GSL_ENOMEM); } state->dx1 = gsl_vector_calloc (n); if (state->dx1 == 0) { gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for dx1", GSL_ENOMEM); } state->x2 = gsl_vector_calloc (n); if (state->x2 == 0) { gsl_vector_free (state->dx1); gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for x2", GSL_ENOMEM); } state->p = gsl_vector_calloc (n); if (state->p == 0) { gsl_vector_free (state->x2); gsl_vector_free (state->dx1); gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for p", GSL_ENOMEM); } state->x0 = gsl_vector_calloc (n); if (state->x0 == 0) { gsl_vector_free (state->p); gsl_vector_free (state->x2); gsl_vector_free (state->dx1); gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for g0", GSL_ENOMEM); } state->g0 = gsl_vector_calloc (n); if (state->g0 == 0) { gsl_vector_free (state->x0); gsl_vector_free (state->p); gsl_vector_free (state->x2); gsl_vector_free (state->dx1); gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for g0", GSL_ENOMEM); } state->dx0 = gsl_vector_calloc (n); if (state->dx0 == 0) { gsl_vector_free (state->g0); gsl_vector_free (state->x0); gsl_vector_free (state->p); gsl_vector_free (state->x2); gsl_vector_free (state->dx1); gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for g0", GSL_ENOMEM); } state->dg0 = gsl_vector_calloc (n); if (state->dg0 == 0) { gsl_vector_free (state->dx0); gsl_vector_free (state->g0); gsl_vector_free (state->x0); gsl_vector_free (state->p); gsl_vector_free (state->x2); gsl_vector_free (state->dx1); gsl_vector_free (state->x1); GSL_ERROR ("failed to allocate space for g0", GSL_ENOMEM); } return GSL_SUCCESS; } static int vector_bfgs_set (void *vstate, gsl_multimin_function_fdf * fdf, const gsl_vector * x, double *f, gsl_vector * gradient, double step_size, double tol) { vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate; state->iter = 0; state->step = step_size; state->max_step = step_size; state->tol = tol; GSL_MULTIMIN_FN_EVAL_F_DF (fdf, x, f, gradient); /* Use the gradient as the initial direction */ gsl_vector_memcpy (state->x0, x); gsl_vector_memcpy (state->p, gradient); gsl_vector_memcpy (state->g0, gradient); { double gnorm = gsl_blas_dnrm2 (gradient); state->pnorm = gnorm; state->g0norm = gnorm; } return GSL_SUCCESS; } static void vector_bfgs_free (void *vstate) { vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate; gsl_vector_free (state->dg0); gsl_vector_free (state->dx0); gsl_vector_free (state->g0); gsl_vector_free (state->x0); gsl_vector_free (state->p); gsl_vector_free (state->x2); gsl_vector_free (state->dx1); gsl_vector_free (state->x1); } static int vector_bfgs_restart (void *vstate) { vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate; state->iter = 0; return GSL_SUCCESS; } static int vector_bfgs_iterate (void *vstate, gsl_multimin_function_fdf * fdf, gsl_vector * x, double *f, gsl_vector * gradient, gsl_vector * dx) { vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate; gsl_vector *x1 = state->x1; gsl_vector *dx1 = state->dx1; gsl_vector *x2 = state->x2; gsl_vector *p = state->p; gsl_vector *g0 = state->g0; gsl_vector *x0 = state->x0; double pnorm = state->pnorm; double g0norm = state->g0norm; double fa = *f, fb, fc; double dir; double stepa = 0.0, stepb, stepc = state->step, tol = state->tol; double g1norm; double pg; if (pnorm == 0.0 || g0norm == 0.0) { gsl_vector_set_zero (dx); return GSL_ENOPROG; } /* Determine which direction is downhill, +p or -p */ gsl_blas_ddot (p, gradient, &pg); dir = (pg >= 0.0) ? +1.0 : -1.0; /* Compute new trial point at x_c= x - step * p, where p is the current direction */ take_step (x, p, stepc, dir / pnorm, x1, dx); /* Evaluate function and gradient at new point xc */ fc = GSL_MULTIMIN_FN_EVAL_F (fdf, x1); if (fc < fa) { /* Success, reduced the function value */ state->step = stepc * 2.0; *f = fc; gsl_vector_memcpy (x, x1); GSL_MULTIMIN_FN_EVAL_DF (fdf, x1, gradient); state->g0norm = gsl_blas_dnrm2 (gradient); return GSL_SUCCESS; } #ifdef DEBUG printf ("got stepc = %g fc = %g\n", stepc, fc); #endif /* Do a line minimisation in the region (xa,fa) (xc,fc) to find an intermediate (xb,fb) satisifying fa > fb < fc. Choose an initial xb based on parabolic interpolation */ intermediate_point (fdf, x, p, dir / pnorm, pg, stepa, stepc, fa, fc, x1, dx1, gradient, &stepb, &fb); minimize (fdf, x, p, dir / pnorm, stepa, stepb, stepc, fa, fb, fc, tol, x1, dx1, x2, dx, gradient, &(state->step), f, &g1norm); gsl_vector_memcpy (x, x2); /* Choose a new conjugate direction for the next step */ state->iter = (state->iter + 1) % x->size; if (state->iter == 0) { gsl_vector_memcpy (p, gradient); state->pnorm = g1norm; } else { /* This is the BFGS update: */ /* p' = g1 - A dx - B dg */ /* A = - (1+ dg.dg/dx.dg) B + dg.g/dx.dg */ /* B = dx.g/dx.dg */ gsl_vector *dx0 = state->dx0; gsl_vector *dg0 = state->dg0; double dxg, dgg, dxdg, dgnorm, A, B; /* dx0 = x - x0 */ gsl_vector_memcpy (dx0, x); gsl_blas_daxpy (-1.0, x0, dx0); /* dg0 = g - g0 */ gsl_vector_memcpy (dg0, gradient); gsl_blas_daxpy (-1.0, g0, dg0); gsl_blas_ddot (dx0, gradient, &dxg); gsl_blas_ddot (dg0, gradient, &dgg); gsl_blas_ddot (dx0, dg0, &dxdg); dgnorm = gsl_blas_dnrm2 (dg0); B = dxg / dxdg; A = -(1.0 + dgnorm * dgnorm / dxdg) * B + dgg / dxdg; gsl_vector_memcpy (p, gradient); gsl_blas_daxpy (-A, dx0, p); gsl_blas_daxpy (-B, dg0, p); state->pnorm = gsl_blas_dnrm2 (p); } gsl_vector_memcpy (g0, gradient); gsl_vector_memcpy (x0, x); state->g0norm = gsl_blas_dnrm2 (g0); #ifdef DEBUG printf ("updated conjugate directions\n"); printf ("p: "); gsl_vector_fprintf (stdout, p, "%g"); printf ("g: "); gsl_vector_fprintf (stdout, gradient, "%g"); #endif return GSL_SUCCESS; } static const gsl_multimin_fdfminimizer_type vector_bfgs_type = { "vector_bfgs", /* name */ sizeof (vector_bfgs_state_t), &vector_bfgs_alloc, &vector_bfgs_set, &vector_bfgs_iterate, &vector_bfgs_restart, &vector_bfgs_free }; const gsl_multimin_fdfminimizer_type * gsl_multimin_fdfminimizer_vector_bfgs = &vector_bfgs_type;
{ "alphanum_fraction": 0.6436835891, "avg_line_length": 24.9117647059, "ext": "c", "hexsha": "bbcbed5e23a8f81ab840ee392ccb3c0dcf244ccc", "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/multimin/vector_bfgs.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/multimin/vector_bfgs.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/multimin/vector_bfgs.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": 2679, "size": 8470 }
/* randist/discrete.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Random Discrete Events Given K discrete events with different probabilities P[k] produce a value k consistent with its probability. 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 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Based on: Alastair J Walker, An efficient method for generating * discrete random variables with general distributions, ACM Trans * Math Soft 3, 253-256 (1977). See also: D. E. Knuth, The Art of * Computer Programming, Volume 2 (Seminumerical algorithms), 3rd * edition, Addison-Wesley (1997), p120. * Walker's algorithm does some preprocessing, and provides two * arrays: floating point F[k] and integer A[k]. A value k is chosen * from 0..K-1 with equal likelihood, and then a uniform random number * u is compared to F[k]. If it is less than F[k], then k is * returned. Otherwise, A[k] is returned. * Walker's original paper describes an O(K^2) algorithm for setting * up the F and A arrays. I found this disturbing since I wanted to * use very large values of K. I'm sure I'm not the first to realize * this, but in fact the preprocessing can be done in O(K) steps. * A figure of merit for the preprocessing is the average value for * the F[k]'s (that is, SUM_k F[k]/K); this corresponds to the * probability that k is returned, instead of A[k], thereby saving a * redirection. Walker's O(K^2) preprocessing will generally improve * that figure of merit, compared to my cheaper O(K) method; from some * experiments with a perl script, I get values of around 0.6 for my * method and just under 0.75 for Walker's. Knuth has pointed out * that finding _the_ optimum lookup tables, which maximize the * average F[k], is a combinatorially difficult problem. But any * valid preprocessing will still provide O(1) time for the call to * gsl_ran_discrete(). I find that if I artificially set F[k]=1 -- * ie, better than optimum! -- I get a speedup of maybe 20%, so that's * the maximum I could expect from the most expensive preprocessing. * Folding in the difference of 0.6 vs 0.75, I'd estimate that the * speedup would be less than 10%. * I've not implemented it here, but one compromise is to sort the * probabilities once, and then work from the two ends inward. This * requires O(K log K), still lots cheaper than O(K^2), and from my * experiments with the perl script, the figure of merit is within * about 0.01 for K up to 1000, and no sign of diverging (in fact, * they seemed to be converging, but it's hard to say with just a * handful of runs). * The O(K) algorithm goes through all the p_k's and decides if they * are "smalls" or "bigs" according to whether they are less than or * greater than the mean value 1/K. The indices to the smalls and the * bigs are put in separate stacks, and then we work through the * stacks together. For each small, we pair it up with the next big * in the stack (Walker always wanted to pair up the smallest small * with the biggest big). The small "borrows" from the big just * enough to bring the small up to mean. This reduces the size of the * big, so the (smaller) big is compared again to the mean, and if it * is smaller, it gets "popped" from the big stack and "pushed" to the * small stack. Otherwise, it stays put. Since every time we pop a * small, we are able to deal with it right then and there, and we * never have to pop more than K smalls, then the algorithm is O(K). * This implementation sets up two separate stacks, and allocates K * elements between them. Since neither stack ever grows, we do an * extra O(K) pass through the data to determine how many smalls and * bigs there are to begin with and allocate appropriately. In all * there are 2*K*sizeof(double) transient bytes of memory that are * used than returned, and K*(sizeof(int)+sizeof(double)) bytes used * in the lookup table. * Walker spoke of using two random numbers (an integer 0..K-1, and a * floating point u in [0,1]), but Knuth points out that one can just * use the integer and fractional parts of K*u where u is in [0,1]. * In fact, Knuth further notes that taking F'[k]=(k+F[k])/K, one can * directly compare u to F'[k] without having to explicitly set * u=K*u-int(K*u). * Usage: * Starting with an array of probabilities P, initialize and do * preprocessing with a call to: * gsl_rng *r; * gsl_ran_discrete_t *f; * f = gsl_ran_discrete_preproc(K,P); * Then, whenever a random index 0..K-1 is desired, use * k = gsl_ran_discrete(r,f); * Note that several different randevent struct's can be * simultaneously active. * Aside: A very clever alternative approach is described in * Abramowitz and Stegun, p 950, citing: Marsaglia, Random variables * and computers, Proc Third Prague Conference in Probability Theory, * 1962. A more accesible reference is: G. Marsaglia, Generating * discrete random numbers in a computer, Comm ACM 6, 37-38 (1963). * If anybody is interested, I (jt) have also coded up this version as * part of another software package. However, I've done some * comparisons, and the Walker method is both faster and more stingy * with memory. So, in the end I decided not to include it with the * GSL package. * Written 26 Jan 1999, James Theiler, jt@lanl.gov * Adapted to GSL, 30 Jan 1999, jt */ #include <config.h> #include <stdio.h> /* used for NULL, also fprintf(stderr,...) */ #include <stdlib.h> /* used for malloc's */ #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #define DEBUG 0 #define KNUTH_CONVENTION 1 /* Saves a few steps of arithmetic * in the call to gsl_ran_discrete() */ /*** Begin Stack (this code is used just in this file) ***/ /* Stack code converted to use unsigned indices (i.e. s->i == 0 now means an empty stack, instead of -1), for consistency and to give a bigger allowable range. BJG */ typedef struct { size_t N; /* max number of elts on stack */ size_t *v; /* array of values on the stack */ size_t i; /* index of top of stack */ } gsl_stack_t; static gsl_stack_t * new_stack(size_t N) { gsl_stack_t *s; s = (gsl_stack_t *)malloc(sizeof(gsl_stack_t)); s->N = N; s->i = 0; /* indicates stack is empty */ s->v = (size_t *)malloc(sizeof(size_t)*N); return s; } static int push_stack(gsl_stack_t *s, size_t v) { if ((s->i) >= (s->N)) { return -1; /* stack overflow (shouldn't happen) */ } (s->v)[s->i] = v; s->i += 1; return 0; } static size_t pop_stack(gsl_stack_t *s) { if ((s->i) == 0) { GSL_ERROR ("internal error - stack exhausted", GSL_ESANITY); } s->i -= 1; return ((s->v)[s->i]); } static inline size_t size_stack(const gsl_stack_t *s) { return s->i; } static void free_stack(gsl_stack_t *s) { free((char *)(s->v)); free((char *)s); } /*** End Stack ***/ /*** Begin Walker's Algorithm ***/ gsl_ran_discrete_t * gsl_ran_discrete_preproc(size_t Kevents, const double *ProbArray) { size_t k,b,s; gsl_ran_discrete_t *g; size_t nBigs, nSmalls; gsl_stack_t *Bigs; gsl_stack_t *Smalls; double *E; double pTotal = 0.0, mean, d; if (Kevents < 1) { /* Could probably treat Kevents=1 as a special case */ GSL_ERROR_VAL ("number of events must be a positive integer", GSL_EINVAL, 0); } /* Make sure elements of ProbArray[] are positive. * Won't enforce that sum is unity; instead will just normalize */ for (k=0; k<Kevents; ++k) { if (ProbArray[k] < 0) { GSL_ERROR_VAL ("probabilities must be non-negative", GSL_EINVAL, 0) ; } pTotal += ProbArray[k]; } /* Begin setting up the main "object" (just a struct, no steroids) */ g = (gsl_ran_discrete_t *)malloc(sizeof(gsl_ran_discrete_t)); g->K = Kevents; g->F = (double *)malloc(sizeof(double)*Kevents); g->A = (size_t *)malloc(sizeof(size_t)*Kevents); E = (double *)malloc(sizeof(double)*Kevents); if (E==NULL) { GSL_ERROR_VAL ("Cannot allocate memory for randevent", GSL_ENOMEM, 0); } for (k=0; k<Kevents; ++k) { E[k] = ProbArray[k]/pTotal; } /* Now create the Bigs and the Smalls */ mean = 1.0/Kevents; nSmalls=nBigs=0; { /* Temporarily use which[k] = g->A[k] to indicate small or large */ size_t * const which = g->A; for (k=0; k<Kevents; ++k) { if (E[k] < mean) { ++nSmalls; which[k] = 0; } else { ++nBigs; which[k] = 1; } } Bigs = new_stack(nBigs); Smalls = new_stack(nSmalls); for (k=0; k<Kevents; ++k) { gsl_stack_t * Dest = which[k] ? Bigs : Smalls; int status = push_stack(Dest,k); if (status) GSL_ERROR_VAL ("failed to build stacks", GSL_EFAILED, 0); } } /* Now work through the smalls */ while (size_stack(Smalls) > 0) { s = pop_stack(Smalls); if (size_stack(Bigs) == 0) { (g->A)[s]=s; (g->F)[s]=1.0; continue; } b = pop_stack(Bigs); (g->A)[s]=b; (g->F)[s]=Kevents*E[s]; #if DEBUG fprintf(stderr,"s=%2d, A=%2d, F=%.4f\n",s,(g->A)[s],(g->F)[s]); #endif d = mean - E[s]; E[s] += d; /* now E[s] == mean */ E[b] -= d; if (E[b] < mean) { push_stack(Smalls,b); /* no longer big, join ranks of the small */ } else if (E[b] > mean) { push_stack(Bigs,b); /* still big, put it back where you found it */ } else { /* E[b]==mean implies it is finished too */ (g->A)[b]=b; (g->F)[b]=1.0; } } while (size_stack(Bigs) > 0) { b = pop_stack(Bigs); (g->A)[b]=b; (g->F)[b]=1.0; } /* Stacks have been emptied, and A and F have been filled */ if ( size_stack(Smalls) != 0) { GSL_ERROR_VAL ("Smalls stack has not been emptied", GSL_ESANITY, 0 ); } #if 0 /* if 1, then artificially set all F[k]'s to unity. This will * give wrong answers, but you'll get them faster. But, not * that much faster (I get maybe 20%); that's an upper bound * on what the optimal preprocessing would give. */ for (k=0; k<Kevents; ++k) { (g->F)[k] = 1.0; } #endif #if KNUTH_CONVENTION /* For convenience, set F'[k]=(k+F[k])/K */ /* This saves some arithmetic in gsl_ran_discrete(); I find that * it doesn't actually make much difference. */ for (k=0; k<Kevents; ++k) { (g->F)[k] += k; (g->F)[k] /= Kevents; } #endif free_stack(Bigs); free_stack(Smalls); free((char *)E); return g; } size_t gsl_ran_discrete(const gsl_rng *r, const gsl_ran_discrete_t *g) { size_t c=0; double u,f; u = gsl_rng_uniform(r); #if KNUTH_CONVENTION c = (u*(g->K)); #else u *= g->K; c = u; u -= c; #endif f = (g->F)[c]; /* fprintf(stderr,"c,f,u: %d %.4f %f\n",c,f,u); */ if (f == 1.0) return c; if (u < f) { return c; } else { return (g->A)[c]; } } void gsl_ran_discrete_free(gsl_ran_discrete_t *g) { RETURN_IF_NULL (g); free((char *)(g->A)); free((char *)(g->F)); free((char *)g); } double gsl_ran_discrete_pdf(size_t k, const gsl_ran_discrete_t *g) { size_t i,K; double f,p=0; K= g->K; if (k>K) return 0; for (i=0; i<K; ++i) { f = (g->F)[i]; #if KNUTH_CONVENTION f = K*f-i; #endif if (i==k) { p += f; } else if (k == (g->A)[i]) { p += 1.0 - f; } } return p/K; }
{ "alphanum_fraction": 0.6219076006, "avg_line_length": 32.972972973, "ext": "c", "hexsha": "a1400eebade8ace37e0c7dee8e68f1f6f040dbb3", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/randist/discrete.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/randist/discrete.c", "max_line_length": 84, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/randist/discrete.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 3814, "size": 13420 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2012-2018 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; 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 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #include "ObitPolnCalFit.h" #include "ObitSpectrumFit.h" #include "ObitThread.h" #include "ObitTableAN.h" #include "ObitTableANUtil.h" #include "ObitTableSU.h" #include "ObitTableSUUtil.h" #include "ObitPrecess.h" #ifdef HAVE_GSL #include <gsl/gsl_blas.h> #endif /* HAVE_GSL */ #ifndef VELIGHT #define VELIGHT 2.997924562e8 #endif /*----------------Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitPolnCalFit.c * ObitPolnCalFit class function definitions. * This class is derived from the Obit base class. */ /** name of the class defined in this file */ static gchar *myClassName = "ObitPolnCalFit"; /** Function to obtain parent ClassInfo */ static ObitGetClassFP ObitParentGetClass = ObitGetClass; /** * ClassInfo structure ObitPolnCalFitClassInfo. * This structure is used by class objects to access class functions. */ static ObitPolnCalFitClassInfo myClassInfo = {FALSE}; /*--------------- File Global Variables ----------------*/ /*---------------Private function prototypes----------------*/ /** Private: Initialize newly instantiated object. */ void ObitPolnCalFitInit (gpointer in); /** Private: Deallocate members. */ void ObitPolnCalFitClear (gpointer in); /** Private: Set Class function pointers. */ static void ObitPolnCalFitClassInfoDefFn (gpointer inClass); /** Private: Write output image */ static void WriteOutput (ObitPolnCalFit* in, ObitUV *outUV, gboolean isOK, ObitErr *err); /** Private: Read data to thread arguments, init soln */ static void ReadData(ObitPolnCalFit *in, ObitUV *inUV, olong *iChan, olong EChan, olong *iIF, olong EIF, gboolean first, ObitErr *err); /* Private: Initialize new Source poln.(CP) table */ static void InitSourceTab(ObitPolnCalFit *in, ObitErr *err); /* Private: Initialize new Instrumental poln.(PD) table */ static void InitInstrumentalTab(ObitPolnCalFit *in, ObitErr *err); /* Private: Initialize new Bandpass.(BP) table */ static void InitBandpassTab(ObitPolnCalFit *in, ObitErr *err); /* Private: Update Source poln.(CP) table */ static void UpdateSourceTab(ObitPolnCalFit *in, ObitErr *err); /* Private: Update Instrumental poln.(PD) table */ static void UpdateInstrumentalTab(ObitPolnCalFit *in, gboolean isOK, ObitErr *err); /* Private: Update Bandpass.(BP) table */ static void UpdateBandpassTab(ObitPolnCalFit *in, gboolean isOK, ObitErr *err); /** Private: Fit spectra in SU list */ static void FitSpectra (ObitPolnCalFit *in, ObitErr *err); /** Private: Fit data */ static gboolean doFitFast(ObitPolnCalFit *in, ObitErr *err); static void doFitGSL (ObitPolnCalFit *in, ObitErr *err); /** Private: Get Chi Sq & derivatives of current model */ static odouble GetChi2 (olong nThreads, ObitPolnCalFit *in, PolnParmType paramType, olong paramNumber, ofloat *ParRMS, ofloat *XRMS, odouble *dChi2, odouble *d2Chi2, ObitErr *err); /** Private: Determine RMS residuals of current model on selected data */ static void GetRMSes (olong nThreads, ObitPolnCalFit *in, olong antNumber, ofloat *ParRMS, ofloat *XRMS, ObitErr *err); /** Private: Fit R/L Phase difference */ ofloat FitRLPhase (ObitPolnCalFit *in, ObitErr *err); /** Private: Make Threaded args */ static void MakePolnFitFuncArgs (ObitPolnCalFit *in, ObitErr *err); /** Private: Delete Threaded args */ static void KillPolnFitFuncArgs (ObitPolnCalFit *in); /** Private: Threaded Chi**2 R/L evaluator */ static gpointer ThreadPolnFitRLChi2 (gpointer arg); /** Private: Threaded Chi**2 X/Y evaluator */ static gpointer ThreadPolnFitXYChi2 (gpointer arg); /** Private: Check for crazy antenna solutions */ static gboolean CheckCrazy(ObitPolnCalFit *in, ObitErr *err); /** Private: Check for one crazy antenna, flag */ static gboolean CheckCrazyOne(ObitPolnCalFit *in, ObitErr *err); /** Private: Reset solutions */ static void ResetAllSoln(ObitPolnCalFit *in); /** Private: Reset blanked solutions */ static void resetSoln(ObitPolnCalFit *in); /** Private: Constrain Linear feed fits */ static ofloat ConstrLinFeed (ObitPolnCalFit *in); #ifdef HAVE_GSL /** Private: Circular feed Solver function evaluation */ static int PolnFitFuncOERL (const gsl_vector *x, void *params, gsl_vector *f); /** Private: Circular feed Solver Jacobian evaluation */ static int PolnFitJacOERL (const gsl_vector *x, void *params, gsl_matrix *J); /** Private: Circular feed Solver function + Jacobian evaluation */ static int PolnFitFuncJacOERL (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); /** Private: Linear feed Solver function evaluation */ static int PolnFitFuncOEXY (const gsl_vector *x, void *params, gsl_vector *f); /** Private: Linear feed Solver Jacobian evaluation */ static int PolnFitJacOEXY (const gsl_vector *x, void *params, gsl_matrix *J); /** Private: Linear feed Solver function + Jacobian evaluation */ static int PolnFitFuncJacOEXY (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); #endif /* HAVE_GSL */ /*----------------------Public functions---------------------------*/ /** * Constructor. * Initializes class if needed on first call. * \param name An optional name for the object. * \return the new object. */ ObitPolnCalFit* newObitPolnCalFit (gchar* name) { ObitPolnCalFit* out; /* Class initialization if needed */ if (!myClassInfo.initialized) ObitPolnCalFitClassInit(); /* allocate/init structure */ out = g_malloc0(sizeof(ObitPolnCalFit)); /* initialize values */ if (name!=NULL) out->name = g_strdup(name); else out->name = g_strdup("Noname"); /* set ClassInfo */ out->ClassInfo = (gpointer)&myClassInfo; /* initialize other stuff */ ObitPolnCalFitInit((gpointer)out); return out; } /* end newObitPolnCalFit */ /** * Returns ClassInfo pointer for the class. * \return pointer to the class structure. */ gconstpointer ObitPolnCalFitGetClass (void) { /* Class initialization if needed */ if (!myClassInfo.initialized) ObitPolnCalFitClassInit(); return (gconstpointer)&myClassInfo; } /* end ObitPolnCalFitGetClass */ /** * Make a deep copy of an ObitPolnCalFit. * NOT YET IMPLEMENTED * \param in The object to copy * \param out An existing object pointer for output or NULL if none exists. * \param err Obit error stack object. * \return pointer to the new object. */ ObitPolnCalFit* ObitPolnCalFitCopy (ObitPolnCalFit *in, ObitPolnCalFit *out, ObitErr *err) { const ObitClassInfo *ParentClass; gboolean oldExist; gchar *outName; /* error checks */ if (err->error) return out; g_assert (ObitIsA(in, &myClassInfo)); if (out) g_assert (ObitIsA(out, &myClassInfo)); /* Create if it doesn't exist */ oldExist = out!=NULL; if (!oldExist) { /* derive object name */ outName = g_strconcat ("Copy: ",in->name,NULL); out = newObitPolnCalFit(outName); g_free(outName); } /* deep copy any base class members */ ParentClass = myClassInfo.ParentClass; g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL)); ParentClass->ObitCopy (in, out, err); /* copy this class */ /* Arrays */ /* reference this class members */ return out; } /* end ObitPolnCalFitCopy */ /** * Make a copy of a object but do not copy the actual data * This is useful to create an PolnCalFit similar to the input one. * NOT YET IMPLEMENTED * \param in The object to copy * \param out An existing object pointer for output, must be defined. * \param err Obit error stack object. */ void ObitPolnCalFitClone (ObitPolnCalFit *in, ObitPolnCalFit *out, ObitErr *err) { const ObitClassInfo *ParentClass; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert (ObitIsA(out, &myClassInfo)); /* deep copy any base class members */ ParentClass = myClassInfo.ParentClass; g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL)); ParentClass->ObitCopy (in, out, err); /* copy this class */ /* Arrays */ /* reference this class members */ } /* end ObitPolnCalFitClone */ /** * Creates an ObitPolnCalFit * \param name An optional name for the object. * \return the new object. */ ObitPolnCalFit* ObitPolnCalFitCreate (gchar* name) { ObitPolnCalFit* out; /* Create basic structure */ out = newObitPolnCalFit (name); return out; } /* end ObitPolnCalFitCreate */ /** * Calculate circular feed model using a thread argument * \param args argument * \param Rarray output array * \param idata 0-rel data number */ static void calcmodelRL (ObitPolnCalFit *args, ofloat Rarray[8], olong idata) { odouble *antParm = args->antParm; odouble *souParm = args->souParm; ofloat *data = args->inData; dcomplex *RS = args->RS; dcomplex *RD = args->RD; dcomplex *LS = args->LS; dcomplex *LD = args->LD; dcomplex *RSc = args->RSc; dcomplex *RDc = args->RDc; dcomplex *LSc = args->LSc; dcomplex *LDc = args->LDc; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; ofloat PD; olong i, ia1, ia2, isou; dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c, ct1, ct2; dcomplex S[4], VRR, VRL, VLR, VLL, MC1, MC2, MC3, MC4; ofloat root2, chi1, chi2; /* R-L phase difference at reference antenna */ PD = args->PD; COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (PA1, 2*chi1); COMPLEX_EXP (PA2, 2*chi2); COMPLEX_CONJUGATE (PA1c, PA1); COMPLEX_CONJUGATE (PA2c, PA2); isou = MAX (0, args->souNo[idata]); /* Source number */ /* Source parameters */ ipol = souParm[isou*4+0]; qpol = souParm[isou*4+1]; upol = souParm[isou*4+2]; vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S[0], ipol+vpol, 0.0); COMPLEX_SET (S[1], qpol, upol); COMPLEX_SET (S[2], qpol, -upol); COMPLEX_SET (S[3], ipol-vpol, 0.0); /* Injest model factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/ root2 = 1.0 / sqrt(2.0); /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_SET(RS[i], root2*(cos(antParm[i*4+1]) + sin(antParm[i*4+1])), 0); COMPLEX_SET(ct1, root2*(cos(antParm[i*4+1]) - sin(antParm[i*4+1])), 0); COMPLEX_EXP(ct2, 2*antParm[i*4+0]); COMPLEX_MUL2 (RD[i], ct1, ct2); COMPLEX_SET (ct1, root2*(cos(antParm[i*4+3]) + sin(antParm[i*4+3])), 0); COMPLEX_EXP (ct2, -2*antParm[i*4+2]); COMPLEX_MUL2 (LS[i], ct1, ct2); COMPLEX_SET (LD[i], root2*(cos(antParm[i*4+3]) - sin(antParm[i*4+3])), 0); COMPLEX_CONJUGATE (RSc[i], RS[i]); COMPLEX_CONJUGATE (RDc[i], RD[i]); COMPLEX_CONJUGATE (LSc[i], LS[i]); COMPLEX_CONJUGATE (LDc[i], LD[i]); } /* Reference antenna phase terms */ if (args->refAnt>0) { COMPLEX_EXP (PRref, antParm[(args->refAnt-1)*4+0]); COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD); } else { COMPLEX_SET(PRref, 1.0, 0.0); COMPLEX_EXP (PLref, PD); } COMPLEX_CONJUGATE (ct1, PLref); COMPLEX_MUL2 (PPRL, PRref, ct1); COMPLEX_CONJUGATE (ct1, PRref); COMPLEX_MUL2 (PPLR, PLref, ct1); ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* VRR = S[0] * RS[ia1] * RSc[ia2] + S[1] * RS[ia1] * RDc[ia2] * PA2c + S[2] * RD[ia1] * RSc[ia2] * PA1 + S[3] * RD[ia1] * RDc[ia2] * PA1 * PA2c; */ COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]); COMPLEX_MUL2 (VRR, S[0], MC1); COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRR, VRR, ct1); Rarray[0] = VRR.real; Rarray[1] = VRR.imag; /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 + S[1] * LS[ia1] * LDc[ia2] * PA1c + S[2] * LD[ia1] * LSc[ia2] * PA2 + S[3] * LD[ia1] * LDc[ia2]; */ COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2 (VLL, S[0], MC1); COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLL, VLL, ct1); Rarray[6] = VLL.real; Rarray[7] = VLL.imag; /* RL */ /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 + PPRL * S[1] * RS[ia1] * LDc[ia2] + PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */ COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (VRL, S[0], MC1); COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRL, VRL, ct1); Rarray[2] = VRL.real; Rarray[3] = VRL.imag; /* LR */ /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c + PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * S[2] * LD[ia1] * RSc[ia2] + PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL2 (VLR, S[0], MC1); COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLR, VLR, ct1); Rarray[4] = VLR.real; Rarray[5] = VLR.imag; } /* end calcmodelRL */ /** * Calculate linear feed model using a thread argument * R Perley version * \param args argument * \param Rarray output array * \param idata 0-rel data number */ static void calcmodelXY (ObitPolnCalFit *args, ofloat Rarray[8], olong idata) { odouble *antParm = args->antParm; odouble *antGain = args->antGain; odouble *souParm = args->souParm; ofloat *data = args->inData; dcomplex *CX = args->RS; dcomplex *SX = args->RD; dcomplex *CY = args->LS; dcomplex *SY = args->LD; dcomplex *CXc = args->RSc; dcomplex *SXc = args->RDc; dcomplex *CYc = args->LSc; dcomplex *SYc = args->LDc; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; olong i, ia1, ia2, isou; dcomplex SPA, DPA, SPAc, DPAc, ct1, ct2, ct3; dcomplex S[4], S0[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4; dcomplex SM1, SM2, SM3, SM4, ggPD; ofloat chi1, chi2, PD; /* Init working variables */ COMPLEX_SET (MC1, 0.0, 0.0); /* Muller matrix */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (SPA,(chi1+chi2)); COMPLEX_EXP (DPA,chi1-chi2); COMPLEX_CONJUGATE (SPAc, SPA); COMPLEX_CONJUGATE (DPAc, DPA); isou = MAX (0, args->souNo[idata]); /* Source number */ /* X-Y phase difference at reference antenna */ PD = args->PD; /* Source parameters */ ipol = souParm[isou*4+0]; qpol = souParm[isou*4+1]; upol = souParm[isou*4+2]; vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S0[0], ipol+vpol, 0.0); COMPLEX_SET (S0[1], qpol, upol); COMPLEX_SET (S0[2], qpol, -upol); COMPLEX_SET (S0[3], ipol-vpol, 0.0); /* Rotate Stokes by parallactic angle */ COMPLEX_MUL2(S[0], DPAc, S0[0]); COMPLEX_MUL2(S[1], SPAc, S0[1]); COMPLEX_MUL2(S[2], SPA, S0[2]); COMPLEX_MUL2(S[3], DPA, S0[3]); /* Injest model factorize into antenna components - data in order 0: Orientation X, 1: Elipticity X, 2: Orientation Y, 3: Elipticity Y */ /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_EXP (ct1, -antParm[i*4+0]); COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (CX[i], ct2, ct1); COMPLEX_EXP (ct1, antParm[i*4+0]); COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (SX[i], ct2, ct1); COMPLEX_EXP (ct1, antParm[i*4+2]); COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (CY[i], ct2, ct1); COMPLEX_EXP (ct1, -antParm[i*4+2]); COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (SY[i], ct2, ct1); COMPLEX_CONJUGATE (CXc[i], CX[i]); COMPLEX_CONJUGATE (SXc[i], SX[i]); COMPLEX_CONJUGATE (CYc[i], CY[i]); COMPLEX_CONJUGATE (SYc[i], SY[i]); } ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* VXX = {S[0] * CX[ia1] * CXc[ia2]c + S[1] * CX[ia1] * SXc[ia2]c + S[2] * SX[ia1] * CXc[ia2] + S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ; */ COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]); COMPLEX_MUL2 (VXX, S[0], MC1); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VXX, VXX, ct1); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VXX, VXX, ct1); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (ct3, VXX, ct1); COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+0], 0); COMPLEX_MUL2 (VXX, ct3, ct1); Rarray[0] = VXX.real; Rarray[1] = VXX.imag; /* VYY = {S[0] * SY[ia1] * SYc[ia2] + S[1] * SY[ia1] * CYc[ia2] + S[2] * CY[ia1] * SYc[ia2] + S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ; */ COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]); COMPLEX_MUL2 (VYY, S[0], MC1); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VYY, VYY, ct1); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VYY, VYY, ct1); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (ct3, VYY, ct1); COMPLEX_SET (ct1, antGain[ia1*2+1]*antGain[ia2*2+1], 0); COMPLEX_MUL2 (VYY, ct3, ct1); Rarray[6] = VYY.real; Rarray[7] = VYY.imag; /* VXY = {S[0] * CX[ia1] * SYc[ia2] + S[1] * CX[ia1] * CYc[ia2] + S[2] * SX[ia1] * SYc[ia2] + S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(i PD); */ COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct3, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+1], 0); COMPLEX_EXP (ct2, PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VXY, ct3, ggPD); Rarray[2] = VXY.real; Rarray[3] = VXY.imag; /* VYX = {S[0] * SY[ia1] * CXc[ia2] + S[1] * SY[ia1] * SXc[ia2] + S[2] * CY[ia1] * CXc[ia2] + S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-i PD); */ COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct3, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+1]*antGain[ia2*2+0], 0); COMPLEX_EXP (ct2, -PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VYX, ct3, ggPD); Rarray[4] = VYX.real; Rarray[5] = VYX.imag; } /* end calcmodelXY */ /** * Fit selected parameters to a UV data. * \param in Spectral fitting object * Potential parameters on in->info: * \li nCal OBIT_int scalar Number of calibrator sources [1] * \li solnType OBIT_string [4] Solution type:'FULD' * \li Sources OBIT_string [16,*] Calibrator sources * \li Qual OBIT_long scalar Source qualifier -1=>any * \li souCode OBIT_string [4] Calibrator code ' '=>any * \li doFitI OBIT_boolean [*] If True fit Stokes I poln, per cal [F] * \li doFitPol OBIT_boolean [*] If True fit source linear poln, per cal [T] * \li doFitV OBIT_boolean [*] If True fit Stokes V poln, per cal [F] * \li doFitRL OBIT_boolean If True fit R-L phase difference [F] * \li XYPhase OBIT_float scalar cross hand phase difference (deg) [def 0.0] * \li RLPhase OBIT_float scalar R-L phase difference @ ref Freq per calibrator * <= -999 => fit value [-1000.] in deg. * \li RM OBIT_float scalar Rotation measure (rad/m^2) to be used with RLPhase * \li PPol OBIT_float scalar Fractional linear polarization per calibrator * \li dPPol OBIT_float scalar freq derivative of PPol (GHz) per calibrator * \li ChWid OBIT_long scalar Number of channels in poln soln [1] * \li ChInc OBIT_long scalar Spacing of poln soln [1] * \li CPSoln OBIT_long scalar Source (CP) table to write, 0=> create new [0] * \li PDSoln OBIT_long scalar Instrumental (PD) table to write, 0=> create new [0] * \li BPSoln OBIT_long scalar Bandpass (BP) table to write, 0=> create new [0] * \li doBlank OBIT_boolean scalar If True blanked failed solns, else default values [T] * \li doBand OBIT_long scalar If >0 then BP table BPVer was applied to input [0] * \li BPVer OBIT_long scalar Input BP table [0] * \li refAnt OBIT_long scalar Reference antenna [0-> none, def 1] * \li BIF OBIT_long scalar First IF (1-rel) selected in outUV [1] * \li BChan OBIT_long scalar First channel (1-rel) selected in outUV [1] * \param inUV Averaged/calibrated/divided UV data to be fitted * Should be averaged to the solInt time. * MUST be a multisource file * \param outUV UV data with fitted results in tables * \param err Obit error stack object. */ void ObitPolnCalFitFit (ObitPolnCalFit* in, ObitUV *inUV, ObitUV *outUV, ObitErr *err) { olong nCal=1; ObitIOCode retCode; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}, sdim[MAXINFOELEMDIM]; ObitInfoType type; ObitTableAN *ANTable = NULL; ObitTableSU *SUTable = NULL; olong i, j, k, iant, isou, numAnt, BChan, EChan, iChan, EIF, iIF; olong first, highANver, iANver, ver, numIF, Qual, suba=1, nvis; olong highSUver, size, oldNparam, oldNdata, iarr[5]={0,0,0,0,0}; ofloat *farr; olong number, maxSUId=-1; gboolean done, xselect=TRUE, *barr, isOK; gchar solnType[5], *Sources, souCode[5]; ofloat endChi2, ParRMS, XRMS; #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ /* Diagnostics */ ofloat ftemp, RArray[8]; odouble RRr, RRi, LLr, LLi, RLr, RLi, LRr, LRi; olong ia1, ia2, refAnt; gchar *routine = "ObitPolnCalFitFit"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitUVIsA(inUV)); g_assert(ObitUVIsA(outUV)); /* How many calibrators? */ ObitInfoListGetTest(in->info, "nCal", &type, dim, &nCal); /* Allocate calibrator arrays */ in->RLPhaseIn= g_malloc0(nCal*sizeof(ofloat)); in->RLPhase = g_malloc0(nCal*sizeof(ofloat)); in->RM = g_malloc0(nCal*sizeof(ofloat)); in->PPol = g_malloc0(nCal*sizeof(ofloat)); in->dPPol = g_malloc0(nCal*sizeof(ofloat)); in->doFitI = g_malloc0(nCal*sizeof(olong)); in->doFitV = g_malloc0(nCal*sizeof(olong)); in->doFitPol = g_malloc0(nCal*sizeof(olong)); in->IFlux0 = g_malloc0(nCal*sizeof(ofloat)); in->IFlux1 = g_malloc0(nCal*sizeof(ofloat)); in->IFlux2 = g_malloc0(nCal*sizeof(ofloat)); /* Control parameters - arrays may be defined larger than nCal */ if (ObitInfoListGetP(in->info, "RLPhase", &type, dim, (gpointer)&farr)) for (i=0; i<nCal; i++) in->RLPhaseIn[i] = farr[i] * DG2RAD; else for (i=0; i<nCal; i++) in->RLPhaseIn[i] =- 1000.0; if (ObitInfoListGetP(in->info, "RM", &type, dim, (gpointer)&farr)) for (i=0; i<nCal; i++) in->RM[i] = farr[i]; else for (i=0; i<nCal; i++) in->RM[i] = 0.0; if (ObitInfoListGetP(in->info, "PPol", &type, dim, (gpointer)&farr)) for (i=0; i<nCal; i++) in->PPol[i] = farr[i]; else for (i=0; i<nCal; i++) in->PPol[i] = 0.0; if (ObitInfoListGetP(in->info, "dPPol", &type, dim, (gpointer)&farr)) for (i=0; i<nCal; i++) in->dPPol[i] = farr[i]*1.0e-9; /* delta freq to GHz */ else for (i=0; i<nCal; i++) in->dPPol[i] = 0.0; if (ObitInfoListGetP(in->info, "doFitI", &type, dim, (gpointer)&barr)) for (i=0; i<nCal; i++) in->doFitI[i] = barr[i]; else for (i=0; i<nCal; i++) in->doFitI[i] = FALSE; if (ObitInfoListGetP(in->info, "doFitV", &type, dim, (gpointer)&barr)) for (i=0; i<nCal; i++) in->doFitV[i] = barr[i]; else for (i=0; i<nCal; i++) in->doFitV[i] = FALSE; if (ObitInfoListGetP(in->info, "doFitPol", &type, dim, (gpointer)&barr)) for (i=0; i<nCal; i++) in->doFitPol[i] = barr[i]; else for (i=0; i<nCal; i++) in->doFitPol[i] = TRUE; ObitInfoListGetTest(in->info, "doFitRL", &type, dim, &in->doFitRL); ObitInfoListGetTest(in->info, "doBlank", &type, dim, &in->doBlank); ObitInfoListGetTest(in->info, "doFitGain",&type, dim, &in->doFitGain); ObitInfoListGetTest(in->info, "doFitOri", &type, dim, &in->doFitOri); ObitInfoListGetTest(in->info, "ChWid", &type, dim, &in->ChWid); ObitInfoListGetTest(in->info, "ChInc", &type, dim, &in->ChInc); ObitInfoListGetTest(in->info, "CPSoln", &type, dim, &in->CPSoln); ObitInfoListGetTest(in->info, "PDSoln", &type, dim, &in->PDSoln); ObitInfoListGetTest(in->info, "BPSoln", &type, dim, &in->BPSoln); ObitInfoListGetTest(in->info, "doBand", &type, dim, &in->doBand); ObitInfoListGetTest(in->info, "BPVer", &type, dim, &in->BPVer); ObitInfoListGetTest(in->info, "BIF", &type, dim, &in->BIF); in->BIF = MAX (1, in->BIF); ObitInfoListGetTest(in->info, "BChan", &type, dim, &in->BChan); in->BChan = MAX (1, in->BChan); ObitInfoListGetTest(in->info, "refAnt", &type, dim, &in->refAnt); ObitInfoListGetTest(in->info, "prtLv", &type, dim, &in->prtLv); ObitInfoListGetTest(in->info, "Qual", &type, dim, &Qual); ObitInfoListGetTest(in->info, "souCode", &type, dim, souCode); strcpy (solnType, "LM "); ObitInfoListGetTest(in->info, "solnType", &type, dim, solnType); strncpy (in->solnType, solnType, 4); ObitInfoListGetP(in->info, "Sources", &type, sdim, (gpointer)&Sources); ftemp = 0.0; ObitInfoListGetTest(in->info, "XPhase", &type, dim, &ftemp); in->PD = ftemp * DG2RAD; /* Phase difference in radians */ /* Open input data to get info */ retCode = ObitUVOpen (inUV, OBIT_IO_ReadOnly, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inUV->name); /* Save in/output descriptor */ in->inDesc = ObitUVDescRef(inUV->myDesc); in->outDesc = ObitUVDescRef(outUV->myDesc); /* Is this circular (linear) feed data? */ in->isCircFeed = (in->outDesc->crval[in->outDesc->jlocs]<0.0) && (in->outDesc->crval[in->outDesc->jlocs]>-1.5); /* Gain fitting only for linear feeeds */ if (in->isCircFeed) in->doFitGain = FALSE; /* Orientation fitting required for circular Feeds */ if (in->isCircFeed) in->doFitGain = TRUE; /* Number of antennas */ numAnt = inUV->myDesc->numAnt[suba-1];/* actually highest antenna number */ in->nant = numAnt; in->nsou = nCal; /* How many AN tables (subarrays) */ highANver = ObitTableListGetHigh (inUV->tableList, "AIPS AN"); /* Antenna lists */ in->AntLists = g_malloc0(highANver*sizeof(ObitAntennaList*)); in->numSubA = highANver; /* Read Info from AN tables */ for (i=0; i<highANver; i++) { iANver = i+1; /* Get table */ ANTable = newObitTableANValue (inUV->name, (ObitData*)inUV, &iANver, OBIT_IO_ReadOnly, 0, 0, 0, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); in->AntLists[i] = ObitTableANGetList (ANTable, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* release table object */ ANTable = ObitTableANUnref(ANTable); } /* End loop over subarrays */ /* Allocate source lookup table */ in->souIDs = g_malloc0(in->nsou*sizeof(olong)); /* Convert SU table into Source List if there is an SU table */ highSUver = ObitTableListGetHigh (outUV->tableList, "AIPS SU"); if (highSUver>0) { ver = 1; numIF = 0; SUTable = newObitTableSUValue (outUV->name, (ObitData*)outUV, &ver, numIF, OBIT_IO_ReadOnly, err); if (SUTable) in->SouList = ObitTableSUGetList (SUTable, err); /* Look up source IDs - one at a time to get correct order */ number = 1; sdim[1] = 1; for (i=0; i<in->nsou; i++) { j = sdim[0]*i; ObitTableSULookup (SUTable, sdim, &Sources[j], Qual, souCode, iarr, &xselect, &number, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); in->souIDs[i] = MAX (1, iarr[0]); } /* End loop over calibrators */ /* Get maximum source id */ for (i=0; i<in->nsou; i++) maxSUId = MAX(maxSUId, in->souIDs[i]); maxSUId = MAX (1, maxSUId); /* Inverse lookup table */ in->isouIDs = g_malloc0(maxSUId*sizeof(olong)); for (j=0; j<maxSUId; j++) in->isouIDs[j] = -1000; for (i=0; i<in->nsou; i++) in->isouIDs[in->souIDs[i]-1] = i; /* Fit spectra to IPol in table */ FitSpectra (in, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); SUTable = ObitTableSUUnref(SUTable); } else { /* Create a single source object */ in->oneSource = newObitSource("Single"); strncpy (in->oneSource->SourceName, inUV->myDesc->object, MIN(20,UVLEN_VALUE)); in->oneSource->equinox = inUV->myDesc->equinox; in->oneSource->RAMean = inUV->myDesc->crval[inUV->myDesc->jlocr]; SUTable = ObitTableSUUnref(SUTable); in->oneSource->DecMean = inUV->myDesc->crval[inUV->myDesc->jlocd]; /* Compute apparent position */ ObitPrecessUVJPrecessApp (inUV->myDesc, in->oneSource); in->souIDs[0] = 1; /* Source ID */ /* Inverse lookup table */ in->isouIDs = g_malloc0(1*sizeof(olong)); in->isouIDs[0] = 0; } /* Allocate Fitting flag/order arrays */ in->gotAnt = g_malloc0(in->nant*sizeof(gboolean*)); in->antFit = g_malloc0(in->nant*sizeof(gboolean*)); for (i=0; i<in->nant; i++) in->antFit[i] = g_malloc0(4*sizeof(gboolean)); in->souFit = g_malloc0(in->nsou*sizeof(gboolean*)); for (i=0; i<in->nsou; i++) in->souFit[i] = g_malloc0(4*sizeof(gboolean)); in->antPNumb = g_malloc0(in->nant*sizeof(gboolean*)); for (i=0; i<in->nant; i++) in->antPNumb[i] = g_malloc0(4*sizeof(gboolean)); in->souPNumb = g_malloc0(in->nsou*sizeof(gboolean*)); for (i=0; i<in->nsou; i++) in->souPNumb[i] = g_malloc0(4*sizeof(gboolean)); oldNparam = 0; oldNdata = 0; /* Parameter/error arrays */ in->antParm = g_malloc0(in->nant*4*sizeof(odouble)); in->antErr = g_malloc0(in->nant*4*sizeof(odouble)); in->souParm = g_malloc0(in->nsou*4*sizeof(odouble)); in->souErr = g_malloc0(in->nsou*4*sizeof(odouble)); in->lastSouParm = g_malloc0(in->nsou*4*sizeof(odouble)); in->souFlux = g_malloc0(in->nsou*4*sizeof(ofloat)); /* Antenna gains for linear feeds? */ if (!in->isCircFeed ) { in->antGain = g_malloc0((in->nant+2)*2*sizeof(odouble)); for (i=0; i<in->nant*2; i++) in->antGain[i] = 1.0; in->antGainErr = g_malloc0(in->nant*2*sizeof(odouble)); in->antGainFit = g_malloc0(in->nant*sizeof(gboolean*)); for (i=0; i<in->nant; i++) { in->antGainFit[i] = g_malloc0(2*sizeof(gboolean)); in->antGainFit[i][0] = FALSE; /* Don't fit Xpol gain */ /* in->antGainFit[i][0] = in->doFitGain; DEBUG */ in->antGainFit[i][1] = in->doFitGain; } in->antGainPNumb = g_malloc0(in->nant*sizeof(gboolean*)); for (i=0; i<in->nant; i++) in->antGainPNumb[i] = g_malloc0(2*sizeof(gboolean)); } /* End create feed gain arrays */ /* Fill Fitting flag arrays */ /* Order of antenna parameters: 0,1 ori, elip (r/x), 2,3 ori, elip (l/y), */ for (i=0; i<in->nant; i++) { /* Initialize FALSE */ in->gotAnt[i] = FALSE; /* Antenna terms */ for (j=0; j<4; j++) in->antFit[i][j] = TRUE; /* Don't fit reference antenna terms, Fix ori 1 if circ. feeds, elip 1&2 if linear feeds*/ if (in->isCircFeed) { /* Circular */ if ((i+1)==in->refAnt) in->antFit[i][0] = FALSE; } else { /* Linear */ if ((i+1)==in->refAnt) in->antFit[i][1] = FALSE; } /* doFitOri=False-> fix orientations */ if (!in->doFitOri) { in->antFit[i][0] = FALSE; in->antFit[i][2] = FALSE; } } /* end filling antenna fitting flags */ /* Order of source parameters: 0, Stokes I, 1, Stokes Q, 2, Stokes U 3, Stokes V */ for (i=0; i<in->nsou; i++) { if (in->doFitI[i]) in->souFit[i][0] = TRUE; else in->souFit[i][0] = FALSE; if (in->doFitPol[i]) {in->souFit[i][1] = TRUE; in->souFit[i][2] = TRUE;} else {in->souFit[i][1] = FALSE; in->souFit[i][2] = FALSE;} if (in->doFitV[i]) in->souFit[i][3] = TRUE; else in->souFit[i][3] = FALSE; in->souParm[i*4+0] = in->souFlux[i]; /* average of input data */ in->souParm[i*4+1] = in->souParm[i*4+2] = in->souParm[i*4+3] = 0.0; /* Last valid source parameters, I<-1000 =>none */ in->lastSouParm[i*4+0] = -1000.0; in->lastSouParm[i*4+1] = in->lastSouParm[i*4+2] = in->lastSouParm[i*4+3] = 0.0; } /* end filling source fitting flags */ /* Get numbers of channels/IFs */ BChan = 1; EChan = in->inDesc->inaxes[in->inDesc->jlocf]; iChan = 1 + in->ChInc/2; if (in->inDesc->jlocif>=0) EIF = in->inDesc->inaxes[in->inDesc->jlocif]; else EIF = 1; iIF = 1; done = FALSE; /* Data tables */ size = in->inDesc->nvis; in->inData = g_malloc0(10*size*sizeof(ofloat)); in->inWt = g_malloc0(4*size*sizeof(ofloat)); in->antNo = g_malloc0(2*size*sizeof(olong)); in->souNo = g_malloc0(size*sizeof(olong)); /* Initialize threads*/ MakePolnFitFuncArgs (in, err); /* Loop over data in blocks of Channels */ while (!done) { /* Read data, init solutions */ first = (iIF!=in->IFno) || (iChan==BChan); /* First of an IF */ ReadData (in, inUV, &iChan, EChan, &iIF, EIF, first, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* average flux densities of input data */ for (i=0; i<in->nsou; i++) { if (in->souFit[i][0]) in->souParm[i*4+0] = in->souFlux[i]; } /* End initializing source flux densities */ if (in->prtLv>=2) { Obit_log_error(err, OBIT_InfoErr, "Process IF %d Channel %d no chan %d", in->IFno+in->BIF-1, in->Chan+in->BChan-1, in->ChWid); ObitErrLog(err); } /* Set order and count number of parameters being fitted */ in->nparam = 0; /* get model parameters - first antenna */ for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (in->antFit[iant][k]) { in->antPNumb[iant][k] = in->nparam++; } else in->antPNumb[iant][k] = -999; } /* end loop over parameters */ } /* end if gotAnt */ } /* end loop over antennas */ /* Antenna gains if needed */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { /* Loop over parameters */ for (k=0; k<2; k++) { /* Fitting? */ if (in->antGainFit[iant][k]) { in->antGainPNumb[iant][k] = in->nparam++; } else in->antGainPNumb[iant][k] = -999; } /* end loop over parameters */ } /* end if gotAnt */ } /* end loop over antennas */ } /* End if antenna gains */ /* now source */ for (isou=0; isou<in->nsou; isou++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (in->souFit[isou][k]) { in->souPNumb[isou][k] = in->nparam++; } else in->souPNumb[isou][k] = -999; } /* end loop over parameters */ } /* end loop over sources */ /* Phase difference parameter number if being fitted */ if (in->doFitRL) in->PDPNumb = in->nparam++; /* Init solver stuff first pass */ nvis = inUV->myDesc->nvis; in->ndata = nvis*4*2; /* 4 complex visibililties */ #ifdef HAVE_GSL if ((in->solnType[0]=='L') && (in->solnType[1]=='M')) { /* Need to rebuild? */ if ((in->solver!=NULL) || (oldNparam!=in->nparam) || (oldNdata!=in->ndata)) { if( in->solver) gsl_multifit_fdfsolver_free (in->solver); in->solver = NULL; if (in->funcStruc) g_free(in->funcStruc); in->funcStruc = NULL; if (in->work) gsl_vector_free(in->work); in->work = NULL; if (in->covar) gsl_matrix_free(in->covar); in->covar = NULL; } if (in->solver==NULL) { oldNparam = in->nparam; oldNdata = in->ndata; T = gsl_multifit_fdfsolver_lmder; in->solver = gsl_multifit_fdfsolver_alloc(T, in->ndata, in->nparam); in->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); in->work = gsl_vector_alloc(in->nparam); in->covar = gsl_matrix_alloc(in->nparam, in->nparam); /* Function by feed type */ if (in->isCircFeed) { /* Circular feeds */ in->funcStruc->f = &PolnFitFuncOERL; in->funcStruc->df = &PolnFitJacOERL; in->funcStruc->fdf = &PolnFitFuncJacOERL; } else { /* Linear feeds */ in->funcStruc->f = &PolnFitFuncOEXY; in->funcStruc->df = &PolnFitJacOEXY; in->funcStruc->fdf = &PolnFitFuncJacOEXY; } } } /* If using LM */ #endif /* HAVE_GSL */ /* Do actual fitting */ /* Make sure solutions are not blanked from last fit */ resetSoln(in); /* zero reference antenna ellipticity for lin. feeds */ if ((!in->isCircFeed) &&(in->refAnt>0)) { refAnt = in->refAnt; in->antParm[(refAnt-1)*4+1] = 0.0; } /* Do fit - fast method to get better soln, then possibly GSL */ isOK = doFitFast (in, err); /* refit with no reference antenna for lin. feeds This doesn't actually do much except better elip. for ref ant */ if ((!in->isCircFeed) &&(in->refAnt>0)) { refAnt = in->refAnt-1; in->antFit[refAnt][1] = TRUE; isOK = doFitFast (in, err); in->antFit[refAnt][1] = FALSE; in->refAnt = refAnt+1; } /* end refit linear */ /* If only one screwy antenna chunk it and try again */ if (CheckCrazyOne(in, err)) isOK = doFitFast (in, err); if (isOK) { if (!strncmp(in->solnType, "LM ", 4)) doFitGSL (in, err); endChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, &ParRMS, &XRMS, NULL, NULL, err); /* Final value */ if (err->prtLv>=2) { Obit_log_error(err, OBIT_InfoErr, "Final Chi2=%g Par RMS %g X RMS %g ", endChi2, ParRMS, XRMS); if (err->error) Obit_traceback_msg (err, routine, inUV->name); } } /* End fit OK */ /* Done? */ done = iIF > EIF; /* Diagnostics */ if (isOK && (err->prtLv>=4)) { /* BL 1-2 sou 1 */ refAnt = in->refAnt-1; fprintf (stderr, "Source 0 IF %d Chan %d\n", in->IFno, in->Chan); /* Header by feed type */ if (in->isCircFeed) { /* Circular feeds */ fprintf (stderr, " bl PA RRr (o,c) RRi LLr LLi RLr RLi LRr LRi \n"); } else { /* Linear feeds */ fprintf (stderr, " bl PA XXr (o,c) XXi YYr YYi XYr XYi YXr YXi \n"); } for (i=0; i<in->nvis; i++) { isou = MAX(0, in->souNo[i]); /* Source number */ ia1 = in->antNo[i*2+0]; ia2 = in->antNo[i*2+1]; /* Diagnostics */ if ((isou==0) && (ia1==1) && (ia2==2)) { /* first source 2-3 */ /* Function by feed type */ if (in->isCircFeed ) { /* Circular feeds */ calcmodelRL (in, RArray, i); } else { /* Linear feeds */ calcmodelXY (in, RArray, i); } RRr = RArray[0]; RRi = RArray[1]; LLr = RArray[6]; LLi = RArray[7]; RLr = RArray[2]; RLi = RArray[3]; LRr = RArray[4]; LRi = RArray[5]; fprintf (stderr, "%2d-%2d %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f \n", ia1+1,ia2+1,in->inData[i*10+0], in->inData[i*10+2], RRr, in->inData[i*10+3], RRi, in->inData[i*10+4], LLr, in->inData[i*10+5], LLi, in->inData[i*10+6], RLr, in->inData[i*10+7], RLi, in->inData[i*10+8], LRr, in->inData[i*10+9], LRi); } } } /* End debug diagnostics */ /* Write output to Tables if some valid XPol data */ isOK = isOK && (XRMS>0.0); WriteOutput(in, outUV, isOK, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); } /* end loop over blocks of channels */ } /* end ObitPolnCalFitFit */ /** * Initialize global ClassInfo Structure. */ void ObitPolnCalFitClassInit (void) { if (myClassInfo.initialized) return; /* only once */ /* Set name and parent for this class */ myClassInfo.ClassName = g_strdup(myClassName); myClassInfo.ParentClass = ObitParentGetClass(); /* Set function pointers */ ObitPolnCalFitClassInfoDefFn ((gpointer)&myClassInfo); myClassInfo.initialized = TRUE; /* Now initialized */ } /* end ObitPolnCalFitClassInit */ /** * Initialize global ClassInfo Function pointers. */ static void ObitPolnCalFitClassInfoDefFn (gpointer inClass) { ObitPolnCalFitClassInfo *theClass = (ObitPolnCalFitClassInfo*)inClass; ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass; if (theClass->initialized) return; /* only once */ /* Check type of inClass */ g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo)); /* Initialize (recursively) parent class first */ if ((ParentClass!=NULL) && (ParentClass->ObitClassInfoDefFn!=NULL)) ParentClass->ObitClassInfoDefFn(theClass); /* function pointers defined or overloaded this class */ theClass->ObitClassInit = (ObitClassInitFP)ObitPolnCalFitClassInit; theClass->newObit = (newObitFP)newObitPolnCalFit; theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitPolnCalFitClassInfoDefFn; theClass->ObitGetClass = (ObitGetClassFP)ObitPolnCalFitGetClass; theClass->ObitCopy = (ObitCopyFP)ObitPolnCalFitCopy; theClass->ObitClone = NULL; theClass->ObitClear = (ObitClearFP)ObitPolnCalFitClear; theClass->ObitInit = (ObitInitFP)ObitPolnCalFitInit; theClass->ObitPolnCalFitCreate = (ObitPolnCalFitCreateFP)ObitPolnCalFitCreate; theClass->ObitPolnCalFitFit = (ObitPolnCalFitFitFP)ObitPolnCalFitFit; } /* end ObitPolnCalFitClassDefFn */ /*---------------Private functions--------------------------*/ /** * Creates empty member objects, initialize reference count. * Parent classes portions are (recursively) initialized first * \param inn Pointer to the object to initialize. */ void ObitPolnCalFitInit (gpointer inn) { ObitClassInfo *ParentClass; ObitPolnCalFit *in = inn; /* error checks */ g_assert (in != NULL); /* recursively initialize parent class members */ ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass); if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) ParentClass->ObitInit (inn); /* set members in this class */ in->thread = newObitThread(); in->info = newObitInfoList(); in->inData = NULL; in->inWt = NULL; in->nant = 0; in->antNo = NULL; in->antParm = NULL; in->antErr = NULL; in->gotAnt = NULL; in->antFit = NULL; in->antGain = NULL; in->antGainErr = NULL; in->antGain = NULL; in->antGainFit = NULL; in->AntLists = NULL; in->nsou = 0; in->souNo = NULL; in->souParm = NULL; in->souFlux = NULL; in->souErr = NULL; in->lastSouParm= NULL; in->souFit = NULL; in->antPNumb = NULL; in->SouList = NULL; in->souIDs = NULL; in->isouIDs = NULL; in->inDesc = NULL; in->outDesc = NULL; in->RLPhaseIn = NULL; in->RLPhase = NULL; in->RM = NULL; in->PPol = NULL; in->dPPol = NULL; in->doFitI = NULL; in->doFitV = NULL; in->doFitPol = NULL; in->IFlux0 = NULL; in->IFlux1 = NULL; in->IFlux2 = NULL; in->CPTable = NULL; in->PDTable = NULL; in->BPTable = NULL; in->doFitRL = FALSE; in->doBlank = TRUE; in->doFitGain = TRUE; in->doFitOri = TRUE; in->BIF = 1; in->BChan = 1; in->ChWid = 1; in->ChInc = 1; in->CPSoln = 0; in->PDSoln = 0; in->BPSoln = 0; in->doBand = 0; in->BPVer = 0; in->doError = TRUE; in->isCircFeed = TRUE; in->maxAnt = 100; in->isInitialized = FALSE; } /* end ObitPolnCalFitInit */ /** * Deallocates member objects. * Does (recursive) deallocation of parent class members. * \param inn Pointer to the object to deallocate. * Actually it should be an ObitPolnCalFit* cast to an Obit*. */ void ObitPolnCalFitClear (gpointer inn) { ObitClassInfo *ParentClass; ObitPolnCalFit *in = inn; olong i; /* error checks */ g_assert (ObitIsA(in, &myClassInfo)); /* delete this class members */ if (in->antFit) { for (i=0; i<in->nant; i++) if (in->antFit[i]) g_free(in->antFit[i]); g_free(in->antFit); } if (in->antGainFit) { for (i=0; i<in->nant; i++) if (in->antGainFit[i]) g_free(in->antGainFit[i]); g_free(in->antGainFit); } if (in->souFit) { for (i=0; i<in->nsou; i++) if (in->souFit[i]) g_free(in->souFit[i]); g_free(in->souFit); } if (in->antPNumb) { for (i=0; i<in->nant; i++) if (in->antPNumb[i]) g_free(in->antPNumb[i]); g_free(in->antPNumb); } if (in->antGainPNumb) { for (i=0; i<in->nant; i++) if (in->antGainPNumb[i]) g_free(in->antGainPNumb[i]); g_free(in->antGainPNumb); } if (in->souPNumb) { for (i=0; i<in->nsou; i++) if (in->souPNumb[i]) g_free(in->souPNumb[i]); g_free(in->souPNumb); } if (in->AntLists) { for (i=0; i<in->numSubA; i++) if (in->AntLists[i]) ObitAntennaListUnref(in->AntLists[i]); g_free(in->AntLists); } if (in->inWt) g_free(in->inWt); if (in->inData) g_free(in->inData); if (in->antNo) g_free(in->antNo); if (in->antParm) g_free(in->antParm); if (in->gotAnt) g_free(in->gotAnt); if (in->antErr) g_free(in->antErr); if (in->antGain) g_free(in->antGain); if (in->antGainErr) g_free(in->antGainErr); if (in->souNo) g_free(in->souNo); if (in->souParm) g_free(in->souParm); if (in->souFlux) g_free(in->souFlux); if (in->souErr) g_free(in->souErr); if (in->lastSouParm) g_free(in->lastSouParm); if (in->souIDs) g_free(in->souIDs); if (in->isouIDs) g_free(in->isouIDs); if (in->RLPhaseIn)g_free(in->RLPhaseIn); if (in->RLPhase) g_free(in->RLPhase); if (in->RM) g_free(in->RM); if (in->PPol) g_free(in->PPol); if (in->dPPol) g_free(in->dPPol); if (in->doFitI) g_free(in->doFitI); if (in->doFitV) g_free(in->doFitV); if (in->doFitPol) g_free(in->doFitPol); if (in->IFlux0) g_free(in->IFlux0); if (in->IFlux1) g_free(in->IFlux1); if (in->IFlux2) g_free(in->IFlux2); if (in->thArgs) KillPolnFitFuncArgs (in); in->inDesc = ObitUVDescUnref(in->inDesc); in->outDesc = ObitUVDescUnref(in->outDesc); in->thread = ObitThreadUnref(in->thread); in->info = ObitInfoListUnref(in->info); in->SouList = ObitSourceListUnref(in->SouList); in->oneSource = ObitSourceUnref(in->oneSource); in->CPTable = ObitTableUnref(in->CPTable); in->PDTable = ObitTableUnref(in->PDTable); in->BPTable = ObitTableUnref(in->BPTable); #ifdef HAVE_GSL if( in->solver) gsl_multifit_fdfsolver_free (in->solver); if (in->funcStruc) g_free(in->funcStruc); if (in->work) gsl_vector_free(in->work); if (in->covar) gsl_matrix_free(in->covar); #endif /* HAVE_GSL */ /* unlink parent class members */ ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass); /* delete parent class members */ if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) ParentClass->ObitClear (inn); } /* end ObitPolnCalFitClear */ /** * Write contents on in to tables on outUV * Tables initialized on call with first thread for chan=IF=1 * (including BChan, BIF) * \param in Fitting object * \param outUV UV date with results in tables * \param isOK Something worth writing * \param err Obit error stack object. */ static void WriteOutput (ObitPolnCalFit* in, ObitUV *outUV, gboolean isOK, ObitErr *err) { oint numPol, numIF, numChan; ObitIOCode retCode; ObitTableBP *oldBPTab=NULL; gboolean sameBP=FALSE, crazy; ObitIOAccess access; ObitUVDesc *IODesc; gchar *routine = "ObitPolnCalFit:WriteOutput"; /* error checks */ if (err->error) return; /* Need to initialize? */ if (!in->isInitialized) { /* First channel and IF if (((in->Chan+in->BChan-1-in->ChInc/2)==1) && ((in->IFno+in->BIF-1)==1)) {*/ in->isInitialized = TRUE; /* This will initialize it */ /* Open output */ retCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outUV->name); /* How many of things? Use underlying sizes */ IODesc = (ObitUVDesc*)outUV->myIO->myDesc; numPol = MIN (2,IODesc->inaxes[IODesc->jlocs]); if (IODesc->jlocif>=0) numIF = IODesc->inaxes[IODesc->jlocif]; else numIF = 1; numChan = IODesc->inaxes[IODesc->jlocf]; /* Source table */ in->CPTable = newObitTableCPValue ("Source", (ObitData*)outUV, &in->CPSoln, OBIT_IO_WriteOnly, numIF, numChan, err); InitSourceTab(in, err); /* Instrumental poln table */ in->PDTable = newObitTablePDValue ("Instrum", (ObitData*)outUV, &in->PDSoln, OBIT_IO_WriteOnly, numPol, numIF, numChan, err); InitInstrumentalTab(in, err); /* BP table used if fitting R/L X/Y phase difference or X/Y gain*/ if (in->doFitRL || in->doFitGain) { /* Bandpass table - copy and update if doBand>0 */ if (in->doBand>0) { oldBPTab = newObitTableBPValue ("Temp BP", (ObitData*)outUV, &in->BPVer, OBIT_IO_ReadOnly, numPol, numIF, numChan, err); /* Check that you're not about to clobber the input */ sameBP = in->BPVer==in->BPSoln; if (sameBP) access = OBIT_IO_ReadWrite; access = OBIT_IO_WriteOnly; /* Warn if overwriting */ if (sameBP) { Obit_log_error(err, OBIT_InfoWarn, "Modifying input BP Table"); ObitErrLog(err); } } else { /* No prior bandpass cal */ if (in->BPSoln<=0) access = OBIT_IO_WriteOnly; else access = OBIT_IO_ReadWrite; } /* Create or open output */ in->BPTable = newObitTableBPValue ("Bandpass", (ObitData*)outUV, &in->BPSoln, access , numPol, numIF, numChan, err); /* Copy old to new */ if ((in->doBand>0) && !sameBP) { in->BPTable = ObitTableBPCopy (oldBPTab, in->BPTable, err); oldBPTab = ObitTableBPUnref(oldBPTab); } else { InitBandpassTab(in, err); } } /* end setup BP table */ /* Close output */ retCode = ObitUVClose (outUV, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outUV->name); /* end init */ } else { /* Make sure output tables defined */ /* How many of things? */ numPol = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]); if (in->outDesc->jlocif>=0) numIF = in->outDesc->inaxes[in->outDesc->jlocif]; else numIF = 1; numChan = in->outDesc->inaxes[in->outDesc->jlocf]; if (!in->CPTable) in->CPTable = newObitTableCPValue ("Source", (ObitData*)outUV, &in->CPSoln, OBIT_IO_ReadWrite, numIF, numChan, err); if (!in->PDTable) in->PDTable = newObitTablePDValue ("Instrum", (ObitData*)outUV, &in->PDSoln, OBIT_IO_ReadWrite, numPol, numIF, numChan, err); if ((!in->BPTable) && (in->doFitRL)) in->BPTable = newObitTableBPValue ("Bandpass", (ObitData*)outUV, &in->BPSoln, OBIT_IO_ReadWrite, numPol, numIF, numChan, err); } /* Check for crazy antenna solutions and reset defaults */ crazy = CheckCrazy(in, err); if (crazy) isOK = FALSE; /* Update Tables */ if (isOK) UpdateSourceTab(in, err); UpdateInstrumentalTab(in, isOK, err); if (in->doFitRL || in->doFitGain) UpdateBandpassTab(in, isOK, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); } /* end WriteOutput */ /** * Read data and load arrays. * Averages ChWid channels centered on each channel. * Require all 4 correlations to be valid in each channel * \param in Fitting object * \param inUV Averaged/calibrated/divided UV data to be fitted * \param iChan Current first channel (1-rel) in thread group, * updated to value for next call on exit; * \param EChan Highest channel * \param iIF Current IF number (1-rel) , updated to value for next call * \param EIF Highest IF * \param init If True, solutions also initialized * \param err Obit error stack object. * \return number of threads with data loaded. */ static void ReadData (ObitPolnCalFit *in, ObitUV *inUV, olong *iChan, olong EChan, olong *iIF, olong EIF, gboolean init, ObitErr *err) { ObitIOCode retCode = OBIT_IO_OK; ObitSource *curSource=NULL; olong ivis, ant1, ant2, isou, jsou, lastSou=-999, jvis, istok, suba; olong nChan, bch, ech, cnt, i, j, indx, indx1, indx2, indx3, indx4, *cntFlux=NULL; olong ChInc=in->ChInc, jChan, jIF; ofloat *buffer, curPA1=0.0, curPA2=0.0, curTime=0.0, lastTime=-1.0e20; ofloat sumRe, sumIm, sumWt, PPol, *sumFlux=NULL; odouble lambdaRef, lambda, ll, sum; gboolean OK, allBad; gchar *routine = "ObitPolnCalFit:ReadData"; /* DEBUG */ #ifdef DEBUG olong dbgCnt1, dbgCnt2; ofloat dbgSum1, dbgSum2, dbgISum1, dbgISum2; #endif /* end DEBUG */ /* Previous error? */ if (err->error) return; lambdaRef = VELIGHT/in->inDesc->freq; /* Wavelength at reference freq */ /* Sums for flux density */ sumFlux = g_malloc0(in->nsou*sizeof(ofloat)); cntFlux = g_malloc0(in->nsou*sizeof(olong)); for (i=0; i<in->nsou; i++) {sumFlux[i] = 0.0; cntFlux[i] = 0;} /* initial center channel/IF */ jChan = *iChan; jIF = *iIF; nChan = in->inDesc->inaxes[in->inDesc->jlocf]; /* Set channel/IF in thread */ ChInc = MAX (1,ChInc); in->Chan = (*iChan); in->IFno = *iIF; (*iChan) += ChInc; /* Next channel */ if (((*iChan)>EChan) && ((*iIF)<EIF)) { /* Done with IF? */ (*iChan) = 1 + ChInc/2; (*iIF)++; } /* Keep track of antennas with data */ for (i=0; i<in->nant; i++) in->gotAnt[i] = FALSE; /* Frequency */ indx = (jIF-1)*nChan + (jChan-1); in->freq = in->inDesc->freqArr[indx]; /* Set RL phases of calibrators */ lambda = VELIGHT/in->freq; /* Loop over calibrators */ for (i=0; i<in->nsou; i++) { /* Set R-L phase if given */ if (in->RLPhaseIn[i]>-900.0) { in->RLPhase[i] = in->RLPhaseIn[i] + 2.0 * (lambda*lambda - lambdaRef*lambdaRef) * in->RM[i]; } else in->RLPhase[i] = 0.0; } /* Beginnning and end channel */ bch = in->Chan - in->ChWid/2; ech = in->Chan + in->ChWid/2; /* Force to range */ bch = MAX (1, bch); ech = MIN (nChan, ech); /* Convert to 0-rel */ bch--; ech--; /* Open input */ retCode = ObitUVOpen (inUV, OBIT_IO_ReadOnly, err); if (err->error) goto cleanup; /* loop loading data */ jvis = 0; while (retCode == OBIT_IO_OK) { /* read buffer */ retCode = ObitUVRead (inUV, NULL, err); if (retCode == OBIT_IO_EOF) break; /* done? */ if (err->error) goto cleanup; /* Loop over buffer */ buffer = inUV->buffer; for (ivis=0; ivis<inUV->myDesc->numVisBuff; ivis++) { /* Check array bounds */ if (jvis>=in->inDesc->nvis) { Obit_log_error(err, OBIT_Error, "%s: Exceeded vis buffer size", routine); goto cleanup; } /* Check that all Stokes correlations in each channel are present, if only partial, flag the rest */ allBad = TRUE; for (i=bch; i<=ech; i++) { indx = inUV->myDesc->nrparm + i*inUV->myDesc->incf + (jIF-1)*inUV->myDesc->incif + 2; indx1 = indx + 0*inUV->myDesc->incs; indx2 = indx + 1*inUV->myDesc->incs; indx3 = indx + 2*inUV->myDesc->incs; indx4 = indx + 3*inUV->myDesc->incs; OK = (buffer[indx1]>0.0) && (buffer[indx2]>0.0) && (buffer[indx3]>0.0) && (buffer[indx4]>0.0); if (!OK) { /* Kill 'em all */ buffer[indx1] = buffer[indx2] = buffer[indx3] = buffer[indx4] = 0.0; } else allBad = FALSE; /* Some OK */ } /* end checking data loop */ /* if all data flagged skip to end */ if (allBad) goto endloop; /* Get info - source ID */ if (inUV->myDesc->ilocsu>=0) isou = buffer[inUV->myDesc->ilocsu]+0.5; else isou = in->souIDs[0]; jsou = in->isouIDs[isou-1]; /* Calibrator number */ /* Antennas */ ObitUVDescGetAnts(inUV->myDesc, buffer, &ant1, &ant2, &suba); /* Source change? */ if (isou!=lastSou) { lastSou = isou; if (in->SouList) curSource = in->SouList->SUlist[isou-1]; else curSource = in->oneSource; } /* Get parallactic angle when time changes */ curTime = buffer[inUV->myDesc->iloct]; if (curTime>lastTime) { curPA1 = ObitAntennaListParAng (in->AntLists[suba-1], ant1, curTime, curSource); curPA2 = ObitAntennaListParAng (in->AntLists[suba-1], ant2, curTime, curSource); lastTime = curTime; } /* Save info */ in->souNo[jvis] = jsou; /* relative to list, not data ID */ in->antNo[jvis*2+0] = ant1-1; in->antNo[jvis*2+1] = ant2-1; /* Parallactic angle */ in->inData[jvis*10] = curPA1; in->inData[jvis*10+1] = curPA2; /* getAnt flags */ in->gotAnt[ant1-1] = TRUE; in->gotAnt[ant2-1] = TRUE; /* Loop over Stokes */ for (istok=0; istok<4; istok++) { /* Average vis */ sumRe = sumIm = sumWt = 0; cnt = 0; for (i=bch; i<=ech; i++) { /* Where in buffer? */ indx = inUV->myDesc->nrparm + i*inUV->myDesc->incf + (jIF-1)*inUV->myDesc->incif + istok*inUV->myDesc->incs; if (buffer[indx+2]>0) { cnt++; sumRe += buffer[indx]; sumIm += buffer[indx+1]; sumWt += buffer[indx+2]; } } /* end average loop */ /* Average */ if ((cnt>0) && (sumWt>0.0)) { sumRe /= cnt; sumIm /= cnt; } else { /* invalid */ sumRe = 0.0; sumIm = 0.0; sumWt = 0.0; } /* Weight */ in->inWt[jvis*4+istok] = sumWt; /* Data */ in->inData[jvis*10+(istok+1)*2] = sumRe; in->inData[jvis*10+(istok+1)*2+1] = sumIm; /* Sums for Stokes */ if (istok<=1) {cntFlux[jsou]++; sumFlux[jsou]+=sumRe; } } /* end Stokes loop */ /* Diagnostic - sample data */ if ((err->prtLv>=5) && (ant1==2) && (ant2==4)) { fprintf (stderr,"vis %d bl %d %d sou %d time %f PA %f Data %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f %8.5f\n", jvis, ant1, ant2, isou, curTime, curPA1, in->inData[jvis*10+2],in->inData[jvis*10+3], in->inData[jvis*10+4],in->inData[jvis*10+5], in->inData[jvis*10+6],in->inData[jvis*10+7], in->inData[jvis*10+8],in->inData[jvis*10+9]); } jvis++; /* Data array visibility index */ endloop: /* to here if data bad */ buffer += inUV->myDesc->lrec; } /* end loop over vis */ } /* end loop reading data */ in->nvis = jvis; /* How many good data? */ /* Initialize solutions if init */ if (init) { /* first zero everything for (i=0; i<in->nsou; i++) { for (j=0; j<4; j++) in->souParm[i*4+j] = 0.0; }*/ for (i=0; i<in->nant; i++) { for (j=0; j<4; j++) in->antParm[i*4+j] = 0.0; if (in->isCircFeed) { /* Circular feeds ori_r, elip_r, ori_l, elip_l */ in->antParm[i*4+0] = 0.0; in->antParm[i*4+1] = G_PI/4.0; in->antParm[i*4+2] = 0.0; in->antParm[i*4+3] = -G_PI/4.0; } else { /* Linear feeds, if the antenna angles on sky are given in the AntennaList[0] use then, otherwise assume Feeds are X, Y ori_x, elip_x, ori_y, elip_y, */ in->antGain[i*2] = in->antGain[i*2+1] = 1.0; /* Gain */ in->antParm[i*4+1] = 0.0; /* ellipticity */ in->antParm[i*4+3] = 0.0; if (fabs (in->AntLists[0]->ANlist[i]->FeedAPA-in->AntLists[0]->ANlist[i]->FeedBPA)<1.0) { /* Assume X, Y */ in->antParm[i*4+0] = 0.0; in->antParm[i*4+2] = +G_PI/2.0; } else { /* Use what's in the AN table as initial convert to radians */ in->antParm[i*4+0] = in->AntLists[0]->ANlist[i]->FeedAPA*DG2RAD; in->antParm[i*4+2] = in->AntLists[0]->ANlist[i]->FeedBPA*DG2RAD; } /* end if antenna angle given */ } } } /* end init */ /* Some parameters always need updating */ /* in->PD = 0.0; R-L (X/Y) phase difference */ for (i=0; i<in->nsou; i++) { /* Stokes I - evaluate spectrum in ln(nu/nu_ref) */ ll = log(in->freq/in->inDesc->freq); sum = in->IFlux1[i]*ll + in->IFlux2[i]*ll*ll; in->souParm[i*4] = exp(sum) * in->IFlux0[i]; /* Fixed linear poln fn? */ if (in->PPol[i]>0.0) { PPol = in->PPol[i] + in->dPPol[i]*(in->freq-in->inDesc->freq); in->souParm[i*4+1] = PPol * in->souParm[i*4] * cos(in->RLPhase[i]); in->souParm[i*4+2] = PPol * in->souParm[i*4] * sin(in->RLPhase[i]); } /* Add 1% linear poln if fitting on init if (init && in->souFit[i][1]) { in->souParm[i*4+1] = 0.01*in->souParm[i*4]; }*/ } /* end loop over source */ /* Cleanup */ cleanup: /* Close data */ ObitUVClose (inUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Set iChan, *iIF for next */ if ((*iChan)>nChan) { /* Done with IF? */ (*iChan) = 1; (*iIF)++; } /* Average Ipol flux densities */ for (i=0; i<in->nsou; i++) { if (cntFlux[i]>0) in->souFlux[i] = sumFlux[i]/cntFlux[i]; else in->souFlux[i] = 0.0; } if (cntFlux) g_free(cntFlux); cntFlux = NULL; if (sumFlux) g_free(sumFlux); sumFlux = NULL; return; } /* end ReadData */ /** * Initialize new Source poln.(CP) table * All zero entries * \param in Fitting object * \param err Obit error stack object. */ static void InitSourceTab(ObitPolnCalFit* in, ObitErr *err) { olong i, irow, nif, nchan, isou; ObitTableCPRow *row=NULL; gchar *routine = "ObitPolnCalFit:InitSourceTab"; /* Clear any existing rows */ ObitTableClearRows ((ObitTable*)in->CPTable, err); /* Open */ ObitTableCPOpen (in->CPTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* define row */ row = newObitTableCPRow(in->CPTable); ObitTableCPSetRow (in->CPTable, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* Set header values */ in->CPTable->FreqID = 0; if (in->outDesc->jlocif>=0) nif = in->outDesc->inaxes[in->outDesc->jlocif]; else nif = 1; nchan = in->outDesc->inaxes[in->outDesc->jlocf]; /* Initialize Row */ row->SourID = 0; for (i=0; i<nif*nchan; i++) row->IPol[i] = 0.0; for (i=0; i<nif*nchan; i++) row->QPol[i] = 0.0; for (i=0; i<nif*nchan; i++) row->UPol[i] = 0.0; for (i=0; i<nif*nchan; i++) row->VPol[i] = 0.0; /* Loop over sources writing */ for (isou=0; isou<in->nsou; isou++) { row->SourID = in->souIDs[isou]; irow = -1; ObitTableCPWriteRow (in->CPTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); } /* End loop onver source writing */ /* Close */ ObitTableCPClose (in->CPTable, err); if (err->error) Obit_traceback_msg (err, routine, in->name); row = ObitTableCPRowUnref(row); /* Cleanup */ } /* end InitSourceTab */ /** * Initialize new Instrumental poln.(PD) table * All zero entries * \param in Fitting object * \param err Obit error stack object. */ static void InitInstrumentalTab(ObitPolnCalFit* in, ObitErr *err) { olong i, irow, iant, npol, nif, nchan; ObitTablePDRow *row=NULL; gchar *routine = "ObitPolnCalFit:InitInstrumentalTab"; /* Clear any existing rows */ ObitTableClearRows ((ObitTable*)in->PDTable, err); /* Open Write only */ ObitTablePDOpen (in->PDTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* define row */ row = newObitTablePDRow(in->PDTable); ObitTablePDSetRow (in->PDTable, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* Set header values */ in->PDTable->numAnt = in->nant; /* Mark soln type */ strncpy (in->PDTable->polType, "ORI-ELP", MAXKEYCHARTABLEPD); if (in->outDesc->jlocif>=0) nif = in->outDesc->inaxes[in->outDesc->jlocif]; else nif = 1; nchan = in->outDesc->inaxes[in->outDesc->jlocf]; npol = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]); /* Initialize Row */ /* row->SourID = 0;*/ row->antNo = 0; row->SubA = 0; row->FreqID = 0; row->RefAnt = in->refAnt; for (i=0; i<nif*nchan; i++) row->RLPhase[i] = 0.0; /* Circular feed default */ if (in->isCircFeed) { for (i=0; i<nif*nchan; i++) row->Real1[i] = G_PI/4.0; for (i=0; i<nif*nchan; i++) row->Imag1[i] = 0.0; if (npol>1) { for (i=0; i<nif*nchan; i++) row->Real2[i] = -G_PI/4.0; for (i=0; i<nif*nchan; i++) row->Imag2[i] = 0.0; } } else { /* Linear feeds ori_x, elip_x, ori_y, elip_y, */ for (i=0; i<nif*nchan; i++) row->Real1[i] = 0.0; for (i=0; i<nif*nchan; i++) row->Imag1[i] = G_PI/4.0; if (npol>1) { for (i=0; i<nif*nchan; i++) row->Real2[i] = 0.0; for (i=0; i<nif*nchan; i++) row->Imag2[i] = 0.0; } } /* Loop over antennas writing */ for (iant=0; iant<in->nant; iant++) { row->antNo = iant+1; irow = -1; ObitTablePDWriteRow (in->PDTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); } /* End loop over source writing */ /* Close */ ObitTablePDClose (in->PDTable, err); if (err->error) Obit_traceback_msg (err, routine, in->name); row = ObitTablePDRowUnref(row); /* Cleanup */ } /* end InitInstrumentalTab */ /** * Initialize new Bandpass.(BP) table * All zero entries * \param in Fitting object * \param err Obit error stack object. */ static void InitBandpassTab(ObitPolnCalFit* in, ObitErr *err) { olong i, irow, iant, npol, nif, nchan, nant; ObitUVDesc *desc; ObitTableBPRow *row=NULL; gchar *routine = "ObitPolnCalFit:InitBandpassTab"; /* Initialize */ nant = in->nant; if (in->outDesc->jlocif>=0) nif = in->outDesc->inaxes[in->outDesc->jlocif]; else nif = 1; nchan = in->outDesc->inaxes[in->outDesc->jlocf]; npol = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]); /* Clear any existing rows */ ObitTableClearRows ((ObitTable*)in->BPTable, err); /* Open */ ObitTableBPOpen (in->BPTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* define row */ row = newObitTableBPRow(in->BPTable); ObitTableBPSetRow (in->BPTable, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* Set header values */ in->BPTable->numAnt = nant; /* Initialize Row */ desc = (ObitUVDesc*)in->outDesc; row->BW = desc->cdelt[desc->jlocf]; row->ChanShift[0] = 0.0; row->ChanShift[1] = 0.0; row->RefAnt1 = in->refAnt; row->RefAnt2 = in->refAnt; row->SubA = 0; row->FreqID = 0; row->TimeI = 24.0; row->SourID = 0; for (i=0; i<nif; i++) row->ChanShift[i] = 0.0; for (i=0; i<nif; i++) row->Weight1[i] = 1.0; if (npol>1) for (i=0; i<nif; i++) row->Weight2[i] = 1.0; for (i=0; i<nchan*nif; i++) { row->Real1[i] = 1.0; row->Imag1[i] = 0.0; if (npol>1) { row->Real2[i] = 1.0; row->Imag2[i] = 0.0; } } /* Loop over antennas writing */ for (iant=0; iant<in->nant; iant++) { row->antNo = iant+1; irow = -1; ObitTableBPWriteRow (in->BPTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); } /* End loop onver source writing */ /* Close */ ObitTableBPClose (in->BPTable, err); if (err->error) Obit_traceback_msg (err, routine, in->name); row = ObitTableBPRowUnref(row); /* Cleanup */ } /* end InitBandpassTab */ /** * Update Source poln.(CP) table * Results obtained from in * \param in Fitting object * \param err Obit error stack object. */ static void UpdateSourceTab(ObitPolnCalFit* in, ObitErr *err) { olong irow, nchan, indx, ich, iif, isou, jsou; olong chanOff=in->BChan-1, ifOff=in->BIF-1, chans[2]; ObitTableCPRow *row=NULL; gchar *routine = "ObitPolnCalFit:UpdateSourceTab"; /* Open */ ObitTableCPOpen (in->CPTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* define row */ row = newObitTableCPRow(in->CPTable); ObitTableCPSetRow (in->CPTable, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); nchan = in->outDesc->inaxes[in->outDesc->jlocf]; /* 0-rel Channels covered in ChInc */ chans[0] = in->Chan-1+chanOff - in->ChInc/2; chans[0] = MAX (0, chans[0]); chans[1] = in->Chan-1+chanOff + in->ChInc/2; chans[1] = MIN (nchan-1, chans[1]); /* Loop over row updating */ for (irow=1; irow<=in->CPTable->myDesc->nrow; irow++) { /* Read previous */ ObitTableCPReadRow (in->CPTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); isou = row->SourID - 1; jsou = in->isouIDs[isou]; /* Calibrator number */ /* Loop over chans */ for (ich=chans[0]; ich<=chans[1]; ich++) { iif = in->IFno-1+ifOff; /* 0 rel IF */ indx = iif*nchan + ich; row->IPol[indx] = in->souParm[jsou*4+0]; row->QPol[indx] = in->souParm[jsou*4+1]; row->UPol[indx] = in->souParm[jsou*4+2]; row->VPol[indx] = in->souParm[jsou*4+3]; } /* end loop over channels */ /* Rewrite */ ObitTableCPWriteRow (in->CPTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); } /* End loop onver source writing */ /* Close */ ObitTableCPClose (in->CPTable, err); if (err->error) Obit_traceback_msg (err, routine, in->name); row = ObitTableCPRowUnref(row); /* Cleanup */ } /* end UpdateSourceTab */ /** * Update Instrumental poln.(PD) table * if in->doBlank, blank failed solutions, else noop * \param in Fitting object * \param isOK was fitting successful? * \param err Obit error stack object. */ static void UpdateInstrumentalTab(ObitPolnCalFit* in, gboolean isOK, ObitErr *err) { olong irow, npol, nchan, indx, ich, iif, iant; ofloat fblank = ObitMagicF(); olong chanOff=in->BChan-1, ifOff=in->BIF-1, chans[2]; ObitTablePDRow *row=NULL; gchar *routine = "ObitPolnCalFit:UpdateInstrumentalTab"; /* If doBlank FALSE and this one failed, simple return */ if (!isOK && (in->doBlank==FALSE)) return; /* Open */ ObitTablePDOpen (in->PDTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* define row */ row = newObitTablePDRow(in->PDTable); ObitTablePDSetRow (in->PDTable, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); nchan = in->outDesc->inaxes[in->outDesc->jlocf]; npol = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]); /* 0-rel Channels covered in ChInc */ chans[0] = in->Chan-1+chanOff - in->ChInc/2; chans[0] = MAX (0, chans[0]); chans[1] = in->Chan-1+chanOff + in->ChInc/2; chans[1] = MIN (nchan-1, chans[1]); /* Fill orphans at end */ if ((nchan-chans[1]-1)>in->ChInc) chans[1] = nchan-1; /* Loop over row updating */ for (irow=1; irow<=in->PDTable->myDesc->nrow; irow++) { /* Read previous */ ObitTablePDReadRow (in->PDTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); iant = row->antNo - 1; /* Update */ /* Loop over chans */ for (ich=chans[0]; ich<=chans[1]; ich++) { iif = in->IFno-1+ifOff; /* 0 rel IF */ indx = iif*nchan + ich; /* OK solution? */ if (isOK && in->gotAnt[iant]) { /* row->RLPhase[indx] = in->PD*RAD2DG; R-L phase difference */ row->Real1[indx] = in->antParm[iant*4+1]; row->Imag1[indx] = in->antParm[iant*4+0]; if (npol>1) { row->Real2[indx] = in->antParm[iant*4+3]; row->Imag2[indx] = in->antParm[iant*4+2]; } } else { /* failed solution */ row->RLPhase[indx] = fblank; row->Real1[indx] = fblank; row->Imag1[indx] = fblank; if (npol>1) { row->Real2[indx] = fblank; row->Imag2[indx] = fblank; } } } /* end loop over channels */ /* Rewrite */ ObitTablePDWriteRow (in->PDTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); } /* End loop over antenna writing */ /* Close */ ObitTablePDClose (in->PDTable, err); if (err->error) Obit_traceback_msg (err, routine, in->name); row = ObitTablePDRowUnref(row); /* Cleanup */ } /* end UpdateInstrumentalTab */ /** * Update Bandpass (BP) table * if in->doBlank, blank failed solutions, else noop * \param in Fitting object * \param isOK was fitting successful? * \param err Obit error stack object. */ static void UpdateBandpassTab(ObitPolnCalFit* in, gboolean isOK, ObitErr *err) { olong irow, npol, nchan, indx, ich, iif, iant; ofloat amp1, amp2, pre, pim, fblank = ObitMagicF(); ObitTableBPRow *row=NULL; olong chanOff=in->BChan-1, ifOff=in->BIF-1, chans[2]; gchar *routine = "ObitPolnCalFit:UpdateBandpassTab"; /* If doBlank FALSE and this one failed, simple return */ if (!isOK && (in->doBlank==FALSE)) return; /* Open */ ObitTableBPOpen (in->BPTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, in->name); /* define row */ row = newObitTableBPRow(in->BPTable); ObitTableBPSetRow (in->BPTable, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); nchan = in->outDesc->inaxes[in->outDesc->jlocf]; npol = MIN (2,in->outDesc->inaxes[in->outDesc->jlocs]); /* 0-rel Channels covered in ChInc */ chans[0] = in->Chan-1+chanOff - in->ChInc/2; chans[0] = MAX (0, chans[0]); chans[1] = in->Chan-1+chanOff + in->ChInc/2; chans[1] = MIN (nchan-1, chans[1]); /* Fill orphans at end */ if ((nchan-chans[1]-1)>in->ChInc) chans[1] = nchan-1; /* Phase difference */ pre = cos(in->PD); pim = sin(-in->PD); /* Loop over row updating */ for (irow=1; irow<=in->BPTable->myDesc->nrow; irow++) { /* Read previous */ ObitTableBPReadRow (in->BPTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); iant = row->antNo - 1; /* Amplitudes of gains */ if (in->doFitGain && in->antGain) { /* Inverse? */ /*{amp1 = 1.0/in->antGain[iant*2];amp2 = 1.0/in->antGain[iant*2+1];}*/ {amp1 = in->antGain[iant*2];amp2 = in->antGain[iant*2+1];} /* Divide the correction between pol1 and pol 2 amp1 = 1.0/sqrt(in->antGain[iant*2+1]); amp2 = sqrt(in->antGain[iant*2+1]);*/ } else {amp1 = 1.0; amp2 = 1.0;} /* Update */ /* Loop over chans */ for (ich=chans[0]; ich<=chans[1]; ich++) { iif = in->IFno-1+ifOff; /* 0 rel IF */ indx = iif*nchan + ich; if (isOK && in->gotAnt[iant]) { row->Real1[indx] = amp1; row->Imag1[indx] = 0.0; if (npol>1) { row->Real2[indx] = amp2*pre; row->Imag2[indx] = pim; } } else { /* failed solution */ row->Real1[indx] = fblank; row->Imag1[indx] = fblank; if (npol>1) { row->Real2[indx] = fblank; row->Imag2[indx] = fblank; } } } /* end loop over channels */ /* Rewrite */ ObitTableBPWriteRow (in->BPTable, irow, row, err); if (err->error) Obit_traceback_msg (err, routine, in->name); } /* End loop onver source writing */ /* Close */ ObitTableBPClose (in->BPTable, err); if (err->error) Obit_traceback_msg (err, routine, in->name); row = ObitTableBPRowUnref(row); /* Cleanup */ } /* end UpdateBandpassTab */ /** * Fit spectra to calibrator IPol flux densities in Source list * \param in Fitting object * \param err Obit error stack object. */ static void FitSpectra (ObitPolnCalFit *in, ObitErr *err) { ofloat *parms=NULL, *sigma=NULL; olong i, isou, jsou, nterm=3, nfreq; gchar *routine="ObitPolnCalFit:FitSpectra"; if (err->error) return; /* Error exists? */ /* Dummy error array */ if (in->inDesc->jlocif>=0) nfreq = in->inDesc->inaxes[in->inDesc->jlocif]; else nfreq = 1; sigma = g_malloc(nfreq*sizeof(ofloat)); for (i=0; i<nfreq; i++) sigma[i] = 0.01; nterm = MIN (3, nfreq); /* Loop over calibrators */ for (isou=0; isou<in->nsou; isou++) { jsou = MAX (1, in->souIDs[isou]); /* Source ID in data */ parms = ObitSpectrumFitSingle (nfreq, nterm, in->inDesc->freq, in->inDesc->freqIF, in->SouList->SUlist[jsou-1]->IFlux, sigma, FALSE, err); if (err->error) Obit_traceback_msg (err, routine, in->name); in->IFlux0[isou] = parms[0]; in->IFlux1[isou] = parms[1]; in->IFlux2[isou] = parms[2]; g_free(parms); } if (sigma) g_free(sigma); } /* end FitSpectra */ /** * Determine Fit Poln parameters * Uses GSL nonlinear solver * \param in Fitting object * \param err Obit error stack object. */ static void doFitGSL (ObitPolnCalFit *in, ObitErr *err) { /*odouble difParam, difChi2=0.0, endChi2=0.0;*/ ofloat fpol, fpa; olong isou=0, iant, i, k=0, iter; olong nparam, ndata, nvalid, nvis, j; odouble sumwt, chi2Test=0.0; double epsabs=1.0e-5, epsrel=1.0e-4; /* Stopping criteria */ olong maxIter=10; /* Stopping criteria */ int status; ofloat chi2, initChi2, ParRMS, XRMS; gchar *routine="ObitPolnCalFit:doFitGSL"; #ifdef HAVE_GSL gsl_multifit_fdfsolver *solver = in->solver; gsl_matrix *covar = in->covar; gsl_vector *work = in->work; gsl_matrix *J; if (err->error) return; /* Error exists? */ /* Set initial parameters */ /* first antenna */ for (iant=0; iant<in->nant; iant++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((in->antFit[iant][k]) && (in->gotAnt[iant])) { j = in->antPNumb[iant][k]; gsl_vector_set(work, j, in->antParm[iant*4+k]); } } /* end loop over parameters */ } /* end loop over antennas */ /* Antenna gains if needed */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { /* Loop over parameters */ for (k=0; k<2; k++) { /* Fitting? */ if (in->antGainFit[iant][k]) { j = in->antGainPNumb[iant][k]; gsl_vector_set(work, j, in->antGain[iant*2+k]); } } /* end loop over parameters */ } /* end if gotAnt */ } /* end loop over antennas */ } /* End if antenna gains */ /* now source */ for (isou=0; isou<in->nsou; isou++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (in->souFit[isou][k]) { j = in->souPNumb[isou][k]; gsl_vector_set(work, j, in->souParm[isou*4+k]); } } /* end loop over parameters */ } /* end loop over sources */ /* Phase difference if being fitted */ if (in->doFitRL) { j = in->PDPNumb; gsl_vector_set(work, j, in->PD); } /* Set up fitting */ nparam = in->nparam; ndata = in->ndata; nvis = in->nvis; in->funcStruc->n = ndata; in->funcStruc->p = nparam; in->funcStruc->params = in; iter = 0; /* init solver */ gsl_multifit_fdfsolver_set (solver, in->funcStruc, work); /* initial Chi2 */ if (err->prtLv>=3) { initChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, &ParRMS, &XRMS, NULL, NULL, err); Obit_log_error(err, OBIT_InfoErr, "Initial LM Chi2=%g Par RMS %g X RMS %g ", initChi2, ParRMS, XRMS); if (err->error) Obit_traceback_msg (err, routine, "diagnostic"); } /* end initial Chi2 */ /* iteration loop */ do { iter++; status = gsl_multifit_fdfsolver_iterate(solver); /* current Chi2 */ if (err->prtLv>=3) { chi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, &ParRMS, &XRMS, NULL, NULL, err); Obit_log_error(err, OBIT_InfoErr, "current LM Chi2=%g Par RMS %g X RMS %g", chi2, ParRMS, XRMS); if (err->error) Obit_traceback_msg (err, routine, "diagnostic"); } /* end Chi2 */ /* Diagnostics */ if (err->prtLv>=5) { sumwt = (ofloat)gsl_blas_dnrm2(solver->f); /*Obit_log_error(err, OBIT_InfoErr,"iter %d status %d ant 1 %g %g %g %g sumwt %f", iter, status, in->antParm[0], in->antParm[1], in->antParm[2], in->antParm[3], sumwt); */ Obit_log_error(err, OBIT_InfoErr,"iter %d status %d grad norm %f", iter, status, sumwt); ObitErrLog(err); } /* end Diagnostics */ /* Minimum of two iterations */ if (iter<2) status = GSL_CONTINUE; /* Convergence test */ if (iter>1) status = gsl_multifit_test_delta (solver->dx, solver->x, epsabs, epsrel); } while ((status==GSL_CONTINUE) && (iter<maxIter)); /* If it didn't work - bail */ if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) { fprintf (stderr, "Failed, status = %s\n", gsl_strerror(status)); goto done; } /* Get fitting results - fixed parameters will still be in the arrays */ /* first antennas */ for (iant=0; iant<in->nant; iant++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((in->antFit[iant][k]) && (in->gotAnt[iant])) { j = in->antPNumb[iant][k]; in->antParm[iant*4+k] = gsl_vector_get(solver->x, j); /* if ((k==0) || (k==2)) undo wraps */ in->antParm[iant*4+k] = fmod(in->antParm[iant*4+k], 2*G_PI); if (in->antParm[iant*4+k]>G_PI) in->antParm[iant*4+k] -= 2*G_PI; } } /* end loop over parameters */ } /* end loop over antennas */ /* Antenna gains if needed */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { /* Loop over parameters */ for (k=0; k<2; k++) { /* Fitting? */ if (in->antGainFit[iant][k]) { j = in->antGainPNumb[iant][k]; in->antGain[iant*2+k] = gsl_vector_get(solver->x, j); } } /* end loop over parameters */ } /* end if gotAnt */ } /* end loop over antennas */ } /* End if antenna gains */ /* now source */ for (isou=0; isou<in->nsou; isou++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (in->souFit[isou][k]) { j = in->souPNumb[isou][k]; in->souParm[isou*4+k] = gsl_vector_get(solver->x, j); } } /* end loop over parameters */ } /* end loop over sources */ if (in->doFitRL) { j = in->PDPNumb; in->PD = gsl_vector_get(solver->x, j); } /* Errors */ if (in->doError) { /* Get covariance matrix - extract diagonal terms */ J = gsl_matrix_alloc(in->ndata, in->nparam); #ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC gsl_multifit_fdfsolver_jac(solver, J); #else gsl_matrix_memcpy(J, solver->J); #endif gsl_multifit_covar (J, 0.0, covar); gsl_matrix_free(J); for (iant=0; iant<in->nant; iant++) { /* Loop over antenna parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((in->antFit[iant][k]) && (in->gotAnt[iant])) { j = in->antPNumb[iant][k]; in->antErr[iant*4+k] = sqrt(gsl_matrix_get(covar, j, j)); } else in->antErr[iant*4+k] = -1.0; } /* end loop over parameters */ } /* end loop over antennas */ /* Antenna gains if needed */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { /* Loop over parameters */ for (k=0; k<2; k++) { /* Fitting? */ if (in->antGainFit[iant][k]) { j = in->antGainPNumb[iant][k]; in->antGainErr[iant*2+k] = sqrt(gsl_matrix_get(covar, j, j)); } else in->antGainErr[iant*2+k] = -1.0; } /* end loop over parameters */ } /* end if gotAnt */ } /* end loop over antennas */ } /* End if antenna gains */ /* now source */ for (isou=0; isou<in->nsou; isou++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (in->souFit[isou][k]) { j = in->souPNumb[isou][k]; in->souErr[isou*4+k] = sqrt(gsl_matrix_get(covar, j, j)); } else in->souErr[isou*4+k] = -1.0; } /* end loop over parameters */ } /* end loop over sources */ /* Now phase difference */ if (in->doFitRL) { j = in->PDPNumb; in->PDerr = sqrt(gsl_matrix_get(covar, j, j)); } /* Count valid data */ nvalid = 0; for (i=0; i<nvis*4; i++) if (in->inWt[i]>0.0) nvalid++; /* normalized Chi squares */ if (nvalid>nparam) { sumwt = (ofloat)gsl_blas_dnrm2(solver->f); chi2Test = (sumwt*sumwt)/(nvalid-nparam); } else chi2Test = -1.0; in->ChiSq = chi2Test; } /* end do error */ /* Diagnostics */ done: if (err->prtLv>=2) { Obit_log_error(err, OBIT_InfoErr, "%d iter LM fit", iter); for (isou=0; isou<in->nsou; isou++) { fpol = sqrt (in->souParm[isou*4+1]*in->souParm[isou*4+1] + in->souParm[isou*4+2]*in->souParm[isou*4+2]) / in->souParm[isou*4+0]; fpa = 57.296*atan2(in->souParm[isou*4+2], in->souParm[isou*4+1]); Obit_log_error(err, OBIT_InfoErr, "sou %3d %8.4f (%8.4f) %8.4f (%8.4f) %8.4f (%8.4f) %8.4f (%8.4f)", isou+1, in->souParm[isou*4+0], in->souErr[isou*4+0], in->souParm[isou*4+1], in->souErr[isou*4+1], in->souParm[isou*4+2], in->souErr[isou*4+2], in->souParm[isou*4+3], in->souErr[isou*4+3]); Obit_log_error(err, OBIT_InfoErr, " (fpol %6.4f %s %6.2f", fpol, "@", fpa); } for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { Obit_log_error(err, OBIT_InfoErr, "ant %3d %8.2f (%8.2f) %8.2f (%8.2f) %8.2f (%8.2f) %8.2f (%8.2f)", iant+1, in->antParm[iant*4+0]*57.296, MAX(-1.0, in->antErr[iant*4+0]*57.296), in->antParm[iant*4+1]*57.296, MAX(-1.0, in->antErr[iant*4+1]*57.296), in->antParm[iant*4+2]*57.296, MAX(-1.0, in->antErr[iant*4+2]*57.296), in->antParm[iant*4+3]*57.296, MAX(-1.0, in->antErr[iant*4+3]*57.296)); } } /* Phase differrence */ if (in->doFitRL) { Obit_log_error(err, OBIT_InfoErr, "Phase difference %8.2f (%8.2f)",in->PD*57.296,in->PDerr*57.296); } /* Antenna gain if fitted */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { Obit_log_error(err, OBIT_InfoErr, "ant %3d gain X %6.3f (%6.3f) Y %6.3f (%6.3f)", iant+1, in->antGain[iant*2+0], in->antGainErr[iant*2+0], in->antGain[iant*2+1], in->antGainErr[iant*2+1]); } } } /* end antenna gain */ } /* end diagnostics */ ObitErrLog(err); #endif /* HAVE_GSL */ return; } /* end doFitGSL */ /** * Determine Fit Poln parameters * Solution uses a relaxation method from Fred Schwab: * Pn+1 = Pn + atan2 (dChi2/dP), (d2Chi2/dP2)) * for each parameter P where n or n+1 indicates a given iteration, * dChi2/dP is the first partial derivative of Chi squared wrt P, * d2Chi2/d2P is the second partial derivative of Chi squared wrt P, * Chi2 = Sum (w (model-obs)**2) * \param in Fitting object * \param err Obit error stack object. * \return TRUE if worked, else FALSE. */ static gboolean doFitFast (ObitPolnCalFit *in, ObitErr *err) { odouble begChi2, endChi2=0.0, iChi2, tChi2, deriv=0.0, deriv2=1.0; odouble difParam, difChi2=0.0, hiChi2=0.0, dChi2, d2Chi2; ofloat tParam, sParam, delta, sdelta = 0.02; ofloat ParRMS, XRMS, fpol, fpa, PPol; olong isou=0, iant, i, k=0, iter, maxIter; olong pas=0, ptype=0, pnumb=-1; gchar *routine="ObitPolnCalFit:doFitFast"; if (err->error) return TRUE; /* Error exists? */ iter = 0; maxIter = 300; while (iter<maxIter) { in->selSou = -1; in->selAnt = -1; begChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, &ParRMS, &XRMS, NULL, NULL, err); /* Initial value */ if (iter==0) in->initChiSq = begChi2; /* Save initial */ /* Test for valid data */ if (begChi2<=0.0) { Obit_log_error(err, OBIT_InfoErr, "No valid data"); ObitErrLog(err); return FALSE; } hiChi2 = MAX (hiChi2, begChi2); difParam = 0.0; ptype = -1; pnumb = -1; if ((iter==0) &&(err->prtLv>=2)) { /*hiChi2 = begChi2; WHAT???*/ Obit_log_error(err, OBIT_InfoErr, "Initial Chi2=%g Parallel RMS %g Cross RMS %g", begChi2, ParRMS, XRMS); } /* Fit phase difference? */ if (in->doFitRL) { iChi2 = GetChi2 (in->nThread, in, polnParmPD, 0, &ParRMS, &XRMS, &dChi2, &d2Chi2, err); /* Initial value */ sParam = in->PD; deriv = dChi2; deriv2 = d2Chi2; if (fabs(deriv2)>(fabs(deriv)*1.0e-4)) { /* Bother with this one?*/ delta = -0.5*atan2(deriv, deriv2); /* Don't go wild */ if (delta>0.) delta = MIN (delta, 20*sdelta); if (delta<0.) delta = MAX (delta, -20*sdelta); /* Loop decreasing delta until fit improves */ for (i=0; i<10; i++) { in->PD = sParam + delta; tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, &ParRMS, &XRMS, NULL, NULL, err); if (tChi2<iChi2) { /* Got new value? */ sParam += delta; if (fabs(difParam)<fabs(delta)) { ptype = 0; pnumb = 0; pas = 0; difParam = delta; } break; } delta *= -0.7; /* Test signs */ if (fabs(delta)<1.0e-6) break; } /* end loop decreasing */ } in->PD = sParam; /* Set parameter to new or old value */ } /* end Fit phase difference */ /* Loop over sources */ for (isou=0; isou<in->nsou; isou++) { in->selSou = isou; /* Loop over parameters ipol, qpol, upol, vpol*/ for (k=0; k<4; k++) { /* Fitting? */ if (in->souFit[isou][k]) { iChi2 = GetChi2 (in->nThread, in, polnParmSou, k, &ParRMS, &XRMS, &dChi2, &d2Chi2, err); /* Initial value */ sParam = in->souParm[isou*4+k]; deriv = dChi2; deriv2 = d2Chi2; if (fabs(deriv2)>(fabs(deriv)*1.0e-4)) /* Bother with this one?*/ delta = -0.5*atan2(deriv, deriv2); else {in->souParm[isou*4+k] = sParam; continue;} if (k<3) delta *= 5; /* Speed up I,Q, U, slow down V*/ else { delta *= 0.03; /* Set bound of 1% of I */ if (in->souParm[isou*4+k]> 0.01*in->souParm[isou*4]) delta = -delta; if (in->souParm[isou*4+k]<-0.01*in->souParm[isou*4]) delta = -delta; } if (delta>0.) delta = MIN (delta, 20*sdelta); if (delta<0.) delta = MAX (delta, -20*sdelta); /* Loop decreasing delta until fit improves */ for (i=0; i<10; i++) { in->souParm[isou*4+k] = sParam + delta; tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, k, &ParRMS, &XRMS, NULL, NULL, err); if (tChi2<iChi2) { /* Got new value */ sParam += delta; if (fabs(difParam)<fabs(delta)) { ptype = 1; pnumb = k; pas = isou; difParam = delta; } break; } delta *= -0.7; /* Test signs */ if (fabs(delta)<1.0e-6) break; } /* end loop decreasing */ in->souParm[isou*4+k] = sParam; /* Set parameter to new or old value */ } /* end if fitting parameter */ else if (k==1) { /* Fixed Q poln? */ if (in->PPol[isou]>0.0) { PPol = in->PPol[isou] + in->dPPol[isou]*(in->freq-in->inDesc->freq); in->souParm[isou*4+k] = PPol * in->souParm[isou*4] * cos(in->RLPhase[isou]);} } /* end Fixed Q poln */ else if (k==2) { /* Fixed U poln? */ if (in->PPol[isou]>0.0) { PPol = in->PPol[isou] + in->dPPol[isou]*(in->freq-in->inDesc->freq); in->souParm[isou*4+k] = PPol * in->souParm[isou*4] * sin(in->RLPhase[isou]);} } /* end Fixed U poln */ if (err->error) Obit_traceback_val (err, routine, in->name, FALSE); } /* end loop over parameters */ } /* end loop over sources */ in->selSou = -1; /* Antenna gain if fitted */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (!in->gotAnt[iant]) continue; /* Have data? */ in->selAnt = iant; /* Loop over parameters, gain_X, Gain_Y */ for (k=0; k<2; k++) { /* Fitting? */ if (in->antGainFit[iant][k]) { iChi2 = GetChi2 (in->nThread, in, polnParmGain, k, &ParRMS, &XRMS, &dChi2, &d2Chi2, err); /* Initial value */ if (iChi2<=0.0) continue; sParam = in->antGain[iant*2+k]; deriv = dChi2; deriv2 = d2Chi2; if ((fabs(deriv2)>(fabs(deriv)*1.0e-4)) && (fabs(deriv)>(fabs(deriv2)*1.0e-3))) /* Bother with this one?*/ delta = -0.5*atan2(deriv, deriv2); else {in->antGain[iant*2+k] = sParam; continue;} /* Loop decreasing delta until fit improves */ for (i=0; i<10; i++) { tParam = sParam + delta; in->antGain[iant*2+k] = tParam; tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, k, &ParRMS, &XRMS, NULL, NULL, err); if (tChi2<iChi2) { /* Got new value */ sParam += delta; if (fabs(difParam)<fabs(delta)) { ptype = 2; pnumb = k; pas = iant; difParam = delta; } break; } delta *= -0.7; /* Test signs */ if (fabs(delta)<1.0e-6) break; } /* end loop decreasing */ in->antGain[iant*2+k] = sParam; /* Set parameter to new or old value */ } else if (k==0) { /* Not fitting gain_X, use 1.gain_Y */ in->antGain[iant*2] = 1.0/in->antGain[iant*2+1]; } /* end if fitting parameter */ if (err->error) Obit_traceback_val (err, routine, in->name, FALSE); } /* end loop over parameters */ } /* end loop over antennas */ } /* end antenna gain */ /* Don't change antenna non-gain parameters the first 3 loops */ if (iter<3) {iter++; continue;} /* Loop over antennas */ for (iant=0; iant<in->nant; iant++) { if (!in->gotAnt[iant]) continue; /* Have data? */ in->selAnt = iant; /* Loop over parameters 0,1 ori, elip (r/x), 2,3 ori, elip (l/y), */ for (k=0; k<4; k++) { /* Fitting? */ if (in->antFit[iant][k]) { iChi2 = GetChi2 (in->nThread, in, polnParmAnt, k, &ParRMS, &XRMS, &dChi2, &d2Chi2, err); /* Initial value */ if (iChi2<=0.0) continue; sParam = in->antParm[iant*4+k]; deriv = dChi2; deriv2 = d2Chi2; if ((fabs(deriv2)>(fabs(deriv)*1.0e-4)) && (fabs(deriv)>(fabs(deriv2)*1.0e-3))) /* Bother with this one?*/ delta = -0.5*atan2(deriv, deriv2); else {in->antParm[iant*4+k] = sParam; continue;} if ((k==0) || (k==2)) { /* Orientation */ delta *= 5; /* Speed up orientation */ /* But don't go crazy */ if (delta>0.1) delta = +0.1; if (delta<-0.1) delta = -0.1; } /* Loop decreasing delta until fit improves */ for (i=0; i<10; i++) { tParam = sParam + delta; in->antParm[iant*4+k] = tParam; /* Restrict elipticities to [-pi/4, +pi/4] */ if ((k==1) && (tParam>+0.25*G_PI)) tParam = +0.5*G_PI - tParam; if ((k==3) && (tParam<-0.25*G_PI)) tParam = -0.5*G_PI - tParam; tChi2 = GetChi2 (in->nThread, in, polnParmUnspec, k, &ParRMS, &XRMS, NULL, NULL, err); if (tChi2<iChi2) { /* Got new value */ sParam = tParam; sParam = fmod (sParam, 2*G_PI); if (sParam> G_PI) sParam -= 2*G_PI; if (sParam<-G_PI) sParam += 2*G_PI; if (fabs(difParam)<fabs(delta)) { ptype = 2; pnumb = k; pas = iant; difParam = delta; } break; } delta *= -0.7; /* Test signs */ if (fabs(delta)<1.0e-6) break; } /* end loop decreasing */ if ((k==0) || (k==2)) { /* Orientation */ /* Make sure in range +/- 2 pi if (sParam>2*G_PI) sParam -= 2*G_PI; if (sParam,-2*G_PI) sParam += 2*G_PI; */ } in->antParm[iant*4+k] = sParam; /* Set parameter to new or old value */ } /* end if fitting parameter */ if (err->error) Obit_traceback_val (err, routine, in->name, FALSE); } /* end loop over parameters */ } /* end loop over antennas */ in->selAnt = -1; in->selSou = -1; in->selAnt = -1; endChi2 = GetChi2 (in->nThread, in, polnParmUnspec, 0, &ParRMS, &XRMS, NULL, NULL, err); /* Final value */ /* Save (final) values */ in->ChiSq = endChi2; in->ParRMS = ParRMS; in->XRMS = XRMS; /*Constrain ellipticities for Lin. Feeds if refAnt<0 */ if ((!in->isCircFeed) &&(in->refAnt<0)) { tParam = ConstrLinFeed(in); if (err->prtLv>=5) { /* Diagnostics */ Obit_log_error(err, OBIT_InfoErr, "iter %d Remove average Ellip = %g", iter+1, tParam); ObitErrLog(err); } } /* end constrain feeds */ /* Convergence test */ difChi2 = fabs(begChi2 - endChi2); if ((fabs(difParam)<1.0e-7) || ((fabs(difParam)<5.0e-4)&&(difChi2<=1.0e-6*hiChi2))) break; /* Diagnostics */ if (err->prtLv>=5) { Obit_log_error(err, OBIT_InfoErr, "%d iter Chi2=%g Param %g type %d numb %d sou/ant %d dChi2 %g", iter+1, endChi2, difParam, ptype, pnumb, pas, difChi2); ObitErrLog(err); } iter++; } /* end iteration loop */ /* Diagnostics */ if (err->prtLv>=2) { Obit_log_error(err, OBIT_InfoErr, "%d iter relaxation Chi2=%g Par RMS %g X RMS %g ", iter+1, endChi2, ParRMS, XRMS); /* Don't give fit is using GSL */ if (strncmp(in->solnType, "LM ", 4) || (err->prtLv>=5)) { Obit_log_error(err, OBIT_InfoErr, "Phase difference %8.2f", in->PD*57.296); for (isou=0; isou<in->nsou; isou++) { fpol = sqrt (in->souParm[isou*4+1]*in->souParm[isou*4+1] + in->souParm[isou*4+2]*in->souParm[isou*4+2]) / in->souParm[isou*4+0]; fpa = 57.296*atan2(in->souParm[isou*4+2], in->souParm[isou*4+1]); Obit_log_error(err, OBIT_InfoErr, "sou %3d %8.4f %8.4f %8.4f %8.4f (fpol %6.4f %s %6.2f)", isou+1, in->souParm[isou*4+0], in->souParm[isou*4+1], in->souParm[isou*4+2], in->souParm[isou*4+3], fpol, "@", fpa); } if (in->isCircFeed) Obit_log_error(err, OBIT_InfoErr, "ant Ori_R Elp_R Ori_L Elp_L Par RMS X RMS"); else Obit_log_error(err, OBIT_InfoErr, "ant Ori_X Elp_X Ori_Y Elp_Y Par RMS X RMS"); for (iant=0; iant<in->nant; iant++) if (in->gotAnt[iant]) { /* Get RMSes */ GetRMSes (in->nThread, in, iant, &ParRMS, &XRMS, err); Obit_log_error(err, OBIT_InfoErr, "%3d %8.2f %8.2f %8.2f %8.2f %10.7f %10.7f", iant+1, in->antParm[iant*4+0]*57.296, in->antParm[iant*4+1]*57.296, in->antParm[iant*4+2]*57.296, in->antParm[iant*4+3]*57.296, ParRMS, XRMS); } /* Antenna gain if fitted */ if (!in->isCircFeed && in->doFitGain) { for (iant=0; iant<in->nant; iant++) { if (in->gotAnt[iant]) { Obit_log_error(err, OBIT_InfoErr, "ant %3d gain X %6.3f Y %6.3f ", iant+1, in->antGain[iant*2+0], in->antGain[iant*2+1]); } } } /* end antenna gain */ } /* end if not LM */ } /* end diagnostics */ ObitErrLog(err); return TRUE; } /* end doFitFast */ /** * Determine Chi Sq and RMS residuals of current model on selected data * Also optionally computes the first and second derivative wrt a given * parameter which is specified by paramType, paramNumber * \param nThreads Number of threads to use * \param in Fitting object * \param paramType Parameter type * \li polnParmUnspec Unspecified = don't compute derivatives * \li polnParmSou Source parameter * \li polnParmAnt Antenna parameter * \li polnParmGain Antenna gains * \li polnParmPD Phase difference * \param paramNumber Parameter number, * Sou: 0=Ipol, 1=Qpol, 2=Upol, 3=VPol * Gain 0=X, 1=Y * Ant: 0= Ori R/X, 1=Elp R/X, 2= Ori L/Y, 1=Elp L/Y, * \param ParRMS [out] Parallel hand RMS * \param XRMS [out] Cross hand RMS * \param dChi2 [out] First derivative of Chi2 wrt parameter * May be NULL if not needed * \param d2Chi2 [out] Second derivative of Chi2 wrt parameter * May be NULL if not needed * \param err Obit error stack object. * \return Chi^2 */ static odouble GetChi2 (olong nThreads, ObitPolnCalFit *in, PolnParmType paramType, olong paramNumber, ofloat *ParRMS, ofloat *XRMS, odouble *dChi2, odouble *d2Chi2, ObitErr *err) { odouble Chi2 = -1.0; ObitThreadFunc func=NULL; odouble sumParResid, sumXResid, sumWt, ldChi2, ld2Chi2; olong iTh, nPobs, nXobs, nVisPerThread; gboolean OK; gchar *routine="ObitPolnCalFit:GetChi2"; if (err->error) return Chi2; /* Error exists? */ if (dChi2!=NULL) *dChi2 = 0.0; if (d2Chi2!=NULL) *d2Chi2 = 1.0; /* Feed polarization type? */ if (in->isCircFeed) { /* Circular feeds */ func = (ObitThreadFunc)ThreadPolnFitRLChi2; } else { /* Linear feeds */ func = (ObitThreadFunc)ThreadPolnFitXYChi2; } /* Init threads */ nVisPerThread = in->nvis / in->nThread; for (iTh=0; iTh<nThreads; iTh++) { in->thArgs[iTh]->selSou = in->selSou; in->thArgs[iTh]->selAnt = in->selAnt; in->thArgs[iTh]->inData = in->inData; in->thArgs[iTh]->inWt = in->inWt; in->thArgs[iTh]->antNo = in->antNo; in->thArgs[iTh]->souNo = in->souNo; in->thArgs[iTh]->PD = in->PD; in->thArgs[iTh]->curFreq= in->freq; in->thArgs[iTh]->nvis = in->nvis; in->thArgs[iTh]->paramType = paramType; in->thArgs[iTh]->paramNumber = paramNumber; in->thArgs[iTh]->lo = iTh*nVisPerThread; /* Zero rel first */ in->thArgs[iTh]->hi = (iTh+1)*nVisPerThread; /* Zero rel last */ } /* Make sure do all data */ iTh = in->nThread-1; in->thArgs[iTh]->hi = MAX (in->thArgs[iTh]->hi, in->nvis); OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)in->thArgs); if (!OK) { Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine); return Chi2; } /* Sum over threads */ Chi2 = sumParResid = sumXResid = sumWt = ldChi2 = ld2Chi2 = 0.0; nPobs = nXobs = 0; for (iTh=0; iTh<nThreads; iTh++) { Chi2 += in->thArgs[iTh]->ChiSq; sumParResid += in->thArgs[iTh]->sumParResid; sumXResid += in->thArgs[iTh]->sumXResid; sumWt += in->thArgs[iTh]->sumWt; nPobs += in->thArgs[iTh]->nPobs; nXobs += in->thArgs[iTh]->nXobs; if (paramType!=polnParmUnspec) { ldChi2 += in->thArgs[iTh]->sumDeriv; ld2Chi2 += in->thArgs[iTh]->sumDeriv2; } } if (sumWt>0.0) Chi2 /= sumWt; /* output RMSes */ *ParRMS = sqrt (sumParResid / nPobs); *XRMS = sqrt (sumXResid / nXobs); if ((paramType!=polnParmUnspec) && (dChi2!=NULL) && (sumWt>0.0)) *dChi2 = ldChi2 / sumWt; if ((paramType!=polnParmUnspec) && (d2Chi2!=NULL) && (sumWt>0.0)) *d2Chi2 = ld2Chi2 / sumWt; return Chi2; } /* end GetChi2 */ /** * Determine RMS residuals of current model on selected data * \param nThreads Number of threads to use * \param in Fitting object * \parma antNumber 0-rel antenna number * \param ParRMS [out] Parallel hand RMS * \param XRMS [out] Cross hand RMS * \param err Obit error stack object. */ static void GetRMSes (olong nThreads, ObitPolnCalFit *in, olong antNumber, ofloat *ParRMS, ofloat *XRMS, ObitErr *err) { ObitThreadFunc func=NULL; odouble sumParResid, sumXResid; olong iTh, nPobs, nXobs, nVisPerThread; gboolean OK; gchar *routine="ObitPolnCalFit:GetRMSes"; *ParRMS = 0.0; *XRMS = 0.0; if (err->error) return; /* Error exists? */ /* Feed polarization type? */ if (in->isCircFeed) { /* Circular feeds */ func = (ObitThreadFunc)ThreadPolnFitRLChi2; } else { /* Linear feeds */ func = (ObitThreadFunc)ThreadPolnFitXYChi2; } /* Init threads */ nVisPerThread = in->nvis / in->nThread; for (iTh=0; iTh<nThreads; iTh++) { in->thArgs[iTh]->selSou = -1; in->thArgs[iTh]->selAnt = antNumber; in->thArgs[iTh]->inData = in->inData; in->thArgs[iTh]->inWt = in->inWt; in->thArgs[iTh]->antNo = in->antNo; in->thArgs[iTh]->souNo = in->souNo; in->thArgs[iTh]->PD = in->PD; in->thArgs[iTh]->curFreq= in->freq; in->thArgs[iTh]->nvis = in->nvis; in->thArgs[iTh]->paramType = polnParmAnt; in->thArgs[iTh]->paramNumber = 0; /* Ori R/X */ in->thArgs[iTh]->lo = iTh*nVisPerThread; /* Zero rel first */ in->thArgs[iTh]->hi = (iTh+1)*nVisPerThread; /* Zero rel last */ } /* Make sure do all data */ iTh = in->nThread-1; in->thArgs[iTh]->hi = MAX (in->thArgs[iTh]->hi, in->nvis); OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)in->thArgs); if (!OK) { Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine); return; } /* Sum over threads */ sumParResid = sumXResid = 0.0; nPobs = nXobs = 0; for (iTh=0; iTh<nThreads; iTh++) { sumParResid += in->thArgs[iTh]->sumParResid; sumXResid += in->thArgs[iTh]->sumXResid; nPobs += in->thArgs[iTh]->nPobs; nXobs += in->thArgs[iTh]->nXobs; } /* Now do orthogonal poln */ for (iTh=0; iTh<nThreads; iTh++) in->thArgs[iTh]->paramNumber = 2; /* Ori L/Y */ OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)in->thArgs); if (!OK) { Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine); return; } /* Sum over threads */ for (iTh=0; iTh<nThreads; iTh++) { sumParResid += in->thArgs[iTh]->sumParResid; sumXResid += in->thArgs[iTh]->sumXResid; nPobs += in->thArgs[iTh]->nPobs; nXobs += in->thArgs[iTh]->nXobs; } /* output RMSes */ *ParRMS = sqrt (sumParResid / MAX(1, nPobs)); *XRMS = sqrt (sumXResid / MAX(1, nXobs)); } /* end GetRMSes */ /** * Determine average R-L phase difference * \param in Fitting object * \param err Obit error stack object. * \return Chi^2 */ ofloat FitRLPhase (ObitPolnCalFit *in, ObitErr *err) { ofloat PD = 0.0; ofloat *RLr=NULL, *RLi=NULL, *LRr=NULL, *LRi=NULL, *RLwt=NULL, *LRwt=NULL; ofloat *data, *wt, iipol, Re1, Re2, Im1, Im2, PPol1, PPol2, Pang1, Pang2; odouble sumr, sumi, sumw; olong i, isou, idata; gboolean OK; /*gchar *routine="ObitPolnCalFit:FitRLPhase";*/ if (err->error) return PD; /* Error exists? */ /* Alias work arrays */ RLr = (ofloat*)in->SR; RLi = (ofloat*)in->DR; LRr = (ofloat*)in->SL; LRi = (ofloat*)in->DL; RLwt = (ofloat*)in->RS; LRwt = (ofloat*)in->RS; /* Init sums */ OK = FALSE; for (i=0; i<in->nsou; i++) { RLr[i] = RLi[i] = LRr[i] = LRi[i] = RLwt[i] = LRwt[i] = 0.0; /* Check for suitable calibrators */ OK = OK || (!in->souFit[i][1] && !in->souFit[i][2] && (in->PPol[i]>0.0001)); } /* Any suitable calibrators? */ if (!OK) return PD; wt = in->inWt; data = in->inData; /* Loop over data */ for (idata=0; idata<in->nvis; idata++) { isou = MAX (0, in->souNo[idata]); /* Source number */ /* This one usable? */ if (in->souFit[isou][1] || in->souFit[isou][2] || (in->PPol[isou]<=0.0001)) continue; /* Normalize data py 1/ipol */ iipol = 1.0 / in->souParm[isou*4]; if (wt[idata*4+2]>0.0) { RLr[isou] += data[idata*10+6] * iipol * wt[idata*4+2]; RLi[isou] += data[idata*10+7] * iipol * wt[idata*4+2]; RLwt[isou] += wt[idata*4+2]; } if (wt[idata*4+3]>0.0) { LRr[isou] += data[idata*10+8] * iipol * wt[idata*4+3]; LRi[isou] += data[idata*10+9] * iipol * wt[idata*4+3]; LRwt[isou] += wt[idata*4+3]; } } /* end loop over data */ /* Loop over sources differences phase with model - weight average by polarized flux, average as real and imaginary parts */ sumr = sumi = sumw = 0.0; /* Signs here need to be checked */ for (isou=0; isou<in->nsou; isou++) { if (in->souFit[isou][1] || in->souFit[isou][2] || (in->PPol[isou]<=0.0001)) continue; /* Get weighted average RL and LR per source */ if (RLwt[isou]>0.0) { Re1 = RLr[isou] / RLwt[isou]; Im1 = RLi[isou] / RLwt[isou]; PPol1 = in->souParm[isou*4] * sqrt (Re1*Re1 + Im1*Im1); } else {Re1 = 1.0; Im1=0.0; PPol1 = 0.0;} Pang1 = atan2 (Im1, Re1); sumr += PPol1 * cos (Pang1 - in->RLPhase[isou]); sumi += PPol1 * sin (Pang1 - in->RLPhase[isou]); sumw += PPol1; if (LRwt[isou]>0.0) { Re2 = LRr[isou] / LRwt[isou]; Im2 = LRi[isou] / LRwt[isou]; PPol2 = in->souParm[isou*4] * sqrt (Re2*Re2 + Im2*Im2); } else {Re2 = 1.0; Im2=0.0; PPol2 = 0.0;} Pang2 = atan2 (Im2, Re2); sumr += PPol2 * cos (Pang2 + in->RLPhase[isou]); sumi -= PPol2 * sin (Pang2 + in->RLPhase[isou]); sumw += PPol2; } if ((sumr!=0.0) || (sumi!=0.0)) PD = atan2 (sumi, sumr); /* Weighted phase difference */ return PD; } /* end FitRLPhase */ /** * Circular polarization version. * Threaded Chi**2 evaluator for polarization fitting * Evaluates sum [(model-observed) / sigma] and derivatives * Parallel hands count 0.3 of cross in sums * If selAnt or selSou are set, then only data involving that * source or antenna (or ref ant) is included. * \param arg PolnFitArg pointer with elements: * \li lo First 0-rel datum in Data/Wt arrays * \li hi Last 0-rel datum in Data/Wt arrays * \li selAnt selected antenna, -1-> all * \li selSou selected source, -1> all * \li paramType Parameter type * \li polnParmUnspec Unspecified = don't compute derivatives * \li polnParmAnt Antenna parameter * \li polnParmSou Source parameter * \li polnParmPD Phase difference * \li paramNumber Parameter number, * Sou: 0=Ipol, 1=Qpol, 2=Upol, 3=VPol Ant: 0= Ori R/X, 1=Elp R/X, 2= Ori L/Y, 1=Elp L/Y, * \li ChiSq [out] computed Chi2 * \li nPobs [out] Number of valid parallel measurements * \li nXobs [out] Number of valid cross pol measurements * \li ParRMS [out] Parallel hand RMS * \li sumParResid [out] Cross hand RMS * \li sumXResid [out] First derivative of Chi2 wrt parameter * \li d2Chi2 [out] Second derivative of Chi2 wrt parameter * \li ithread thread number, <0 -> no threading * \return NULL */ static gpointer ThreadPolnFitRLChi2 (gpointer arg) { PolnFitArg *args = (PolnFitArg*)arg; odouble *antParm = args->antParm; gboolean **antFit = args->antFit; odouble *souParm = args->souParm; gboolean **souFit = args->souFit; ofloat *data = args->inData; ofloat *wt = args->inWt; odouble *SR = args->SR; odouble *DR = args->DR; odouble *SL = args->SL; odouble *DL = args->DL; dcomplex *PR = args->PR; dcomplex *PRc = args->PRc; dcomplex *PL = args->PL; dcomplex *PLc = args->PLc; dcomplex *RS = args->RS; dcomplex *RD = args->RD; dcomplex *LS = args->LS; dcomplex *LD = args->LD; dcomplex *RSc = args->RSc; dcomplex *RDc = args->RDc; dcomplex *LSc = args->LSc; dcomplex *LDc = args->LDc; PolnParmType paramType = args->paramType; olong paramNumber = args->paramNumber; olong selSou = args->selSou; olong selAnt = args->selAnt; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble residR=0.0, residI=0.0, isigma=0.0; odouble sumParResid, sumXResid; ofloat PD, chi1, chi2, PPol; olong nPobs, nXobs, ia1, ia2, isou, idata, isouLast=-999; gboolean isAnt1, isAnt2; size_t i; odouble sum=0.0, sumwt=0.0, sumd, sumd2; dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c; dcomplex ct1, ct2, ct3, ct4, ct5, ct6, dt1, dt2; dcomplex S[4], VRR, VRL, VLR, VLL, MC1, MC2, MC3, MC4, DFDP, DFDP2; ofloat root2; COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VRR, 0.0, 0.0); COMPLEX_SET (VLL, 0.0, 0.0); COMPLEX_SET (VLR, 0.0, 0.0); COMPLEX_SET (VRL, 0.0, 0.0); COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); COMPLEX_SET (dt1, 0.0, 0.0); COMPLEX_SET (dt2, 0.0, 0.0); /* Init others */ isouLast=-999; sum = sumwt = 0.0; ipol = qpol = upol = vpol = 0.0; residR = residI = isigma = 0.0; /* RMS sums and counts */ sumParResid = sumXResid = 0.0; sumd = sumd2 = 0.0; nPobs = nXobs = 0; /* R-L phase difference at reference antenna */ PD = args->PD; /* Injest model, factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */ root2 = 1.0 / sqrt(2.0); /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { SR[i] = cos(antParm[i*4+1]) + sin(antParm[i*4+1]); DR[i] = cos(antParm[i*4+1]) - sin(antParm[i*4+1]); SL[i] = cos(antParm[i*4+3]) + sin(antParm[i*4+3]); DL[i] = cos(antParm[i*4+3]) - sin(antParm[i*4+3]); COMPLEX_SET (RS[i], root2*SR[i], 0.); COMPLEX_SET (ct1, root2*DR[i], 0.); COMPLEX_EXP (PR[i], 2*antParm[i*4+0]); COMPLEX_CONJUGATE (PRc[i], PR[i]); COMPLEX_MUL2 (RD[i], ct1, PR[i]); COMPLEX_SET (ct1, root2*SL[i], 0.); COMPLEX_EXP (PL[i], -2*antParm[i*4+2]); COMPLEX_CONJUGATE (PLc[i], PL[i]); COMPLEX_MUL2 (LS[i], ct1, PL[i]); COMPLEX_SET (LD[i], root2*DL[i], 0.); COMPLEX_CONJUGATE (RSc[i], RS[i]); COMPLEX_CONJUGATE (RDc[i], RD[i]); COMPLEX_CONJUGATE (LSc[i], LS[i]); COMPLEX_CONJUGATE (LDc[i], LD[i]); } /* Reference antenna phase terms */ if (args->refAnt>0) { COMPLEX_EXP (PRref, antParm[(args->refAnt-1)*4+0]); COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD); } else { COMPLEX_SET (PRref, 1.0, 0.0); COMPLEX_EXP (PLref, PD); } COMPLEX_CONJUGATE (ct1, PLref); COMPLEX_MUL2(PPRL, PRref, ct1); COMPLEX_CONJUGATE (ct1, PRref); COMPLEX_MUL2(PPLR, PLref, ct1); /* Loop over data */ i = 0; for (idata=args->lo; idata<args->hi; idata++) { isou = MAX (0, args->souNo[idata]); /* Source number */ /* Selected source? */ if ((selSou>=0) && (selSou!=isou)) continue; /* Antenna parameters (0 ref) */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* Selected source? */ if ((selAnt>=0) && ((selAnt!=ia1) && (ia1!=args->refAnt)) && (selAnt!=ia2) && (ia2!=args->refAnt)) continue; /* Which antenna is the selected one in the baseline? */ if (selAnt==ia1) {isAnt1 = TRUE; isAnt2 = FALSE;} else if (selAnt==ia2) {isAnt2 = TRUE; isAnt1 = FALSE;} else {isAnt1 = FALSE; isAnt2 = FALSE;} /* Only refant */ /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (PA1,2*chi1); COMPLEX_EXP (PA2,2*chi2); COMPLEX_CONJUGATE (PA1c, PA1); COMPLEX_CONJUGATE (PA2c, PA2); /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->curFreq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou]+ args->dPPol[isou]*(args->curFreq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S[0], ipol+vpol, 0.0); COMPLEX_SET (S[1], qpol, upol); COMPLEX_SET (S[2], qpol, -upol); COMPLEX_SET (S[3], ipol-vpol, 0.0); } /* Calculate residals - Note different order for LL */ /* RR */ if (wt[idata*4]>0.0) { isigma = 0.3*wt[idata*4]; /* downweight parallel */ /* VRR = S[0] * RS[ia1] * RSc[ia2] + S[1] * RS[ia1] * RDc[ia2] * PA2c + S[2] * RD[ia1] * RSc[ia2] * PA1 + S[3] * RD[ia1] * RDc[ia2] * PA1 * PA2c; */ COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]); COMPLEX_MUL2 (VRR, S[0], MC1); COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRR, VRR, ct1); residR = VRR.real - data[idata*10+2]; sum += isigma * residR * residR; sumwt += isigma; residI = VRR.imag - data[idata*10+3]; sum += isigma * residI * residI; sumwt += isigma; nPobs++; sumParResid += residR * residR + residI * residI; /* Derivatives */ if (paramType==polnParmAnt) { /* Antenna parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* RR wrt Or */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[2], MC3); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[1], MC2); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } break; case 1: /* RR wrt Er */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = r2 * DR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) - r2 * SR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + S[3] * RDc[ia2] * PA1 * PA2c) */ COMPLEX_MUL2(ct1, S[0], RSc[ia2]); COMPLEX_MUL3(ct2, S[1], RDc[ia2], PA2c); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL2(ct5, ct4, dt1); COMPLEX_MUL3(ct1, S[2], RSc[ia2], PA1); COMPLEX_MUL4(ct2, S[3], RDc[ia2], PA1, PA2c); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PR[ia1], dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) - r2 * DR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + S[3] * RDc[ia2] * PA1 * PA2c) */ COMPLEX_SET (ct4, -root2*SR[ia1], 0.0); COMPLEX_MUL2(ct5, ct4, dt1); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PR[ia1], dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = r2 * DR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) - r2 * SR[ia2] * PRc[ia2] * PA2c * (S[1] * RS[ia1] * PA2c w+ S[3] * RD[ia1] * PA1) */ COMPLEX_MUL2(ct1, S[0], RS[ia1]); COMPLEX_MUL3(ct2, S[2], RD[ia1], PA1); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL2(ct5, ct4, dt1); COMPLEX_MUL2(ct1, S[1], RS[ia1]); COMPLEX_MUL3(ct2, S[3], RD[ia1], PA1); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia2], 0.0); COMPLEX_MUL4(ct6, ct4, PRc[ia2], PA2c, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) - r2 * DR[ia2] * PRc[ia2] * PA2c * (S[1] * RS[ia1] + S[3] * RD[ia1] * PA1) */ COMPLEX_SET (ct4, -root2*SR[ia2], 0.0); COMPLEX_MUL2(ct5, ct4, dt1); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL4(ct6, ct4, PRc[ia2], PA2c, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } break; case 2: /* RR wrt Ol - nope */ break; case 3: /* RR wrt El - nope */ break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* RR wrt I */ if (souFit[isou][paramNumber]) { /* part = MC1 + MC4 */ COMPLEX_ADD2(DFDP, MC1, MC4); } break; case 1: /* RR wrt QPol */ if (souFit[isou][paramNumber]) { /* part = MC2 + MC3 */ COMPLEX_ADD2(DFDP, MC2, MC3); } break; case 2: /* RR wrt UPol */ if (souFit[isou][paramNumber]) { /* part = i (MC2 - MC3) */ COMPLEX_SUB (ct3, MC2, MC3); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); } break; case 3: /* RR wrt Vpol */ if (souFit[isou][paramNumber]) { /* part = MC1 - MC4 */ COMPLEX_SUB (DFDP, MC1, MC4); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmPD) { /* R-L Phase difference */ /* No dependence on RR */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); } /* end R-L phase difference */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ /* LL */ if (wt[idata*4+1]>0.0) { isigma = 0.3*wt[idata*4+1]; /* downweight parallel */ /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 + S[1] * LS[ia1] * LDc[ia2] * PA1c + S[2] * LD[ia1] * LSc[ia2] * PA2 + S[3] * LD[ia1] * LDc[ia2]; */ COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2 (VLL, S[0], MC1); COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLL, VLL, ct1); residR = VLL.real - data[idata*10+4]; sum += isigma * residR * residR; sumwt += isigma; residI = VLL.imag - data[idata*10+5]; sum += isigma * residI * residI; sumwt += isigma; nPobs++; sumParResid += residR * residR + residI * residI; /* Derivatives */ if (paramType==polnParmAnt) { /* Antenna parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* LL wrt Or - nope */ break; case 1: /* LL wrt Er - nope*/ break; case 2: /* LL wrt Ol */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[1], MC2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[2], MC3); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } break; case 3: /* LL wrt El */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = r2 * DL[ia1] * PL[ia1] * PA1c * (S[0] * LSc[ia2] * PA2 + S[1] * LDc[ia2) - r2 * SL[ia1] * (S[2] * LSc[ia2] * PA2 + S[3] * LDc[ia2]) */ COMPLEX_MUL3(ct1, S[0], LSc[ia2], PA2); COMPLEX_MUL2(ct2, S[1], LDc[ia2]); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL4(ct5, ct4, PL[ia1], PA1c, dt1); COMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2); COMPLEX_MUL2(ct2, S[3], LDc[ia2]); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia1], 0.0); COMPLEX_MUL2(ct6, ct4, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SL[ia1] * PL[ia1] * PA1c * (S[0] * LSc[ia2] * PA2 + S[1] * LDc[ia2]) - r2 * DL[ia1] * (S[2] * LSc[ia2] * PA2 + S[3] * LDc[ia2]) */ COMPLEX_SET (ct4, -root2*SL[ia1], 0.0); COMPLEX_MUL4(ct5, ct4, PL[ia1], PA1c, dt1); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL2(ct6, ct4, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = r2 * DL[ia2] * PLc[ia2] * PA2 * (S[0] * LS[ia1] * PA1c + S[2] * LD[ia1]) - r2 * SL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */ COMPLEX_MUL3(ct1, S[0], LS[ia1], PA1c); COMPLEX_MUL2(ct2, S[2], LD[ia1]); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL4(ct5, ct4, PLc[ia2], PA2, dt1); COMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c); COMPLEX_MUL2(ct2, S[3], LD[ia1]); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia2], 0.0); COMPLEX_MUL2(ct6, ct4, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SL[ia2] * PLc[ia2] * PA2 * (S[0] * LS[ia1] * PA1c + S[2] * LD[ia1) - r2 * DL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */ COMPLEX_SET (ct4, -root2*SL[ia2], 0.0); COMPLEX_MUL4(ct5, ct4, PLc[ia2], PA2, dt1); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL2(ct6, ct4, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* LL wrt I */ if (souFit[isou][paramNumber]) { /* part = MC1 + MC4 */ COMPLEX_ADD2(DFDP, MC1, MC4); } break; case 1: /* LL wrt QPol */ if (souFit[isou][paramNumber]) { /* part = MC2 + MC3 */ COMPLEX_ADD2(DFDP, MC2, MC3); } break; case 2: /* LL wrt UPol */ if (souFit[isou][paramNumber]) { /* part = i (MC2 - MC3) */ COMPLEX_SUB (ct3, MC2, MC3); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); } break; case 3: /* LL wrt Vpol */ if (souFit[isou][paramNumber]) { /* part = MC1 - MC4 */ COMPLEX_SUB (DFDP, MC1, MC4); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmPD) { /* R-L Phase difference */ /* No dependence on LL */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); } /* end R-L phase difference */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ /* RL */ if (wt[idata*4+2]>0.0) { isigma = wt[idata*4+2]; /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 + PPRL * S[1] * RS[ia1] * LDc[ia2] + PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */ COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (VRL, S[0], MC1); COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRL, VRL, ct1); residR = VRL.real - data[idata*10+6]; sum += isigma * residR * residR; sumwt += isigma; residI = VRL.imag - data[idata*10+7]; sum += isigma * residI * residI; sumwt += isigma; nXobs++; sumXResid += residR * residR + residI * residI; /* Derivatives */ if (paramType==polnParmAnt) { /* Antenna parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* RL wrt Or */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[2], MC3); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } /* If ia1==refant) */ if (ia1==args->refAnt) { COMPLEX_SET (ct1, 0.0, 1.0); COMPLEX_MUL2(ct2, ct1, VRL); COMPLEX_ADD2(DFDP, DFDP, ct2); COMPLEX_MUL2(ct2, ct1, DFDP); COMPLEX_ADD2(DFDP2, DFDP2, ct2); } break; case 1: /* RL wrt Er */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = r2 * DR[ia1] * PPRL * (S[0] * LSc[ia2] * PA2 +S[1] * LDc[ia2]) - r2 * SR[ia1] * PR[ia1] * PPRL * PA1 * (S[2] * LSc[ia2] * PA2 + S[3] * LDc[ia2]) */ COMPLEX_MUL3(ct1, S[0], LSc[ia2], PA2); COMPLEX_MUL2(ct2, S[1], LDc[ia2]); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL3(ct5, ct4, PPRL, dt1); COMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2); COMPLEX_MUL2(ct2, S[3], LDc[ia2]); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia1], 0.0); COMPLEX_MUL5(ct6, ct4, PR[ia1], PPRL, PA1, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SR[ia1] * PPRL * (S[0] * LSc[ia2] * PA2 + S[1] * LDc[ia2]) - r2 * DR[ia1] * PR[ia1] * PPRL * PA1 * (S[2] * LSc[ia2] * PA2 + S[3] * LDc[ia2] ) */ COMPLEX_SET (ct4, -root2*SR[ia1], 0.0); COMPLEX_MUL3(ct5, ct4, PPRL, dt1); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL5(ct6, ct4, PR[ia1], PPRL, PA1, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } break; case 2: /* RL wrt Ol */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[2], MC3); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } /* If ia2==refant) */ if (ia2==args->refAnt) { COMPLEX_SET (ct1, 0.0, 1.0); COMPLEX_MUL2(ct2, ct1, VRL); COMPLEX_ADD2(DFDP, DFDP, ct2); COMPLEX_MUL2(ct2, ct1, DFDP); COMPLEX_ADD2(DFDP2, DFDP2, ct2); } break; case 3: /* RL wrt El */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = r2 * DL[ia2] * PLc[ia2] * PPRL * PA2 * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) - r2 * SL[ia2] * PPRL * (S[1] * RS[ia1] + S[3] * RD[ia1] * PA1) */ COMPLEX_MUL2(ct1, S[0], RS[ia1]); COMPLEX_MUL3(ct2, S[2], RD[ia1], PA1); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL5(ct5, ct4, PLc[ia2], PPRL, PA2, dt1); COMPLEX_MUL2(ct1, S[1], RS[ia1]); COMPLEX_MUL3(ct2, S[3], RD[ia1], PA1); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia2], 0.0); COMPLEX_MUL3(ct6, ct4, PPRL, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SL[ia2] * PLc[ia2] * PPRL * PA2 * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) - r2 * DL[ia2] * PPRL * S[1] * RS[ia1] + S[3] * RD[ia1] * PA1) */ COMPLEX_SET (ct4, -root2*SL[ia2], 0.0); COMPLEX_MUL5(ct5, ct4, PLc[ia2], PPRL, PA2, dt1); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL3(ct6, ct4, PPRL, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* RL wrt I */ if (souFit[isou][paramNumber]) { /* part = MC1 + MC4 */ COMPLEX_ADD2(DFDP, MC1, MC4); } break; case 1: /* RL wrt QPol */ if (souFit[isou][paramNumber]) { /* part = MC2 + MC3 */ COMPLEX_ADD2(DFDP, MC2, MC3); } break; case 2: /* RL wrt UPol */ if (souFit[isou][paramNumber]) { /* part = i (MC2 - MC3) */ COMPLEX_SUB (ct3, MC2, MC3); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); } break; case 3: /* RL wrt Vpol */ if (souFit[isou][paramNumber]) { /* part = MC1 - MC4 */ COMPLEX_SUB (DFDP, MC1, MC4); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmPD) { /* R-L Phase difference */ COMPLEX_SET (ct1, 0.0, -1.0); COMPLEX_MUL2(DFDP, ct1, VRL); COMPLEX_MUL2(DFDP2, ct1, DFDP); } /* end R-L phase difference */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ /* LR */ if (wt[idata*4+3]>0.0) { isigma = wt[idata*4+3]; /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c + PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * S[2] * LD[ia1] * RSc[ia2] + PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL2 (VLR, S[0], MC1); COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLR, VLR, ct1); residR = VLR.real - data[idata*10+8]; sum += isigma * residR * residR; sumwt += isigma; residI = VLR.imag - data[idata*10+9]; sum += isigma * residI * residI; sumwt += isigma; nXobs++; sumXResid += residR * residR + residI * residI; /* Derivatives */ if (paramType==polnParmAnt) { /* Antenna parameters */ /* Default partials if only refant on baseline */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* LR wrt Or */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[1], MC2); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } } /* If ia2==refant */ if (ia2==args->refAnt) { COMPLEX_SET (ct1, 0.0, -1.0); COMPLEX_MUL2(ct2, ct1, VLR); COMPLEX_ADD2(DFDP, DFDP, ct2); COMPLEX_MUL2(ct2, ct1, DFDP); COMPLEX_ADD2(DFDP2, DFDP2, ct2); } break; case 1: /* LR wrt Er */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = r2 * DR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) - r2 * SR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + PPLR * S[3] * LD[ia1] * PA2c) */ COMPLEX_MUL3(ct1, S[0], LS[ia1], PA1c); COMPLEX_MUL2(ct2, S[2], LD[ia1]); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL3(ct5, ct4, PPLR, dt1); COMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c); COMPLEX_MUL2(ct2, S[3], LD[ia1]); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia2], 0.0); COMPLEX_MUL5(ct6, ct4, PRc[ia2], PPLR, PA2c, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) - r2 * DR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + PPLR * S[3] * LD[ia1] * PA2c) */ COMPLEX_SET (ct4, -root2*SR[ia2], 0.0); COMPLEX_MUL3(ct5, ct4, PPLR, dt1); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL5(ct6, ct4, PRc[ia2], PPLR, PA2c, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } break; case 2: /* LR wrt Ol */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[1], MC2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); COMPLEX_MUL2(DFDP2, ct1, DFDP); } /* If ia1==refant) */ } else if (ia1==args->refAnt) { COMPLEX_SET (ct1, 0.0, -1.0); COMPLEX_MUL2(ct2, ct1, VLR); COMPLEX_ADD2(DFDP, DFDP, ct2); COMPLEX_MUL2(ct2, ct1, DFDP); COMPLEX_ADD2(DFDP2, DFDP2, ct2); } break; case 3: /* LR wrt El */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = r2 * DL[ia1] * PL[ia1] * PPLR * PA1c * (S[0] * RSc[ia2 + S[1] * RDc[ia2] * PA2c) - r2 * SL[ia1] * PPLR * (S[2] * RSc[ia2] + S[3] * RDc[ia2] * PA2c) */ COMPLEX_MUL2(ct1, S[0], RSc[ia2]); COMPLEX_MUL3(ct2, S[1], RDc[ia2], PA1c); COMPLEX_ADD2(dt1, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL5(ct5, ct4, PL[ia1], PPLR, PA1c, dt1); COMPLEX_MUL2(ct1, S[2], RSc[ia2]); COMPLEX_MUL3(ct2, S[3], RDc[ia2], PA2c); COMPLEX_ADD2(dt2, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PPLR, dt2); COMPLEX_SUB (DFDP, ct5, ct6); /* part2 = -r2 * SL[ia1] * PL[ia1] * PPLR * PA1c * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) - r2 * DL[ia1] * PPLR * (S[2] * RSc[ia2] + S[3] * RDc[ia2] * PA2c) */ COMPLEX_SET (ct4, -root2*SL[ia1], 0.0); COMPLEX_MUL5(ct5, ct4, PL[ia1], PPLR, PA1c, dt1); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PPLR, dt2); COMPLEX_SUB (DFDP2, ct5, ct6); } } break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* LR wrt I */ if (souFit[isou][paramNumber]) { /* part = MC1 + MC4 */ COMPLEX_ADD2(DFDP, MC1, MC4); } break; case 1: /* LR wrt QPol */ if (souFit[isou][paramNumber]) { /* part = MC2 + MC3 */ COMPLEX_ADD2(DFDP, MC2, MC3); } break; case 2: /* LR wrt UPol */ if (souFit[isou][paramNumber]) { /* part = i (MC2 - MC3) */ COMPLEX_SUB (ct3, MC2, MC3); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); } break; case 3: /* LR wrt Vpol */ if (souFit[isou][paramNumber]) { /* part = MC1 - MC4 */ COMPLEX_SUB (DFDP, MC1, MC4); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmPD) { /* R-L Phase difference */ /* No dependence on MORE HERE */ COMPLEX_SET (ct1, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct1, VRL); COMPLEX_MUL2(DFDP2, ct1, DFDP); } /* end R-L phase difference */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0*isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0*isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ } /* End loop over visibilities */ if (sumwt<=0.0) sumwt = 1.0; /* Trap no data */ args->ChiSq = sum; /* Save results */ args->sumParResid = sumParResid; args->sumXResid = sumXResid; args->sumWt = sumwt; args->nPobs = nPobs; args->nXobs = nXobs; if (paramType!=polnParmUnspec) args->sumDeriv = sumd; if (paramType!=polnParmUnspec) args->sumDeriv2 = sumd2; /* Indicate completion if threaded */ if (args->ithread>=0) ObitThreadPoolDone (args->thread, (gpointer)&args->ithread); return NULL; } /* end ThreadPolnFitRLChi2 */ /** * Linear polarization version. * Threaded Chi**2 evaluator for polarization fitting * Evaluates sum [(model-observed) / sigma] and derivatives * Parallel hands count 0.3 of cross in sums * If selAnt or selSou are set, then only data involving that * source or antenna (or ref ant) is included. * \param arg PolnFitArg pointer with elements: * \li lo First 0-rel datum in Data/Wt arrays * \li hi Last 0-rel datum in Data/Wt arrays * \li selAnt selected antenna, -1-> all * \li selSou selected source, -1-> all * \li paramType Parameter type * \li polnParmUnspec Unspecified = don't compute derivatives * \li polnParmAnt Antenna parameter * \li polnParmGain Antenna gains * \li polnParmSou Source parameter * \li polnParmPD Phase difference * \li paramNumber Parameter number, * Sou: 0=Ipol, 1=Qpol, 2=Upol, 3=VPol Ant: 0= Ori R/X, 1=Elp R/X, 2= Ori L/Y, 1=Elp L/Y, * \li ChiSq [out] computed Chi2 * \li nPobs [out] Number of valid parallel measurements * \li nXobs [out] Number of valid cross pol measurements * \li ParRMS [out] Parallel hand RMS * \li sumParResid [out] Cross hand RMS * \li sumXResid [out] First derivative of Chi2 wrt parameter * \li d2Chi2 [out] Second derivative of Chi2 wrt parameter * \li ithread thread number, <0 -> no threading * \return NULL */ static gpointer ThreadPolnFitXYChi2 (gpointer arg) { PolnFitArg *args = (PolnFitArg*)arg; odouble *antParm = args->antParm; gboolean **antFit = args->antFit; odouble *antGain = args->antGain; gboolean **antGainFit= args->antGainFit; odouble *souParm = args->souParm; gboolean **souFit = args->souFit; ofloat *data = args->inData; ofloat *wt = args->inWt; dcomplex *CX = args->RS; dcomplex *SX = args->RD; dcomplex *CY = args->LS; dcomplex *SY = args->LD; dcomplex *CXc = args->RSc; dcomplex *SXc = args->RDc; dcomplex *CYc = args->LSc; dcomplex *SYc = args->LDc; PolnParmType paramType = args->paramType; olong paramNumber = args->paramNumber; olong selSou = args->selSou; olong selAnt = args->selAnt; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble residR=0.0, residI=0.0, isigma=0.0; odouble sumParResid, sumXResid; ofloat PD, chi1, chi2, PPol; olong nPobs, nXobs, ia1, ia2, isou, idata, isouLast=-999; gboolean isAnt1=FALSE, isAnt2=FALSE; size_t i; odouble sum=0.0, sumwt=0.0, sumd, sumd2; dcomplex SPA, DPA, SPAc, DPAc, ggPD; dcomplex ct1, ct2, ct3, ct4, ct5, Jm, Jp; dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4, DFDP, DFDP2; dcomplex SM1, SM2, SM3, SM4; /* DEBUG */ #ifdef DEBUG olong dbgCnt1, dbgCnt2; ofloat dbgSum1, dbgSum2, dbgISum1, dbgISum2; #endif COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (S0[0], 0.0, 0.0); COMPLEX_SET (S0[1], 0.0, 0.0); COMPLEX_SET (S0[2], 0.0, 0.0); COMPLEX_SET (S0[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VXX, 0.0, 0.0); COMPLEX_SET (VYY, 0.0, 0.0); COMPLEX_SET (VYX, 0.0, 0.0); COMPLEX_SET (VXY, 0.0, 0.0); COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); COMPLEX_SET (Jm, 0.0,-1.0); COMPLEX_SET (Jp, 0.0, 1.0); /* Init others */ isouLast=-999; sum = sumwt = 0.0; ipol = qpol = upol = vpol = 0.0; residR = residI = isigma = 0.0; isAnt1 = isAnt2 = TRUE; /* RMS sums and counts */ sumParResid = sumXResid = 0.0; sumd = sumd2 = 0.0; nPobs = nXobs = 0; /* X-Y phase difference at reference antenna */ PD = args->PD; /* Injest model, factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */ /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_EXP (ct1, -antParm[i*4+0]); COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (CX[i], ct2, ct1); COMPLEX_EXP (ct1, antParm[i*4+0]); COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (SX[i], ct2, ct1); COMPLEX_EXP (ct1, antParm[i*4+2]); COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (CY[i], ct2, ct1); COMPLEX_EXP (ct1, -antParm[i*4+2]); COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (SY[i], ct2, ct1); COMPLEX_CONJUGATE (CXc[i], CX[i]); COMPLEX_CONJUGATE (SXc[i], SX[i]); COMPLEX_CONJUGATE (CYc[i], CY[i]); COMPLEX_CONJUGATE (SYc[i], SY[i]); /* Default X gain = 1.0/Y gain if (!antGainFit[i][0]) antGain[i*2+0] = 1.0 / antGain[i*2+1]; */ } /* Loop over data */ i = 0; for (idata=args->lo; idata<args->hi; idata++) { isou = MAX (0, args->souNo[idata]); /* Source number */ /* Selected source? */ if ((selSou>=0) && (selSou!=isou)) continue; /* Antenna parameters (0 ref) */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* Selected source? */ if ((selAnt>=0) && (selAnt!=ia1) && (selAnt!=ia2)) continue; /* Which antenna is the selected one in the baseline? */ if (selAnt==ia1) {isAnt1 = TRUE; isAnt2 = FALSE;} else if (selAnt==ia2) {isAnt2 = TRUE; isAnt1 = FALSE;} /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (SPA,(chi1+chi2)); COMPLEX_EXP (DPA,chi1-chi2); COMPLEX_CONJUGATE (SPAc, SPA); COMPLEX_CONJUGATE (DPAc, DPA); /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->curFreq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->curFreq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S0[0], ipol+vpol, 0.0); COMPLEX_SET (S0[1], qpol, upol); COMPLEX_SET (S0[2], qpol, -upol); COMPLEX_SET (S0[3], ipol-vpol, 0.0); } /* Rotate Stokes by parallactic angle */ COMPLEX_MUL2(S[0], DPAc, S0[0]); COMPLEX_MUL2(S[1], SPAc, S0[1]); COMPLEX_MUL2(S[2], SPA, S0[2]); COMPLEX_MUL2(S[3], DPA, S0[3]); /* Calculate residals - XX */ if (wt[idata*4]>0.0) { isigma = wt[idata*4]; /* VXX = {S[0] * CX[ia1] * CXc[ia2] + S[1] * CX[ia1] * SXc[ia2] + S[2] * SX[ia1] * CXc[ia2] + S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ; */ COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+0]*antGain[ia2*2+0], 0); COMPLEX_MUL2 (VXX, ct5, ggPD); residR = VXX.real - data[idata*10+2]; sum += isigma * residR * residR; sumwt += isigma; residI = VXX.imag - data[idata*10+3]; sum += isigma * residI * residI; sumwt += isigma; nPobs++; sumParResid += residR * residR + residI * residI; /* Derivatives */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); if (paramType==polnParmAnt) { /* Antenna parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* XX wrt Ox */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gX[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* -VXX */ COMPLEX_NEGATE(DFDP2, VXX); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gX[ia1] * gX[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* -VXX */ COMPLEX_NEGATE(DFDP2, VXX); } } break; case 1: /* XX wrt Ex */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {-S[0] * CXc[ia2] * SXc[ia1] - S[1] * SXc[ia2] * SXc[ia1] + S[2] * CXc[ia2] * CXc[ia1] + S[3] * SXc[ia2] * CXc[ia1]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], CXc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], SXc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], CXc[ia2], SXc[ia1]); COMPLEX_MUL3(ct4, S[3], SXc[ia2], CXc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VXX */ COMPLEX_NEGATE(DFDP2, VXX); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {-S[0] * CX[ia1] * SX[ia2] + S[1] * CX[ia1] * CX[ia2] - S[2] * SX[ia1] * SX[ia2] + S[3] * SX[ia1] * CX[ia2]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], CX[ia1], SX[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], CX[ia1], CX[ia2]); COMPLEX_MUL3(ct5, S[2], SX[ia1], SX[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], SX[ia1], CX[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VXX */ COMPLEX_NEGATE(DFDP2, VXX); } } break; case 2: /* XX wrt Oy - nope */ break; case 3: /* XX wrt Ey - nope */ break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* XX wrt I */ if (souFit[isou][paramNumber]) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 1: /* XX wrt QPol */ if (souFit[isou][paramNumber]) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 2: /* XX wrt UPol */ if (souFit[isou][paramNumber]) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 3: /* XX wrt Vpol */ if (souFit[isou][paramNumber]) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmGain) { /* Antenna Gains */ switch (paramNumber) { /* Switch over parameter */ case 0: /* XX wrt gX */ if (isAnt1 && (antGainFit[ia1][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+0], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); /* part2 = 0 */ } else if (isAnt2 && (antGainFit[ia2][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); /* part2 = 0 */ } break; case 1: /* XX wrt gY - nope */ break; default: break; } /* end gain switch */ } else if (paramType==polnParmPD) { /* X-Y phase difference */ } /* end parameter types */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ /* YY */ if (wt[idata*4+1]>0.0) { isigma = wt[idata*4+1]; /* VYY = {S[0] * SY[ia1] * SYc[ia2] + S[1] * SY[ia1] * CYc[ia2] + S[2] * CY[ia1] * SYc[ia2] + S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ; */ COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+1]*antGain[ia2*2+1], 0); COMPLEX_MUL2 (VYY, ct5, ggPD); residR = VYY.real - data[idata*10+4]; sum += isigma * residR * residR; sumwt += isigma; residI = VYY.imag - data[idata*10+5]; sum += isigma * residI * residI; sumwt += isigma; nPobs++; sumParResid += residR * residR + residI * residI; /* Derivatives */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); if (paramType==polnParmAnt) { /* Antenna parameters */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); switch (paramNumber) { /* Switch over parameter */ case 0: /* YY wrt Ox - nope */ break; case 1: /* YY wrt Ex - nope*/ break; case 2: /* YY wrt Oy */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gY[ia1] * gY[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* part2 = -VYY */ COMPLEX_NEGATE(DFDP2, VYY); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gY[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* part2 = -VYY */ COMPLEX_NEGATE(DFDP2, VYY); } } break; case 3: /* YY wrt Ey */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {-S[0] * SYc[ia2] * CYc[ia1] - S[1] * CYc[ia2] * CYc[ia1] + S[2] * SYc[ia2] * SYc[ia1] + S[3] * CYc[ia2] * SYc[ia1]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], SYc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CYc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SYc[ia2], SYc[ia1]); COMPLEX_MUL3(ct4, S[3], CYc[ia2], SYc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VYY */ COMPLEX_NEGATE(DFDP2, VYY); } } else if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {-S[0] * SY[ia1] * CY[ia2] + S[1] * SY[ia1] * SY[ia2] - S[2] * CY[ia1] * CY[ia2] + S[3] * CY[ia1] * SY[ia2]} * gY[ia1] * gY[ia2] */ COMPLEX_MUL3(ct5, S[0], SY[ia1], CY[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], SY[ia1], SY[ia2]); COMPLEX_MUL3(ct5, S[2], CY[ia1], CY[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], CY[ia1], SY[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VYY */ COMPLEX_NEGATE(DFDP2, VYY); } } break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* YY wrt IPol */ if (souFit[isou][paramNumber]) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 1: /* YY wrt QPol */ if (souFit[isou][paramNumber]) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 2: /* YY wrt UPol */ if (souFit[isou][paramNumber]) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 3: /* YY wrt Vpol */ if (souFit[isou][paramNumber]) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmGain) { /* Antenna Gains */ switch (paramNumber) { /* Switch over parameter */ case 0: /* YY wrt gX - nope */ break; case 1: /* YY wrt gY */ if (isAnt1 && (antGainFit[ia1][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+1], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); /* part2 = 0 */ } else if (isAnt2 && (antGainFit[ia2][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+1], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); /* part2 = 0 */ } break; default: break; } /* end gain switch */ } else if (paramType==polnParmPD) { /* X-Y phase difference */ /* Nope */ } /* end parameter types */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ /* XY */ if (wt[idata*4+2]>0.0) { /* Increase X hand weight */ isigma = 3.0 * wt[idata*4+2]; /* VXY = {S[0] * CX[ia1] * SYc[ia2] + S[1] * CX[ia1] * CYc[ia2] + S[2] * SX[ia1] * SYc[ia2] + S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD); */ COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+1], 0); COMPLEX_EXP (ct2, PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VXY, ct5, ggPD); residR = VXY.real - data[idata*10+6]; sum += isigma * residR * residR; sumwt += isigma; residI = VXY.imag - data[idata*10+7]; sum += isigma * residI * residI; sumwt += isigma; nXobs++; sumXResid += residR * residR + residI * residI; /* Derivatives */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); if (paramType==polnParmAnt) { /* Antenna parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* XY wrt Ox */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* part2 = -VXY */ COMPLEX_NEGATE(DFDP2, VXY); } } break; case 1: /* XY wrt Ex */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {-S[0] * SYc[ia2] * SXc[ia1] - S[1] * CYc[ia2] * SXc[ia1] + S[2] * SYc[ia2] * CXc[ia1] + S[3] * CYc[ia2] * CXc[ia1] } * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_MUL3(ct5, S[0], SYc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CYc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SYc[ia2], CXc[ia1]); COMPLEX_MUL3(ct4, S[3], CYc[ia2], CXc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VXY */ COMPLEX_NEGATE(DFDP2, VXY); } } break; case 2: /* XY wrt Oy */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct5, ct2, ct3); COMPLEX_MUL2 (DFDP, ct5, ggPD); /* part2 = -VXY */ COMPLEX_NEGATE(DFDP2, VXY); } } break; case 3: /* XY wrt Ey */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {-S[0] * CX[ia1] * CY[ia2] + S[1] * CX[ia1] * SY[ia2] - S[2] * SX[ia1] * CY[ia2] + S[3] * SX[ia1] * SY[ia2]} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_MUL3(ct5, S[0], CX[ia1], CY[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CX[ia1], SY[ia2]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SX[ia1], CY[ia2]); COMPLEX_MUL3(ct4, S[3], SX[ia1], SY[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VXY */ COMPLEX_NEGATE(DFDP2, VXY); } } break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* XY wrt I */ if (souFit[isou][paramNumber]) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 1: /* XY wrt QPol */ if (souFit[isou][paramNumber]) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 2: /* XY wrt UPol */ if (souFit[isou][paramNumber]) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 3: /* XY wrt Vpol */ if (souFit[isou][paramNumber]) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmGain) { /* Antenna Gains */ switch (paramNumber) { /* Switch over parameter */ case 0: /* XY wrt gX */ if (isAnt1 && (antGainFit[ia1][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] * exp(j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+1], 0); COMPLEX_EXP (ct3, PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); /* part2 = 0 */ } break; case 1: /* XY wrt gY */ if (isAnt2 && (antGainFit[ia2][paramNumber])) { /* part = {S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] * exp(j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 0); COMPLEX_EXP (ct3, PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); /* part2 = 0 */ } break; default: break; } /* end gain switch */ } else if (paramType==polnParmPD) { /* X-Y phase difference */ /* part = (0, 1) * VXY */ COMPLEX_MUL2 (DFDP, Jp, VXY); /* part2 = -VXY */ COMPLEX_NEGATE(DFDP2, VXY); } /* end parameter types */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0 * isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ /* YX */ if (wt[idata*4+3]>0.0) { /* Increase X hand weight */ isigma = 3.0 * wt[idata*4+3]; /* VYX = {S[0] * SY[ia1] * CXc[ia2] + S[1] * SY[ia1] * SXc[ia2] + S[2] * CY[ia1] * CXc[ia2] + S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD) */ COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+1]*antGain[ia2*2+0], 0); COMPLEX_EXP (ct2, -PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VYX, ct5, ggPD); residR = VYX.real - data[idata*10+8]; sum += isigma * residR * residR; sumwt += isigma; residI = VYX.imag - data[idata*10+9]; sum += isigma * residI * residI; sumwt += isigma; nXobs++; sumXResid += residR * residR + residI * residI; /* Derivatives */ /* Default partials */ COMPLEX_SET (DFDP, 0.0, 0.0); COMPLEX_SET (DFDP2, 0.0, 0.0); if (paramType==polnParmAnt) { /* Antenna parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* YX wrt Ox */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* part2 = -VYX */ COMPLEX_NEGATE(DFDP2, VYX); } } break; case 1: /* YX wrt Ex */ if (isAnt2) { if (antFit[ia2][paramNumber]) { /* part = {-S[0] * SY[ia1] * SX[ia2] + S[1] * SY[ia1] * CX[ia2] - S[2] * CY[ia1] * SX[ia2] + S[3] * CY[ia1] * CX[ia2]} * gY[ia1] * gX[ia2] * exp(-j PD)*/ COMPLEX_MUL3(ct5, S[0], SY[ia1], SX[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], SY[ia1], CX[ia2]); COMPLEX_MUL3(ct5, S[2], CY[ia1], SX[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], CY[ia1], CX[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VYX */ COMPLEX_NEGATE(DFDP2, VYX); } } break; case 2: /* YX wrt Oy */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(-j PD) */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); /* part2 = -VYX */ COMPLEX_NEGATE(DFDP2, VYX); } } break; case 3: /* YX wrt Ey */ if (isAnt1) { if (antFit[ia1][paramNumber]) { /* part = {-S[0] * CXc[ia2] * CYc[ia1] - S[1] * SXc[ia2] * CYc[ia1] + S[2] * CXc[ia2] * SYc[ia1] + S[3] * SXc[ia2] * SYc[ia1]} * gY[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL3(ct5, S[0], CXc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], SXc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], CXc[ia2], SYc[ia1]); COMPLEX_MUL3(ct4, S[3], SXc[ia2], SYc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); /* part2 = -VYX */ COMPLEX_NEGATE(DFDP2, VYX); } } break; default: break; }; /* end antenna parameter switch */ /* end antenna param */ } else if (paramType==polnParmSou) { /* Source parameters */ switch (paramNumber) { /* Switch over parameter */ case 0: /* YX wrt IPol */ if (souFit[isou][paramNumber]) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 1: /* YX wrt QPol */ if (souFit[isou][paramNumber]) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 2: /* YX wrt UPol */ if (souFit[isou][paramNumber]) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; case 3: /* YX wrt Vpol */ if (souFit[isou][paramNumber]) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); } break; default: break; }; /* end source parameter switch */ /* end source param */ } else if (paramType==polnParmGain) { /* Antenna Gains */ switch (paramNumber) { /* Switch over parameter */ case 0: /* YX wrt gX */ if (isAnt2 && (antGainFit[ia2][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] * exp(-j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+1], 0); COMPLEX_EXP (ct3, -PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); /* part2 = 0 */ } break; case 1: /* YX wrt gY */ if (isAnt1 && (antGainFit[ia1][paramNumber])) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] * exp(-j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+0], 0); COMPLEX_EXP (ct3, -PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); } break; default: break; } /* end gain switch */ } else if (paramType==polnParmPD) { /* X-Y phase difference */ /* part = (0, -1) * VYX */ COMPLEX_MUL2 (DFDP, Jm, VYX); /* part2 = -VYX */ COMPLEX_NEGATE(DFDP2, VYX); } /* end parameter types */ /* Accumulate partials */ if (paramType!=polnParmUnspec) { sumd += 2.0 * isigma * (residR*DFDP.real + residI*DFDP.imag); sumd2 += 2.0*isigma * (DFDP.real*DFDP.real + DFDP.imag*DFDP.imag + residR*DFDP2.real + residI*DFDP2.imag); } /* end set partials */ } /* end valid data */ } /* End loop over visibilities */ if (sumwt<=0.0) sumwt = 1.0; /* Trap no data */ args->ChiSq = sum; /* Save results */ args->sumParResid = sumParResid; args->sumXResid = sumXResid; args->sumWt = sumwt; args->nPobs = nPobs; args->nXobs = nXobs; if (paramType!=polnParmUnspec) args->sumDeriv = sumd; if (paramType!=polnParmUnspec) args->sumDeriv2 = sumd2; /* Indicate completion if threaded */ if (args->ithread>=0) ObitThreadPoolDone (args->thread, (gpointer)&args->ithread); return NULL; } /* end ThreadPolnFitXYChi2 */ /** * Create threading arguments * \param in Fitting object * \param err Obit error stack object. */ static void MakePolnFitFuncArgs (ObitPolnCalFit *in, ObitErr *err) { olong i, nVisPerThread; /* If they already exist, first delete */ if (in->thArgs) KillPolnFitFuncArgs(in); /* How many threads? */ in->nThread = MAX (1, ObitThreadNumProc(in->thread)); nVisPerThread = in->nvis / in->nThread; /* Initialize threadArg array */ in->thArgs = g_malloc0(in->nThread*sizeof(PolnFitArg*)); for (i=0; i<in->nThread; i++) in->thArgs[i] = g_malloc0(sizeof(PolnFitArg)); for (i=0; i<in->nThread; i++) { in->thArgs[i]->thread = ObitThreadRef(in->thread); in->thArgs[i]->err = ObitErrRef(err); in->thArgs[i]->ithread = i; if (in->nThread<=1) in->thArgs[i]->ithread = -1; in->thArgs[i]->doError = in->doError; in->thArgs[i]->lo = i*nVisPerThread; /* Zero rel first */ in->thArgs[i]->hi = (i+1)*nVisPerThread; /* Zero rel last */ in->thArgs[i]->ndata = in->nvis*8; in->thArgs[i]->inData = in->inData; in->thArgs[i]->inWt = in->inWt; in->thArgs[i]->souNo = in->souNo; in->thArgs[i]->antNo = in->antNo; in->thArgs[i]->nant = in->nant; in->thArgs[i]->refAnt = in->refAnt; in->thArgs[i]->doFitRL = in->doFitRL; in->thArgs[i]->doFitI = in->doFitI; in->thArgs[i]->doFitPol = in->doFitPol; in->thArgs[i]->doFitV = in->doFitV; in->thArgs[i]->doFitGain= in->doFitGain; in->thArgs[i]->isCircFeed= in->isCircFeed; in->thArgs[i]->antParm = in->antParm; in->thArgs[i]->antErr = in->antErr; in->thArgs[i]->antFit = in->antFit; in->thArgs[i]->antPNumb = in->antPNumb; in->thArgs[i]->antGain = in->antGain; in->thArgs[i]->antGainErr = in->antGainErr; in->thArgs[i]->antGainFit = in->antGainFit; in->thArgs[i]->antGainPNumb = in->antGainPNumb; in->thArgs[i]->nsou = in->nsou; in->thArgs[i]->souParm = in->souParm; in->thArgs[i]->souErr = in->souErr; in->thArgs[i]->souFit = in->souFit; in->thArgs[i]->souPNumb = in->souPNumb; in->thArgs[i]->souIDs = in->souIDs; in->thArgs[i]->isouIDs = in->isouIDs; in->thArgs[i]->nparam = in->nparam; in->thArgs[i]->freq = in->inDesc->freq; in->thArgs[i]->refFreq = in->freq; in->thArgs[i]->curFreq = in->freq; /* Initial value */ in->thArgs[i]->RLPhase = in->RLPhase; in->thArgs[i]->PPol = in->PPol; in->thArgs[i]->dPPol = in->dPPol; in->thArgs[i]->Chan = 0; in->thArgs[i]->IFno = 0; in->thArgs[i]->ChiSq = 0.0; in->thArgs[i]->maxAnt = 100; } /* end loop over thread args */ /* Make sure do all data */ i = in->nThread-1; in->thArgs[i]->hi = MAX (in->thArgs[i]->hi, in->nvis); } /* end MakePolnFitFuncArgs */ /** * Delete threading arguments * \param in Fitting object */ static void KillPolnFitFuncArgs (ObitPolnCalFit *in) { olong i; /* If they already exist? */ if (in->thArgs==NULL) return; /* Loop over threadArg arrays */ for (i=0; i<in->nThread; i++) { ObitThreadUnref(in->thArgs[i]->thread); ObitErrUnref(in->thArgs[i]->err); g_free(in->thArgs[i]); in->thArgs[i] = NULL; } /* end loop over thread args */ g_free(in->thArgs ); in->thArgs = NULL; } /* end KillPolnFitFuncArgs*/ /** * Check for crazy antenna solutions, reset defaults if so. * If One antenna is the cause of large errors, disable it * \param in Fitting object * \param err Obit error stack object. * \return TRUE if refitting needed */ static gboolean CheckCrazyOne(ObitPolnCalFit *in, ObitErr *err) { gboolean crazyOne = FALSE; odouble sum, RMS, test, maxDif; ofloat fblank = ObitMagicF(); olong i, k, imax, idata; if (err->error) return crazyOne; /* Error detected? */ /* Was final Chi^2 not 50% better than initial and Was parallel hand fit better than cross?*/ if ((in->ChiSq>0.5*in->initChiSq) && (in->XRMS>1.1*in->ParRMS)) goto reset; /* Get mean square difference from default elipticity */ sum = 0.0; maxDif=0.0; imax = -1; for (i=0; i<in->nant; i++) { if (in->isCircFeed) { /* Circular feeds ori_r, elip_r, ori_l, elip_l */ test = (in->antParm[i*4+1] - G_PI/4.0)*(in->antParm[i*4+1] - G_PI/4.0) + (in->antParm[i*4+3] + G_PI/4.0)*(in->antParm[i*4+3] + G_PI/4.0); } else { /* Linear feeds ori_x, elip_x, ori_y, elip_y, */ test = (in->antParm[i*4+1])*(in->antParm[i*4+1]) + (in->antParm[i*4+3])*(in->antParm[i*4+3]); } sum += test; if (maxDif<test) {maxDif = test; imax=i;} } /* end loop over antennas */ /* is it OK? */ sum /= in->nant*2.0; RMS = sqrt(sum)*RAD2DG; crazyOne = (RMS > 10.0); if (!crazyOne) return FALSE; /* See if it's OK if we chuck the worst */ sum = 0.0; for (i=0; i<in->nant; i++) { if (i==imax) continue; if (in->isCircFeed) { /* Circular feeds ori_r, elip_r, ori_l, elip_l */ test = (in->antParm[i*4+1] - G_PI/4.0)*(in->antParm[i*4+1] - G_PI/4.0) + (in->antParm[i*4+3] + G_PI/4.0)*(in->antParm[i*4+3] + G_PI/4.0); } else { /* Linear feeds ori_x, elip_x, ori_y, elip_y, */ test = (in->antParm[i*4+1])*(in->antParm[i*4+1]) + (in->antParm[i*4+3])*(in->antParm[i*4+3]); } sum += test; } /* end loop over antennas */ /* is it OK now? */ sum /= in->nant*2.0; RMS = sqrt(sum)*RAD2DG; crazyOne = (RMS <= 10.0); /* OK = True */ if (!crazyOne) return FALSE; if (err->prtLv>=2) { Obit_log_error(err, OBIT_InfoWarn, "Tossing bad antenna %d - refit", imax+1); ObitErrLog(err); } /* Antenna imax+1 is the baddest, rest ~ OK - Flag */ in->gotAnt[imax] = FALSE; for (idata=0; idata<in->nvis; idata++) { if ((in->antNo[idata*2+0]==imax) || (in->antNo[idata*2+1]==imax)) { for (k=0; k<4; k++) in->inWt[idata*4+k] = 0.0; } } /* Flag solutions - don't refit */ if (!in->isCircFeed ) { /* Linear feed */ /*in->antGainFit[imax][0] = in->antGainFit[imax][1] = FALSE;*/ in->antGain[imax*2+0] = in->antGain[imax*2+1] = 1.0; } /*in->antFit[imax][0] = in->antFit[imax][1] = in->antFit[imax][2] = in->antFit[imax][3] = FALSE;*/ in->antParm[imax*4+0] = in->antParm[imax*4+1] = in->antParm[imax*4+2] = in->antParm[imax*4+3] = fblank; return TRUE; /* Reset solutions */ reset: Obit_log_error(err, OBIT_InfoWarn, "Questionable solution, reset, retry"); ResetAllSoln (in); return TRUE; } /* end CheckCrazyOne */ /** * Check for crazy antenna solutions, reset defaults if so. * If the RMS deviation from the default elipticity exceeds 10 deg * the fit is deemed crazy. * Uses last valid set of source parameters in reset * \param in Fitting object * \param err Obit error stack object. * \return TRUE if reset defaults, else FALSE */ static gboolean CheckCrazy(ObitPolnCalFit *in, ObitErr *err) { gboolean crazy = FALSE; odouble sum, RMS; ofloat fblank = ObitMagicF(); olong i, j; if (err->error) return crazy; /* Error detected? */ /* Get mean square difference from default elipticity */ sum = 0.0; for (i=0; i<in->nant; i++) { if ((!in->gotAnt[i]) || (in->antParm[i*4+1]==fblank) || ((in->antParm[i*4+3]==fblank))) continue; if (in->isCircFeed) { /* Circular feeds ori_r, elip_r, ori_l, elip_l */ sum += (in->antParm[i*4+1] - G_PI/4.0)*(in->antParm[i*4+1] - G_PI/4.0) + (in->antParm[i*4+3] + G_PI/4.0)*(in->antParm[i*4+3] + G_PI/4.0); } else { /* Linear feeds ori_x, elip_x, ori_y, elip_y, */ sum += (in->antParm[i*4+1])*(in->antParm[i*4+1]) + (in->antParm[i*4+3])*(in->antParm[i*4+3]); } } /* end loop over antennas */ /* mean */ sum /= in->nant*2.0; RMS = sqrt(sum)*RAD2DG; crazy = RMS > 10.0; /* Crazy? -> reset */ if (crazy) { Obit_log_error(err, OBIT_InfoWarn, "Antenna solution crazy, RMS %lf, reseting defaults", RMS); ResetAllSoln (in); } /* end reset */ else { /* OK - save source parameters */ for (i=0; i<in->nsou; i++) { for (j=0; j<4; j++) in->lastSouParm[i*4+j] = in->souParm[i*4+j]; } } /* end save parameters */ return crazy; } /* end CheckCrazy */ /** * Resets all solutions to the default * \param in Fitting object */ static void ResetAllSoln(ObitPolnCalFit *in) { olong i, j; for (i=0; i<in->nant; i++) { for (j=0; j<4; j++) in->antParm[i*4+j] = 0.0; if (in->isCircFeed) { /* Circular feeds ori_r, elip_r, ori_l, elip_l */ in->antParm[i*4+0] = 0.0; in->antParm[i*4+1] = G_PI/4.0; in->antParm[i*4+2] = 0.0; in->antParm[i*4+3] = -G_PI/4.0; } else { /* Linear feeds, if the antenna angles on sky are given in the AntennaList[0] use then, otherwise assume Feeds are X, Y ori_x, elip_x, ori_y, elip_y, */ if (fabs (in->AntLists[0]->ANlist[i]->FeedAPA-in->AntLists[0]->ANlist[i]->FeedBPA)<1.0) { /* Assume X, Y */ in->antParm[i*4+0] = 0.0; in->antParm[i*4+2] = +G_PI/2.0; } else { /* Use what's in the AN table as initial convert to radians */ in->antParm[i*4+0] = in->AntLists[0]->ANlist[i]->FeedAPA*DG2RAD; in->antParm[i*4+2] = in->AntLists[0]->ANlist[i]->FeedBPA*DG2RAD; } /* end if antenna angle given */ } } /* end loop over antennas */ /* Reset source parameters */ for (i=0; i<in->nsou; i++) { for (j=0; j<4; j++) { if (in->lastSouParm[i*4+j]>0.0) in->souParm[i*4+j] = in->lastSouParm[i*4+j]; else in->souParm[i*4+j] = 0.0; } } } /* end ResetAllSoln */ /** * Reset blanked antenna solutions * \param in Fitting object */ static void resetSoln(ObitPolnCalFit *in) { ofloat fblank = ObitMagicF(); olong i; for (i=0; i<in->nant; i++) { if (in->gotAnt[i] && ((in->antParm[i*4+1]==fblank) || (in->antParm[i*4+3]==fblank))) { /*in->antFit[i][0] = in->antFit[i][1] = in->antFit[i][2] = in->antFit[i][3] = TRUE;*/ if (in->isCircFeed) { /* Circular feeds ori_r, elip_r, ori_l, elip_l */ in->antParm[i*4+0] = 0.0; in->antParm[i*4+1] = G_PI/4.0; in->antParm[i*4+2] = 0.0; in->antParm[i*4+3] = -G_PI/4.0; } else { /*in->antGainFit[i][0] = in->antGainFit[i][1] = TRUE;*/ in->antGain[i*2+0] = in->antGain[i*2+1] = 1.0; /* Linear feeds, if the antenna angles on sky are given in the AntennaList[0] use then, otherwise assume Feeds are X, Y ori_x, elip_x, ori_y, elip_y, */ in->antParm[i*4+1] = 0.0; /* ellipticity */ in->antParm[i*4+3] = 0.0; if (fabs (in->AntLists[0]->ANlist[i]->FeedAPA-in->AntLists[0]->ANlist[i]->FeedBPA)<1.0) { /* Assume X, Y */ in->antParm[i*4+0] = 0.0; in->antParm[i*4+2] = +G_PI/2.0; } else { /* Use what's in the AN table as initial convert to radians */ in->antParm[i*4+0] = in->AntLists[0]->ANlist[i]->FeedAPA*DG2RAD; in->antParm[i*4+2] = in->AntLists[0]->ANlist[i]->FeedBPA*DG2RAD; } } } } } /* end resetSoln */ /** * Constrain linear feed values if refAnt<0 * subtract average * \param in Fitting object * \return amount by which ellipticies were corrected in deg. */ static ofloat ConstrLinFeed(ObitPolnCalFit *in) { ofloat out, sum; ofloat fblank = ObitMagicF(); olong i, cnt; /* Do I want to do this? */ out = 0.0; if (in->isCircFeed) return out; if (in->refAnt>=0) return out; /* Sum values */ sum = 0.0; cnt = 0; for (i=0; i<in->nant; i++) { if (in->gotAnt[i] && in->antFit[i][1] && (in->antParm[i*4+1]!=fblank)) { cnt++; sum += in->antParm[i*4+1]; } if (in->gotAnt[i] && in->antFit[i][3] && (in->antParm[i*4+3]!=fblank)) { cnt++; sum -= in->antParm[i*4+3]; /* Opposite sign */ } } /* end summing loop */ /* Correction */ out = sum / cnt; /* Correct values */ for (i=0; i<in->nant; i++) { if (in->gotAnt[i] && in->antFit[i][1] && (in->antParm[i*4+1]!=fblank)) { in->antParm[i*4+1] -= out; } if (in->gotAnt[i] && in->antFit[i][3] && (in->antParm[i*4+3]!=fblank)) { in->antParm[i*4+3] += out; } } /* end correcting loop */ return out*RAD2DG; } /* end ConstrLinFeed */ #ifdef HAVE_GSL /** * Circular feed function evaluator for polarization fitting solver * Orientation/Ellipticity version * Evaluates (model-observed) / sigma * Function from * \param x Vector of parameters to be fitted * Flux,array_of polarization_terms * \param param Function parameter structure (ObitPolnCalFit) * \param f Vector of (model-obs)/sigma for data points * \return completion code GSL_SUCCESS=OK */ static int PolnFitFuncOERL (const gsl_vector *x, void *params, gsl_vector *f) { ObitPolnCalFit *args = (ObitPolnCalFit*)params; ofloat *data, *wt; gboolean **antFit = args->antFit; olong **antPNumb = args->antPNumb; odouble *antParm = args->antParm; gboolean **souFit = args->souFit; odouble *souParm = args->souParm; olong **souPNumb = args->souPNumb; dcomplex *RS = args->RS; dcomplex *RD = args->RD; dcomplex *LS = args->LS; dcomplex *LD = args->LD; dcomplex *RSc = args->RSc; dcomplex *RDc = args->RDc; dcomplex *LSc = args->LSc; dcomplex *LDc = args->LDc; ofloat PD, chi1, chi2, PPol; double val; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble residR=0.0, residI=0.0, isigma=0.0; olong k, iant, ia1, ia2, isou, idata; olong isouLast=-999; dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c, ct1, ct2; dcomplex S[4], VRR, VRL, VLR, VLL; ofloat root2, maxElp=G_PI/4; size_t i, j; /* Initialize output */ val = 0.0; for (i=0; i<args->ndata; i++) gsl_vector_set(f, i, val); COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); /* R-L phase difference at reference antenna */ if (args->doFitRL) { j = args->PDPNumb; PD = gsl_vector_get(x, j); } else PD = args->PD; /* get model parameters - first antenna */ for (iant=0; iant<args->nant; iant++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((antFit[iant][k]) && (args->gotAnt[iant])) { j = antPNumb[iant][k]; antParm[iant*4+k] = gsl_vector_get(x, j); } } /* end loop over parameters */ } /* end loop over antennas */ /* now source */ for (isou=0; isou<args->nsou; isou++) { /* Loop over parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (souFit[isou][k]) { j = souPNumb[isou][k]; souParm[isou*4+k] = gsl_vector_get(x, j); } } /* end loop over parameters */ } /* end loop over sources */ /* data & wt pointers */ data = args->inData; wt = args->inWt; /* Injest model factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/ root2 = 1.0 / sqrt(2.0); /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_SET(RS[i], root2*(cos(antParm[i*4+1]) + sin(antParm[i*4+1])), 0.); COMPLEX_SET(ct1, root2*(cos(antParm[i*4+1]) - sin(antParm[i*4+1])), 0.); COMPLEX_EXP(ct2, 2*antParm[i*4+0]); COMPLEX_MUL2 (RD[i], ct1, ct2); COMPLEX_SET (ct1, root2*(cos(antParm[i*4+3]) + sin(antParm[i*4+3])), 0.); COMPLEX_EXP (ct2, -2*antParm[i*4+2]); COMPLEX_MUL2 (LS[i], ct1, ct2); COMPLEX_SET (LD[i], root2*(cos(antParm[i*4+3]) - sin(antParm[i*4+3])), 0.); COMPLEX_CONJUGATE (RSc[i], RS[i]); COMPLEX_CONJUGATE (RDc[i], RD[i]); COMPLEX_CONJUGATE (LSc[i], LS[i]); COMPLEX_CONJUGATE (LDc[i], LD[i]); } /* Reference antenna phase terms */ if (args->refAnt>0) { COMPLEX_EXP (PRref, antParm[(args->refAnt-1)*4+0]); COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD); } else { COMPLEX_SET (PRref, 1.0, 0.0); COMPLEX_EXP (PLref, PD); } COMPLEX_CONJUGATE (ct1, PLref); COMPLEX_MUL2 (PPRL, PRref, ct1); COMPLEX_CONJUGATE (ct1, PRref); COMPLEX_MUL2 (PPLR, PLref, ct1); /* Loop over data */ i = 0; for (idata=0; idata<args->nvis; idata++) { /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (PA1, 2*chi1); COMPLEX_EXP (PA2, 2*chi2); COMPLEX_CONJUGATE (PA1c, PA1); COMPLEX_CONJUGATE (PA2c, PA2); isou = MAX (0, args->souNo[idata]); /* Source number */ /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); qpol = PPol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S[0], ipol+vpol, 0.0); COMPLEX_SET (S[1], qpol, upol); COMPLEX_SET (S[2], qpol, -upol); COMPLEX_SET (S[3], ipol-vpol, 0.0); } /* Antenna parameters (0 ref) */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* Loop over correlations calcularing residuals */ for (k=0; k<4; k++) { isigma = wt[idata*4+k]; if (k<2) isigma *= 0.3; /* Downweight parallel hand */ switch (k) { case 0: /* RR */ if (wt[idata*4+k]>0.0) { /* Check for ellipticity in range */ if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+1]>maxElp)) { /* out of range - give big residual */ residR = MAX((antParm[ia1*4+1]-maxElp),(antParm[ia2*4+1]-maxElp)) * ipol * 100.; residI = residR; } else { /* OK */ /* VRR = S[0] * RS[ia1] * RSc[ia2] + S[1] * RS[ia1] * RDc[ia2] * PA2c + S[2] * RD[ia1] * RSc[ia2] * PA1 + S[3] * RD[ia1] * RDc[ia2] * PA1 * PA2c; */ COMPLEX_MUL3 (VRR, S[0], RS[ia1], RSc[ia2]); COMPLEX_MUL4 (ct1, S[1], RS[ia1], RDc[ia2], PA2c); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL4 (ct1, S[2], RD[ia1], RSc[ia2], PA1); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL5 (ct1, S[3], RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_ADD2 (VRR, VRR, ct1); residR = VRR.real - data[idata*10+(k+1)*2]; residI = VRR.imag - data[idata*10+(k+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ break; case 1: /* LL */ if (wt[idata*4+k]>0.0) { /* Check for ellipticity in range */ if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+3]<-maxElp)) { /* out of range - give big residual */ residR = MAX((maxElp-antParm[ia1*4+3]),(maxElp-antParm[ia2*4+3])) * ipol * 100.; residI = residR; } else { /* OK */ /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 + S[1] * LS[ia1] * LDc[ia2] * PA1c + S[2] * LD[ia1] * LSc[ia2] * PA2 + S[3] * LD[ia1] * LDc[ia2]; */ COMPLEX_MUL5 (VLL, S[0], LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL4 (ct1, S[1], LS[ia1], LDc[ia2], PA1c); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL4 (ct1, S[2], LD[ia1], LSc[ia2], PA2); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL3 (ct1, S[3], LD[ia1], LDc[ia2]); COMPLEX_ADD2 (VLL, VLL, ct1); residR = VLL.real - data[idata*10+(k+1)*2]; residI = VLL.imag - data[idata*10+(k+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ break; case 2: /* RL */ if (wt[idata*4+k]>0.0) { /* Check for ellipticity in range */ if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+3]<-maxElp)) { /* out of range - give big residual */ residR = MAX((antParm[ia1*4+1]-maxElp),(maxElp-antParm[ia2*4+3])) * ipol * 100.; residI = residR; } else { /* OK */ /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 + PPRL * S[1] * RS[ia1] * LDc[ia2] + PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */ COMPLEX_MUL4 (VRL, S[0], RS[ia1], LSc[ia2], PA2); COMPLEX_MUL3 (ct1, S[1], RS[ia1], LDc[ia2]); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL5 (ct1, S[2], RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL4 (ct1, S[3], RD[ia1], LDc[ia2], PA1); COMPLEX_ADD2 (ct2, VRL, ct1); COMPLEX_MUL2 (VRL, PPRL, ct2); residR = VRL.real - data[idata*10+(k+1)*2]; residI = VRL.imag - data[idata*10+(k+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ break; case 3: /* LR */ if (wt[idata*4+k]>0.0) { /* Check for ellipticity in range */ if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+1]>maxElp)) { /* out of range - give big residual */ residR = MAX((maxElp-antParm[ia1*4+3]),(antParm[ia2*4+1]-maxElp)) * ipol * 100.; residI = residR; } else { /* OK */ /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c + PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * S[2] * LD[ia1] * RSc[ia2] + PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4 (VLR, S[0], LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL5 (ct1, S[1], LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL3 (ct1, S[2], LD[ia1], RSc[ia2]); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL4 (ct1, S[3], LD[ia1], RDc[ia2], PA2c); COMPLEX_ADD2 (ct2, VLR, ct1); COMPLEX_MUL2 (VLR, PPLR, ct2); residR = VLR.real - data[idata*10+(k+1)*2]; residI = VLR.imag - data[idata*10+(k+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ break; default: break; }; /* end switch */ gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ i++; /* Update datum number */ } /* end loop over correlations */ } /* End loop over visibilities */ return GSL_SUCCESS; } /* end PolnFitFuncOERL */ /** * Circular feed Jacobian evaluator for polarization fitting solver * Orientation/Ellipticity version * Evaluates partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of polarization_terms * \param param Function parameter structure (ObitPolnCalFit) * \param J Jacobian matrix J[data_point, parameter] * \return completion code GSL_SUCCESS=OK */ static int PolnFitJacOERL (const gsl_vector *x, void *params, gsl_matrix *J) { ObitPolnCalFit *args = (ObitPolnCalFit*)params; ofloat *data, *wt; gboolean **antFit = args->antFit; olong **antPNumb = args->antPNumb; odouble *antParm = args->antParm; gboolean **souFit = args->souFit; odouble *souParm = args->souParm; olong **souPNumb = args->souPNumb; odouble *SR = args->SR; odouble *DR = args->DR; odouble *SL = args->SL; odouble *DL = args->DL; dcomplex *PR = args->PR; dcomplex *PRc = args->PRc; dcomplex *PL = args->PL; dcomplex *PLc = args->PLc; dcomplex *RS = args->RS; dcomplex *RD = args->RD; dcomplex *LS = args->LS; dcomplex *LD = args->LD; dcomplex *RSc = args->RSc; dcomplex *RDc = args->RDc; dcomplex *LSc = args->LSc; dcomplex *LDc = args->LDc; ofloat PD, chi1, chi2, PPol; double val; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble modelR, modelI, residR, residI, gradR, gradI, isigma; olong k, kk, iant, ia1, ia2, isou, idata, refAnt; olong isouLast=-999; dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c; dcomplex ct1, ct2, ct3, ct4, ct5, ct6; dcomplex S[4], VRR, VRL, VLR, VLL, DFDP, MC1, MC2, MC3, MC4; ofloat root2, maxElp=G_PI/4; size_t i, j; /* Initialize output */ val = 0.0; for (i=0; i<args->ndata; i++) { for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val); } COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VRR, 0.0, 0.0); COMPLEX_SET (VLL, 0.0, 0.0); COMPLEX_SET (VLR, 0.0, 0.0); COMPLEX_SET (VRL, 0.0, 0.0); /* R-L phase difference at reference antenna */ if (args->doFitRL) { j = args->PDPNumb; PD = gsl_vector_get(x, j); } else PD = args->PD; /* get model parameters - first antenna */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((antFit[iant][k]) && (args->gotAnt[iant])) { j = antPNumb[iant][k]; antParm[iant*4+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ } /* end loop over antennas */ /* Ref antenna - 0 rel */ refAnt = MAX(-1, args->refAnt-1); /* now source */ for (isou=0; isou<args->nsou; isou++) { /* Loop over source parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (souFit[isou][k]) { j = souPNumb[isou][k]; souParm[isou*4+k] = gsl_vector_get(x, j); } } /* end loop over source parameters */ } /* end loop over sources */ /* data & wt pointers */ data = args->inData; wt = args->inWt; /* Injest model factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/ root2 = 1.0 / sqrt(2.0); /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { SR[i] = cos(antParm[i*4+1]) + sin(antParm[i*4+1]); DR[i] = cos(antParm[i*4+1]) - sin(antParm[i*4+1]); SL[i] = cos(antParm[i*4+3]) + sin(antParm[i*4+3]); DL[i] = cos(antParm[i*4+3]) - sin(antParm[i*4+3]); COMPLEX_SET (RS[i], root2*SR[i], 0.); COMPLEX_SET (ct1, root2*DR[i], 0.); COMPLEX_EXP (PR[i], 2*antParm[i*4+0]); COMPLEX_CONJUGATE (PRc[i], PR[i]); COMPLEX_MUL2 (RD[i], ct1, PR[i]); COMPLEX_SET (ct1, root2*SL[i], 0.); COMPLEX_EXP (PL[i], -2*antParm[i*4+2]); COMPLEX_CONJUGATE (PLc[i], PL[i]); COMPLEX_MUL2 (LS[i], ct1, PL[i]); COMPLEX_SET (LD[i], root2*DL[i], 0.); COMPLEX_CONJUGATE (RSc[i], RS[i]); COMPLEX_CONJUGATE (RDc[i], RD[i]); COMPLEX_CONJUGATE (LSc[i], LS[i]); COMPLEX_CONJUGATE (LDc[i], LD[i]); } /* Reference antenna phase terms */ if (args->refAnt>0) { COMPLEX_EXP (PRref, antParm[(args->refAnt-1)*4+0]); COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD); } else { COMPLEX_SET (PRref, 1.0, 0.0); COMPLEX_EXP (PLref, PD); } COMPLEX_CONJUGATE (ct1, PLref); COMPLEX_MUL2 (PPRL, PRref, ct1); COMPLEX_CONJUGATE (ct1, PRref); COMPLEX_MUL2 (PPLR, PLref, ct1); /* Loop over data */ i = 0; for (idata=0; idata<args->nvis; idata++) { /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (PA1, 2*chi1); COMPLEX_EXP (PA2, 2*chi2); COMPLEX_CONJUGATE (PA1c, PA1); COMPLEX_CONJUGATE (PA2c, PA2); isou = MAX (0, args->souNo[idata]); /* Source number */ /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S[0], ipol+vpol, 0.0); COMPLEX_SET (S[1], qpol, upol); COMPLEX_SET (S[2], qpol, -upol); COMPLEX_SET (S[3], ipol-vpol, 0.0); } /* Antenna parameters */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* i = datum number */ /* Loop over correlations calculating derivatives */ for (kk=0; kk<4; kk++) { isigma = wt[idata*4+kk]; if (kk<2) isigma *= 0.3; /* Downweight parallel hand */ switch (kk) { case 0: /* RR */ if (wt[idata*4+kk]>0.0) { /* VRR = S[0] * RS[ia1] * RSc[ia2] + S[1] * RS[ia1] * RDc[ia2] * PA2c + S[2] * RD[ia1] * RSc[ia2] * PA1 + S[3] * RD[ia1] * RDc[ia2] * PA1 * PA2c; */ COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]); COMPLEX_MUL2 (VRR, S[0], MC1); COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRR, VRR, ct1); modelR = VRR.real; modelI = VRR.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+1]>maxElp)) { /* out of range - give big residual */ residR = MAX((antParm[ia1*4+1]-maxElp),(antParm[ia2*4+1]-maxElp)) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[2], MC3); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RrrR wrt Or1 */ gradI = DFDP.imag; /* RrrI wrt Or1 */ } else gradR = gradI =0.0; /* Invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Er1 */ /* part = r2 * DR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) - r2 * SR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + S[3] * RDc[ia2] * PA1 * PA2c) */ COMPLEX_MUL2(ct1, S[0], RSc[ia2]); COMPLEX_MUL3(ct2, S[1], RDc[ia2], PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL3(ct1, S[2], RSc[ia2], PA1); COMPLEX_MUL4(ct2, S[3], RDc[ia2], PA1, PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PR[ia1], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RrrR wrt Er1 */ gradI = DFDP.imag; /* RrrI wrt Er1 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt OL1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt EL1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Or1 */ /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[1], MC2); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RrrR wrt Ol2 */ gradI = DFDP.imag; /* RrrI wrt Ol2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Er2 */ /* part = r2 * DR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) - r2 * SR[ia2] * PRc[ia2] * (S[1] * RS[ia1] * PA2c + S[3] * RD[ia1] * PA1 * PA2c) */ COMPLEX_MUL2(ct1, S[0], RS[ia1]); COMPLEX_MUL3(ct2, S[2], RD[ia1], PA1); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL3(ct1, S[1], RS[ia1], PA2c ); COMPLEX_MUL4(ct2, S[3], RD[ia1], PA1, PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia2], 0.0); COMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RrrR wrt Ol2 */ gradI = DFDP.imag; /* RrrI wrt Ol2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt Ol2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt El2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt I */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = RS[ia1] * RSc[ia2] + RD[ia1] * RDc[ia2] * PA1 * PA2c */ COMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]); COMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RrrR wrt ipol */ gradI = DFDP.imag; /* RrrI wrt ipol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt qpol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = RS[ia1] * RDc[ia2] * PA2c + RD[ia1] * RSc[ia2] * PA1 */ COMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RrrR wrt qpol */ gradI = DFDP.imag; /* RrrI wrt qpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt upol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i (RS[ia1] * RDc[ia2] * PA2c - RD[ia1] * RSc[ia2] * PA1) */ COMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); gradR = DFDP.real; /* RrrR wrt upol */ gradI = DFDP.imag; /* RrrI wrt upol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt V */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = RS[ia1] * RSc[ia2] - RD[ia1] * RDc[ia2] * PA1 * PA2c */ COMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]); COMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; /* RrrR wrt vpol */ gradI = DFDP.imag; /* RrrI wrt vpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD = 0 */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; /* End RR */ case 1: /* LL */ if (wt[idata*4+kk]>0.0) { /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 + S[1] * LS[ia1] * LDc[ia2] * PA1c + S[2] * LD[ia1] * LSc[ia2] * PA2 + S[3] * LD[ia1] * LDc[ia2]; */ COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2 (VLL, S[0], MC1); COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLL, VLL, ct1); modelR = VLL.real; modelI = VLL.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+3]<-maxElp)) { /* out of range - give big residual */ residR = MAX((maxElp-antParm[ia1*4+3]),(maxElp-antParm[ia2*4+3])) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt OR1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* wrt Er1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* wrt Ol1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Or1 */ /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[1], MC2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RllR wrt Ol1 */ gradI = DFDP.imag; /* RllI wrt Ol1 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt El1 */ /* part = r2 * DL[ia1] * PL[ia1] * (S[0] * LSc[ia2] * PA1c * PA2 + S[1] * LDc[ia2] * PA1c) - r2 * SL[ia1] * (S[2] * LSc[ia2] * PA2 + S[3] * LDc[ia2]) */ COMPLEX_MUL4(ct1, S[0], LSc[ia2], PA1c, PA2); COMPLEX_MUL3(ct2, S[1], LDc[ia2], PA1c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL3(ct5, ct4, PL[ia1], ct3); COMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2); COMPLEX_MUL2(ct2, S[3], LDc[ia2]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia1], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RllR wrt El1 */ gradI = DFDP.imag; /* RllI wrt El1 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* Rll wrt E2r = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* Rll wrt Ol2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Ol2 */ /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[2], MC3); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RllR wrt Ol2 */ gradI = DFDP.imag; /* RllI wrt Ol2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt El2 */ /* part = r2 * DL[ia2] * PLc[ia2] * (S[0] * LS[ia1] * PA1c * PA2 + S[2] * LD[ia1] * PA2) - r2 * SL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */ COMPLEX_MUL4(ct1, S[0], LS[ia1], PA1c, PA2); COMPLEX_MUL3(ct2, S[2], LD[ia1], PA2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3); COMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c); COMPLEX_MUL2(ct2, S[3], LD[ia1]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia2], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RllR wrt El2 */ gradI = DFDP.imag; /* RllI wrt El2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt I */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = LS[ia1] * LSc[ia2] * PA1c * PA2 + LD[ia1] * LDc[ia2] */ COMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RLLR wrt ipol */ gradI = DFDP.imag; /* RLLI wrt ipol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Qpol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (LS[ia1] * LDc[ia2] * PA1c + LD[ia1] * LSc[ia2] * PA2) */ COMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RllR wrt qpol */ gradI = DFDP.imag; /* RllI wrt qpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i( LS[ia1] * LDc[ia2] * PA1c - LD[ia1] * LSc[ia2] * PA2) */ COMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); gradR = DFDP.real; /* RllR wrt upol */ gradI = DFDP.imag; /* RllI wrt upol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt V */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = LS[ia1] * LSc[ia2] * PA1c * PA2 - LD[ia1] * LDc[ia2] */ COMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; /* RllR wrt vpol */ gradI = DFDP.imag; /* RllI wrt vpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD - no effect */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; /* End LL */ break; /* End LL */ case 2: /* RL */ if (wt[idata*4+kk]>0.0) { /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 + PPRL * S[1] * RS[ia1] * LDc[ia2] + PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */ COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (VRL, S[0], MC1); COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRL, VRL, ct1); modelR = VRL.real; modelI = VRL.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+3]<-maxElp)) { /* out of range - give big residual */ residR = MAX((antParm[ia1*4+1]-maxElp),(maxElp-antParm[ia2*4+3])) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[2], MC3); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia1==refant) */ if (ia1==refAnt) { COMPLEX_MUL2(ct2, ct1, VRL); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DR[ia1] * (PPRL * S[0] * LSc[ia2] * PA2 + PPRL * S[1] * LDc[ia2]) - r2 * SR[ia1] * PR[ia1] * (PPRL * S[2] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * LDc[ia2] * PA1) */ COMPLEX_MUL4(ct1, PPRL, S[0], LSc[ia2], PA2); COMPLEX_MUL3(ct2, PPRL, S[1], LDc[ia2]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL5(ct1, PPRL, S[2], LSc[ia2], PA1, PA2); COMPLEX_MUL4(ct2, PPRL, S[3], LDc[ia2], PA1); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PR[ia1], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt Ol1 =0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* wrt Er2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* wrt Ol2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[2], MC3); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia2==refant) */ if (ia2==refAnt) { COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(ct2, ct1, VRL); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DL[ia2] * PLc[ia2] * (PPRL * S[0] * RS[ia1] * PA2 + PPRL * S[2] * RD[ia1] * PA1 * PA2) - r2 * SL[ia2] * (PPRL * S[1] * RS[ia1] + PPRL * S[3] * RD[ia1] * PA1) */ COMPLEX_MUL4(ct1, PPRL, S[0], RS[ia1], PA2); COMPLEX_MUL5(ct2, PPRL, S[2], RD[ia1], PA1, PA2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3); COMPLEX_MUL3(ct1, PPRL, S[1], RS[ia1]); COMPLEX_MUL4(ct2, PPRL, S[3], RD[ia1], PA1); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia2], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt I */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPRL * RS[ia1] * LSc[ia2] * PA2 + PPRL * RD[ia1] * LDc[ia2] * PA1*/ COMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2 ); COMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (PPRL * RS[ia1] * LDc[ia2] + PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */ COMPLEX_MUL3(ct1, PPRL, RS[ia1], LDc[ia2]); COMPLEX_MUL5(ct2, PPRL, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i(PPRL * RS[ia1] * LDc[ia2] - PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */ COMPLEX_MUL2(ct1, RS[ia1], LDc[ia2]); COMPLEX_MUL4(ct2, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL3(DFDP, ct4, PPRL, ct3); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt V */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPRL * RS[ia1] * LSc[ia2] * PA2 - PPRL * RD[ia1] * LDc[ia2] * PA1 */ COMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { COMPLEX_SET(ct1, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct1, VRL); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; /* End RL */ case 3: /* LR */ if (wt[idata*4+kk]>0.0) { /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c + PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * S[2] * LD[ia1] * RSc[ia2] + PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL2 (VLR, S[0], MC1); COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLR, VLR, ct1); modelR = VLR.real; modelI = VLR.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+1]>maxElp)) { /* out of range - give big residual */ residR = MAX((maxElp-antParm[ia1*4+3]),(antParm[ia2*4+1]-maxElp)) * ipol * 100.; residI = residI; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* wrt Er1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* wrt Ol1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[1], MC2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia1==refant) */ if (ia1==refAnt) { COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(ct2, ct1, VLR); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DL[ia1] * PL[ia1] * (PPLR * S[0] * RSc[ia2] * PA1c + PPLR * S[1] * RDc[ia2] * PA1c * PA2c) - r2 * SL[ia1] * (PPLR * S[2] * RSc[ia2] + PPLR * S[3] * RDc[ia2] * PA2c) */ COMPLEX_MUL4(ct1, PPLR, S[0], RSc[ia2], PA1c); COMPLEX_MUL5(ct2, PPLR, S[1], RDc[ia2], PA1c, PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL3(ct5, ct4, PL[ia1], ct3); COMPLEX_MUL3(ct1, PPLR, S[2], RSc[ia2]); COMPLEX_MUL4(ct2, PPLR, S[3], RDc[ia2], PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia1], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[1], MC2); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia2==refant */ if (ia2==refAnt) { COMPLEX_MUL2(ct2, ct1, VLR); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) - r2 * SR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + PPLR * S[3] * LD[ia1] * PA2c) */ COMPLEX_MUL4(ct1, PPLR, S[0], LS[ia1], PA1c); COMPLEX_MUL3(ct2, PPLR, S[2], LD[ia1]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL5(ct1, PPLR, S[1], LS[ia1], PA1c, PA2c); COMPLEX_MUL4(ct2, PPLR, S[3], LD[ia1], PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia2], 0.0); COMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt Ol2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt El2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt I */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPLR * LS[ia1] * RSc[ia2] * PA1c + PPLR * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * LD[ia1] * RSc[ia2]) */ COMPLEX_MUL5(ct1, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL3(ct2, PPLR, LD[ia1], RSc[ia2]); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c - PPLR * LD[ia1] * RSc[ia2]) */ COMPLEX_MUL4(ct1, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL2(ct2, LD[ia1], RSc[ia2]); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL3(DFDP, ct4, PPLR, ct3); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt Vpol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPLR * LS[ia1] * RSc[ia2] * PA1c - PPLR * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { COMPLEX_SET(ct1, 0.0, -1.0); COMPLEX_MUL2(DFDP, ct1, VLR); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* End LR */ }; /* end switch over data correlation */ i++; /* Update complex datum number */ } /* end loop over correlations */ } /* End loop over visibilities */ return GSL_SUCCESS; } /* end PolnFitJacOERL */ /** * Circular feed Function & Jacobian evaluator for polarization fitting solver * Orientation/Ellipticity for circular feeds version * Evaluates partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of polarization_terms * \param param Function parameter structure (ObitPolnCalFit) * \param f Vector of (model-obs)/sigma for data points * \param J Jacobian matrix J[data_point, parameter] * \return completion code GSL_SUCCESS=OK */ static int PolnFitFuncJacOERL (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) { ObitPolnCalFit *args = (ObitPolnCalFit*)params; ofloat *data, *wt; gboolean **antFit = args->antFit; olong **antPNumb = args->antPNumb; odouble *antParm = args->antParm; gboolean **souFit = args->souFit; odouble *souParm = args->souParm; olong **souPNumb = args->souPNumb; odouble *SR = args->SR; odouble *DR = args->DR; odouble *SL = args->SL; odouble *DL = args->DL; dcomplex *PR = args->PR; dcomplex *PRc = args->PRc; dcomplex *PL = args->PL; dcomplex *PLc = args->PLc; dcomplex *RS = args->RS; dcomplex *RD = args->RD; dcomplex *LS = args->LS; dcomplex *LD = args->LD; dcomplex *RSc = args->RSc; dcomplex *RDc = args->RDc; dcomplex *LSc = args->LSc; dcomplex *LDc = args->LDc; ofloat PD, chi1, chi2, PPol; double val; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble residR, residI, gradR, gradI, modelR, modelI, isigma; olong k, kk, iant, ia1, ia2, isou, idata, refAnt; olong isouLast=-999; dcomplex PRref, PLref, PPRL, PPLR, PA1, PA2, PA1c, PA2c; dcomplex ct1, ct2, ct3, ct4, ct5, ct6; dcomplex S[4], VRR, VRL, VLR, VLL, DFDP, MC1, MC2, MC3, MC4; ofloat root2, maxElp=G_PI/4; size_t i, j; /* Initialize output */ val = 0.0; for (i=0; i<args->ndata; i++) { gsl_vector_set(f, i, val); for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val); } COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VRR, 0.0, 0.0); COMPLEX_SET (VLL, 0.0, 0.0); COMPLEX_SET (VLR, 0.0, 0.0); COMPLEX_SET (VRL, 0.0, 0.0); /* R-L phase difference at reference antenna */ if (args->doFitRL) { j = args->PDPNumb; PD = gsl_vector_get(x, j); } else PD = args->PD; /* get model parameters - first antenna */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((antFit[iant][k]) && (args->gotAnt[iant])) { j = antPNumb[iant][k]; antParm[iant*4+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ } /* end loop over antennas */ /* Ref antenna - 0 rel */ refAnt = MAX(-1, args->refAnt-1); /* now source */ for (isou=0; isou<args->nsou; isou++) { /* Loop over source parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (souFit[isou][k]) { j = souPNumb[isou][k]; souParm[isou*4+k] = gsl_vector_get(x, j); } } /* end loop over source parameters */ } /* end loop over sources */ /* data & wt pointers */ data = args->inData; wt = args->inWt; /* Injest model factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y*/ root2 = 1.0 / sqrt(2.0); /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { SR[i] = cos(antParm[i*4+1]) + sin(antParm[i*4+1]); DR[i] = cos(antParm[i*4+1]) - sin(antParm[i*4+1]); SL[i] = cos(antParm[i*4+3]) + sin(antParm[i*4+3]); DL[i] = cos(antParm[i*4+3]) - sin(antParm[i*4+3]); COMPLEX_SET (RS[i], root2*SR[i], 0.); COMPLEX_SET (ct1, root2*DR[i], 0.); COMPLEX_EXP (PR[i], 2*antParm[i*4+0]); COMPLEX_CONJUGATE (PRc[i], PR[i]); COMPLEX_MUL2 (RD[i], ct1, PR[i]); COMPLEX_SET (ct1, root2*SL[i], 0.); COMPLEX_EXP (PL[i], -2*antParm[i*4+2]); COMPLEX_CONJUGATE (PLc[i], PL[i]); COMPLEX_MUL2 (LS[i], ct1, PL[i]); COMPLEX_SET (LD[i], root2*DL[i], 0.); COMPLEX_CONJUGATE (RSc[i], RS[i]); COMPLEX_CONJUGATE (RDc[i], RD[i]); COMPLEX_CONJUGATE (LSc[i], LS[i]); COMPLEX_CONJUGATE (LDc[i], LD[i]); } /* Reference antenna phase terms */ if (args->refAnt>0) { COMPLEX_EXP (PRref, antParm[(args->refAnt-1)*4+0]); COMPLEX_EXP (PLref, -antParm[(args->refAnt-1)*4+2]+PD); } else { COMPLEX_SET (PRref, 1.0, 0.0); COMPLEX_EXP (PLref, PD); } COMPLEX_CONJUGATE (ct1, PLref); COMPLEX_MUL2 (PPRL, PRref, ct1); COMPLEX_CONJUGATE (ct1, PRref); COMPLEX_MUL2 (PPLR, PLref, ct1); /* Loop over data */ i = 0; for (idata=0; idata<args->nvis; idata++) { /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (PA1, 2*chi1); COMPLEX_EXP (PA2, 2*chi2); COMPLEX_CONJUGATE (PA1c, PA1); COMPLEX_CONJUGATE (PA2c, PA2); isou = MAX (0, args->souNo[idata]); /* Source number */ /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S[0], ipol+vpol, 0.0); COMPLEX_SET (S[1], qpol, upol); COMPLEX_SET (S[2], qpol, -upol); COMPLEX_SET (S[3], ipol-vpol, 0.0); } /* Antenna parameters */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* i = datum number */ /* Loop over correlations calculating derivatives */ for (kk=0; kk<4; kk++) { isigma = wt[idata*4+kk]; if (kk<2) isigma *= 0.3; /* Downweight parallel hand */ switch (kk) { case 0: /* RR */ if (wt[idata*4+kk]>0.0) { /* VRR = S[0] * RS[ia1] * RSc[ia2] + S[1] * RS[ia1] * RDc[ia2] * PA2c + S[2] * RD[ia1] * RSc[ia2] * PA1 + S[3] * RD[ia1] * RDc[ia2] * PA1 * PA2c; */ COMPLEX_MUL2 (MC1, RS[ia1], RSc[ia2]); COMPLEX_MUL2 (VRR, S[0], MC1); COMPLEX_MUL3 (MC2, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL3 (MC3, RD[ia1], RSc[ia2], PA1); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRR, VRR, ct1); COMPLEX_MUL4 (MC4, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRR, VRR, ct1); modelR = VRR.real; modelI = VRR.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+1]>maxElp)) { /* out of range - give big residual */ residR = MAX((antParm[ia1*4+1]-maxElp),(antParm[ia2*4+1]-maxElp)) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[2], MC3); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RrrR wrt Or1 */ gradI = DFDP.imag; /* RrrI wrt Or1 */ } else gradR = gradI =0.0; /* Invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Er1 */ /* part = r2 * DR[ia1] * (S[0] * RSc[ia2] + S[1] * RDc[ia2] * PA2c) - r2 * SR[ia1] * PR[ia1] * (S[2] * RSc[ia2] * PA1 + S[3] * RDc[ia2] * PA1 * PA2c) */ COMPLEX_MUL2(ct1, S[0], RSc[ia2]); COMPLEX_MUL3(ct2, S[1], RDc[ia2], PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL3(ct1, S[2], RSc[ia2], PA1); COMPLEX_MUL4(ct2, S[3], RDc[ia2], PA1, PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PR[ia1], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RrrR wrt Er1 */ gradI = DFDP.imag; /* RrrI wrt Er1 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt OL1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt EL1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Or1 */ /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[1], MC2); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RrrR wrt Ol2 */ gradI = DFDP.imag; /* RrrI wrt Ol2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Er1 */ /* part = r2 * DR[ia2] * (S[0] * RS[ia1] + S[2] * RD[ia1] * PA1) - r2 * SR[ia2] * PRc[ia2] * (S[1] * RS[ia1] * PA2c + S[3] * RD[ia1] * PA1 * PA2c) */ COMPLEX_MUL2(ct1, S[0], RS[ia1]); COMPLEX_MUL3(ct2, S[2], RD[ia1], PA1); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL3(ct1, S[1], RS[ia1], PA2c ); COMPLEX_MUL4(ct2, S[3], RD[ia1], PA1, PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia2], 0.0); COMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RrrR wrt Ol2 */ gradI = DFDP.imag; /* RrrI wrt Ol2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt Ol2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt El2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = RS[ia1] * RSc[ia2] + RD[ia1] * RDc[ia2] * PA1 * PA2c */ COMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]); COMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RrrR wrt ipol */ gradI = DFDP.imag; /* RrrI wrt ipol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (RS[ia1] * RDc[ia2] * PA2c + RD[ia1] * RSc[ia2] * PA1) */ COMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RrrR wrt qpol */ gradI = DFDP.imag; /* RrrI wrt qpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i (RS[ia1] * RDc[ia2] * PA2c - RD[ia1] * RSc[ia2] * PA1) */ COMPLEX_MUL3(ct1, RS[ia1], RDc[ia2], PA2c); COMPLEX_MUL3(ct2, RD[ia1], RSc[ia2], PA1); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); gradR = DFDP.real; /* RrrR wrt upol */ gradI = DFDP.imag; /* RrrI wrt upol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = RS[ia1] * RSc[ia2] - RD[ia1] * RDc[ia2] * PA1 * PA2c */ COMPLEX_MUL2(ct1, RS[ia1], RSc[ia2]); COMPLEX_MUL4(ct2, RD[ia1], RDc[ia2], PA1, PA2c); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; /* RrrR wrt vpol */ gradI = DFDP.imag; /* RrrI wrt vpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD = 0 */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; /* End RR */ case 1: /* LL */ if (wt[idata*4+kk]>0.0) { /* VLL = S[0] * LS[ia1] * LSc[ia2] * PA1c * PA2 + S[1] * LS[ia1] * LDc[ia2] * PA1c + S[2] * LD[ia1] * LSc[ia2] * PA2 + S[3] * LD[ia1] * LDc[ia2]; */ COMPLEX_MUL4 (MC1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2 (VLL, S[0], MC1); COMPLEX_MUL3 (MC2, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL3 (MC3, LD[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLL, VLL, ct1); COMPLEX_MUL2 (MC4, LD[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLL, VLL, ct1); modelR = VLL.real; modelI = VLL.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+3]<-maxElp)) { /* out of range - give big residual */ residR = MAX((maxElp-antParm[ia1*4+3]),(maxElp-antParm[ia2*4+3])) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt OR1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* wrt Er1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* wrt Ol1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Or1 */ /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[1], MC2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RllR wrt Ol1 */ gradI = DFDP.imag; /* RllI wrt Ol1 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt El1 */ /* part = r2 * DL[ia1] * PL[ia1] * (S[0] * LSc[ia2] * PA1c * PA2 + S[1] * LDc[ia2] * PA1c) - r2 * SL[ia1] * (S[2] * LSc[ia2] * PA2 + S[3] * LDc[ia2]) */ COMPLEX_MUL4(ct1, S[0], LSc[ia2], PA1c, PA2); COMPLEX_MUL3(ct2, S[1], LDc[ia2], PA1c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL3(ct5, ct4, PL[ia1], ct3); COMPLEX_MUL3(ct1, S[2], LSc[ia2], PA2); COMPLEX_MUL2(ct2, S[3], LDc[ia2]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia1], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RllR wrt El1 */ gradI = DFDP.imag; /* RllI wrt El1 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* Rll wrt E2r = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* Rll wrt Ol2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt Ol2 */ /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[2], MC3); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); gradR = DFDP.real; /* RllR wrt Ol2 */ gradI = DFDP.imag; /* RllI wrt Ol2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* Derivative of model wrt El2 */ /* part = r2 * DL[ia2] * PLc[ia2] * (S[0] * LS[ia1] * PA1c * PA2 + S[2] * LD[ia1] * PA2) - r2 * SL[ia2] * (S[1] * LS[ia1] * PA1c + S[3] * LD[ia1]) */ COMPLEX_MUL4(ct1, S[0], LS[ia1], PA1c, PA2); COMPLEX_MUL3(ct2, S[2], LD[ia1], PA2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3); COMPLEX_MUL3(ct1, S[1], LS[ia1], PA1c); COMPLEX_MUL2(ct2, S[3], LD[ia1]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia2], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; /* RllR wrt El2 */ gradI = DFDP.imag; /* RllI wrt El2 */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = LS[ia1] * LSc[ia2] * PA1c * PA2 + LD[ia1] * LDc[ia2] */ COMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RLLR wrt ipol */ gradI = DFDP.imag; /* RLLI wrt ipol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Qpol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (LS[ia1] * LDc[ia2] * PA1c + LD[ia1] * LSc[ia2] * PA2) */ COMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; /* RllR wrt qpol */ gradI = DFDP.imag; /* RllI wrt qpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i (LS[ia1] * LDc[ia2] * PA1c - LD[ia1] * LSc[ia2] * PA2) */ COMPLEX_MUL3(ct1, LS[ia1], LDc[ia2], PA1c); COMPLEX_MUL3(ct2, LD[ia1], LSc[ia2], PA2); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct4, ct3); gradR = DFDP.real; /* RllR wrt upol */ gradI = DFDP.imag; /* RllI wrt upol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = LS[ia1] * LSc[ia2] * PA1c * PA2 - LD[ia1] * LDc[ia2] */ COMPLEX_MUL4(ct1, LS[ia1], LSc[ia2], PA1c, PA2); COMPLEX_MUL2(ct2, LD[ia1], LDc[ia2]); COMPLEX_SUB(DFDP, ct1, ct2); gradR = DFDP.real; /* RllR wrt vpol */ gradI = DFDP.imag; /* RllI wrt vpol */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD - no effect */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; /* End LL */ case 2: /* RL */ if (wt[idata*4+kk]>0.0) { /* VRL = PPRL * S[0] * RS[ia1] * LSc[ia2] * PA2 + PPRL * S[1] * RS[ia1] * LDc[ia2] + PPRL * S[2] * RD[ia1] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * RD[ia1] * LDc[ia2] * PA1; */ COMPLEX_MUL4 (MC1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL2 (VRL, S[0], MC1); COMPLEX_MUL3 (MC2, PPRL, RS[ia1], LDc[ia2]); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL5 (MC3, PPRL, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VRL, VRL, ct1); COMPLEX_MUL4 (MC4, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VRL, VRL, ct1); modelR = VRL.real; modelI = VRL.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+1]>maxElp) || (antParm[ia2*4+3]<-maxElp)) { /* out of range - give big residual */ residR = MAX((antParm[ia1*4+1]-maxElp),(maxElp-antParm[ia2*4+3])) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* (0, 2 i) * (S[2]*MC3 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[2], MC3); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia1==refant) */ if (ia1==refAnt) { COMPLEX_MUL2(ct2, ct1, VRL); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DR[ia1] * (PPRL * S[0] * LSc[ia2] * PA2 + PPRL * S[1] * LDc[ia2]) - r2 * SR[ia1] * PR[ia1] * (PPRL * S[2] * LSc[ia2] * PA1 * PA2 + PPRL * S[3] * LDc[ia2] * PA1) */ COMPLEX_MUL4(ct1, PPRL, S[0], LSc[ia2], PA2); COMPLEX_MUL3(ct2, PPRL, S[1], LDc[ia2]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia1], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL5(ct1, PPRL, S[2], LSc[ia2], PA1, PA2); COMPLEX_MUL4(ct2, PPRL, S[3], LDc[ia2], PA1); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia1], 0.0); COMPLEX_MUL3(ct6, ct4, PR[ia1], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt Ol1 =0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt El1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* wrt Er2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* wrt Ol2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* (0, 2 i) * (S[0]*MC1 + S[2]*MC3) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[2], MC3); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia2==refant) */ if (ia2==refAnt) { COMPLEX_SET (ct1, 0.0, 2.0); COMPLEX_MUL2(ct2, ct1, VRL); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DL[ia2] * PLc[ia2] * (PPRL * S[0] * RS[ia1] * PA2 + PPRL * S[2] * RD[ia1] * PA1 * PA2) - r2 * SL[ia2] * (PPRL * S[1] * RS[ia1] + PPRL * S[3] * RD[ia1] * PA1) */ COMPLEX_MUL4(ct1, PPRL, S[0], RS[ia1], PA2); COMPLEX_MUL5(ct2, PPRL, S[2], RD[ia1], PA1, PA2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia2], 0.0); COMPLEX_MUL3(ct5, ct4, PLc[ia2], ct3); COMPLEX_MUL3(ct1, PPRL, S[1], RS[ia1]); COMPLEX_MUL4(ct2, PPRL, S[3], RD[ia1], PA1); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia2], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPRL * RS[ia1] * LSc[ia2] * PA2 + PPRL * RD[ia1] * LDc[ia2] * PA1*/ COMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (PPRL * RS[ia1] * LDc[ia2] - PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */ COMPLEX_MUL3(ct1, PPRL, RS[ia1], LDc[ia2]); COMPLEX_MUL5(ct2, PPRL, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i (PPRL * RS[ia1] * LDc[ia2] - PPRL * RD[ia1] * LSc[ia2] * PA1 * PA2) */ COMPLEX_MUL2(ct1, RS[ia1], LDc[ia2]); COMPLEX_MUL4(ct2, RD[ia1], LSc[ia2], PA1, PA2); COMPLEX_SUB(ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL3(DFDP, ct4, PPRL, ct3); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPRL * RS[ia1] * LSc[ia2] * PA2 - PPRL * RD[ia1] * LDc[ia2] * PA1 */ COMPLEX_MUL4(ct1, PPRL, RS[ia1], LSc[ia2], PA2); COMPLEX_MUL4(ct2, PPRL, RD[ia1], LDc[ia2], PA1); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { COMPLEX_SET(ct1, 0.0, 1.0); COMPLEX_MUL2(DFDP, ct1, VRL); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; /* End RL */ case 3: /* LR */ if (wt[idata*4+kk]>0.0) { /* VLR = PPLR * S[0] * LS[ia1] * RSc[ia2] * PA1c + PPLR * S[1] * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * S[2] * LD[ia1] * RSc[ia2] + PPLR * S[3] * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4 (MC1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL2 (VLR, S[0], MC1); COMPLEX_MUL5 (MC2, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL2 (ct1, S[1], MC2); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL3 (MC3, PPLR, LD[ia1], RSc[ia2]); COMPLEX_MUL2 (ct1, S[2], MC3); COMPLEX_ADD2 (VLR, VLR, ct1); COMPLEX_MUL4 (MC4, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_MUL2 (ct1, S[3], MC4); COMPLEX_ADD2 (VLR, VLR, ct1); modelR = VLR.real; modelI = VLR.imag; /* Check for ellipticity in range */ if ((antParm[ia1*4+3]<-maxElp) || (antParm[ia2*4+1]>maxElp)) { /* out of range - give big residual */ residR = MAX((maxElp-antParm[ia1*4+3]),(antParm[ia2*4+1]-maxElp)) * ipol * 100.; residI = residR; } else { /* OK */ residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; } gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* wrt Er1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* wrt Ol1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* (0,-2 i) * (S[0]*MC1 + S[1]*MC2) */ COMPLEX_MUL2(ct1, S[0], MC1); COMPLEX_MUL2(ct2, S[1], MC2); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia1==refant) */ if (ia1==refAnt) { COMPLEX_MUL2(ct2, ct1, VLR); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt El1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DL[ia1] * PL[ia1] * (PPLR * S[0] * RSc[ia2] * PA1c + PPLR * S[1] * RDc[ia2] * PA1c * PA2c) - r2 * SL[ia1] * (PPLR * S[2] * RSc[ia2] + PPLR * S[3] * RDc[ia2] * PA2c) */ COMPLEX_MUL4(ct1, PPLR, S[0], RSc[ia2], PA1c); COMPLEX_MUL5(ct2, PPLR, S[1], RDc[ia2], PA1c, PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DL[ia1], 0.0); COMPLEX_MUL3(ct5, ct4, PL[ia1], ct3); COMPLEX_MUL3(ct1, PPLR, S[2], RSc[ia2]); COMPLEX_MUL4(ct2, PPLR, S[3], RDc[ia2], PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SL[ia1], 0.0); COMPLEX_MUL2(ct6, ct4, ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt Or2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* (0,-2 i) * (S[1]*MC2 + S[3]*MC4) */ COMPLEX_MUL2(ct1, S[1], MC2); COMPLEX_MUL2(ct2, S[3], MC4); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct1, 0.0, -2.0); COMPLEX_MUL2(DFDP, ct1, ct3); /* If ia2==refant */ if (ia2==refAnt) { COMPLEX_MUL2(ct2, ct1, VLR); COMPLEX_ADD2(DFDP, DFDP, ct2); } gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt Er2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = r2 * DR[ia2] * (PPLR * S[0] * LS[ia1] * PA1c + PPLR * S[2] * LD[ia1]) - r2 * SR[ia2] * PRc[ia2] * (PPLR * S[1] * LS[ia1] * PA1c * PA2c + PPLR * S[3] * LD[ia1] * PA2c) */ COMPLEX_MUL4(ct1, PPLR, S[0], LS[ia1], PA1c); COMPLEX_MUL3(ct2, PPLR, S[2], LD[ia1]); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*DR[ia2], 0.0); COMPLEX_MUL2(ct5, ct4, ct3); COMPLEX_MUL5(ct1, PPLR, S[1], LS[ia1], PA1c, PA2c); COMPLEX_MUL4(ct2, PPLR, S[3], LD[ia1], PA2c); COMPLEX_ADD2(ct3, ct1, ct2); COMPLEX_SET (ct4, root2*SR[ia2], 0.0); COMPLEX_MUL3(ct6, ct4, PRc[ia2], ct3); COMPLEX_SUB (DFDP, ct5, ct6); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt Ol2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* wrt El2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPLR * LS[ia1] * RSc[ia2] * PA1c + PPLR * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c + PPLR * LD[ia1] * RSc[ia2]) */ COMPLEX_MUL5(ct1, PPLR, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL3(ct2, PPLR, LD[ia1], RSc[ia2]); COMPLEX_ADD2(DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = i (PPLR * LS[ia1] * RDc[ia2] * PA1c * PA2c - PPLR * LD[ia1] * RSc[ia2]) */ COMPLEX_MUL4(ct1, LS[ia1], RDc[ia2], PA1c, PA2c); COMPLEX_MUL2(ct2, LD[ia1], RSc[ia2]); COMPLEX_SUB (ct3, ct1, ct2); COMPLEX_SET(ct4, 0.0, 1.0); COMPLEX_MUL3(DFDP, ct4, PPLR, ct3); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = PPLR * LS[ia1] * RSc[ia2] * PA1c - PPLR * LD[ia1] * RDc[ia2] * PA2c */ COMPLEX_MUL4(ct1, PPLR, LS[ia1], RSc[ia2], PA1c); COMPLEX_MUL4(ct2, PPLR, LD[ia1], RDc[ia2], PA2c); COMPLEX_SUB (DFDP, ct1, ct2); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { COMPLEX_SET(ct1, 0.0, -1.0); COMPLEX_MUL2(DFDP, ct1, VLR); gradR = DFDP.real; gradI = DFDP.imag; } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* End LR */ }; /* end switch over data correlation */ i++; /* Update complex datum number */ } /* end loop over correlations */ } /* End loop over visibilities */ return GSL_SUCCESS; } /* end PolnFitFuncJacOERL */ /** * Linear feed function evaluator for polarization fitting solver * Orientation/Ellipticity version * Evaluates (model-observed) / sigma * Function from * \param x Vector of parameters to be fitted * Flux,array_of polarization_terms * \param param Function parameter structure (ObitPolnCalFit) * \param f Vector of (model-obs)/sigma for data points * \return completion code GSL_SUCCESS=OK */ static int PolnFitFuncOEXY (const gsl_vector *x, void *params, gsl_vector *f) { ObitPolnCalFit *args = (ObitPolnCalFit*)params; ofloat *data, *wt; gboolean **antFit = args->antFit; olong **antPNumb = args->antPNumb; odouble *antGain = args->antGain; gboolean **antGainFit = args->antGainFit; olong **antGainPNumb = args->antGainPNumb; odouble *antParm = args->antParm; gboolean **souFit = args->souFit; odouble *souParm = args->souParm; olong **souPNumb = args->souPNumb; dcomplex *CX = args->RS; dcomplex *SX = args->RD; dcomplex *CY = args->LS; dcomplex *SY = args->LD; dcomplex *CXc = args->RSc; dcomplex *SXc = args->RDc; dcomplex *CYc = args->LSc; dcomplex *SYc = args->LDc; ofloat PD, chi1, chi2, PPol; double val; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble residR, residI, modelR, modelI, isigma; olong k, kk, iant, ia1, ia2, isou, idata; olong isouLast=-999; dcomplex SPA, DPA, SPAc, DPAc, ggPD; dcomplex ct1, ct2, ct5; dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4; dcomplex SM1, SM2, SM3, SM4; size_t i, j; /* Initialize output */ val = 0.0; for (i=0; i<args->ndata; i++) { gsl_vector_set(f, i, val); } COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (S0[0], 0.0, 0.0); COMPLEX_SET (S0[1], 0.0, 0.0); COMPLEX_SET (S0[2], 0.0, 0.0); COMPLEX_SET (S0[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VXX, 0.0, 0.0); COMPLEX_SET (VYY, 0.0, 0.0); COMPLEX_SET (VYX, 0.0, 0.0); COMPLEX_SET (VXY, 0.0, 0.0); /* R-L phase difference at reference antenna */ if (args->doFitRL) { j = args->PDPNumb; PD = gsl_vector_get(x, j); } else PD = args->PD; /* get model parameters - first antenna */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((antFit[iant][k]) && (args->gotAnt[iant])) { j = antPNumb[iant][k]; antParm[iant*4+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ } /* end loop over antennas */ /* antenna gain */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna gains */ for (k=0; k<2; k++) { /* Fitting? */ if ((antGainFit[iant][k]) && (args->gotAnt[iant])) { j = antGainPNumb[iant][k]; antGain[iant*2+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ /* Default X gain = 1.0/Y gain if (!antGainFit[iant][0]) antGain[iant*2+0] = 1.0 / antGain[iant*2+1]; */ } /* end loop over antennas */ /* now source */ for (isou=0; isou<args->nsou; isou++) { /* Loop over source parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (souFit[isou][k]) { j = souPNumb[isou][k]; souParm[isou*4+k] = gsl_vector_get(x, j); } } /* end loop over source parameters */ } /* end loop over sources */ /* data & wt pointers */ data = args->inData; wt = args->inWt; /* Injest model, factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */ /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_EXP (ct1, -antParm[i*4+0]); COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (CX[i], ct1, ct2); COMPLEX_EXP (ct1, antParm[i*4+0]); COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (SX[i], ct1, ct2); COMPLEX_EXP (ct1, antParm[i*4+2]); COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (CY[i], ct1, ct2); COMPLEX_EXP (ct1, -antParm[i*4+2]); COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (SY[i], ct1, ct2); COMPLEX_CONJUGATE (CXc[i], CX[i]); COMPLEX_CONJUGATE (SXc[i], SX[i]); COMPLEX_CONJUGATE (CYc[i], CY[i]); COMPLEX_CONJUGATE (SYc[i], SY[i]); } /* Loop over data */ i = 0; for (idata=0; idata<args->nvis; idata++) { /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (SPA,(chi1+chi2)); COMPLEX_EXP (DPA,chi1-chi2); COMPLEX_CONJUGATE (SPAc, SPA); COMPLEX_CONJUGATE (DPAc, DPA); isou = MAX (0, args->souNo[idata]); /* Source number */ /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S0[0], ipol+vpol, 0.0); COMPLEX_SET (S0[1], qpol, upol); COMPLEX_SET (S0[2], qpol, -upol); COMPLEX_SET (S0[3], ipol-vpol, 0.0); } /* Rotate Stokes by parallactic angle */ COMPLEX_MUL2(S[0], DPAc, S0[0]); COMPLEX_MUL2(S[1], SPAc, S0[1]); COMPLEX_MUL2(S[2], SPA, S0[2]); COMPLEX_MUL2(S[3], DPA, S0[3]); /* Antenna parameters */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* idata = datum number */ /* Loop over correlations calculating derivatives */ for (kk=0; kk<4; kk++) { switch (kk) { case 0: /* XX */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VXX = {S[0] * CX[ia1] * CXc[ia2] + S[1] * CX[ia1] * SXc[ia2] + S[2] * SX[ia1] * CXc[ia2] + S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ; */ COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+0]*antGain[ia2*2+0], 0); COMPLEX_MUL2 (VXX, ct5, ggPD); modelR = VXX.real; modelI = VXX.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } break; /* End XX */ case 1: /* YY */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VYY = {S[0] * SY[ia1] * SYc[ia2] + S[1] * SY[ia1] * CYc[ia2] + S[2] * CY[ia1] * SYc[ia2] + S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ; */ COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+1]*antGain[ia2*2+1], 0); COMPLEX_MUL2 (VYY, ct5, ggPD); modelR = VYY.real; modelI = VYY.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } break; /* End YY */ case 2: /* XY */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VXY = {S[0] * CX[ia1] * SYc[ia2] + S[1] * CX[ia1] * CYc[ia2] + S[2] * SX[ia1] * SYc[ia2] + S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD); */ COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+1], 0); COMPLEX_EXP (ct2, PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VXY, ct5, ggPD); modelR = VXY.real; modelI = VXY.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } break; /* End XY */ case 3: /* YX */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VYX = {S[0] * SY[ia1] * CXc[ia2] + S[1] * SY[ia1] * SXc[ia2] + S[2] * CY[ia1] * CXc[ia2] + S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD) */ COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+1]*antGain[ia2*2+0], 0); COMPLEX_EXP (ct2, -PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VYX, ct5, ggPD); modelR = VYX.real; modelI = VYY.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } break; /* End YX */ default: break; }; /* end switch over data correlation */ i++; /* Update complex datum number */ } /* end loop over correlations */ } /* End loop over visibilities */ return GSL_SUCCESS; } /* end PolnFitFuncOEXY */ /** * Linear feed Jacobian evaluator for polarization fitting solver * Orientation/Ellipticity version * Evaluates partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of polarization_terms * \param param Function parameter structure (ObitPolnCalFit) * \param J Jacobian matrix J[data_point, parameter] * \return completion code GSL_SUCCESS=OK */ static int PolnFitJacOEXY (const gsl_vector *x, void *params, gsl_matrix *J) { ObitPolnCalFit *args = (ObitPolnCalFit*)params; ofloat *data, *wt; gboolean **antFit = args->antFit; olong **antPNumb = args->antPNumb; odouble *antParm = args->antParm; odouble *antGain = args->antGain; gboolean **antGainFit = args->antGainFit; olong **antGainPNumb = args->antGainPNumb; gboolean **souFit = args->souFit; odouble *souParm = args->souParm; olong **souPNumb = args->souPNumb; dcomplex *CX = args->RS; dcomplex *SX = args->RD; dcomplex *CY = args->LS; dcomplex *SY = args->LD; dcomplex *CXc = args->RSc; dcomplex *SXc = args->RDc; dcomplex *CYc = args->LSc; dcomplex *SYc = args->LDc; ofloat PD, chi1, chi2, PPol; double val; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble gradR=0.0, gradI=0.0, isigma=0.0; olong k, kk, iant, ia1, ia2, isou, idata; olong isouLast=-999; dcomplex SPA, DPA, SPAc, DPAc, ggPD; dcomplex ct1, ct2, ct3, ct4, ct5, Jm, Jp; dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4, DFDP; dcomplex SM1, SM2, SM3, SM4; size_t i, j; /* Initialize output */ val = 0.0; for (i=0; i<args->ndata; i++) { for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val); } COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (S0[0], 0.0, 0.0); COMPLEX_SET (S0[1], 0.0, 0.0); COMPLEX_SET (S0[2], 0.0, 0.0); COMPLEX_SET (S0[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VXX, 0.0, 0.0); COMPLEX_SET (VYY, 0.0, 0.0); COMPLEX_SET (VYX, 0.0, 0.0); COMPLEX_SET (VXY, 0.0, 0.0); COMPLEX_SET (Jm, 0.0,-1.0); COMPLEX_SET (Jp, 0.0, 1.0); COMPLEX_SET (SM1, 0.0, 0.0); COMPLEX_SET (SM2, 0.0, 0.0); COMPLEX_SET (SM3, 0.0, 0.0); COMPLEX_SET (SM4, 0.0, 0.0); COMPLEX_SET (ggPD, 0.0, 0.0); /* R-L phase difference at reference antenna */ if (args->doFitRL) { j = args->PDPNumb; PD = gsl_vector_get(x, j); } else PD = args->PD; /* get model parameters - first antenna */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((antFit[iant][k]) && (args->gotAnt[iant])) { j = antPNumb[iant][k]; antParm[iant*4+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ } /* end loop over antennas */ /* antenna gain */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna gains */ for (k=0; k<2; k++) { /* Fitting? */ if ((antGainFit[iant][k]) && (args->gotAnt[iant])) { j = antGainPNumb[iant][k]; antGain[iant*2+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ /* Default X gain = 1.0/Y gain if (!antGainFit[iant][0]) antGain[iant*2+0] = 1.0 / antGain[iant*2+1]; */ } /* end loop over antennas */ /* now source */ for (isou=0; isou<args->nsou; isou++) { /* Loop over source parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (souFit[isou][k]) { j = souPNumb[isou][k]; souParm[isou*4+k] = gsl_vector_get(x, j); } } /* end loop over source parameters */ } /* end loop over sources */ /* data & wt pointers */ data = args->inData; wt = args->inWt; /* Injest model, factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */ /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_EXP (ct1, -antParm[i*4+0]); COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (CX[i], ct1, ct2); COMPLEX_EXP (ct1, antParm[i*4+0]); COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (SX[i], ct1, ct2); COMPLEX_EXP (ct1, antParm[i*4+2]); COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (CY[i], ct1, ct2); COMPLEX_EXP (ct1, -antParm[i*4+2]); COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (SY[i], ct1, ct2); COMPLEX_CONJUGATE (CXc[i], CX[i]); COMPLEX_CONJUGATE (SXc[i], SX[i]); COMPLEX_CONJUGATE (CYc[i], CY[i]); COMPLEX_CONJUGATE (SYc[i], SY[i]); } /* Loop over data */ i = 0; for (idata=0; idata<args->nvis; idata++) { /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (SPA,(chi1+chi2)); COMPLEX_EXP (DPA,chi1-chi2); COMPLEX_CONJUGATE (SPAc, SPA); COMPLEX_CONJUGATE (DPAc, DPA); isou = MAX (0, args->souNo[idata]); /* Source number */ /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S0[0], ipol+vpol, 0.0); COMPLEX_SET (S0[1], qpol, upol); COMPLEX_SET (S0[2], qpol, -upol); COMPLEX_SET (S0[3], ipol-vpol, 0.0); } /* Rotate Stokes by parallactic angle */ COMPLEX_MUL2(S[0], DPAc, S0[0]); COMPLEX_MUL2(S[1], SPAc, S0[1]); COMPLEX_MUL2(S[2], SPA, S0[2]); COMPLEX_MUL2(S[3], DPA, S0[3]); /* Antenna parameters */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* i = datum number */ /* Loop over correlations calculating derivatives */ for (kk=0; kk<4; kk++) { switch (kk) { case 0: /* XX */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VXX = {S[0] * CX[ia1] * CXc[ia2] + S[1] * CX[ia1] * SXc[ia2] + S[2] * SX[ia1] * CXc[ia2] + S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ; */ COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+0]*antGain[ia2*2+0], 0); COMPLEX_MUL2 (VXX, ct5, ggPD); } /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt Ox1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gX[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RxxR wrt Ox1 */ gradI = DFDP.imag; /* RxxI wrt Ox1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI =0.0; /* Invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt Ex1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CXc[ia2] * SXc[ia1] - S[1] * SXc[ia2] * SXc[ia1] + S[2] * CXc[ia2] * CXc[ia1] + S[3] * SXc[ia2] * CXc[ia1]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], CXc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], SXc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], CXc[ia2], SXc[ia1]); COMPLEX_MUL3(ct4, S[3], SXc[ia2], CXc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RxxR wrt Ex1 */ gradI = DFDP.imag; /* RxxI wrt Ex1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XX wrt OY1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* XX wrt EY1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt Ox2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gX[ia1] * gX[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RxxR wrt Ox2 */ gradI = DFDP.imag; /* RxxI wrt Ox2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt Ex2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CX[ia1] * SX[ia2] + S[1] * CX[ia1] * CX[ia2] - S[2] * SX[ia1] * SX[ia2] + S[3] * SX[ia1] * CX[ia2]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], CX[ia1], SX[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], CX[ia1], CX[ia2]); COMPLEX_MUL3(ct5, S[2], SX[ia1], SX[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], SX[ia1], CX[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RxxR wrt Ox2 */ gradI = DFDP.imag; /* RxxI wrt Ox2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XX wrt Oy2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* XX wrt Ey2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt ipol */ gradI = DFDP.imag; /* RxxI wrt ipol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt qpol */ gradI = DFDP.imag; /* RxxI wrt qpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XX wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt upol */ gradI = DFDP.imag; /* RxxI wrt upol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* XX wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt vpol */ gradI = DFDP.imag; /* RxxI wrt vpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD = 0 */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt gX1 */ /* Fitting? */ if (antGainFit[ia1][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+0], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RxxR wrt gX1 */ gradI = DFDP.imag; /* RxxI wrt gX1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt gX2 */ if (antGainFit[ia2][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RxxR wrt gX2 */ gradI = DFDP.imag; /* RxxI wrt gX2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ break; /* End XX */ case 1: /* YY */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VYY = {S[0] * SY[ia1] * SYc[ia2] + S[1] * SY[ia1] * CYc[ia2] + S[2] * CY[ia1] * SYc[ia2] + S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ; */ COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+1]*antGain[ia2*2+1], 0); COMPLEX_MUL2 (VYY, ct5, ggPD); } /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt Ox1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* YY wrt Ex1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* YY wrt Oy1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC2 + (0, 1) * S[3] * MC4} * gY[ia1] * gY[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RyyR wrt Oy2 */ gradI = DFDP.imag; /* RyyI wrt Oy2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YY wrt Ey1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SYc[ia2] * CYc[ia1] - S[1] * CYc[ia2] * CYc[ia1] + S[2] * SYc[ia2] * SYc[ia1] + S[3] * CYc[ia2] * SYc[ia1]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], SYc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CYc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SYc[ia2], SYc[ia1]); COMPLEX_MUL3(ct4, S[3], CYc[ia2], SYc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RyyR wrt Ey1 */ gradI = DFDP.imag; /* RyyI wrt Ey1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt Ox2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* YY wrt Ex2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* YY wrt Oy2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gY[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RyyR wrt Oy2 */ gradI = DFDP.imag; /* RyyI wrt Oy2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YY wrt Ey2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SY[ia1] * CY[ia2] + S[1] * SY[ia1] * SY[ia2] - S[2] * CY[ia1] * CY[ia2] + S[3] * CY[ia1] * SY[ia2]} * gY[ia1] * gY[ia2] */ COMPLEX_MUL3(ct5, S[0], SY[ia1], CY[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], SY[ia1], SY[ia2]); COMPLEX_MUL3(ct5, S[2], CY[ia1], CY[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], CY[ia1], SY[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RyyR wrt Ey2 */ gradI = DFDP.imag; /* RyyI wrt Ey2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt ipol */ gradI = DFDP.imag; /* RyyI wrt ipol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YY wrt Qpol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt qpol */ gradI = DFDP.imag; /* RyyI wrt qpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* YY wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt upol */ gradI = DFDP.imag; /* RyyI wrt upol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YY wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt vpol */ gradI = DFDP.imag; /* RyyI wrt vpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD - no effect */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt gY1 */ /* Fitting? */ if (antGainFit[ia1][1]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+1], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RyyR wrt gY1 */ gradI = DFDP.imag; /* RyyI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YY wrt gY2 */ if (antGainFit[ia2][1]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 1); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RyyR wrt gY2 */ gradI = DFDP.imag; /* RyyI wrt gY2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ break; /* End YY */ case 2: /* XY */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VXY = {S[0] * CX[ia1] * SYc[ia2] + S[1] * CX[ia1] * CYc[ia2] + S[2] * SX[ia1] * SYc[ia2] + S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD); */ COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+1], 0); COMPLEX_EXP (ct2, PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VXY, ct5, ggPD); } /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt Ox1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XY wrt Ex1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SYc[ia2] * SXc[ia1] - S[1] * CYc[ia2] * SXc[ia1] + S[2] * SYc[ia2] * CXc[ia1] + S[3] * CYc[ia2] * CXc[ia1] } * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_MUL3(ct5, S[0], SYc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CYc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SYc[ia2], CXc[ia1]); COMPLEX_MUL3(ct4, S[3], CYc[ia2], CXc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XY wrt Oy1 =0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* XY wrt Ey1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt Ox2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* XY wrt Ex2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* XY wrt Oy2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* XY wrt Ey2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CX[ia1] * CY[ia2] + S[1] * CX[ia1] * SY[ia2] - S[2] * SX[ia1] * CY[ia2] + S[3] * SX[ia1] * SY[ia2]} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_MUL3(ct5, S[0], CX[ia1], CY[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CX[ia1], SY[ia2]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SX[ia1], CY[ia2]); COMPLEX_MUL3(ct4, S[3], SX[ia1], SY[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyxR wrt gY1 */ gradI = DFDP.imag; /* RyxI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XY wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XY wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* XY wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyxR wrt gY1 */ gradI = DFDP.imag; /* RyxI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { /* part = (0, 1) * VXY */ COMPLEX_MUL2 (DFDP, Jp, VXY); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt gX1 */ /* Fitting? */ if (antGainFit[ia1][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] * exp(j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, 1./antGain[ia2*2+1], 0); COMPLEX_EXP (ct3, PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RxyR wrt gX1 */ gradI = DFDP.imag; /* RxyI wrt gX1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XY wrt gY2 */ if (antGainFit[ia2][1]) { if (wt[idata*4+kk]>0.0) { /* part = {S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] * exp(j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 0); COMPLEX_EXP (ct3, PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RxyR wrt gY2 */ gradI = DFDP.imag; /* RxyI wrt gY2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ break; /* End XY */ case 3: /* YX */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VYX = {S[0] * SY[ia1] * CXc[ia2] + S[1] * SY[ia1] * SXc[ia2] + S[2] * CY[ia1] * CXc[ia2] + S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD) */ COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+1]*antGain[ia2*2+0], 0); COMPLEX_EXP (ct2, -PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VYX, ct5, ggPD); } /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt Ox1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* YX wrt Ex1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* YX wrt Oy1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + ( 0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(-j PD) */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YX wrt Ey1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CXc[ia2] * CYc[ia1] - S[1] * SXc[ia2] * CYc[ia1] + S[2] * CXc[ia2] * SYc[ia1] + S[3] * SXc[ia2] * SYc[ia1]} * gY[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL3(ct5, S[0], CXc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], SXc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], CXc[ia2], SYc[ia1]); COMPLEX_MUL3(ct4, S[3], SXc[ia2], SYc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt Ox2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YX wrt Ex2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SY[ia1] * SX[ia2] + S[1] * SY[ia1] * CX[ia2] - S[2] * CY[ia1] * SX[ia2] + S[3] * CY[ia1] * CX[ia2]} * gY[ia1] * gX[ia2] * exp(-j PD)*/ COMPLEX_MUL3(ct5, S[0], SY[ia1], SX[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], SY[ia1], CX[ia2]); COMPLEX_MUL3(ct5, S[2], CY[ia1], SX[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], CY[ia1], CX[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* YX wrt Oy2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* YX wrt Ey2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YX wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* YX wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YX wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { /* part = (0, -1) * VYX */ COMPLEX_MUL2 (DFDP, Jm, VYX); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt gY1 */ /* Fitting? */ if (antGainFit[ia1][1]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] * exp(-j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+1], 0); COMPLEX_EXP (ct3, -PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RyxR wrt gY1 */ gradI = DFDP.imag; /* RyxI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* wrt gX2 */ if (antGainFit[ia2][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] * exp(-j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+1], 0); COMPLEX_EXP (ct3, -PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RyxR wrt gX2 */ gradI = DFDP.imag; /* RyxI wrt gX2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ /* End YX */ default: break; }; /* end switch over data correlation */ i++; /* Update complex datum number */ } /* end loop over correlations */ } /* End loop over visibilities */ return GSL_SUCCESS; } /* end PolnFitJacOEXY */ /** * Linear feed Function & Jacobian evaluator for polarization fitting solver * Orientation/Ellipticity for linear feeds version * Evaluates partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of polarization_terms * \param param Function parameter structure (ObitPolnCalFit) * \param f Vector of (model-obs)/sigma for data points * \param J Jacobian matrix J[data_point, parameter] * \return completion code GSL_SUCCESS=OK */ static int PolnFitFuncJacOEXY (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) { ObitPolnCalFit *args = (ObitPolnCalFit*)params; ofloat *data, *wt; gboolean **antFit = args->antFit; olong **antPNumb = args->antPNumb; odouble *antParm = args->antParm; odouble *antGain = args->antGain; gboolean **antGainFit= args->antGainFit; olong **antGainPNumb = args->antGainPNumb; gboolean **souFit = args->souFit; odouble *souParm = args->souParm; olong **souPNumb = args->souPNumb; dcomplex *CX = args->RS; dcomplex *SX = args->RD; dcomplex *CY = args->LS; dcomplex *SY = args->LD; dcomplex *CXc = args->RSc; dcomplex *SXc = args->RDc; dcomplex *CYc = args->LSc; dcomplex *SYc = args->LDc; ofloat PD, chi1, chi2, PPol; double val; odouble ipol=0.0, qpol=0.0, upol=0.0, vpol=0.0; odouble residR=0.0, residI=0.0, gradR=0.0, gradI=0.0, modelR=0.0, modelI=0.0, isigma=0.0; olong k, kk, iant, ia1, ia2, isou, idata; olong isouLast=-999; dcomplex SPA, DPA, SPAc, DPAc, ggPD; dcomplex ct1, ct2, ct3, ct4, ct5, Jm, Jp; dcomplex S0[4], S[4], VXX, VXY, VYX, VYY, MC1, MC2, MC3, MC4, DFDP; dcomplex SM1, SM2, SM3, SM4; size_t i, j; /* Initialize output */ val = 0.0; for (i=0; i<args->ndata; i++) { gsl_vector_set(f, i, val); for (j=0; j<args->nparam; j++) gsl_matrix_set(J, i, j, val); } COMPLEX_SET (S[0], 0.0, 0.0); /* Initialize poln vector */ COMPLEX_SET (S[1], 0.0, 0.0); COMPLEX_SET (S[2], 0.0, 0.0); COMPLEX_SET (S[3], 0.0, 0.0); COMPLEX_SET (S0[0], 0.0, 0.0); COMPLEX_SET (S0[1], 0.0, 0.0); COMPLEX_SET (S0[2], 0.0, 0.0); COMPLEX_SET (S0[3], 0.0, 0.0); COMPLEX_SET (MC1, 0.0, 0.0); /* Other stuff */ COMPLEX_SET (MC2, 0.0, 0.0); COMPLEX_SET (MC3, 0.0, 0.0); COMPLEX_SET (MC4, 0.0, 0.0); COMPLEX_SET (VXX, 0.0, 0.0); COMPLEX_SET (VYY, 0.0, 0.0); COMPLEX_SET (VYX, 0.0, 0.0); COMPLEX_SET (VXY, 0.0, 0.0); COMPLEX_SET (Jm, 0.0,-1.0); COMPLEX_SET (Jp, 0.0, 1.0); COMPLEX_SET (SM1, 0.0, 0.0); COMPLEX_SET (SM2, 0.0, 0.0); COMPLEX_SET (SM3, 0.0, 0.0); COMPLEX_SET (SM4, 0.0, 0.0); COMPLEX_SET (ggPD, 0.0, 0.0); /* R-L phase difference */ if (args->doFitRL) { j = args->PDPNumb; PD = gsl_vector_get(x, j); } else PD = args->PD; /* get model parameters - first antenna */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna parameters */ for (k=0; k<4; k++) { /* Fitting? */ if ((antFit[iant][k]) && (args->gotAnt[iant])) { j = antPNumb[iant][k]; antParm[iant*4+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ } /* end loop over antennas */ /* antenna gain */ for (iant=0; iant<args->nant; iant++) { /* Loop over antenna gains */ for (k=0; k<2; k++) { /* Fitting? */ if ((antGainFit[iant][k]) && (args->gotAnt[iant])) { j = antGainPNumb[iant][k]; antGain[iant*2+k] = gsl_vector_get(x, j); } } /* end loop over antenna parameters */ /* Default X gain = 1.0/Y gain if (!antGainFit[iant][0]) antGain[iant*2+0] = 1.0 / antGain[iant*2+1]; */ } /* end loop over antennas */ /* now source */ for (isou=0; isou<args->nsou; isou++) { /* Loop over source parameters */ for (k=0; k<4; k++) { /* Fitting? */ if (souFit[isou][k]) { j = souPNumb[isou][k]; souParm[isou*4+k] = gsl_vector_get(x, j); } } /* end loop over source parameters */ } /* end loop over sources */ /* data & wt pointers */ data = args->inData; wt = args->inWt; /* Injest model, factorize into antenna components - data in order Orientation R/X, Elipticity R/X, Orientation L/Y, Elipticity L/Y */ /* Elipticity, Orientation terms */ for (i=0; i<args->nant; i++) { COMPLEX_EXP (ct1, -antParm[i*4+0]); COMPLEX_SET (ct2, cos(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (CX[i], ct1, ct2); COMPLEX_EXP (ct1, antParm[i*4+0]); COMPLEX_SET (ct2, sin(G_PI*0.25+antParm[i*4+1]), 0.0); COMPLEX_MUL2 (SX[i], ct1, ct2); COMPLEX_EXP (ct1, antParm[i*4+2]); COMPLEX_SET (ct2, cos(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (CY[i], ct1, ct2); COMPLEX_EXP (ct1, -antParm[i*4+2]); COMPLEX_SET (ct2, sin(G_PI*0.25-antParm[i*4+3]), 0.0); COMPLEX_MUL2 (SY[i], ct1, ct2); COMPLEX_CONJUGATE (CXc[i], CX[i]); COMPLEX_CONJUGATE (SXc[i], SX[i]); COMPLEX_CONJUGATE (CYc[i], CY[i]); COMPLEX_CONJUGATE (SYc[i], SY[i]); } /* Loop over data */ i = 0; for (idata=0; idata<args->nvis; idata++) { /* Parallactic angle terms */ chi1 = data[idata*10+0]; /* parallactic angle ant 1 */ chi2 = data[idata*10+1]; /* parallactic angle ant 2 */ COMPLEX_EXP (SPA,(chi1+chi2)); COMPLEX_EXP (DPA,chi1-chi2); COMPLEX_CONJUGATE (SPAc, SPA); COMPLEX_CONJUGATE (DPAc, DPA); isou = MAX (0, args->souNo[idata]); /* Source number */ /* New source? get parameters */ if (isou!=isouLast) { isouLast = isou; /* Source parameters */ ipol = souParm[isou*4+0]; /* Fitting or fixed? */ if (args->souFit[isou][1]) qpol = souParm[isou*4+1]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); qpol = PPol*ipol*cos(args->RLPhase[isou]);} if (args->souFit[isou][2]) upol = souParm[isou*4+2]; else { PPol = args->PPol[isou] + args->dPPol[isou]*(args->freq-args->refFreq); upol = PPol*ipol*sin(args->RLPhase[isou]);} vpol = souParm[isou*4+3]; /* Complex Stokes array */ COMPLEX_SET (S0[0], ipol+vpol, 0.0); COMPLEX_SET (S0[1], qpol, upol); COMPLEX_SET (S0[2], qpol, -upol); COMPLEX_SET (S0[3], ipol-vpol, 0.0); } /* Rotate Stokes by parallactic angle */ COMPLEX_MUL2(S[0], DPAc, S0[0]); COMPLEX_MUL2(S[1], SPAc, S0[1]); COMPLEX_MUL2(S[2], SPA, S0[2]); COMPLEX_MUL2(S[3], DPA, S0[3]); /* Antenna parameters */ ia1 = args->antNo[idata*2+0]; ia2 = args->antNo[idata*2+1]; /* i = datum number */ /* Loop over correlations calculating derivatives */ for (kk=0; kk<4; kk++) { switch (kk) { case 0: /* XX */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VXX = {S[0] * CX[ia1] * CXc[ia2] + S[1] * CX[ia1] * SXc[ia2] + S[2] * SX[ia1] * CXc[ia2] + S[3] * SX[ia1] * SXc[ia2]} * g1X * g2X ; */ COMPLEX_MUL2 (MC1, CX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+0]*antGain[ia2*2+0], 0); COMPLEX_MUL2 (VXX, ct5, ggPD); modelR = VXX.real; modelI = VXX.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt Ox1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gX[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RxxR wrt Ox1 */ gradI = DFDP.imag; /* RxxI wrt Ox1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI =0.0; /* Invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt Ex1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CXc[ia2] * SXc[ia1] - S[1] * SXc[ia2] * SXc[ia1] + S[2] * CXc[ia2] * CXc[ia1] + S[3] * SXc[ia2] * CXc[ia1]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], CXc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], SXc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], CXc[ia2], SXc[ia1]); COMPLEX_MUL3(ct4, S[3], SXc[ia2], CXc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RxxR wrt Ex1 */ gradI = DFDP.imag; /* RxxI wrt Ex1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XX wrt OY1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* XX wrt EY1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt Ox2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gX[ia1] * gX[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RxxR wrt Ox2 */ gradI = DFDP.imag; /* RxxI wrt Ox2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt Ex2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CX[ia1] * SX[ia2] + S[1] * CX[ia1] * CX[ia2] - S[2] * SX[ia1] * SX[ia2] + S[3] * SX[ia1] * CX[ia2]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], CX[ia1], SX[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], CX[ia1], CX[ia2]); COMPLEX_MUL3(ct5, S[2], SX[ia1], SX[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], SX[ia1], CX[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RxxR wrt Ox2 */ gradI = DFDP.imag; /* RxxI wrt Ox2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XX wrt Oy2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* XX wrt Ey2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt ipol */ gradI = DFDP.imag; /* RxxI wrt ipol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt qpol */ gradI = DFDP.imag; /* RxxI wrt qpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XX wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt upol */ gradI = DFDP.imag; /* RxxI wrt upol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* XX wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RxxR wrt vpol */ gradI = DFDP.imag; /* RxxI wrt vpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD = 0 */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* XX wrt gX1 */ /* Fitting? */ if (antGainFit[ia1][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia2] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+0], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RxxR wrt gX1 */ gradI = DFDP.imag; /* RxxI wrt gX1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XX wrt gX2 */ if (antGainFit[ia2][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RxxR wrt gX2 */ gradI = DFDP.imag; /* RxxI wrt gX2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ break; /* End XX */ case 1: /* YY */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VYY = {S[0] * SY[ia1] * SYc[ia2] + S[1] * SY[ia1] * CYc[ia2] + S[2] * CY[ia1] * SYc[ia2] + S[3] * CY[ia1] * CYc[ia2]} * g1Y * g2Y ; */ COMPLEX_MUL2 (MC1, SY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ggPD, antGain[ia1*2+1]*antGain[ia2*2+1], 0); COMPLEX_MUL2 (VYY, ct5, ggPD); modelR = VYY.real; modelI = VYY.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt Ox1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* YY wrt Ex1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* YY wrt Oy1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC2 + (0, 1) * S[3] * MC4} * gY[ia1] * gY[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RyyR wrt Oy1 */ gradI = DFDP.imag; /* RyyI wrt Oy1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YY wrt Ey1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SYc[ia2] * CYc[ia1] - S[1] * CYc[ia2] * CYc[ia1] + S[2] * SYc[ia2] * SYc[ia1] + S[3] * CYc[ia2] * SYc[ia1]} * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct5, S[0], SYc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CYc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SYc[ia2], SYc[ia1]); COMPLEX_MUL3(ct4, S[3], CYc[ia2], SYc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RyyR wrt Ey1 */ gradI = DFDP.imag; /* RyyI wrt Ey1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt Ox2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* YY wrt Ex2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* YY wrt Oy2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gY[ia2] */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; /* RyyR wrt Oy2 */ gradI = DFDP.imag; /* RyyI wrt Oy2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YY wrt Ey2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SY[ia1] * CY[ia2] + S[1] * SY[ia1] * SY[ia2] - S[2] * CY[ia1] * CY[ia2] + S[3] * CY[ia1] * SY[ia2]} * gY[ia1] * gY[ia2] */ COMPLEX_MUL3(ct5, S[0], SY[ia1], CY[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], SY[ia1], SY[ia2]); COMPLEX_MUL3(ct5, S[2], CY[ia1], CY[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], CY[ia1], SY[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; /* RyyR wrt Ey2 */ gradI = DFDP.imag; /* RyyI wrt Ey2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt ipol */ gradI = DFDP.imag; /* RyyI wrt ipol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YY wrt Qpol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt qpol */ gradI = DFDP.imag; /* RyyI wrt qpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* YY wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt upol */ gradI = DFDP.imag; /* RyyI wrt upol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YY wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyyR wrt vpol */ gradI = DFDP.imag; /* RyyI wrt vpol */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD - no effect */ if (args->doFitRL) { gradR = gradI = 0.0; j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* YY wrt gY1 */ /* Fitting? */ if (antGainFit[ia1][1]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+1], 0); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RyyR wrt gY1 */ gradI = DFDP.imag; /* RyyI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YY wrt gY2 */ if (antGainFit[ia2][1]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 1); COMPLEX_MUL2 (DFDP, ct1, ct2); gradR = DFDP.real; /* RyyR wrt gY2 */ gradI = DFDP.imag; /* RyyI wrt gY2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ break; /* End YY */ case 2: /* XY */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VXY = {S[0] * CX[ia1] * SYc[ia2] + S[1] * CX[ia1] * CYc[ia2] + S[2] * SX[ia1] * SYc[ia2] + S[3] * SX[ia1] * CYc[ia2]}} * g1X * g2Y * exp(j PD); */ COMPLEX_MUL2 (MC1, CX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC2, CX[ia1], CYc[ia2]); COMPLEX_MUL2 (MC3, SX[ia1], SYc[ia2]); COMPLEX_MUL2 (MC4, SX[ia1], CYc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+0]*antGain[ia2*2+1], 0); COMPLEX_EXP (ct2, PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VXY, ct5, ggPD); modelR = VXY.real; modelI = VXY.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt Ox1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XY wrt Ex1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SYc[ia2] * SXc[ia1] - S[1] * CYc[ia2] * SXc[ia1] + S[2] * SYc[ia2] * CXc[ia1] + S[3] * CYc[ia2] * CXc[ia1] } * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_MUL3(ct5, S[0], SYc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CYc[ia2], SXc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SYc[ia2], CXc[ia1]); COMPLEX_MUL3(ct4, S[3], CYc[ia2], CXc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XY wrt Oy1 =0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* XY wrt Ey1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt Ox2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* XY wrt Ex2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* XYwrt Oy2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* XY wrt Ey2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CX[ia1] * CY[ia2] + S[1] * CX[ia1] * SY[ia2] - S[2] * SX[ia1] * CY[ia2] + S[3] * SX[ia1] * SY[ia2]} * gX[ia1] * gY[ia2] * exp(j PD) */ COMPLEX_MUL3(ct5, S[0], CX[ia1], CY[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], CX[ia1], SY[ia2]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], SX[ia1], CY[ia2]); COMPLEX_MUL3(ct4, S[3], SX[ia1], SY[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XY wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* XY wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; gradR = -gradR; gradI = -gradI; /* DEBUG why does this help??? */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* XY wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; /* RyxR wrt gY1 */ gradI = DFDP.imag; /* RyxI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { /* part = (0, 1) * VXY */ COMPLEX_MUL2 (DFDP, Jp, VXY); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* XY wrt gX1 */ /* Fitting? */ if (antGainFit[ia1][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia2] * exp(j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia2*2+1], 0); COMPLEX_EXP (ct3, PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RxyR wrt gX1 */ gradI = DFDP.imag; /* RxyI wrt gX1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* XY wrt gY2 */ if (antGainFit[ia2][1]) { if (wt[idata*4+kk]>0.0) { /* part = {S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gX[ia1] * exp(j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+0], 0); COMPLEX_EXP (ct3, PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RxyR wrt gY2 */ gradI = DFDP.imag; /* RxyI wrt gY2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ break; /* End XY */ case 3: /* YX */ if (wt[idata*4+kk]>0.0) { isigma = wt[idata*4+kk]; /* VYX = {S[0] * SY[ia1] * CXc[ia2] + S[1] * SY[ia1] * SXc[ia2] + S[2] * CY[ia1] * CXc[ia2] + S[3] * CY[ia1] * SXc[ia2]} * g1Y * g2X * exp(-j PD) */ COMPLEX_MUL2 (MC1, SY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC2, SY[ia1], SXc[ia2]); COMPLEX_MUL2 (MC3, CY[ia1], CXc[ia2]); COMPLEX_MUL2 (MC4, CY[ia1], SXc[ia2]); COMPLEX_MUL2 (SM1, S[0], MC1); COMPLEX_MUL2 (SM2, S[1], MC2); COMPLEX_MUL2 (SM3, S[2], MC3); COMPLEX_MUL2 (SM4, S[3], MC4); COMPLEX_ADD4 (ct5, SM1, SM2, SM3, SM4); COMPLEX_SET (ct1, antGain[ia1*2+1]*antGain[ia2*2+0], 0); COMPLEX_EXP (ct2, -PD); COMPLEX_MUL2 (ggPD, ct1, ct2); COMPLEX_MUL2 (VYX, ct5, ggPD); modelR = VYX.real; modelI = VYX.imag; residR = modelR - data[idata*10+(kk+1)*2]; residI = modelI - data[idata*10+(kk+1)*2+1]; gsl_vector_set(f, i*2, residR*isigma); /* Save function resids */ gsl_vector_set(f, i*2+1, residI*isigma); /* Save function resids */ } else residR = residI = 0.0; /* Invalid data */ /* Loop over first antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt Ox1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 1: /* YX wrt Ex1 = 0 */ /* Fitting? */ if (antFit[ia1][k]) { gradR = gradI = 0.0; j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 2: /* YX wrt Oy1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, -1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + ( 0, 1) * S[2] * MC3 + (0, 1) * S[3] * MC4} * gX[ia1] * gY[ia2] * exp(-j PD) */ COMPLEX_ADD2 (ct1, SM1, SM2); COMPLEX_MUL2 (ct2, Jm, ct1); COMPLEX_ADD2 (ct1, SM3, SM4); COMPLEX_MUL2 (ct3, Jp, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YX wrt Ey1 */ /* Fitting? */ if (antFit[ia1][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * CXc[ia2] * CYc[ia1] - S[1] * SXc[ia2] * CYc[ia1] + S[2] * CXc[ia2] * SYc[ia1] + S[3] * SXc[ia2] * SYc[ia1]} * gY[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL3(ct5, S[0], CXc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct5, S[1], SXc[ia2], CYc[ia1]); COMPLEX_NEGATE(ct2, ct5); COMPLEX_MUL3(ct3, S[2], CXc[ia2], SYc[ia1]); COMPLEX_MUL3(ct4, S[3], SXc[ia2], SYc[ia1]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia1][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end first antenna parameter switch */ } /* end loop over first antenna parameters */ /* Loop over second antenna parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt Ox2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {(0, 1) * S[0] * MC1 + (0, -1) * S[1] * MC2 + (0, 1) * S[2] * MC3 + (0, -1) * S[3] * MC4} * gY[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_ADD2 (ct1, SM1, SM3); COMPLEX_MUL2 (ct2, Jp, ct1); COMPLEX_ADD2 (ct1, SM2, SM4); COMPLEX_MUL2 (ct3, Jm, ct1); COMPLEX_ADD2 (ct2, ct2, ct3); COMPLEX_MUL2 (DFDP, ct2, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YX wrt Ex2 */ /* Fitting? */ if (antFit[ia2][k]) { if (wt[idata*4+kk]>0.0) { /* part = {-S[0] * SY[ia1] * SX[ia2] + S[1] * SY[ia1] * CX[ia2] - S[2] * CY[ia1] * SX[ia2] + S[3] * CY[ia1] * CX[ia2]} * gY[ia1] * gX[ia2] * exp(-j PD)*/ COMPLEX_MUL3(ct5, S[0], SY[ia1], SX[ia2]); COMPLEX_NEGATE(ct1, ct5); COMPLEX_MUL3(ct2, S[1], SY[ia1], CX[ia2]); COMPLEX_MUL3(ct5, S[2], CY[ia1], SX[ia2]); COMPLEX_NEGATE(ct3, ct5); COMPLEX_MUL3(ct4, S[3], CY[ia1], CX[ia2]); COMPLEX_ADD4(ct5, ct1, ct2, ct3, ct4); COMPLEX_MUL2(DFDP, ct5, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* YX wrt Oy2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; case 3: /* YX wrt Ey2 = 0 */ /* Fitting? */ if (antFit[ia2][k]) { gradR = gradI = 0.0; j = antPNumb[ia2][k]; gsl_matrix_set(J, i*2, j, gradR); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI); /* Save Jacobian */ } break; default: break; }; /* end second antenna parameter switch */ } /* end loop over second antenna parameters */ /* Loop over source parameters */ for (k=0; k<4; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt IPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC1*DPAc + MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YX wrt QPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* part = (MC2*SPAc + MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC2, SPAc); COMPLEX_MUL2(ct3, MC3, SPA); COMPLEX_ADD2(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 2: /* YX wrt UPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (j MC2*SPAc - j MC3*SPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL3(ct2, Jp, MC2, SPAc); COMPLEX_MUL3(ct3, Jp, MC3, SPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; gradR = -gradR; gradI = -gradI; /* DEBUG why does this help??? */ /*gradR = gradI = 0.0; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 3: /* YX wrt VPol */ /* Fitting? */ if (souFit[isou][k]) { if (wt[idata*4+kk]>0.0) { /* (MC1*DPAc - MC4*DPA) * gX[ia1] * gX[ia2] * exp(-j PD) */ COMPLEX_MUL2(ct2, MC1, DPAc); COMPLEX_MUL2(ct3, MC4, DPA); COMPLEX_SUB(ct1, ct2, ct3); COMPLEX_MUL2(DFDP, ct1, ggPD); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = souPNumb[isou][k]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end source parameter switch */ } /* end loop over source parameters */ /* gradient wrt PD */ if (args->doFitRL) { if (wt[idata*4+kk]>0.0) { /* part = (0, -1) * VYX */ COMPLEX_MUL2 (DFDP, Jm, VYX); gradR = DFDP.real; gradI = DFDP.imag; /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = args->PDPNumb; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } /* Loop over antenna gains */ for (k=0; k<2; k++) { switch (k) { /* Switch over parameter */ case 0: /* YX wrt gY1 */ /* Fitting? */ if (antGainFit[ia1][1]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] * exp(-j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+1], 0); COMPLEX_EXP (ct3, -PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RyxR wrt gY1 */ gradI = DFDP.imag; /* RyxI wrt gY1 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia1][1]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; case 1: /* YX wrt gX2 */ if (antGainFit[ia2][0]) { if (wt[idata*4+kk]>0.0) { /* part = (S[0]*MC1 + S[1]*MC2 + S[2]*MC3 + S[3]*MC4) * gY[ia1] * exp(-j PD) */ COMPLEX_ADD4(ct1, SM1, SM2, SM3, SM4); COMPLEX_SET (ct2, antGain[ia1*2+1], 0); COMPLEX_EXP (ct3, -PD); COMPLEX_MUL3 (DFDP, ct1, ct2, ct3); gradR = DFDP.real; /* RyxR wrt gX2 */ gradI = DFDP.imag; /* RyxI wrt gX2 */ /*gradR = -gradR; gradI = -gradI; DEBUG */ } else gradR = gradI = 0.0; /* invalid data */ j = antGainPNumb[ia2][0]; gsl_matrix_set(J, i*2, j, gradR*isigma); /* Save Jacobian */ gsl_matrix_set(J, i*2+1, j, gradI*isigma); /* Save Jacobian */ } break; default: break; }; /* end gain switch */ } /* end loop over gains */ /* End YX */ default: break; }; /* end switch over data correlation */ i++; /* Update complex datum number */ } /* end loop over correlations */ } /* End loop over visibilities */ return GSL_SUCCESS; } /* end PolnFitFuncJacOEXY */ #endif /* HAVE_GSL */
{ "alphanum_fraction": 0.5543792657, "avg_line_length": 35.2907211075, "ext": "c", "hexsha": "f697932a75854d23bb9b36ebc38c6cfef5235876", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "kettenis/Obit", "max_forks_repo_path": "ObitSystem/Obit/src/ObitPolnCalFit.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "kettenis/Obit", "max_issues_repo_path": "ObitSystem/Obit/src/ObitPolnCalFit.c", "max_line_length": 180, "max_stars_count": null, "max_stars_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "kettenis/Obit", "max_stars_repo_path": "ObitSystem/Obit/src/ObitPolnCalFit.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 159772, "size": 402773 }
#include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "regional.h" void init_weights(t_stochasticity_grid *g) { /* The weights will be normalized s.t. the sum of squared weights is one */ g->weights[0] = 1.0; double sum = 1.0; for (int i = 1; i<g->depth; i++) { double val = g->weights[i-1] / g->weight_factor; g->weights[i] = val; sum += val*val; } double N = sqrt(sum); for (int i = 0; i < g->depth; i++) { g->weights[i] /= N; } } /* 'arr' should point to a double array of size at least height*width. */ t_stochasticity_grid *create_stochasticity_grid(double *arr, int height, int width, double weight_factor, double mean, double stddev, long int seed) { t_stochasticity_grid *g = malloc( sizeof(t_stochasticity_grid) ); g->arr = arr; g->height = height; g->width = width; /* It is best to use array dimensions of power of 2 */ int d = height > width ? height : width; // Take the max g->depth = ceil(log2(d)) + 1; g->stddev = stddev; g->mean = mean; g->weight_factor = weight_factor; g->rng = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(g->rng, seed); g->weights = malloc( sizeof(double) * g->depth ); init_weights(g); return g; } void free_stochasticity_grid(t_stochasticity_grid *g) { gsl_rng_free(g->rng); free(g->weights); g->weights = NULL; g->arr = NULL; free(g); } static inline double gaussian(const gsl_rng *rng, double stddev) { return gsl_ran_gaussian_ziggurat(rng, stddev); } void fill_quadrant(const t_stochasticity_grid *g, int y0, int x0, int y1, int x1, int level) { double weight = g->weights[level]; double rval = gaussian(g->rng, g->stddev); for(int i = y0; i < y1; i++) { for(int j = x0; j < x1; j++) { int offset = i * g->width + j; double val = rval*weight; g->arr[offset] += val; } } } void recursive_division(const t_stochasticity_grid *g, int level, int y0, int x0, int y1, int x1) { if (level >= g->depth) return; if (x1-x0 == 1 && y1-y0 == 1) return; // Skip 1x1 grids if (y0 >= y1) return; if (x0 >= x1) return; //printf("Depth: %i. (%i, %i, %i, %i)\n", level, y0, x0, y1, x1); fill_quadrant(g, y0, x0, y1, x1, level); if (level + 1 == g->depth) return; // Avoid unnecessary recursion; skip level with 1x1 grids int ydist = (y1-y0)/2.0 + 0.5; int xdist = (x1-x0)/2.0 + 0.5; int ymid = y0+ydist; int xmid = x0+xdist; /* Upper left */ recursive_division(g, level+1, y0, x0, ymid, xmid); /* Upper right */ recursive_division(g, level+1, ymid, x0, y1, xmid); /* Bottom left */ recursive_division(g, level+1, y0, xmid, ymid, x1); /* Bottom right */ recursive_division(g, level+1, ymid, xmid, y1, x1); } /** Generate spatially autocorrelated coefficients using a recursive quadtree subdivision. The pointer 'arr' is a 2-dimensional output array of size 'height' * 'width'. The variable 'variance' gives the variance of the log-norm distribution with mean and cut-off at 1.0. */ void generate_stochasticity(t_stochasticity_grid *g) { /* Initialize the array by generating the last level (i.e., 1x1 grids) */ for(int i = 0; i < g->height; i++) { for(int j = 0; j < g->width; j++) { double weight = g->weights[g->depth-1]; g->arr[i*g->width + j] = weight*gaussian(g->rng, g->stddev); } } recursive_division(g, 0, 0, 0, g->height, g->width); for(int i = 0; i < g->height; i++) { for(int j = 0; j < g->width; j++) { double y = g->arr[i*g->width + j]; y = exp(y + g->mean); if (y > 1.0) y = 1.0; g->arr[i*g->width + j] = y; } } }
{ "alphanum_fraction": 0.5639989902, "avg_line_length": 30.4692307692, "ext": "c", "hexsha": "b873455e0f118fa1d6d577cfa59ee13101e2e346", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rybicki/corridor-spom", "max_forks_repo_path": "passive/spom/model/src/regional.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rybicki/corridor-spom", "max_issues_repo_path": "passive/spom/model/src/regional.c", "max_line_length": 151, "max_stars_count": null, "max_stars_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rybicki/corridor-spom", "max_stars_repo_path": "passive/spom/model/src/regional.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1231, "size": 3961 }
#pragma once #if SEAL_COMPILER == SEAL_COMPILER_GCC // We require GCC >= 6 #if (__GNUC__ < 6) || not defined(__cplusplus) #error "SEAL requires __GNUC__ >= 6" #endif // Read in config.h #include "config.h" // Are we using MSGSL? #ifdef SEAL_USE_MSGSL #include <gsl/gsl> #endif // Are intrinsics enabled? #ifdef SEAL_USE_INTRIN #include <x86intrin.h> #ifdef SEAL_USE___BUILTIN_CLZLL #define SEAL_MSB_INDEX_UINT64(result, value) { \ *result = 63 - __builtin_clzll(value); \ } #endif #ifdef SEAL_USE___INT128 #define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) { \ *hw64 = static_cast<uint64_t>((static_cast<unsigned __int128>(operand1) \ * static_cast<unsigned __int128>(operand2)) >> 64); \ } #define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) { \ unsigned __int128 product = static_cast<unsigned __int128>(operand1) * operand2;\ result128[0] = static_cast<uint64_t>(product); \ result128[1] = product >> 64; \ } #endif #ifdef SEAL_USE__ADDCARRY_U64 #define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64( \ carry, \ static_cast<unsigned long long>(operand1), \ static_cast<unsigned long long>(operand2), \ reinterpret_cast<unsigned long long*>(result)) #endif #ifdef SEAL_USE__SUBBORROW_U64 #if ((__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)) || (__GNUC__ >= 8) // The inverted arguments problem was fixed in GCC-7.2 // (https://patchwork.ozlabs.org/patch/784309/) #define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64( \ borrow, \ static_cast<unsigned long long>(operand1), \ static_cast<unsigned long long>(operand2), \ reinterpret_cast<unsigned long long*>(result)) #else // Warning: Note the inverted order of operand1 and operand2 #define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64( \ borrow, \ static_cast<unsigned long long>(operand2), \ static_cast<unsigned long long>(operand1), \ reinterpret_cast<unsigned long long*>(result)) #endif //(__GNUC__ == 7) && (__GNUC_MINOR__ >= 2) #endif #endif //SEAL_USE_INTRIN #endif
{ "alphanum_fraction": 0.5468526466, "avg_line_length": 39.9428571429, "ext": "h", "hexsha": "1b2d4390f306d35eb8480635069e3cc80ca828c2", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-11-26T02:31:56.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-29T10:15:40.000Z", "max_forks_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MarbleHE/SEAL4Pyfhel", "max_forks_repo_path": "SEAL/seal2/gcc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "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": "MarbleHE/SEAL4Pyfhel", "max_issues_repo_path": "SEAL/seal2/gcc.h", "max_line_length": 85, "max_stars_count": 2, "max_stars_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MarbleHE/SEAL4Pyfhel", "max_stars_repo_path": "SEAL/seal2/gcc.h", "max_stars_repo_stars_event_max_datetime": "2020-12-27T06:25:36.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-19T17:09:42.000Z", "num_tokens": 605, "size": 2796 }
/* fft/bitreverse.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_fft.h> #include "complex_internal.h" #include "bitreverse.h" static int FUNCTION(fft_complex,bitreverse_order) (BASE data[], const size_t stride, const size_t n, size_t logn) { /* This is the Goldrader bit-reversal algorithm */ size_t i; size_t j = 0; logn = 0 ; /* not needed for this algorithm */ for (i = 0; i < n - 1; i++) { size_t k = n / 2 ; if (i < j) { const BASE tmp_real = REAL(data,stride,i); const BASE tmp_imag = IMAG(data,stride,i); REAL(data,stride,i) = REAL(data,stride,j); IMAG(data,stride,i) = IMAG(data,stride,j); REAL(data,stride,j) = tmp_real; IMAG(data,stride,j) = tmp_imag; } while (k <= j) { j = j - k ; k = k / 2 ; } j += k ; } return 0; } static int FUNCTION(fft_real,bitreverse_order) (BASE data[], const size_t stride, const size_t n, size_t logn) { /* This is the Goldrader bit-reversal algorithm */ size_t i; size_t j = 0; logn = 0 ; /* not needed for this algorithm */ for (i = 0; i < n - 1; i++) { size_t k = n / 2 ; if (i < j) { const BASE tmp = VECTOR(data,stride,i); VECTOR(data,stride,i) = VECTOR(data,stride,j); VECTOR(data,stride,j) = tmp; } while (k <= j) { j = j - k ; k = k / 2 ; } j += k ; } return 0; }
{ "alphanum_fraction": 0.5387058356, "avg_line_length": 24.6960784314, "ext": "c", "hexsha": "15e0e8a2510e862a741cabdd8a25b5910a3f19e9", "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/fft/bitreverse.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/fft/bitreverse.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/fft/bitreverse.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": 657, "size": 2519 }
#pragma once #include "schedule.h" #include <boost/random/uniform_01.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <gsl/gsl-lite.hpp> #include <pcg_random.hpp> #include <random> namespace angonoka::stun { using RandomEngine = pcg32; /** Miscellaneous random number generators. */ class RandomUtils { public: /** Default constructor. */ RandomUtils(); /** Constructor with a fixed PRNG seed. @param seed Random engine seed */ RandomUtils(gsl::index seed); /** Uniformally distributed real value between 0 and 1. @return Random number */ float uniform_01() noexcept; /** Uniformally distributed discrete value between 0 and max. @param max Maximum value @return Random number */ int16 uniform_int(int16 max) noexcept; private: RandomEngine generator{ pcg_extras::seed_seq_from<std::random_device>{}}; boost::random::uniform_01<float> uniform_01_; boost::random::uniform_int_distribution<std::int_fast16_t> uniform_int_; }; } // namespace angonoka::stun
{ "alphanum_fraction": 0.6663708962, "avg_line_length": 20.8703703704, "ext": "h", "hexsha": "f315cd7ba8c20b4d10e612b92c08fa84d6821e1b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_path": "src/stun/random_utils.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_path": "src/stun/random_utils.h", "max_line_length": 65, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_path": "src/stun/random_utils.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "num_tokens": 258, "size": 1127 }
#undef FP_T #undef FP_ID #undef VECTOR_T #undef VECTOR_ID #undef MATRIX_T #undef MATRIX_ID #ifdef GSL_FLOAT #define MATLAB_NAMESPACE matlab_float #define BCT_NAMESPACE bct_float #define FP_T float #define FP_ID(id) id##_##float #define VECTOR_T gsl_vector_float #define VECTOR_ID(id) gsl_vector_float##_##id #define MATRIX_T gsl_matrix_float #define MATRIX_ID(id) gsl_matrix_float##_##id #include <gsl/gsl_matrix_float.h> #include <gsl/gsl_vector_float.h> #endif #ifdef GSL_DOUBLE #define MATLAB_NAMESPACE matlab #define BCT_NAMESPACE bct #define FP_T double #define FP_ID(id) id##_##double #define VECTOR_T gsl_vector #define VECTOR_ID(id) gsl_vector##_##id #define MATRIX_T gsl_matrix #define MATRIX_ID(id) gsl_matrix##_##id #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #endif #ifdef GSL_LONG_DOUBLE #define MATLAB_NAMESPACE matlab_long_double #define BCT_NAMESPACE bct_long_double #define FP_T long double #define FP_ID(id) id##_##long_double #define VECTOR_T gsl_vector_long_double #define VECTOR_ID(id) gsl_vector_long_double##_##id #define MATRIX_T gsl_matrix_long_double #define MATRIX_ID(id) gsl_matrix_long_double##_##id #include <gsl/gsl_matrix_long_double.h> #include <gsl/gsl_vector_long_double.h> #endif
{ "alphanum_fraction": 0.8139723802, "avg_line_length": 26.7608695652, "ext": "h", "hexsha": "582a96f20e3931fc048d90b2b5304cf0b2bd815c", "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": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "devuci/bct-cpp", "max_forks_repo_path": "precision.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "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": "devuci/bct-cpp", "max_issues_repo_path": "precision.h", "max_line_length": 51, "max_stars_count": null, "max_stars_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "devuci/bct-cpp", "max_stars_repo_path": "precision.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 306, "size": 1231 }
/* vector/gsl_vector_long.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_LONG_H__ #define __GSL_VECTOR_LONG_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_long.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; long *data; gsl_block_long *block; int owner; } gsl_vector_long; typedef struct { gsl_vector_long vector; } _gsl_vector_long_view; typedef _gsl_vector_long_view gsl_vector_long_view; typedef struct { gsl_vector_long vector; } _gsl_vector_long_const_view; typedef const _gsl_vector_long_const_view gsl_vector_long_const_view; /* Allocation */ GSL_EXPORT gsl_vector_long *gsl_vector_long_alloc (const size_t n); GSL_EXPORT gsl_vector_long *gsl_vector_long_calloc (const size_t n); GSL_EXPORT gsl_vector_long *gsl_vector_long_alloc_from_block (gsl_block_long * b, const size_t offset, const size_t n, const size_t stride); GSL_EXPORT gsl_vector_long *gsl_vector_long_alloc_from_vector (gsl_vector_long * v, const size_t offset, const size_t n, const size_t stride); GSL_EXPORT void gsl_vector_long_free (gsl_vector_long * v); /* Views */ GSL_EXPORT _gsl_vector_long_view gsl_vector_long_view_array (long *v, size_t n); GSL_EXPORT _gsl_vector_long_view gsl_vector_long_view_array_with_stride (long *base, size_t stride, size_t n); GSL_EXPORT _gsl_vector_long_const_view gsl_vector_long_const_view_array (const long *v, size_t n); GSL_EXPORT _gsl_vector_long_const_view gsl_vector_long_const_view_array_with_stride (const long *base, size_t stride, size_t n); GSL_EXPORT _gsl_vector_long_view gsl_vector_long_subvector (gsl_vector_long *v, size_t i, size_t n); GSL_EXPORT _gsl_vector_long_view gsl_vector_long_subvector_with_stride (gsl_vector_long *v, size_t i, size_t stride, size_t n); GSL_EXPORT _gsl_vector_long_const_view gsl_vector_long_const_subvector (const gsl_vector_long *v, size_t i, size_t n); GSL_EXPORT _gsl_vector_long_const_view gsl_vector_long_const_subvector_with_stride (const gsl_vector_long *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_EXPORT long gsl_vector_long_get (const gsl_vector_long * v, const size_t i); GSL_EXPORT void gsl_vector_long_set (gsl_vector_long * v, const size_t i, long x); GSL_EXPORT long *gsl_vector_long_ptr (gsl_vector_long * v, const size_t i); GSL_EXPORT const long *gsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i); GSL_EXPORT void gsl_vector_long_set_zero (gsl_vector_long * v); GSL_EXPORT void gsl_vector_long_set_all (gsl_vector_long * v, long x); GSL_EXPORT int gsl_vector_long_set_basis (gsl_vector_long * v, size_t i); GSL_EXPORT int gsl_vector_long_fread (FILE * stream, gsl_vector_long * v); GSL_EXPORT int gsl_vector_long_fwrite (FILE * stream, const gsl_vector_long * v); GSL_EXPORT int gsl_vector_long_fscanf (FILE * stream, gsl_vector_long * v); GSL_EXPORT int gsl_vector_long_fprintf (FILE * stream, const gsl_vector_long * v, const char *format); GSL_EXPORT int gsl_vector_long_memcpy (gsl_vector_long * dest, const gsl_vector_long * src); GSL_EXPORT int gsl_vector_long_reverse (gsl_vector_long * v); GSL_EXPORT int gsl_vector_long_swap (gsl_vector_long * v, gsl_vector_long * w); GSL_EXPORT int gsl_vector_long_swap_elements (gsl_vector_long * v, const size_t i, const size_t j); GSL_EXPORT long gsl_vector_long_max (const gsl_vector_long * v); GSL_EXPORT long gsl_vector_long_min (const gsl_vector_long * v); GSL_EXPORT void gsl_vector_long_minmax (const gsl_vector_long * v, long * min_out, long * max_out); GSL_EXPORT size_t gsl_vector_long_max_index (const gsl_vector_long * v); GSL_EXPORT size_t gsl_vector_long_min_index (const gsl_vector_long * v); GSL_EXPORT void gsl_vector_long_minmax_index (const gsl_vector_long * v, size_t * imin, size_t * imax); GSL_EXPORT int gsl_vector_long_add (gsl_vector_long * a, const gsl_vector_long * b); GSL_EXPORT int gsl_vector_long_sub (gsl_vector_long * a, const gsl_vector_long * b); GSL_EXPORT int gsl_vector_long_mul (gsl_vector_long * a, const gsl_vector_long * b); GSL_EXPORT int gsl_vector_long_div (gsl_vector_long * a, const gsl_vector_long * b); GSL_EXPORT int gsl_vector_long_scale (gsl_vector_long * a, const double x); GSL_EXPORT int gsl_vector_long_add_constant (gsl_vector_long * a, const double x); GSL_EXPORT int gsl_vector_long_isnull (const gsl_vector_long * v); #ifdef HAVE_INLINE extern inline long gsl_vector_long_get (const gsl_vector_long * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } extern inline void gsl_vector_long_set (gsl_vector_long * v, const size_t i, long x) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } extern inline long * gsl_vector_long_ptr (gsl_vector_long * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (long *) (v->data + i * v->stride); } extern inline const long * gsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const long *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_LONG_H__ */
{ "alphanum_fraction": 0.6750873421, "avg_line_length": 31.6680851064, "ext": "h", "hexsha": "cc1ee2d75ff1faa20fc278bcd8e5d513baeaa5c5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_long.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_long.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_long.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1767, "size": 7442 }
#ifndef bfkl_H_INCLUDED #define bfkl_H_INCLUDED #include <stdio.h> #include <math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "cubature.h" #include "string.h" #include "alphas.h" #include "wf.h" //number of tabulated points in z and x for BFKL Kernel #define Nz 94 #define Nx 1201 #define Nhar 24 #define ZMIN (0.15) #define ZMAX (4.8) #define XMAX (100.00) void ReadInBFKL(); double BFKLfunc(double z, double x, int n); double d2N_BFKL(double pT, double qT, double phi, double yp, double yq, double rts); struct bfkl_params { double pT; double qT; double phi; double x1, x2; double dy; } ; #endif
{ "alphanum_fraction": 0.7179856115, "avg_line_length": 19.3055555556, "ext": "h", "hexsha": "13ff8d1013a1cae53b1bfafa8d6d7f3ad59369c7", "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": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_path": "src/bfkl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "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": "kdusling/mpc", "max_issues_repo_path": "src/bfkl.h", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_path": "src/bfkl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 220, "size": 695 }
/* randist/gsl_randist.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_RANDIST_H__ #define __GSL_RANDIST_H__ #include <gsl/gsl_rng.h> #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 unsigned int gsl_ran_bernoulli (const gsl_rng * r, double p); GSL_EXPORT double gsl_ran_bernoulli_pdf (const unsigned int k, double p); GSL_EXPORT double gsl_ran_beta (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_beta_pdf (const double x, const double a, const double b); GSL_EXPORT unsigned int gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n); GSL_EXPORT unsigned int gsl_ran_binomial_knuth (const gsl_rng * r, double p, unsigned int n); GSL_EXPORT unsigned int gsl_ran_binomial_tpe (const gsl_rng * r, double p, unsigned int n); GSL_EXPORT double gsl_ran_binomial_pdf (const unsigned int k, const double p, const unsigned int n); GSL_EXPORT double gsl_ran_exponential (const gsl_rng * r, const double mu); GSL_EXPORT double gsl_ran_exponential_pdf (const double x, const double mu); GSL_EXPORT double gsl_ran_exppow (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_exppow_pdf (const double x, const double a, const double b); GSL_EXPORT double gsl_ran_cauchy (const gsl_rng * r, const double a); GSL_EXPORT double gsl_ran_cauchy_pdf (const double x, const double a); GSL_EXPORT double gsl_ran_chisq (const gsl_rng * r, const double nu); GSL_EXPORT double gsl_ran_chisq_pdf (const double x, const double nu); GSL_EXPORT void gsl_ran_dirichlet (const gsl_rng * r, const size_t K, const double alpha[], double theta[]); GSL_EXPORT double gsl_ran_dirichlet_pdf (const size_t K, const double alpha[], const double theta[]); GSL_EXPORT double gsl_ran_dirichlet_lnpdf (const size_t K, const double alpha[], const double theta[]); GSL_EXPORT double gsl_ran_erlang (const gsl_rng * r, const double a, const double n); GSL_EXPORT double gsl_ran_erlang_pdf (const double x, const double a, const double n); GSL_EXPORT double gsl_ran_fdist (const gsl_rng * r, const double nu1, const double nu2); GSL_EXPORT double gsl_ran_fdist_pdf (const double x, const double nu1, const double nu2); GSL_EXPORT double gsl_ran_flat (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_flat_pdf (double x, const double a, const double b); GSL_EXPORT double gsl_ran_gamma (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_gamma_int (const gsl_rng * r, const unsigned int a); GSL_EXPORT double gsl_ran_gamma_pdf (const double x, const double a, const double b); GSL_EXPORT double gsl_ran_gamma_mt (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_gaussian (const gsl_rng * r, const double sigma); GSL_EXPORT double gsl_ran_gaussian_ratio_method (const gsl_rng * r, const double sigma); GSL_EXPORT double gsl_ran_gaussian_ziggurat (const gsl_rng * r, const double sigma); GSL_EXPORT double gsl_ran_gaussian_pdf (const double x, const double sigma); GSL_EXPORT double gsl_ran_ugaussian (const gsl_rng * r); GSL_EXPORT double gsl_ran_ugaussian_ratio_method (const gsl_rng * r); GSL_EXPORT double gsl_ran_ugaussian_pdf (const double x); GSL_EXPORT double gsl_ran_gaussian_tail (const gsl_rng * r, const double a, const double sigma); GSL_EXPORT double gsl_ran_gaussian_tail_pdf (const double x, const double a, const double sigma); GSL_EXPORT double gsl_ran_ugaussian_tail (const gsl_rng * r, const double a); GSL_EXPORT double gsl_ran_ugaussian_tail_pdf (const double x, const double a); GSL_EXPORT void gsl_ran_bivariate_gaussian (const gsl_rng * r, double sigma_x, double sigma_y, double rho, double *x, double *y); GSL_EXPORT double gsl_ran_bivariate_gaussian_pdf (const double x, const double y, const double sigma_x, const double sigma_y, const double rho); GSL_EXPORT double gsl_ran_landau (const gsl_rng * r); GSL_EXPORT double gsl_ran_landau_pdf (const double x); GSL_EXPORT unsigned int gsl_ran_geometric (const gsl_rng * r, const double p); GSL_EXPORT double gsl_ran_geometric_pdf (const unsigned int k, const double p); GSL_EXPORT unsigned int gsl_ran_hypergeometric (const gsl_rng * r, unsigned int n1, unsigned int n2, unsigned int t); GSL_EXPORT double gsl_ran_hypergeometric_pdf (const unsigned int k, const unsigned int n1, const unsigned int n2, unsigned int t); GSL_EXPORT double gsl_ran_gumbel1 (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_gumbel1_pdf (const double x, const double a, const double b); GSL_EXPORT double gsl_ran_gumbel2 (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_gumbel2_pdf (const double x, const double a, const double b); GSL_EXPORT double gsl_ran_logistic (const gsl_rng * r, const double a); GSL_EXPORT double gsl_ran_logistic_pdf (const double x, const double a); GSL_EXPORT double gsl_ran_lognormal (const gsl_rng * r, const double zeta, const double sigma); GSL_EXPORT double gsl_ran_lognormal_pdf (const double x, const double zeta, const double sigma); GSL_EXPORT unsigned int gsl_ran_logarithmic (const gsl_rng * r, const double p); GSL_EXPORT double gsl_ran_logarithmic_pdf (const unsigned int k, const double p); GSL_EXPORT void gsl_ran_multinomial (const gsl_rng * r, const size_t K, const unsigned int N, const double p[], unsigned int n[] ); GSL_EXPORT double gsl_ran_multinomial_pdf (const size_t K, const double p[], const unsigned int n[] ); GSL_EXPORT double gsl_ran_multinomial_lnpdf (const size_t K, const double p[], const unsigned int n[] ); GSL_EXPORT unsigned int gsl_ran_negative_binomial (const gsl_rng * r, double p, double n); GSL_EXPORT double gsl_ran_negative_binomial_pdf (const unsigned int k, const double p, double n); GSL_EXPORT unsigned int gsl_ran_pascal (const gsl_rng * r, double p, unsigned int n); GSL_EXPORT double gsl_ran_pascal_pdf (const unsigned int k, const double p, unsigned int n); GSL_EXPORT double gsl_ran_pareto (const gsl_rng * r, double a, const double b); GSL_EXPORT double gsl_ran_pareto_pdf (const double x, const double a, const double b); GSL_EXPORT unsigned int gsl_ran_poisson (const gsl_rng * r, double mu); GSL_EXPORT void gsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[], double mu); GSL_EXPORT double gsl_ran_poisson_pdf (const unsigned int k, const double mu); GSL_EXPORT double gsl_ran_rayleigh (const gsl_rng * r, const double sigma); GSL_EXPORT double gsl_ran_rayleigh_pdf (const double x, const double sigma); GSL_EXPORT double gsl_ran_rayleigh_tail (const gsl_rng * r, const double a, const double sigma); GSL_EXPORT double gsl_ran_rayleigh_tail_pdf (const double x, const double a, const double sigma); GSL_EXPORT double gsl_ran_tdist (const gsl_rng * r, const double nu); GSL_EXPORT double gsl_ran_tdist_pdf (const double x, const double nu); GSL_EXPORT double gsl_ran_laplace (const gsl_rng * r, const double a); GSL_EXPORT double gsl_ran_laplace_pdf (const double x, const double a); GSL_EXPORT double gsl_ran_levy (const gsl_rng * r, const double c, const double alpha); GSL_EXPORT double gsl_ran_levy_skew (const gsl_rng * r, const double c, const double alpha, const double beta); GSL_EXPORT double gsl_ran_weibull (const gsl_rng * r, const double a, const double b); GSL_EXPORT double gsl_ran_weibull_pdf (const double x, const double a, const double b); GSL_EXPORT void gsl_ran_dir_2d (const gsl_rng * r, double * x, double * y); GSL_EXPORT void gsl_ran_dir_2d_trig_method (const gsl_rng * r, double * x, double * y); GSL_EXPORT void gsl_ran_dir_3d (const gsl_rng * r, double * x, double * y, double * z); GSL_EXPORT void gsl_ran_dir_nd (const gsl_rng * r, size_t n, double * x); GSL_EXPORT void gsl_ran_shuffle (const gsl_rng * r, void * base, size_t nmembm, size_t size); GSL_EXPORT int gsl_ran_choose (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ; GSL_EXPORT void gsl_ran_sample (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ; typedef struct { /* struct for Walker algorithm */ size_t K; size_t *A; double *F; } gsl_ran_discrete_t; GSL_EXPORT gsl_ran_discrete_t * gsl_ran_discrete_preproc (size_t K, const double *P); GSL_EXPORT void gsl_ran_discrete_free(gsl_ran_discrete_t *g); GSL_EXPORT size_t gsl_ran_discrete (const gsl_rng *r, const gsl_ran_discrete_t *g); GSL_EXPORT double gsl_ran_discrete_pdf (size_t k, const gsl_ran_discrete_t *g); __END_DECLS #endif /* __GSL_RANDIST_H__ */
{ "alphanum_fraction": 0.7677774317, "avg_line_length": 51.7903225806, "ext": "h", "hexsha": "712ed5135f786a13ef248149f1bc47b7662dc111", "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_randist.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_randist.h", "max_line_length": 144, "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_randist.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2587, "size": 9633 }
/* sys/ldfrexp.c * * Copyright (C) 2002, Gert Van den Eynde * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> double gsl_ldexp (const double x, const int e) { double p2 = pow (2.0, (double)e); return x * p2; } double gsl_frexp (const double x, int *e) { if (x == 0.0) { *e = 0; return 0.0; } else { double ex = ceil (log (fabs (x)) / M_LN2); int ei = (int) ex; double f = gsl_ldexp (x, -ei); while (fabs (f) >= 1.0) { ei++; f /= 2.0; } while (fabs (f) < 0.5) { ei--; f *= 2.0; } *e = ei; return f; } }
{ "alphanum_fraction": 0.5968772179, "avg_line_length": 23.0983606557, "ext": "c", "hexsha": "c5ba3a6a734193e06fa88580b807ca3c961545b8", "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/sys/ldfrexp.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/sys/ldfrexp.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/sys/ldfrexp.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": 410, "size": 1409 }
/* histogram/gsl-histogram.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <gsl/gsl_histogram.h> void print_help(void) { fprintf (stderr, "Usage: gsl-histogram [-u] xmin xmax [n]\n"); fprintf (stderr, "Computes a histogram of the data on stdin using n bins from xmin to xmax.\n" "If n is unspecified then bins of integer width are used.\n" "If -u is given, histogram is normalized so that sum of all bins is unity.\n"); } int main (int argc, char **argv) { double a = 0.0, b = 1.0; size_t n = 10; int unit = 0; int c; while ((c = getopt(argc, argv, "u")) != (-1)) { switch (c) { case 'u': unit = 1; break; default: print_help(); exit(0); break; } } if (argc - optind < 2) { print_help(); exit(0); } a = atof (argv[optind++]); b = atof (argv[optind++]); if (argc - optind > 0) n = atoi (argv[optind++]); else n = (int)(b - a) ; { double x; gsl_histogram *h = gsl_histogram_alloc (n); gsl_histogram_set_ranges_uniform (h, a, b); while (fscanf(stdin, "%lg", &x) == 1) { gsl_histogram_increment(h, x); } #ifdef DISPLAY_STATS { double mean = gsl_histogram_mean (h); double sigma = gsl_histogram_sigma (h); fprintf (stdout, "# mean = %g\n", mean); fprintf (stdout, "# sigma = %g\n", sigma); } #endif /* normalize histogram if needed */ if (unit) { double sum = gsl_histogram_sum(h); if (sum > 0.0) gsl_histogram_scale(h, 1.0 / sum); } gsl_histogram_fprintf (stdout, h, "%g", "%g"); gsl_histogram_free (h); } return 0; }
{ "alphanum_fraction": 0.5941470928, "avg_line_length": 24.0462962963, "ext": "c", "hexsha": "0897883b356dcbef6f7eec611fa435448ad86c39", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/gsl-histogram.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/gsl-histogram.c", "max_line_length": 98, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/gsl-histogram.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 713, "size": 2597 }
#include <linux/types.h> #include <linux/types.h> #include <stdio.h> #include <gsl/gsl_rng.h> #include <math.h> #include "sweeny_dc.h" #include "timeseries.h" #include "extract_args.h" #define BUF_LEN 512 char fn[BUF_LEN]; char verbose = 0; #define TS_FILE_D "../time_series/dc/simulation_l%u_q%.4f_b%.4f_c%.4f_s%u.hdf5" char impl_title[] = "Dynamic Connectivity implementation"; __u32 DX; __u32 seed; __u32 cutoff; __u32 steps; double beta; double coupling; double q; double rnd_num; __u32 *num_bonds, *num_cluster, *size_giant; __u64 *sec_cs_moment,*four_cs_moment; int main(int argc, char **argv) { if(!extractArgs(argc, argv,impl_title)) return EXIT_FAILURE; snprintf(fn,BUF_LEN,TS_FILE_D,DX,q,beta,coupling,seed); if(!init_observables()) return EXIT_FAILURE; if(!init_sweeny_dc(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_dc()) return EXIT_FAILURE; destroy_sweeny_dc(); save_timeseries(); destroy_observables(); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.7105263158, "avg_line_length": 21.5094339623, "ext": "c", "hexsha": "e3d7bf6111e5d0f541f444ec03c73574c66097b8", "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_dc_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_dc_mc.c", "max_line_length": 93, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ermeel86/sweeny", "max_stars_repo_path": "src/sy_dc_mc.c", "max_stars_repo_stars_event_max_datetime": "2018-08-14T15:05:04.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-24T09:04:04.000Z", "num_tokens": 324, "size": 1140 }
/*****************************************************************\ __ / / / / __ __ / /______ _______ / / / / ________ __ __ / ______ \ /_____ \ / / / / / _____ | / / / / / / | / _______| / / / / / / /____/ / / / / / / / / / / _____ / / / / / / _______/ / / / / / / / / / /____/ / / / / / / |______ / |______/ / /_/ /_/ |________/ / / / / \_______/ \_______ / /_/ /_/ / / / / High Level Game Framework /_/ --------------------------------------------------------------- Copyright (c) 2007-2011 - Rodrigo Braz Monteiro. This file is subject to the terms of halley_license.txt. \*****************************************************************/ #pragma once #include <halley/utils/utils.h> #include <halley/support/exception.h> #include <gsl/span> #include <cstdint> namespace Halley { class MT199937AR; class Random { public: static Random& getGlobal(); Random(); Random(uint32_t seed); Random(uint64_t seed); Random(gsl::span<const gsl::byte> data); ~Random(); Random(const Random& other) = delete; Random(Random&& other) noexcept; Random& operator=(const Random& other) = delete; Random& operator=(Random&& other) noexcept; int32_t getInt(int32_t min, int32_t max); // [min, max] uint32_t getInt(uint32_t min, uint32_t max); // [min, max] int64_t getInt(int64_t min, int64_t max); // [min, max] uint64_t getInt(uint64_t min, uint64_t max); // [min, max] size_t getSizeT(size_t min, size_t max); // [min, max] float getFloat(float min, float max); // [min, max) double getDouble(double min, double max); // [min, max) template <typename T> size_t getRandomIndex(const T& vec) { size_t size = std::end(vec) - std::begin(vec); if (size == 0) { throw Exception("Can't get random index of empty sequence.", HalleyExceptions::Utils); } return getSizeT(size_t(0), size_t(size - 1)); } template <typename T> auto getRandomElement(T& vec) -> decltype(vec[0])& { return vec[getRandomIndex(vec)]; } void getBytes(gsl::span<gsl::byte> dst); void getBytes(gsl::span<Byte> dst); void setSeed(uint32_t seed); void setSeed(uint64_t seed); void setSeed(gsl::span<const gsl::byte> data); void setSeed(gsl::span<Byte> data); uint32_t getRawInt(); float getRawFloat(); double getRawDouble(); private: std::unique_ptr<MT199937AR> generator; }; }
{ "alphanum_fraction": 0.5301204819, "avg_line_length": 29.5747126437, "ext": "h", "hexsha": "d933de766cfaac3352d80d081a2b65766648aeb3", "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": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "moonantonio/halley", "max_forks_repo_path": "src/engine/utils/include/halley/maths/random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "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": "moonantonio/halley", "max_issues_repo_path": "src/engine/utils/include/halley/maths/random.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "moonantonio/halley", "max_stars_repo_path": "src/engine/utils/include/halley/maths/random.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 712, "size": 2573 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_sf.h> #include "adkGSL.h" #include "AFS.h" #include "cs.h" #include "adkCSparse.h" #include "AFS_ctmc.h" #include <pthread.h> void coalMarkovChainTopologyMatrix_pthread(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz); void coalMarkovChainTopologyMatrix_sparse_pthread(afsStateSpace *S,double *topol, int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz); typedef struct matrixThreadObject { int nnz,start, stop; int *dim1,*dim2; struct island_lik_params *island_params; } matrixThreadObject; typedef struct matrixThreadObject_sparse { int nnz,start, stop, nnzA; int *dim1,*dim2, *moveType; double *topol; struct im_lik_params *im_params; } matrixThreadObject_sparse; //gonna try to use a global declared in island.c void *threadDoRows(void* arg){ matrixThreadObject *obj = (matrixThreadObject*)(arg); coalMarkovChainTopologyMatrix_pthread(obj->island_params->stateSpace,obj->island_params->topol, obj->island_params->moveType, obj->dim1,obj->dim2,obj->start,obj->stop,&(obj->nnz)); //obj->nnz -= 1; pthread_exit((void* )obj); } //sparse matrix version void *threadDoRows_sparse(void* arg){ matrixThreadObject_sparse *obj = (matrixThreadObject_sparse*)(arg); coalMarkovChainTopologyMatrix_sparse_pthread(obj->im_params->stateSpace,obj->topol, obj->moveType, obj->dim1,obj->dim2,obj->start,obj->stop,&(obj->nnz)); //obj->nnz -= 1; pthread_exit((void* )obj); } //sparse matrix version on reduced state space void *threadDoRows_sparse_reduced(void* arg){ matrixThreadObject_sparse *obj = (matrixThreadObject_sparse*)(arg); coalMarkovChainTopologyMatrix_sparse_pthread(obj->im_params->reducedStateSpace,obj->topol, obj->moveType, obj->dim1,obj->dim2,obj->start,obj->stop,&(obj->nnzA)); //obj->nnz -= 1; pthread_exit((void* )obj); } void coalMarkovChainTopologyMatrix_pthread(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz){ int i,j,k,steps,x,y; double top,bottom; afsObject *delta; int **activePos1, **activePos2; //first dimension here relates to 2 popns int nlin1,nlin2,compat; int nonZeroCount, tot, tCount; int size = 200; nlin1 = nlin2 = 0; nonZeroCount = 0; if(S->nstates != topol->size1 || S->nstates != moveType->size1){ fprintf(stderr,"Error: StateSpace and matrices are not of equal size\n"); exit(1); } *nnz = 0; //arrays for finding positions of entries activePos1 = malloc(size*sizeof(int *)); activePos2 = malloc(size*sizeof(int *)); for(i=0;i<size;i++){ activePos1[i] = malloc(2*sizeof(int)); activePos1[i][0] = activePos1[i][1] = 0; activePos2[i] = malloc(2*sizeof(int)); activePos2[i][0] = activePos2[i][1] = 0; } tot = S->nstates * S->nstates; tCount = 0; delta = afsObjectNewFrom(S->states[0]); for(i=start;i<stop;i++){ for(j=0;j<S->nstates;j++){ gsl_matrix_int_set(moveType,i,j,666); //is ith state root state? if(S->states[i]->nalleles == 1){ //set correct absorbing conditions if(i==j){ gsl_matrix_set(topol,i,j,1.0); gsl_matrix_int_set(moveType,i,j,-1); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } else{ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,-1); } } else{ //ith not root; what is the move? steps = S->states[i]->nalleles - S->states[j]->nalleles ; if(steps < 2){ // delta = afsObjectDelta(S->states[i],S->states[j]); afsObjectDeltaPre(S->states[i],S->states[j],delta); switch(steps){ case 0: // 0 "steps", so no changes in nalleles between two //check counts and positions if(abs(matrixSum(delta->popMats[0])) == 1){ nonZeroEntries(delta->popMats[0], activePos1, &nlin1); nonZeroEntries(delta->popMats[1], activePos2, &nlin2); //migration? if(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] && (gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0)) { //migration popn1? if(matrixSum(delta->popMats[0]) == 1){ gsl_matrix_set(topol,i,j, (double) gsl_matrix_int_get(S->states[i]->popMats[0], activePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0]); gsl_matrix_int_set(moveType,i,j,2); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } else{ //migration popn2 gsl_matrix_set(topol,i,j, (double) gsl_matrix_int_get(S->states[i]->popMats[1], activePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1]); gsl_matrix_int_set(moveType,i,j,3); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } break; case 1://coalescent? //coal popn1? if(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 ){ entriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat != 1){ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,666); } else{ top = 1.0; bottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= (float) xchoosey(gsl_matrix_int_get(S->states[i]->popMats[0],x,y), gsl_matrix_int_get(delta->popMats[0],x,y)); } gsl_matrix_set(topol,i,j,top/bottom); gsl_matrix_int_set(moveType,i,j,0); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } else{ if(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 ){ entriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat != 1){ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,666); } else{ top = 1.0; bottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= xchoosey(gsl_matrix_int_get(S->states[i]->popMats[1],x,y), gsl_matrix_int_get(delta->popMats[1],x,y)); } gsl_matrix_set(topol,i,j,top/bottom); gsl_matrix_int_set(moveType,i,j,1); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } } break; } //afsObjectFree(delta); } } } } //cleanup and free for(i=0;i<size;i++){ free(activePos1[i]); free(activePos2[i]); } free(activePos1); free(activePos2); *nnz = nonZeroCount; } void coalMarkovChainTopologyMatrix_sparse_pthread(afsStateSpace *S,double *topol, int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz){ int i,j,k,steps,x,y; double top,bottom; afsObject *delta; int **activePos1, **activePos2; //first dimension here relates to 2 popns int nlin1,nlin2,compat; int nonZeroCount, tot, tCount; int size = 400; nlin1 = nlin2 = 0; nonZeroCount = 0; *nnz = 0; //arrays for finding positions of entries activePos1 = malloc(size*sizeof(int *)); activePos2 = malloc(size*sizeof(int *)); for(i=0;i<size;i++){ activePos1[i] = malloc(2*sizeof(int)); activePos1[i][0] = activePos1[i][1] = 0; activePos2[i] = malloc(2*sizeof(int)); activePos2[i][0] = activePos2[i][1] = 0; } tot = S->nstates * S->nstates; tCount = 0; delta = afsObjectNewFrom(S->states[0]); for(i=start;i<stop;i++){ for(j=0;j<S->nstates;j++){ // printf("nonzerocount=%d\n",nonZeroCount); if(S->states[i]->nalleles == 1){ //set correct absorbing conditions if(i==j){ topol[nonZeroCount] = 1.0; moveType[nonZeroCount] = -1; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } else{ //ith not root; what is the move? steps = S->states[i]->nalleles - S->states[j]->nalleles ; if(steps < 2){ delta = afsObjectDelta(S->states[i],S->states[j]); switch(steps){ case 0: // 0 "steps", so no changes in nalleles between two //check counts and positions if(abs(matrixSum(delta->popMats[0])) == 1){ nonZeroEntries(delta->popMats[0], activePos1, &nlin1); nonZeroEntries(delta->popMats[1], activePos2, &nlin2); //migration? if(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] && (gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0)){ //migration popn1? if(matrixSum(delta->popMats[0]) == 1){ topol[nonZeroCount] = (double) gsl_matrix_int_get(S->states[i]->popMats[0], activePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0]; moveType[nonZeroCount] = 2; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } else{ //migration popn2 topol[nonZeroCount] = (double) gsl_matrix_int_get(S->states[i]->popMats[1], activePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1]; moveType[nonZeroCount] = 3; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } break; case 1://coalescent? //coal popn1? if(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 ){ entriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat == 1){ top = 1.0; bottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= (float) xchoosey(gsl_matrix_int_get(S->states[i]->popMats[0],x,y), gsl_matrix_int_get(delta->popMats[0],x,y)); } topol[nonZeroCount] = top/bottom; moveType[nonZeroCount] = 0; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } else{ if(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 ){ entriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat == 1){ top = 1.0; bottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= xchoosey(gsl_matrix_int_get(S->states[i]->popMats[1],x,y), gsl_matrix_int_get(delta->popMats[1],x,y)); } topol[nonZeroCount] = top/bottom; moveType[nonZeroCount] = 1; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } } break; } //afsObjectFree(delta); } } } } //cleanup and free for(i=0;i<size;i++){ free(activePos1[i]); free(activePos2[i]); } free(activePos1); free(activePos2); *nnz = nonZeroCount; }
{ "alphanum_fraction": 0.5809721092, "avg_line_length": 31.9550827423, "ext": "c", "hexsha": "3efad2141106ddd96fb2155e6e9044a24f2ce551", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_path": "AFS_pthreads.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_path": "AFS_pthreads.c", "max_line_length": 158, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_path": "AFS_pthreads.c", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "num_tokens": 4551, "size": 13517 }
#pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cblas.h> #include <time.h> void random_matrix(double *matrix, int N); void print_vector(double *vector, int N); void print_matrix(double *matrix, int N); void matrix_vector_mult(double *matrix, double *vector, double *result, int N); void matrix_matrix_mult(double *mat_1, double *mat_2, double *result, int N); void matrix_power(double *matrix, double *result, int N, int power);
{ "alphanum_fraction": 0.6547169811, "avg_line_length": 31.1764705882, "ext": "h", "hexsha": "94e855ce350a8a964ab684a3b162f885d4014dc3", "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": "bc9a3966c4f2b165b1b2d568b811f947aafe98bf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Illumaria/made-high-performance-computing", "max_forks_repo_path": "hw4/src/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bc9a3966c4f2b165b1b2d568b811f947aafe98bf", "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": "Illumaria/made-high-performance-computing", "max_issues_repo_path": "hw4/src/matrix.h", "max_line_length": 55, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bc9a3966c4f2b165b1b2d568b811f947aafe98bf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Illumaria/made-high-performance-computing", "max_stars_repo_path": "hw4/src/matrix.h", "max_stars_repo_stars_event_max_datetime": "2021-12-25T02:36:32.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-25T02:36:32.000Z", "num_tokens": 121, "size": 530 }
 /** *************************************************************************** * * Copyright 2018 Jose Fernando Lopez Fernandez - All Rights Reserved * See the file AUTHORS included with the application distribution for * specific information. * * 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 OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * *************************************************************************** * * @author Jose Fernando Lopez Fernandez * @date 15-June-2018 * @brief This is the main keygen driver file * * Tasks: * 1. @todo Add file details * 2. @todo Add file details * * **************************************************************************/ #ifndef KEYGEN_INCLUDE_KEYGEN_H_ #define KEYGEN_INCLUDE_KEYGEN_H_ #define TRUE 1 #define FALSE 0 /** @def _CRT_SECURE_NO_WARNINGS * @brief This preprocessor definition disables Visual Studio's warnings * when not using the safe string functions provided by the MSVC runtime. * * Disable the safe string library due to its lack of compatibility with * *nix systems. * */ #define _CRT_SECURE_NO_WARNINGS #ifndef _CRT_SECURE_NO_WARNINGS #error "The safe string library is not compatible with *nix systems" #endif /** Include Microsoft's Guideline Support Library (GSL). * * The Guideline Support Library (GSL) contains functions and types that are * suggested for use by the C++ Core Guidelines maintained by the Standard C++ * Foundation. This repo contains Microsoft's implementation of GSL. * * The library includes types like span<T>, string_span, owner<> and others. * * The entire implementation is provided inline in the headers under the gsl * directory. The implementation generally assumes a platform that implements * C++14 support. There are specific workarounds to support MSVC 2015. * * While some types have been broken out into their own headers * (e.g. gsl/span), it is simplest to just include gsl/gsl and gain access to * the entire library. * */ #include <gsl/gsl> #include <cstdio> #include <cstdlib> #include <cstring> #include <cstddef> #include <cstdint> #include <cerrno> #include <csignal> #include <cmath> #include <ctime> /** C++ Standard Library Headers * */ #include <algorithm> #include <chrono> #include <iostream> #include <limits> #include <ratio> #include <sstream> #include <string> #include <string_view> #include <vector> #include <utility> /** @file config.h * @brief This file contains customization settings and project metadata such * as the current release version, compilation settings, etc. * */ #include "config.h" #include "password.h" #endif // KEYGEN_KEYGEN_H_
{ "alphanum_fraction": 0.6981808865, "avg_line_length": 31.7317073171, "ext": "h", "hexsha": "0834b773d5dc8665d4f2fd0a0024788d27d4819a", "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": "dd6c746a658ba225482411ea058d362445474ea8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lopezfjose/KeyGen", "max_forks_repo_path": "keygen/include/keygen.h", "max_issues_count": 10, "max_issues_repo_head_hexsha": "dd6c746a658ba225482411ea058d362445474ea8", "max_issues_repo_issues_event_max_datetime": "2018-06-19T20:04:20.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-17T03:19:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lopezfjose/KeyGen", "max_issues_repo_path": "keygen/include/keygen.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dd6c746a658ba225482411ea058d362445474ea8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lopezfjose/KeyGen", "max_stars_repo_path": "keygen/include/keygen.h", "max_stars_repo_stars_event_max_datetime": "2018-06-21T12:59:41.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-21T12:59:41.000Z", "num_tokens": 839, "size": 3903 }
/** * * @file qwrapper_zlantr.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <lapacke.h> #include "common.h" void CORE_zlantr_quark(Quark *quark); void CORE_zlantr_f1_quark(Quark *quark); /***************************************************************************//** * **/ void QUARK_CORE_zlantr(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const PLASMA_Complex64_t *A, int LDA, int szeA, int szeW, double *result) { szeW = max(1, szeW); DAG_CORE_LANGE; QUARK_Insert_Task(quark, CORE_zlantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(PLASMA_Complex64_t)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(double)*szeW, NULL, SCRATCH, sizeof(double), result, OUTPUT, 0); } /***************************************************************************//** * **/ void QUARK_CORE_zlantr_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const PLASMA_Complex64_t *A, int LDA, int szeA, int szeW, double *result, double *fake, int szeF) { szeW = max(1, szeW); DAG_CORE_LANGE; if ( result == fake ) { QUARK_Insert_Task(quark, CORE_zlantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(PLASMA_Complex64_t)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(double)*szeW, NULL, SCRATCH, sizeof(double), result, OUTPUT | GATHERV, 0); } else { QUARK_Insert_Task(quark, CORE_zlantr_f1_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(PLASMA_Complex64_t)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(double)*szeW, NULL, SCRATCH, sizeof(double), result, OUTPUT, sizeof(double)*szeF, fake, OUTPUT | GATHERV, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zlantr_quark = PCORE_zlantr_quark #define CORE_zlantr_quark PCORE_zlantr_quark #endif void CORE_zlantr_quark(Quark *quark) { double *normA; PLASMA_enum norm, uplo, diag; int M; int N; PLASMA_Complex64_t *A; int LDA; double *work; quark_unpack_args_9(quark, norm, uplo, diag, M, N, A, LDA, work, normA); *normA = LAPACKE_zlantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zlantr_f1_quark = PCORE_zlantr_f1_quark #define CORE_zlantr_f1_quark PCORE_zlantr_f1_quark #endif void CORE_zlantr_f1_quark(Quark *quark) { double *normA; PLASMA_enum norm, uplo, diag; int M; int N; PLASMA_Complex64_t *A; int LDA; double *work; double *fake; quark_unpack_args_10(quark, norm, uplo, diag, M, N, A, LDA, work, normA, fake); *normA = LAPACKE_zlantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); }
{ "alphanum_fraction": 0.484430512, "avg_line_length": 34.4244604317, "ext": "c", "hexsha": "ad29e4db1d4448c9a1fe697b309aadc11f484905", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_zlantr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_zlantr.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_zlantr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1254, "size": 4785 }
/* Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com> Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #include "morn_tensor.h" struct TensorBatchNormPara { MLayer *prev; int res_valid; float rate; float decay; float momentum; }; void *mTensorBatchNormPara(MList *ini,char *name) { struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)mMalloc(sizeof(struct TensorBatchNormPara)); char *value = mINIRead(ini,name,"prev"); para->prev = mNetworkLayer(ini,value); mException((para->prev == NULL),EXIT,"invalid prev"); para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0); value = mINIRead(ini,name,"rate"); if(value != NULL) para->rate = atof(value); else { value = mINIRead(ini,"para","rate"); if(value != NULL) para->rate = atof(value); else para->rate = 0.001; } value = mINIRead(ini,name,"decay"); if(value != NULL) para->decay = atof(value); else { value = mINIRead(ini,"para","decay"); if(value != NULL) para->decay = atof(value); else para->decay = 0.01; } mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay"); value = mINIRead(ini,name,"momentum"); if(value != NULL) para->momentum = atof(value); else { value = mINIRead(ini,"para","momentum"); if(value != NULL) para->momentum = atof(value); else para->momentum = 0.9; } return para; } struct HandleTensorBatchNorm { float *k; float *b; float *k_update; float *b_update; double *mean; double *var; float *roll_mean; float *roll_var; }; void endTensorBatchNorm(void *info) { struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)info; if(handle->k != NULL) mFree(handle->k); if(handle->b != NULL) mFree(handle->b); if(handle->mean != NULL) mFree(handle->mean); if(handle->var != NULL) mFree(handle->var ); if(handle->roll_mean!= NULL) mFree(handle->roll_mean); if(handle->roll_var != NULL) mFree(handle->roll_var ); } #define HASH_TensorBatchNorm 0xde8952f6 void TensorBatchNormSet(MLayer *layer) { if(layer->state != DFLT) return; struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)(layer->para); MTensor *in = para->prev->tns; MTensor *res= para->prev->res; MTensor *out=layer->tns; MHandle *hdl=mHandle(out,TensorBatchNorm); struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)(hdl->handle); if(handle->k != NULL) {mFree(handle->k);} handle->k =(float *)mMalloc(in->channel*sizeof(float)); if(handle->b != NULL) {mFree(handle->b);} handle->b =(float *)mMalloc(in->channel*sizeof(float)); if(handle->mean!= NULL) {mFree(handle->mean);} handle->mean=(double *)mMalloc(in->channel*sizeof(double)); if(handle->var != NULL) {mFree(handle->var );} handle->var =(double *)mMalloc(in->channel*sizeof(double)); if(handle->roll_mean!= NULL) {mFree(handle->roll_mean);} handle->roll_mean=(float *)mMalloc(in->channel*sizeof(float)); if(handle->roll_var != NULL) {mFree(handle->roll_var );} handle->roll_var =(float *)mMalloc(in->channel*sizeof(float)); mTensorRedefine(out,in->batch,in->channel,in->height,in->width,NULL); if(morn_network_flag == MORN_TRAIN) { if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,out->data); else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL); handle->k_update = handle->roll_mean; handle->b_update = handle->roll_var ; memset(handle->k_update,0,in->channel*sizeof(float)); memset(handle->b_update,0,in->channel*sizeof(float)); } if(morn_network_parafile==NULL) { for(int i=0;i<in->channel;i++){handle->k[i] = 1.0f;handle->b[i] = 1.0f;} // printf("handle->k[0] is %f\n",handle->k[0]); // printf("handle->b[0] is %f\n",handle->b[0]); } else { mNetworkParaRead(layer,"scale",handle->k,in->channel*sizeof(float)); mNetworkParaRead(layer,"bias" ,handle->b,in->channel*sizeof(float)); // printf("handle->k[0] is %f\n",handle->k[0]); // printf("handle->b[0] is %f\n",handle->b[0]); } hdl->valid = 1; } void mTensorBatchNormForward(MLayer *layer) { mException(INVALID_POINTER(layer),EXIT,"invalid input"); mException(strcmp("BatchNorm",mLayerType(layer)),EXIT,"invalid layer type"); struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)(layer->para); MTensor *in = para->prev->tns; MTensor *out=layer->tns; TensorBatchNormSet(layer); MHandle *hdl=mHandle(out,TensorBatchNorm); struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)(hdl->handle); int in_size = in->height*in->width; memset(handle->mean,0,in->channel*sizeof(double)); memset(handle->var ,0,in->channel*sizeof(double)); for(int b=0;b<in->batch;b++)for(int c=0;c<in->channel;c++)for(int i=0;i<in_size;i++) { double data = (double)(in->data[b][c*in_size+i]); handle->mean[c] += data; handle->var [c] += data*data; } for(int c=0;c<in->channel;c++) { handle->mean[c] = handle->mean[c]/(double)(in->batch*in_size); handle->var [c] = handle->var [c]/(double)(in->batch*in_size); handle->var [c]-= (handle->mean[c]*handle->mean[c]); handle->var [c] = (handle->var[c]<=0.0f)?0.00001f:sqrt(handle->var[c]); // printf("handle->mean[c] is %f,handle->var[c] is %f\n",handle->mean[c],handle->var[c]); } if(morn_network_flag == MORN_PREDICT) { for(int c=0;c<in->channel;c++) { if(layer->state == DFLT) { handle->roll_mean[c] = handle->mean[c]; handle->roll_var [c] = handle->var [c]; } handle->mean[c] = handle->roll_mean[c]*0.99f+handle->mean[c]*0.01; handle->var [c] = handle->roll_var [c]*0.99f+handle->var [c]*0.01; handle->roll_mean[c] = handle->mean[c]; handle->roll_var [c] = handle->var [c]; } } for(int b=0;b<in->batch;b++)for(int c=0;c<in->channel;c++)for(int i=0;i<in_size;i++) { float data = in->data[b][c*in_size+i]; out->data[b][c*in_size+i] = ((data-handle->mean[c])/handle->var[c])*handle->k[c]+handle->b[c]; } layer->state = MORN_FORWARD; } void mTensorBatchNormBackward(MLayer *layer) { mException(INVALID_POINTER(layer),EXIT,"invalid input"); mException(strcmp("BatchNorm",mLayerType(layer)),EXIT,"invalid layer type"); struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)(layer->para); MTensor *in = para->prev->tns; MTensor *res= para->prev->res; MTensor *out= layer->res; MHandle *hdl=mHandle(layer->tns,TensorBatchNorm); struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)(hdl->handle); mException((hdl->valid == 0),EXIT,"no forward operate"); mNetworkParaWrite(layer,"scale",handle->k,in->channel*sizeof(float)); mNetworkParaWrite(layer,"bias" ,handle->b,in->channel*sizeof(float)); int in_size = in->height*in->width; for(int c=0;c<in->channel;c++) { handle->k_update[c] *= para->momentum; handle->b_update[c] *= para->momentum; } for(int b=0;b<in->batch;b++)for(int c=0;c<in->channel;c++)for(int i=0;i<in_size;i++) { int idx = c*in_size+i; handle->k_update[c] += out->data[b][idx]*((in->data[b][idx]-handle->mean[c])/handle->var[c]); handle->b_update[c] += out->data[b][idx]; } for(int c=0;c<in->channel;c++) { handle->k[c] = (handle->k[c]*(1.0f-(para->decay*para->rate)))-(handle->k_update[c]*para->rate/(float)(in->batch*in_size)); handle->b[c] = (handle->b[c]*(1.0f-(para->decay*para->rate)))-(handle->b_update[c]*para->rate/(float)(in->batch*in_size)); } if(para->res_valid==0) return; for(int b=0;b<in->batch;b++)for(int c=0;c<in->channel;c++)for(int i=0;i<in_size;i++) { int idx = c*in_size+i; float data; data = (in->data[b][idx] - handle->mean[c])/handle->var[c]; data = (out->data[b][idx]*handle->k[c]/handle->var[c])*(1.0+(1.0f-data*data)/((float)(in->batch*in_size))); res->data[b][idx]=(para->prev->state == MORN_FORWARD)?data:(res->data[b][idx]+data); } para->prev->state = MORN_BACKWARD; }
{ "alphanum_fraction": 0.606279672, "avg_line_length": 37.674796748, "ext": "c", "hexsha": "ad4982a1d814a11e94acdd8b4175f8f906f3540a", "lang": "C", "max_forks_count": 35, "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z", "max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ishine/Morn", "max_forks_repo_path": "src/deep_learning/morn_tensor_batch_normlize.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ishine/Morn", "max_issues_repo_path": "src/deep_learning/morn_tensor_batch_normlize.c", "max_line_length": 501, "max_stars_count": 121, "max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ishine/Morn", "max_stars_repo_path": "src/deep_learning/morn_tensor_batch_normlize.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z", "num_tokens": 2666, "size": 9268 }
#ifndef STATEMENT_INCLUDE #define STATEMENT_INCLUDE #include <string> #include <gsl/gsl> #include "executionContent.h" #include "yaml.h" namespace execHelper { namespace test { namespace baseUtils { using StatementKey = std::string; using StatementCollection = ExecutionContent::ConfigCommand; class Statement { public: virtual ~Statement() = default; virtual StatementKey getKey() const noexcept = 0; virtual void write(gsl::not_null<YamlWriter*> yaml, const std::string& command) const noexcept = 0; virtual inline unsigned int getNumberOfExecutions() const noexcept { return m_execution.getNumberOfExecutions(); } virtual inline void resetExecutions() noexcept { m_execution.clear(); } protected: Statement(ReturnCode returnCode) noexcept : m_execution(returnCode) {} ExecutionContent m_execution; }; } // namespace baseUtils } // namespace test } // namespace execHelper #endif /* STATEMENT_INCLUDE */
{ "alphanum_fraction": 0.7245934959, "avg_line_length": 24, "ext": "h", "hexsha": "4a01ca7037b4ed8248ba6aae98bdbe30676f84c2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "exec-helper/source", "max_forks_repo_path": "test/base-utils/include/base-utils/statement.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "exec-helper/source", "max_issues_repo_path": "test/base-utils/include/base-utils/statement.h", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "exec-helper/source", "max_stars_repo_path": "test/base-utils/include/base-utils/statement.h", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "num_tokens": 204, "size": 984 }
#ifndef __GSL_MANAGED_H__ #define __GSL_MANAGED_H__ #include "cuda.h" #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_vector_double.h> gsl_matrix *gsl_matrix_alloc_managed(const size_t n1, const size_t n2); gsl_matrix *gsl_matrix_calloc_managed(const size_t n1, const size_t n2); void gsl_matrix_free_managed(gsl_matrix *m); __host__ __device__ double *gsl_matrix_ptr_managed(gsl_matrix * m, const size_t i, const size_t j); gsl_vector *gsl_vector_alloc_managed(const size_t n, bool readmostly); gsl_vector *gsl_vector_calloc_managed(const size_t n, bool readmostly); __host__ __device__ double gsl_vector_get_managed(gsl_vector *vec, const size_t i); void gsl_vector_free_managed(gsl_vector *m); #endif /* __GSL_MANAGED_H__ */
{ "alphanum_fraction": 0.8222523745, "avg_line_length": 38.7894736842, "ext": "h", "hexsha": "c49cba6d6401042760ab8fbe1fd591e0815d8ed6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "artis-mcrt/artis", "max_forks_repo_path": "gsl_managed.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z", "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "artis-mcrt/artis", "max_issues_repo_path": "gsl_managed.h", "max_line_length": 99, "max_stars_count": 4, "max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "artis-mcrt/artis", "max_stars_repo_path": "gsl_managed.h", "max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z", "num_tokens": 204, "size": 737 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "tests.h" void test_hemm (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int side = 141; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {0.0f, 0.1f}; float beta[2] = {0.0f, 0.1f}; float A[] = { -0.126f, 0.079f }; int lda = 1; float B[] = { -0.954f, -0.059f, 0.296f, -0.988f }; int ldb = 2; float C[] = { -0.859f, -0.731f, 0.737f, 0.593f }; int ldc = 2; float C_expected[] = { 0.0723566f, -0.0738796f, -0.0717488f, 0.0699704f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1550) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1550) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {0.0f, 0.1f}; float beta[2] = {0.0f, 0.1f}; float A[] = { 0.652f, 0.584f }; int lda = 1; float B[] = { -0.983f, -0.734f, -0.422f, -0.825f }; int ldb = 1; float C[] = { 0.387f, 0.341f, -0.734f, 0.632f }; int ldc = 1; float C_expected[] = { 0.0137568f, -0.0253916f, -0.00941f, -0.100914f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1551) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1551) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.78f, 0.885f, 0.507f, 0.765f, 0.911f, -0.461f, 0.707f, 0.508f }; int lda = 2; float B[] = { -0.905f, 0.633f, 0.85f, -0.943f }; int ldb = 2; float C[] = { 0.045f, -0.237f, 0.078f, -0.252f }; int ldc = 2; float C_expected[] = { 0.589611f, -0.759345f, 0.960095f, -0.09013f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1552) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1552) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.947f, 0.939f, -0.267f, -0.819f, -0.827f, -0.937f, 0.991f, 0.838f }; int lda = 2; float B[] = { 0.871f, -0.988f, -0.232f, -0.434f }; int ldb = 1; float C[] = { -0.261f, 0.927f, -0.351f, -0.203f }; int ldc = 1; float C_expected[] = { 1.0551f, 0.496359f, 0.780145f, -1.67298f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1553) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1553) imag"); }; }; }; { int order = 101; int side = 141; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 0.0f}; float A[] = { -0.593f, -0.9f }; int lda = 1; float B[] = { -0.861f, 0.747f, -0.984f, 0.595f }; int ldb = 2; float C[] = { -0.589f, -0.671f, -0.011f, -0.417f }; int ldc = 2; float C_expected[] = { -0.510573f, 0.442971f, -0.583512f, 0.352835f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1554) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1554) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 0.0f}; float A[] = { -0.79f, 0.132f }; int lda = 1; float B[] = { -0.243f, -0.12f, 0.633f, -0.556f }; int ldb = 1; float C[] = { -0.658f, -0.74f, -0.47f, 0.481f }; int ldc = 1; float C_expected[] = { -0.19197f, -0.0948f, 0.50007f, -0.43924f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1555) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1555) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; float A[] = { -0.114f, -0.515f, -0.513f, -0.527f, -0.995f, 0.986f, 0.229f, -0.076f }; int lda = 2; float B[] = { 0.084f, 0.522f, 0.61f, 0.694f }; int ldb = 2; float C[] = { 0.802f, 0.136f, -0.161f, -0.364f }; int ldc = 2; float C_expected[] = { 0.269101f, 0.716492f, 0.237088f, 0.0290666f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1556) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1556) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; float A[] = { 0.798f, -0.324f, -0.693f, -0.893f, -0.223f, 0.749f, 0.102f, -0.357f }; int lda = 2; float B[] = { -0.572f, -0.569f, -0.391f, -0.938f }; int ldb = 1; float C[] = { 0.152f, -0.834f, -0.633f, -0.473f }; int ldc = 1; float C_expected[] = { 1.08642f, -0.113853f, 0.234826f, -0.48289f }; cblas_chemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "chemm(case 1557) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "chemm(case 1557) imag"); }; }; }; { int order = 101; int side = 141; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {0, 0.1}; double beta[2] = {0, 0.1}; double A[] = { -0.359, 0.089 }; int lda = 1; double B[] = { -0.451, -0.337, -0.901, -0.871 }; int ldb = 2; double C[] = { 0.729, 0.631, 0.364, 0.246 }; int ldc = 2; double C_expected[] = { -0.0751983, 0.0890909, -0.0558689, 0.0687459 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1558) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1558) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {0, 0.1}; double beta[2] = {0, 0.1}; double A[] = { 0.044, -0.496 }; int lda = 1; double B[] = { -0.674, 0.281, 0.366, 0.888 }; int ldb = 1; double C[] = { -0.9, 0.919, 0.857, -0.049 }; int ldc = 1; double C_expected[] = { -0.0931364, -0.0929656, 0.0009928, 0.0873104 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1559) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1559) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {0, 0}; double beta[2] = {0, 0.1}; double A[] = { -0.314, 0.115, 0.114, 0.878, 0.961, -0.224, 0.973, 0.771 }; int lda = 2; double B[] = { 0.5, -0.016, -0.5, 0.149 }; int ldb = 2; double C[] = { -0.054, 0.064, 0.02, 0.245 }; int ldc = 2; double C_expected[] = { -0.0064, -0.0054, -0.0245, 0.002 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1560) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1560) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {0, 0}; double beta[2] = {0, 0.1}; double A[] = { 0.186, 0.578, 0.797, -0.957, -0.539, -0.969, -0.21, 0.354 }; int lda = 2; double B[] = { 0.641, -0.968, 0.15, -0.569 }; int ldb = 1; double C[] = { -0.556, -0.9, 0.197, 0.31 }; int ldc = 1; double C_expected[] = { 0.09, -0.0556, -0.031, 0.0197 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1561) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1561) imag"); }; }; }; { int order = 101; int side = 141; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {1, 0}; double beta[2] = {1, 0}; double A[] = { 0.323, 0.641 }; int lda = 1; double B[] = { -0.188, 0.091, -0.235, 0.523 }; int ldb = 2; double C[] = { 0.919, 0.806, 0.823, -0.94 }; int ldc = 2; double C_expected[] = { 0.858276, 0.835393, 0.747095, -0.771071 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1562) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1562) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {1, 0}; double beta[2] = {1, 0}; double A[] = { -0.688, 0.915 }; int lda = 1; double B[] = { 0.914, -0.204, 0.205, -0.476 }; int ldb = 1; double C[] = { 0.27, -0.628, -0.079, 0.507 }; int ldc = 1; double C_expected[] = { -0.358832, -0.487648, -0.22004, 0.834488 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1563) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1563) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {0, 1}; double beta[2] = {0, 0.1}; double A[] = { 0.681, 0.574, -0.425, -0.64, 0.792, 0.661, -0.009, 0.005 }; int lda = 2; double B[] = { -0.221, 0.554, -0.465, -0.95 }; int ldb = 2; double C[] = { 0.331, -0.958, -0.826, -0.972 }; int ldc = 2; double C_expected[] = { 0.778291, 0.142269, -0.496199, 0.112747 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1564) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1564) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {0, 1}; double beta[2] = {0, 0.1}; double A[] = { 0.959, 0.34, -0.23, 0.064, 0.516, -0.275, 0.714, 0.899 }; int lda = 2; double B[] = { -0.502, -0.987, -0.134, 0.215 }; int ldb = 1; double C[] = { 0.929, 0.181, -0.16, -0.921 }; int ldc = 1; double C_expected[] = { 0.986459, -0.371458, -0.320548, -0.059384 }; cblas_zhemm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zhemm(case 1565) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zhemm(case 1565) imag"); }; }; }; }
{ "alphanum_fraction": 0.5070364238, "avg_line_length": 28.2242990654, "ext": "c", "hexsha": "ce1b888927ad6eb977a517f1df88552697b93cd5", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_hemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_hemm.c", "max_line_length": 88, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_hemm.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": 5486, "size": 12080 }
/* specfunc/bessel_K0.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * Copyright (C) 2016 Pavel Holoborodko, 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. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_bessel.h> #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* Minimax rational approximation for [0,1), peak relative error = 2.04*GSL_DBL_EPSILON. Source: http://www.advanpix.com/?p=3812 */ static double k0_poly[8] = { 1.1593151565841244842077226e-01, 2.7898287891460317300886539e-01, 2.5248929932161220559969776e-02, 8.4603509072136578707676406e-04, 1.4914719243067801775856150e-05, 1.6271068931224552553548933e-07, 1.2082660336282566759313543e-09, 6.6117104672254184399933971e-12 }; static double i0_poly[7] = { 1.0000000000000000044974165e+00, 2.4999999999999822316775454e-01, 2.7777777777892149148858521e-02, 1.7361111083544590676709592e-03, 6.9444476047072424198677755e-05, 1.9288265756466775034067979e-06, 3.9908220583262192851839992e-08 }; /* Chebyshev expansion for [1,8], peak relative error = 1.28*GSL_DBL_EPSILON. Source: Pavel Holoborodko. */ static double ak0_data[24] = { -3.28737867094650101e-02, -4.49369057710236880e-02, +2.98149992004308095e-03, -3.03693649396187920e-04, +3.91085569307646836e-05, -5.86872422399215952e-06, +9.82873709937322009e-07, -1.78978645055651171e-07, +3.48332306845240957e-08, -7.15909210462546599e-09, +1.54019930048919494e-09, -3.44555485579194210e-10, +7.97356101783753023e-11, -1.90090968913069735e-11, +4.65295609304114621e-12, -1.16614287433470780e-12, +2.98554375218596891e-13, -7.79276979512292169e-14, +2.07027467168948402e-14, -5.58987860393825313e-15, +1.53202965950646914e-15, -4.25737536712188186e-16, +1.19840238501357389e-16, -3.41407346762502397e-17 }; static cheb_series ak0_cs = { ak0_data, 23, -1, 1, 10 }; /* Chebyshev expansion for [8,inf), peak relative error = 1.25*GSL_DBL_EPSILON. Source: SLATEC/dbsk0e.f */ static double ak02_data[14] = { -.1201869826307592240E-1, -.9174852691025695311E-2, +.1444550931775005821E-3, -.4013614175435709729E-5, +.1567831810852310673E-6, -.7770110438521737710E-8, +.4611182576179717883E-9, -.3158592997860565771E-10, +.2435018039365041128E-11, -.2074331387398347898E-12, +.1925787280589917085E-13, -.1927554805838956104E-14, +.2062198029197818278E-15, -.2341685117579242403E-16 }; static cheb_series ak02_cs = { ak02_data, 13, -1, 1, 8 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(x < 1.0) { const double lx = log(x); const double ex = exp(x); const double x2 = x*x; result->val = ex * (gsl_poly_eval(k0_poly,8,x2)-lx*(1.0+0.25*x2*gsl_poly_eval(i0_poly,7,0.25*x2))); result->err = ex * (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x <= 8.0) { const double sx = sqrt(x); gsl_sf_result c; cheb_eval_e(&ak0_cs, (16.0/x-9.0)/7.0, &c); result->val = (1.203125 + c.val) / sx; /* 1.203125 = 77/64 */ result->err = c.err / sx; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double sx = sqrt(x); gsl_sf_result c; cheb_eval_e(&ak02_cs, 16.0/x-1.0, &c); result->val = (1.25 + c.val) / sx; result->err = (c.err + GSL_DBL_EPSILON) / sx; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(x < 1.0) { const double lx = log(x); const double x2 = x*x; result->val = gsl_poly_eval(k0_poly,8,x2)-lx*(1.0+0.25*x2*gsl_poly_eval(i0_poly,7,0.25*x2)); result->err = (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { gsl_sf_result K0_scaled; int stat_K0 = gsl_sf_bessel_K0_scaled_e(x, &K0_scaled); int stat_e = gsl_sf_exp_mult_err_e(-x, GSL_DBL_EPSILON*fabs(x), K0_scaled.val, K0_scaled.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K0); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_K0_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_K0_scaled_e(x, &result)); } double gsl_sf_bessel_K0(const double x) { EVAL_RESULT(gsl_sf_bessel_K0_e(x, &result)); }
{ "alphanum_fraction": 0.6717303999, "avg_line_length": 27.5336538462, "ext": "c", "hexsha": "127fcb9efcaa30165a191e8f533340bb0d80dd64", "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/specfunc/bessel_K0.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_K0.c", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_K0.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": 2127, "size": 5727 }
#ifndef DBJ_VARIOUS_SIMPLE_MATMULS_INC #define DBJ_VARIOUS_SIMPLE_MATMULS_INC // not using any kind of "matrix framework" #include "../dbj_matmul_common.h" // DBJ_MATRIX_DATA_TYPE #include <stdlib.h> #include <intrin.h> // #define __SSE__ 1 #ifdef HAVE_CBLAS #include <cblas.h> #endif #undef DBJ_API #define DBJ_API ////////////////////////////////////////////////////////////////////// #ifndef DBJ_SANITY_MAX_ROW_COUNT #define DBJ_SANITY_MAX_ROW_COUNT 0xFFFF #endif #ifndef DBJ_SANITY_MAX_COL_COUNT #define DBJ_SANITY_MAX_COL_COUNT 0xFFFF #endif ////////////////////////////////////////////////////////////////////// typedef void* (*simple_mat_mul_function)( const unsigned, const unsigned, const unsigned, DBJ_MATRIX_DATA_TYPE[][*], DBJ_MATRIX_DATA_TYPE[][*], DBJ_MATRIX_DATA_TYPE[][*] /* the result */ ); typedef struct { const char* description; simple_mat_mul_function function; } simple_description_function_pair; #define DF_PAIR(D_, F_) \ (simple_description_function_pair) { .description = D_, .function = F_ } ////////////////////////////////////////////////////////////////////// DBJ_API DBJ_MATRIX_DATA_TYPE* new_simple_matrix(const unsigned, const unsigned); DBJ_API DBJ_MATRIX_DATA_TYPE* make_simple_matrix( const unsigned, const unsigned, DBJ_MATRIX_DATA_TYPE(*)(void)); DBJ_API void* simple_mat_transpose( const unsigned, const unsigned, DBJ_MATRIX_DATA_TYPE[][*], DBJ_MATRIX_DATA_TYPE[][*]); DBJ_API void* simple_mat_mul_null( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { // used for when algorithms are not implemented yet (void)a; (void)b; (void)m; return NULL; } DBJ_API void* simple_mat_mul_0_0( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE(*ax)[n_a_cols], DBJ_MATRIX_DATA_TYPE(*bx)[n_a_cols], DBJ_MATRIX_DATA_TYPE(*mx)[n_a_cols]); DBJ_API void* simple_mat_mul_0(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/]); DBJ_API void* simple_mat_mul_1(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/]); DBJ_API void* simple_mat_mul_3(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/]); DBJ_API void* simple_mat_mul_4(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE[/*n_a_rows*/][* /*n_b_cols*/]); #if __SSE__ DBJ_API void* simple_mat_mul_2(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE a[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE b[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE m[/*n_a_rows*/][* /*n_b_cols*/]); DBJ_API void* simple_mat_mul_7(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE a[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE b[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE m[/*n_a_rows*/][* /*n_b_cols*/]); #endif // __SSE__ #ifdef HAVE_CBLAS DBJ_API void* simple_mat_mul_5(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE a[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE b[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE m[/*n_a_rows*/][* /*n_b_cols*/]); DBJ_API void* simple_mat_mul_6(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, DBJ_MATRIX_DATA_TYPE a[/*n_a_rows*/][* /*n_a_cols*/], DBJ_MATRIX_DATA_TYPE b[/*n_a_rows*/][* /*n_b_cols*/], DBJ_MATRIX_DATA_TYPE m[/*n_a_rows*/][* /*n_b_cols*/]); #endif // HAVE_CBLAS const simple_description_function_pair dbj_simple_matmuls_algo_table[] = { DF_PAIR("0: MAX optimization", simple_mat_mul_0_0), DF_PAIR("1: simple naive - no optimization", simple_mat_mul_0), DF_PAIR("2: simple transposing the second matrix", simple_mat_mul_1), DF_PAIR("3: simple explicitly vectorized sdot() with SSE", simple_mat_mul_2), /* requires __SSE__ */ DF_PAIR("4: simple explicitly SSE sdot() plus loop tiling", simple_mat_mul_7) , /* requires __SSE__ */ DF_PAIR("5: simple implicitly vectorized sdot()", simple_mat_mul_3), DF_PAIR("6: simple no vectorization hints", simple_mat_mul_4), #ifdef HAVE_CBLAS DF_PAIR("7: simple with sdot() from an external CBLAS library", simple_mat_mul_5), DF_PAIR("8: simple with sgemm() from an external CBLAS library", simple_mat_mul_6), #endif // ! HAVE_CBLAS }; static const unsigned dbj_simple_matmuls_algo_table_size = (sizeof(dbj_simple_matmuls_algo_table) / sizeof(dbj_simple_matmuls_algo_table[0])); ////////////////////////////////////////////////////////////////////// #ifdef DBJ_VARIOUS_SIMPLE_MATMULS_IMPLEMENTATION ////////////////////////////////////////////////////////////////////// DBJ_API DBJ_MATRIX_DATA_TYPE* new_simple_matrix(const unsigned n_rows, const unsigned n_cols) { DBJ_MATRIX_DATA_TYPE* retval = calloc(n_rows * n_cols, sizeof(DBJ_MATRIX_DATA_TYPE)); if (!retval) { fprintf(stderr, "\n%s(%d) new_simple_matrix() failed?\n", __FILE__, __LINE__); perror(" "); exit(1); } return retval; } DBJ_API DBJ_MATRIX_DATA_TYPE* make_simple_matrix( const unsigned n_rows, const unsigned n_cols, DBJ_MATRIX_DATA_TYPE(*value_provider)(void)) { DBJ_MATRIX_DATA_TYPE* rezult = new_simple_matrix(n_rows, n_cols); typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_cols]; matrix mx = (matrix)rezult; for (unsigned i = 0; i < n_rows; ++i) for (unsigned j = 0; j < n_cols; ++j) mx[i][j] = value_provider(); // return rezult; } DBJ_API void* simple_mat_transpose( const unsigned n_rows, const unsigned n_cols, DBJ_MATRIX_DATA_TYPE a[static n_rows][n_cols], DBJ_MATRIX_DATA_TYPE m[static n_cols][n_rows]) { for (unsigned i = 0; i < n_rows; ++i) for (unsigned j = 0; j < n_cols; ++j) m[j][i] = a[i][j]; return m; } DBJ_API DBJ_MATRIX_DATA_TYPE simple_sdot_1(int n, const DBJ_MATRIX_DATA_TYPE x[static n], const DBJ_MATRIX_DATA_TYPE y[static n]) { DBJ_MATRIX_DATA_TYPE s = 0.0f; for (int i = 0; i < n; ++i) s += x[i] * y[i]; return s; } DBJ_API DBJ_MATRIX_DATA_TYPE simple_sdot_8(int n, const DBJ_MATRIX_DATA_TYPE x[static n], const DBJ_MATRIX_DATA_TYPE y[static n]) { int i, n8 = n >> 3 << 3; DBJ_MATRIX_DATA_TYPE s = 0.0f, t[8] = { 0.0f }; // t[0] = t[1] = t[2] = t[3] = t[4] = t[5] = t[6] = t[7] = 0.0f; for (i = 0; i < n8; i += 8) { t[0] += x[i + 0] * y[i + 0]; t[1] += x[i + 1] * y[i + 1]; t[2] += x[i + 2] * y[i + 2]; t[3] += x[i + 3] * y[i + 3]; t[4] += x[i + 4] * y[i + 4]; t[5] += x[i + 5] * y[i + 5]; t[6] += x[i + 6] * y[i + 6]; t[7] += x[i + 7] * y[i + 7]; } for (s = 0.0f; i < n; ++i) s += x[i] * y[i]; s += t[0] + t[1] + t[2] + t[3] + t[4] + t[5] + t[6] + t[7]; return s; } #ifdef __SSE__ DBJ_API DBJ_MATRIX_DATA_TYPE simple_sdot_sse(int n, const DBJ_MATRIX_DATA_TYPE x[static n], const DBJ_MATRIX_DATA_TYPE y[static n]) { int i, n8 = n >> 3 << 3; __m128 vs1, vs2; DBJ_MATRIX_DATA_TYPE s, t[4]; vs1 = _mm_setzero_ps(); vs2 = _mm_setzero_ps(); for (i = 0; i < n8; i += 8) { __m128 vx1, vx2, vy1, vy2; vx1 = _mm_loadu_ps(&x[i]); vx2 = _mm_loadu_ps(&x[i + 4]); vy1 = _mm_loadu_ps(&y[i]); vy2 = _mm_loadu_ps(&y[i + 4]); vs1 = _mm_add_ps(vs1, _mm_mul_ps(vx1, vy1)); vs2 = _mm_add_ps(vs2, _mm_mul_ps(vx2, vy2)); } for (s = 0.0f; i < n; ++i) s += x[i] * y[i]; _mm_storeu_ps(t, vs1); s += t[0] + t[1] + t[2] + t[3]; _mm_storeu_ps(t, vs2); s += t[0] + t[1] + t[2] + t[3]; return s; } #endif // __SSE__ /************************************************** Various Matrix multiplication algorithms NOTE: check and choose for your RT Env there are differences but are *very* dependant on compiler, OS and hardware */ DBJ_API void* simple_mat_mul_0_0( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE(*ax)[n_a_cols], DBJ_MATRIX_DATA_TYPE(*bx)[n_a_cols], DBJ_MATRIX_DATA_TYPE(*mx)[n_a_cols]) { // runtime casting takes time const unsigned n_b_rows = n_a_cols; // DBJ_MATRIX_DATA_TYPE(*ax)[n_a_cols] = a; // DBJ_MATRIX_DATA_TYPE(*bx)[n_b_cols] = b; // DBJ_MATRIX_DATA_TYPE(*mx)[n_b_rows] = m; for (unsigned i = 0; i < n_a_rows; ++i) { for (unsigned j = 0; j < n_b_cols; ++j) { DBJ_MATRIX_DATA_TYPE t = 0.0; for (unsigned k = 0; k < n_a_cols; ++k) t += ax[i][k] * bx[k][j]; mx[i][j] = t; } } return mx; } DBJ_API void* simple_mat_mul_0( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { for (unsigned i = 0; i < n_a_rows; ++i) { for (unsigned j = 0; j < n_b_cols; ++j) { DBJ_MATRIX_DATA_TYPE t = 0.0; for (unsigned k = 0; k < n_a_cols; ++k) t += a[i][k] * b[k][j]; m[i][j] = t; } } return m; } DBJ_API void* simple_mat_mul_1( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { const unsigned n_b_rows = n_a_cols; DBJ_MATRIX_DATA_TYPE* Temp = new_simple_matrix(n_b_cols, n_b_rows); // Temp rows and cols are inverted ! typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_b_rows]; matrix bT = (matrix)Temp; (void)simple_mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) { const DBJ_MATRIX_DATA_TYPE* ai = a[i]; DBJ_MATRIX_DATA_TYPE* mi = m[i]; for (unsigned j = 0; j < n_b_cols; ++j) { DBJ_MATRIX_DATA_TYPE t = 0.0f, * bTj = bT[j]; for (unsigned k = 0; k < n_a_cols; ++k) t += ai[k] * bTj[k]; mi[j] = t; } } free(Temp); return m; } DBJ_API void* simple_mat_mul_2( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { #ifndef __SSE__ #error __SEE__ is required here #endif const unsigned n_b_rows = n_a_cols; DBJ_MATRIX_DATA_TYPE* Temp = new_simple_matrix(n_b_cols, n_b_rows); // Temp rows and cols are inverted ! typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_b_rows]; matrix bT = (matrix)Temp; (void)simple_mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = simple_sdot_sse(n_a_cols, a[i], bT[j]); free(Temp); return m; } DBJ_API void* simple_mat_mul_7( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { #ifndef __SSE__ #error __SEE__ is required here #endif const unsigned x = 16, n_b_rows = n_a_cols; DBJ_MATRIX_DATA_TYPE* Temp = new_simple_matrix(n_b_cols, n_b_rows); // Temp rows and cols are inverted ! typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_b_rows]; matrix bT = (matrix)Temp; (void)simple_mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; i += x) { for (unsigned j = 0; j < n_b_cols; j += x) { unsigned je = n_b_cols < j + x ? n_b_cols : j + x; unsigned ie = n_a_rows < i + x ? n_a_rows : i + x; for (unsigned ii = i; ii < ie; ++ii) for (unsigned jj = j; jj < je; ++jj) m[ii][jj] += simple_sdot_sse(n_a_cols, a[ii], bT[jj]); } } free(Temp); return m; } ///////////////////////////////////////////////////////////////////////////////////// DBJ_API void* simple_mat_mul_3( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { int n_b_rows = n_a_cols; DBJ_MATRIX_DATA_TYPE* Temp = new_simple_matrix(n_b_cols, n_b_rows); // Temp rows and cols are inverted ! typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_b_rows]; matrix bT = (matrix)Temp; (void)simple_mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = simple_sdot_8(n_a_cols, a[i], bT[j]); free(Temp); return m; } DBJ_API void* simple_mat_mul_4( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { int n_b_rows = n_a_cols; DBJ_MATRIX_DATA_TYPE* Temp = new_simple_matrix(n_b_cols, n_b_rows); // Temp rows and cols are inverted ! typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_b_rows]; matrix bT = (matrix)Temp; (void)simple_mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = simple_sdot_1(n_a_cols, a[i], bT[j]); free(Temp); return m; } #ifdef HAVE_CBLAS DBJ_API void* simple_mat_mul_5( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { const unsigned n_b_rows = n_a_cols; DBJ_MATRIX_DATA_TYPE* Temp = new_simple_matrix(n_rows, n_cols); // Temp rows and cols are inverted ! typedef DBJ_MATRIX_DATA_TYPE(*matrix)[n_rows]; matrix bT = (matrix)Temp; (void)simple_mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = cblas_sdot(n_a_cols, a[i], 1, bT[j], 1); // clas_sdot() ??? free(Temp); return m; } DBJ_API void* simple_mat_mul_6( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, DBJ_MATRIX_DATA_TYPE a[static n_a_rows][n_a_cols], DBJ_MATRIX_DATA_TYPE b[static n_a_rows][n_b_cols], DBJ_MATRIX_DATA_TYPE m[static n_a_rows][n_b_cols]) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_a_rows, n_b_cols, n_a_cols, 1.0f, a[0], n_a_rows, b[0], n_b_rows, 0.0f, m[0], n_a_rows); return m; } #endif // HAVE_CBLAS ////////////////////////////////////////////////////////////////////// #endif // DBJ_VARIOUS_SIMPLE_MATMULS_IMPLEMENTATION ////////////////////////////////////////////////////////////////////// #undef DF_PAIR #endif // DBJ_VARIOUS_SIMPLE_MATMULS_INC
{ "alphanum_fraction": 0.679201639, "avg_line_length": 35.2703962704, "ext": "h", "hexsha": "db4362cb1894d2c795fd39ee8901e5dfae1b04f8", "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": "e1f1c6ce0724afa3afb8d38bcc63e4772b9f2866", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "DBJDBJ/dbj_matmul", "max_forks_repo_path": "r_and_d/simple_matmuls.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e1f1c6ce0724afa3afb8d38bcc63e4772b9f2866", "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": "DBJDBJ/dbj_matmul", "max_issues_repo_path": "r_and_d/simple_matmuls.h", "max_line_length": 163, "max_stars_count": null, "max_stars_repo_head_hexsha": "e1f1c6ce0724afa3afb8d38bcc63e4772b9f2866", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "DBJDBJ/dbj_matmul", "max_stars_repo_path": "r_and_d/simple_matmuls.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4823, "size": 15131 }
#pragma once #include <type_traits> #include <utility> #include <cuda/define_specifiers.hpp> #include <cuda/runtime_api.hpp> #include <gsl-lite/gsl-lite.hpp> namespace thrustshift { namespace kernel { template <typename SrcT, typename DstT, class F> __global__ void transform(gsl_lite::span<const SrcT> src, gsl_lite::span<DstT> dst, F f) { const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; if (gtid < src.size()) { dst[gtid] = f(src[gtid]); } } } // namespace kernel namespace async { template <class SrcRange, class DstRange, class UnaryFunctor> void transform(cuda::stream_t& stream, SrcRange&& src, DstRange&& dst, UnaryFunctor f) { gsl_Expects(src.size() == dst.size()); if (src.empty()) { return; } using src_value_type = typename std::remove_reference<SrcRange>::type::value_type; using dst_value_type = typename std::remove_reference<DstRange>::type::value_type; constexpr cuda::grid::block_dimension_t block_dim = 128; const cuda::grid::dimension_t grid_dim = (src.size() + block_dim - 1) / block_dim; auto c = cuda::make_launch_config(grid_dim, block_dim); auto k = kernel::transform<src_value_type, dst_value_type, decltype(f)>; cuda::enqueue_launch(k, stream, c, src, dst, f); } } // namespace async namespace array { namespace detail { template <typename T, std::size_t N, template <typename, std::size_t> class Arr, class F, std::size_t... I> CUDA_FHD auto transform_impl(const Arr<T, N>& arr, F&& f, std::index_sequence<I...>) { return Arr<T, N>({f(arr[I])...}); } } // namespace detail template <typename T, std::size_t N, template <typename, std::size_t> class Arr, class F, typename Indices = std::make_index_sequence<N>> CUDA_FHD auto transform(const Arr<T, N>& arr, F&& f) { return detail::transform_impl(arr, std::forward<F>(f), Indices{}); } } // namespace array namespace tuple { namespace detail { template <typename Tuple, typename F, std::size_t... I> CUDA_FHD auto transform_impl(Tuple&& t, F&& f, std::index_sequence<I...>) { using TupleT = typename std::remove_reference<Tuple>::type; using std::get; return TupleT(f(get<I>(t))...); } } // namespace detail template <typename... Ts, template <typename...> class TupleT, typename F> CUDA_FHD auto transform(TupleT<Ts...> const& t, F&& f) { using std::tuple_size; auto seq = std::make_index_sequence<tuple_size<TupleT<Ts...>>::value>{}; return detail::transform_impl(t, std::forward<F>(f), seq); } } // namespace tuple } // namespace thrustshift
{ "alphanum_fraction": 0.6369912791, "avg_line_length": 25.247706422, "ext": "h", "hexsha": "bd0c8e69731f2359c238e5275e56f83c4d51ee2f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_path": "include/thrustshift/transform.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_path": "include/thrustshift/transform.h", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_path": "include/thrustshift/transform.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 683, "size": 2752 }
/** * \file gps_single.c Implements GPS single point solution using Least Squares * \author Duncan Greer * $Id: gps_single.c 3579 2010-06-26 10:57:31Z greerd $ */ #include <stdio.h> #include <sys/types.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <time.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_linalg.h> #include "../../novatelstore/src/novatel.h" #include "gps.h" #include "../../novatelstore/src/shmdef.h" #include "matrix.h" /** Controls whether or not the program should keep running. */ int iShutdown = 0; #define MODULE_NAME "[GPS_SINGLE]" #define log(string) fprintf(stdout,"%s %s\n", MODULE_NAME, string) #define err(string) fprintf(stderr,"%s ERROR: %s\n", MODULE_NAME, string) #define ELEVATION_CUTOFF_RAD (10.0 * DEG2RAD) /** \function CalculateDOP Calculates the Dilution of Precision based on the provided G Matrix. \author Duncan Greer and Troy Bruggemann Note that the G-Matrix must be provided already transformed to the horizontal plane. */ void CalculateDOP(gsl_matrix *G, double *DOP); /** * \fn HandleSignal * \brief Handle caught signals * * This function sets a flag (iShutdown) to shut the program down. */ void HandleSignal(int signal) { fprintf(stdout,"Got Signal: %d\n",signal); iShutdown = 1; } /** * \fn Usage * \brief Print Usage Information */ void Usage(char *arg) { /* options */ /* b = baudrate p = port l = logging f = log filename t = enable tcp server */ fprintf(stdout,"Usage: %s <options>\n",arg); fprintf(stdout," -l Log results to file (OFF)\n"); fprintf(stdout," -f log filename\n"); fprintf(stdout," -L Use specified log file path (/data/gps)\n"); } int main (int argc, char **argv) { gsl_matrix *G; gsl_matrix *G_LTP; // gsl_matrix *GT; // gsl_matrix *tempNN; // gsl_matrix *V; // gsl_vector *S; // gsl_matrix *U; gsl_vector *W; gsl_vector *y; gsl_vector *delta_y; gsl_vector *x; gsl_vector *delta_x; gsl_vector *x_error; gsl_vector *x_true; gsl_vector *temp1; gsl_multifit_linear_workspace *gsl_workspace; gsl_vector *SVPos[MAX_SV]; double SVPos_calc[4]; double dSSE; gsl_matrix *SolutionCovariance; int iReturnValue = 0; int iNumberStates = 4; int iNumberMeasurements = 9; int iNumberValidEphemeris = 0; int iNumberValidObservations = 0; int iIndex; GPSTime gtObservationTime; unsigned short usPRN; int iIteration; int iUseSV[NOVATEL_MAXPRNS]; double user_x,user_y,user_z,user_t = 0.0; double sat_x,sat_y,sat_z,sat_t; // double sat_x_calc,sat_y_calc,sat_z_calc,sat_t_calc; double dTemp; double range; double delta_pr_omegaedot; double ecef[3]; double llh[3]; double TECEF2ENU[3][3]; gsl_matrix *T_ECEF2NED_44; double NEDError[3]; double ECEFError[3]; double UserPos[4]; double ION_Alpha[4]; double ION_Beta[4]; double IonoDelay[NOVATEL_MAXCHANNELS]; double TropoDelay[NOVATEL_MAXCHANNELS]; double SV_Azimuth[NOVATEL_MAXCHANNELS]; double SV_Elevation[NOVATEL_MAXCHANNELS]; double dTransmissionTime; GPSEPHEM GPSEphemData[NOVATEL_MAXPRNS]; RANGE GPSRangeData; double GDOP,PDOP; double DOPS[5]; double limit; int iUseSHM = 1; int iSHM_FID; int iRow,iCol; shm_struct *shm = NULL; unsigned long ulSignalType = 0; char copt; /* log files */ FILE *fpLogFile = NULL; /* pointer to log file stream */ char azcLogFileName[256]; /* log file name */ char azcLogFilePath[255]; char azcLogFileNameWithPath[1024]; struct tm *timestruct; time_t tCurrentTime = 0; time_t tLogFileStart = 0; /* options flags */ struct { int iLogResults; int iCustomLogFile; } options; // default options options.iLogResults = 0; options.iCustomLogFile = 0; /* setup signal handlers */ signal(SIGHUP, HandleSignal); signal(SIGTERM, HandleSignal); signal(SIGKILL, HandleSignal); signal(SIGALRM, HandleSignal); signal(SIGINT, HandleSignal); /* get the current time to use as a timestamp in the log file name */ tCurrentTime = time(NULL); timestruct = gmtime(&tCurrentTime); /* setting default log file path */ sprintf(azcLogFilePath,"%s","/data/gps"); /* read input parameters */ while((copt = getopt(argc,argv,"lf:L:")) && copt != -1) { switch(copt) { case 'l': /* log results to file */ options.iLogResults = 1; log("Logging enabled"); strftime(azcLogFileName,sizeof(azcLogFileName),"gps_single_%g%m%d%H%M%S.csv",timestruct); break; case 'f': /* set the log file name */ sprintf(azcLogFileName,"%s",optarg); options.iCustomLogFile = 1; /* since we're using a user specified log file name, we dont want to recycle it every hour */ break; case 'L': /* setting log file path */ sprintf(azcLogFilePath,"%s",optarg); fprintf(stdout,"%s Setting log file path to %s",MODULE_NAME,azcLogFilePath); break; case '?': Usage(argv[0]); return 0; break; } } for(iIndex=0;iIndex<NOVATEL_MAXPRNS;iIndex++) { iUseSV[iIndex] = 0; } fprintf(stdout,"Allocating Matrices\n"); x = gsl_vector_alloc(iNumberStates); delta_x = gsl_vector_alloc(iNumberStates); x_true = gsl_vector_alloc(iNumberStates); x_error = gsl_vector_alloc(iNumberStates); SolutionCovariance = gsl_matrix_alloc(iNumberStates,iNumberStates); temp1 = gsl_vector_alloc(3); for(iIndex=0;iIndex<MAX_SV;iIndex++) { SVPos[iIndex] = gsl_vector_alloc(4); } T_ECEF2NED_44 = gsl_matrix_alloc(4,4); /* setup shared memory */ if(iUseSHM == 1) { iSHM_FID = shm_open("/novatel0",O_RDWR,0777); if(iSHM_FID == -1) { perror("shm_open: "); iUseSHM = 0; } else { /* memory map the shm object */ shm = mmap(0,sizeof(*shm),PROT_READ,MAP_SHARED,iSHM_FID,0); if(shm == MAP_FAILED) { perror("shm mmap: "); iUseSHM = 0; } else { fprintf(stdout,"%s SHM Address Is: 0x%08x\n",MODULE_NAME,(unsigned int)shm); } } } /* setup time */ gtObservationTime.usGPSWeek = 1416; gtObservationTime.fGPSSecondOfWeek = 135900.0; /* setup measurements */ /* GPSRangeData.usPRN[0] = 10; GPSRangeData.usPRN[1] = 12; GPSRangeData.usPRN[2] = 30; GPSRangeData.usPRN[3] = 29; GPSRangeData.usPRN[4] = 7; GPSRangeData.usPRN[5] = 26; GPSRangeData.usPRN[6] = 22; GPSRangeData.usPRN[7] = 24; GPSRangeData.dPseudorange[0] = 23677691.85548; GPSRangeData.dPseudorange[1] = 24609189.10747; GPSRangeData.dPseudorange[2] = 22288602.64148; GPSRangeData.dPseudorange[3] = 22641003.92448; GPSRangeData.dPseudorange[4] = 20042814.45649; GPSRangeData.dPseudorange[5] = 23024522.23148; GPSRangeData.dPseudorange[6] = 24837761.16146; GPSRangeData.dPseudorange[7] = 21114887.48349; */ /* setup sat positions */ /* estimated position - starting point */ gsl_vector_set(x,0,-5046773.0); gsl_vector_set(x,1, 2568446.0); gsl_vector_set(x,2,-2925289.0); gsl_vector_set(x,3, 0.0); llh[0] = -0.47; llh[1] = 2.53; llh[2] = 0.0; //gsl_vector_fprintf(stdout,x,"%10.3f"); /* true position */ gsl_vector_set(x_true,0,-5053034.84 ); gsl_vector_set(x_true,1, 2562951.08); gsl_vector_set(x_true,2,-2919245.94); gsl_vector_set(x_true,3,0.0); /* // PRN 10 gsl_vector_set(SVPos[10],0,-11106779.576); gsl_vector_set(SVPos[10],1,-10162086.179); gsl_vector_set(SVPos[10],2,-21984106.076); gsl_vector_set(SVPos[10],3, 98.034009e-6*GPS_SPEEDOFLIGHT); // PRN 12 gsl_vector_set(SVPos[12],0,-20114520.008); gsl_vector_set(SVPos[12],1, 6748657.642); gsl_vector_set(SVPos[12],2, 16058860.089); gsl_vector_set(SVPos[12],3,-47.814630e-6*GPS_SPEEDOFLIGHT); // PRN 30 gsl_vector_set(SVPos[30],0, -19111202.845); gsl_vector_set(SVPos[30],1, 17011909.480); gsl_vector_set(SVPos[30],2, 6599201.305); gsl_vector_set(SVPos[30],3, 26.513082e-6*GPS_SPEEDOFLIGHT); // PRN 29 gsl_vector_set(SVPos[29],0, -22931680.210); gsl_vector_set(SVPos[29],1, -10007127.790); gsl_vector_set(SVPos[29],2, -9208106.350); gsl_vector_set(SVPos[29],3, 358.103982e-6*GPS_SPEEDOFLIGHT); // PRN 7 gsl_vector_set(SVPos[7],0, -18000552.275); gsl_vector_set(SVPos[7],1, 10196913.772); gsl_vector_set(SVPos[7],2, -16363130.228); gsl_vector_set(SVPos[7],3, 402.849928e-6*GPS_SPEEDOFLIGHT); // PRN 26 gsl_vector_set(SVPos[26],0, -24783876.733); gsl_vector_set(SVPos[26],1, -8910991.974); gsl_vector_set(SVPos[26],2, -5742918.813); gsl_vector_set(SVPos[26],3, -62.236139e-6*GPS_SPEEDOFLIGHT); // PRN 22 gsl_vector_set(SVPos[22],0, -8616964.914); gsl_vector_set(SVPos[22],1, 22105308.026); gsl_vector_set(SVPos[22],2, 12074730.766); gsl_vector_set(SVPos[22],3, 169.425839e-6*GPS_SPEEDOFLIGHT); // PRN 24 gsl_vector_set(SVPos[24],0, -15110809.416); gsl_vector_set(SVPos[24],1, 2514877.198); gsl_vector_set(SVPos[24],2, -21514889.442); gsl_vector_set(SVPos[24],3, 80.656626e-6*GPS_SPEEDOFLIGHT); */ /* open log file */ if(options.iLogResults == 1) { sprintf(azcLogFileNameWithPath,"%s/%s",azcLogFilePath,azcLogFileName); if((fpLogFile = fopen(azcLogFileNameWithPath,"a")) == NULL) { fprintf(stderr,"Error opening %s for writing: %s\n",azcLogFileNameWithPath,strerror(errno)); return -1; } else { tLogFileStart = tCurrentTime; fprintf(stdout,"Using log file: %s\n",azcLogFileNameWithPath); } } while(iShutdown == 0) { /* if log file has been opend for > 1 hour, start a new one */ if(options.iLogResults == 1 && options.iCustomLogFile == 0) { tCurrentTime = time(NULL); if(difftime(tCurrentTime,tLogFileStart) > 3600.0) { /* start a new log file */ fclose(fpLogFile); timestruct = gmtime(&tCurrentTime); strftime(azcLogFileName,sizeof(azcLogFileName),"gps_single_%g%m%d%H%M%S.csv",timestruct); sprintf(azcLogFileNameWithPath,"%s/%s",azcLogFilePath,azcLogFileName); if((fpLogFile = fopen(azcLogFileNameWithPath,"a")) == NULL) { fprintf(stderr,"Error opening %s for writing: %s\n",azcLogFileNameWithPath,strerror(errno)); options.iLogResults = 0; } else { tLogFileStart = tCurrentTime; fprintf(stdout,"%s Started New Logfile: %s\n",MODULE_NAME,azcLogFileNameWithPath); } } } /* TODO: replace this sleep with a semaphore to wait for new data */ sleep(1); fprintf(stdout,"====== Single-Point Solution ======\n"); /* retrive the current data from shm */ if(iUseSHM == 1) { memcpy(&GPSEphemData,&shm->CurrentGPSEPHEM,sizeof(GPSEPHEM)*NOVATEL_MAXPRNS); // get the current observation time to compare with ephemeris memcpy(&gtObservationTime,&shm->CurrentRANGE.gtTimeStamp,sizeof(GPSTime)); /* ensure we have ephemeris for all measurements, otherwise exclude */ iNumberValidEphemeris = 0; for(iIndex=0;iIndex<NOVATEL_MAXPRNS;iIndex++) { if((GPSEphemData[iIndex].ulPRN != 0) && (GPSEphemData[iIndex].ulHealth == 0) && (GPSEphemData[iIndex].dTOE < (gtObservationTime.fGPSSecondOfWeek+7500.0)) && (GPSEphemData[iIndex].dTOE > (gtObservationTime.fGPSSecondOfWeek-7500.0)) ) { iUseSV[iIndex] = 1; iNumberValidEphemeris++; // fprintf(stdout,"SV%d ",iIndex); } else { iUseSV[iIndex] = 0; } } /* loop through measurements and see if we have valid ephem for each */ memcpy(&GPSRangeData.gtTimeStamp,&shm->CurrentRANGE.gtTimeStamp,sizeof(GPSTime)); iNumberValidObservations = 0; for(iIndex=0;iIndex<shm->CurrentRANGE.lNumberObservations;iIndex++) { if(iUseSV[shm->CurrentRANGE.usPRN[iIndex]] == 1) { ulSignalType = shm->CurrentRANGE.ulTrackingStatus[iIndex] & 0x3E00000; // check that we're only getting hte L1 signal if (ulSignalType == 0) { // use current range data for now memcpy(&GPSRangeData.usPRN[iNumberValidObservations], &shm->CurrentRANGE.usPRN[iIndex],sizeof(unsigned short)); memcpy(&GPSRangeData.dPseudorange[iNumberValidObservations], &shm->CurrentRANGE.dPseudorange[iIndex], sizeof(double)); iNumberValidObservations++; } else { // not an L1 obs //fprintf(stdout,"Value of Signal Type for PRN%02d was 0x%0x\n", // shm->CurrentRANGE.usPRN[iIndex], // ulSignalType); } } else { fprintf(stdout,"NE: %d; ",shm->CurrentRANGE.usPRN[iIndex]); } } fprintf(stdout,"Obs: %d; \n",iNumberValidObservations); GPSRangeData.lNumberObservations = iNumberValidObservations; iNumberMeasurements = GPSRangeData.lNumberObservations; if(iNumberMeasurements < 4) { fprintf(stdout,"Less than 4 measurements\n"); continue; } /* if(iNumberMeasurements > 9) { iNumberMeasurements = 9; } if(iNumberMeasurements < 9) { err("Less than 9 measurements!"); } */ G = gsl_matrix_alloc(iNumberMeasurements,iNumberStates); G_LTP = gsl_matrix_alloc(iNumberMeasurements,iNumberStates); y = gsl_vector_alloc(iNumberMeasurements); delta_y = gsl_vector_alloc(iNumberMeasurements); W = gsl_vector_alloc(iNumberMeasurements); gsl_workspace = gsl_multifit_linear_alloc (iNumberMeasurements,iNumberStates); /* calculate G-matrix */ gsl_matrix_set_zero (G); //gsl_matrix_fprintf(stdout,G,"%5.3f"); /* calculate W-matrix */ gsl_vector_set_all(W,1.0); } else { log("No Shared Memory"); } for(iIteration=0;iIteration<20;iIteration++) { // fprintf(stdout,"\n===== ITERATION %d =====\n",iIteration+1); user_x = gsl_vector_get(x,0); user_y = gsl_vector_get(x,1); user_z = gsl_vector_get(x,2); user_t = gsl_vector_get(x,3); UserPos[0] = user_x; UserPos[1] = user_y; UserPos[2] = user_z; UserPos[3] = user_t; ION_Alpha[0] = shm->CurrentIONUTC.a0; ION_Alpha[1] = shm->CurrentIONUTC.a1; ION_Alpha[2] = shm->CurrentIONUTC.a2; ION_Alpha[3] = shm->CurrentIONUTC.a3; ION_Beta[0] = shm->CurrentIONUTC.b0; ION_Beta[1] = shm->CurrentIONUTC.b1; ION_Beta[2] = shm->CurrentIONUTC.b2; ION_Beta[3] = shm->CurrentIONUTC.b3; // fprintf(stdout,"User: [%+10.3f\t%+10.3f\t%+10.3f\t%+10.3f]\n",user_x,user_y,user_z,user_t); for (iIndex=0;iIndex<iNumberMeasurements;iIndex++) { dTransmissionTime = (double)gtObservationTime.fGPSSecondOfWeek - GPSRangeData.dPseudorange[iIndex]/GPS_SPEEDOFLIGHT; GPSOrbitPropagator(dTransmissionTime, GPSRangeData.usPRN[iIndex], &GPSEphemData[GPSRangeData.usPRN[iIndex]], 7500.0, SVPos_calc); usPRN = GPSRangeData.usPRN[iIndex]; sat_x = SVPos_calc[0]; sat_y = SVPos_calc[1]; sat_z = SVPos_calc[2]; sat_t = SVPos_calc[3]*GPS_SPEEDOFLIGHT; // find the range //gsl_vector_memcpy(temp1,SVPos[usPRN]); //gsl_vector_sub(temp1,x); gsl_vector_set(temp1,0,sat_x - user_x); gsl_vector_set(temp1,1,sat_y - user_y); gsl_vector_set(temp1,2,sat_z - user_z); range = gsl_blas_dnrm2(temp1); gsl_matrix_set(G,iIndex,0,-(sat_x - user_x)/range); gsl_matrix_set(G,iIndex,1,-(sat_y - user_y)/range); gsl_matrix_set(G,iIndex,2,-(sat_z - user_z)/range); gsl_matrix_set(G,iIndex,3,1.0); gsl_vector_set(y,iIndex,GPSRangeData.dPseudorange[iIndex]); // calculate earth rotation correction delta_pr_omegaedot = -(GPS_OMEGAEDOT/GPS_SPEEDOFLIGHT) * (sat_x*user_y - sat_y*user_x); // calculate iono correction ICD200_IonoModel(gtObservationTime, UserPos, SVPos_calc, ION_Alpha, ION_Beta, &IonoDelay[iIndex], &SV_Azimuth[iIndex], &SV_Elevation[iIndex]); // examine sv elevations - if less than cutoff, set corresponding row of 'G' to zeros if (SV_Elevation[iIndex] < ELEVATION_CUTOFF_RAD) { gsl_matrix_set(G,iIndex,0,0.0); gsl_matrix_set(G,iIndex,1,0.0); gsl_matrix_set(G,iIndex,2,0.0); gsl_matrix_set(G,iIndex,3,0.0); fprintf(stdout,"Ignoring PRN%02d due low elevation (%3.1fdeg)\n", GPSRangeData.usPRN[iIndex],SV_Elevation[iIndex]*RAD2DEG); TropoDelay[iIndex] = 0.0; gsl_vector_set(delta_y,iIndex,0.0); } else { TropoDelay[iIndex] = TropoDelayModel(SV_Elevation[iIndex],llh[2]); gsl_vector_set(delta_y,iIndex,GPSRangeData.dPseudorange[iIndex]-range-(user_t-sat_t)+delta_pr_omegaedot-IonoDelay[iIndex]-TropoDelay[iIndex]); } // fprintf(stdout,"Sat %d:\t[%+10.3f\t%+10.3f\t%+10.3f\t%+10.3f] range=%f, delta_pr=%f\n",usPRN,sat_x,sat_y,sat_z,sat_t,range,delta_pr_omegaedot); // fprintf(stdout,"Sat %d:\t[%+10.3f\t%+10.3f\t%+10.3f\t%+10.3f]\n",usPRN,sat_x,sat_y,sat_z,sat_t); } // fprintf(stdout,"delta_y: \n"); // gsl_vector_fprintf(stdout,delta_y,"%10.3f"); // fprintf(stdout,"G-Matrix: \n"); // for (iIndex=0;iIndex<iNumberMeasurements;iIndex++) // { // fprintf(stdout,"[%+10.3f\t%+10.3f\t%+10.3f\t%+10.3f]\n", // gsl_matrix_get(G,iIndex,0), // gsl_matrix_get(G,iIndex,1), // gsl_matrix_get(G,iIndex,2), // gsl_matrix_get(G,iIndex,3)); // // } /* weight measurements according to elevation */ // for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) // { // gsl_vector_set(W,iIndex,SV_Elevation[iIndex]); // } //gsl_vector_fprintf(stdout,W,"%f"); iReturnValue = gsl_multifit_wlinear(G, W, delta_y, delta_x, SolutionCovariance, &dSSE, gsl_workspace); /*iReturnValue = gsl_multifit_linear(G, delta_y, delta_x, SolutionCovariance, &dSSE, gsl_workspace); */ gsl_vector_add(x,delta_x); // fprintf(stdout,"Least-squares fit returned value: %d; RSS=%f\n",iReturnValue,sqrt(dSSE)); // fprintf(stdout,"delta_x: \n"); // gsl_vector_fprintf(stdout,delta_x,"%20.12f"); gsl_vector_memcpy(x_error,x); gsl_vector_sub(x_error,x_true); /* test if we should break out */ limit = gsl_blas_dnrm2(delta_x); if (limit < 1e-8) { fprintf(stdout,"%f:Least-Squares solved in %d iterations; RSS=%f\n", gtObservationTime.fGPSSecondOfWeek,iIteration+1,sqrt(dSSE)); /* convert to LLH */ ecef[0] = gsl_vector_get(x,0); ecef[1] = gsl_vector_get(x,1); ecef[2] = gsl_vector_get(x,2); WGS84_ECEF2LLH(ecef, llh); T_ECEF2ENU(llh[0], llh[1], (double **)TECEF2ENU); // fprintf(stdout,"[%f %f %f]\n",TECEF2ENU[0][0],TECEF2ENU[0][1],TECEF2ENU[0][2]); // fprintf(stdout,"[%f %f %f]\n",TECEF2ENU[1][0],TECEF2ENU[1][1],TECEF2ENU[1][2]); // fprintf(stdout,"[%f %f %f]\n",TECEF2ENU[2][0],TECEF2ENU[2][1],TECEF2ENU[2][2]); ECEFError[0] = gsl_vector_get(x_error,0); ECEFError[1] = gsl_vector_get(x_error,1); ECEFError[2] = gsl_vector_get(x_error,2); MatMul331(TECEF2ENU, ECEFError, NEDError); /* must swap ENU to NED */ dTemp = NEDError[0]; NEDError[0] = NEDError[1]; NEDError[1] = dTemp; NEDError[2] = -NEDError[2]; //fprintf(stdout,"X error: \n"); //gsl_vector_fprintf(stdout,x_error,"%10.5f m"); //fprintf(stdout,"X: \n"); //gsl_vector_fprintf(stdout,x,"%10.5f m"); /* calculate DOPS */ for(iRow=0;iRow<3;iRow++) { for(iCol=0;iCol<3;iCol++) { // note that TECEF2ENU must be transposed gsl_matrix_set(T_ECEF2NED_44, iRow,iCol,TECEF2ENU[iCol][iRow]); } gsl_matrix_set(T_ECEF2NED_44,iRow,3,0.0); } for(iCol=0;iCol<3;iCol++) { gsl_matrix_set(T_ECEF2NED_44,3,iCol,0.0); } gsl_matrix_set(T_ECEF2NED_44,3,3,1.0); gsl_matrix_set_zero(G_LTP); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, G, T_ECEF2NED_44, 1.0, G_LTP); CalculateDOP(G_LTP,DOPS); GDOP = DOPS[0]; PDOP = DOPS[1]; /* write results to shared memory */ // memcpy(&shm->dDOPS[0],&DOPS[0],sizeof(double)); // memcpy(shm->dLLH_LSQ,llh,sizeof(double)*3); // memcpy(shm->dECEF_LSQ,ecef,sizeof(double)*3); // shm->dRxClock_LSQ = gsl_vector_get(x,3); fprintf(stdout,"Lat: %f, Long: %f, Height: %f\n", llh[0]*RAD2DEG,llh[1]*RAD2DEG,llh[2]); fprintf(stdout,"GDOP=%f, PDOP=%f, HDOP=%f, VDOP=%f, TDOP=%f\n", GDOP,PDOP,DOPS[2],DOPS[3],DOPS[4]); fprintf(stdout,"NED Error: %fm %fm %fm\n",NEDError[0], NEDError[1], NEDError[2]); fprintf(stdout,"SV: "); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { fprintf(stdout,"%d ",GPSRangeData.usPRN[iIndex]); } fprintf(stdout,"\n"); fprintf(stdout,"Iono: "); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { fprintf(stdout,"%3.1fm ",IonoDelay[iIndex]); } fprintf(stdout,"\n"); fprintf(stdout,"Tropo: "); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { fprintf(stdout,"%3.1fm ",TropoDelay[iIndex]); } fprintf(stdout,"\n"); fprintf(stdout,"Elevation: "); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { fprintf(stdout,"%3.1f ",SV_Elevation[iIndex]*RAD2DEG); } fprintf(stdout,"\n"); fprintf(stdout,"Azimuth: "); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { fprintf(stdout,"%3.1f ",SV_Azimuth[iIndex]*RAD2DEG); } fprintf(stdout,"\n"); // check if we should log to disk if(options.iLogResults == 1 && fpLogFile != NULL) { fprintf(fpLogFile, "%d,%f,%d,%lf,%d,%lf,%lf,%lf,%.10lf,%.10lf,%lf,%f,%f,%f,%f,%f\n", gtObservationTime.usGPSWeek, gtObservationTime.fGPSSecondOfWeek, iIteration+1, sqrt(dSSE), iNumberMeasurements, ecef[0], ecef[1], ecef[2], llh[0], llh[1], llh[2], DOPS[0], DOPS[1], DOPS[2], DOPS[3], DOPS[4] ); fflush(fpLogFile); } break; } } if (iIteration == 20) { fprintf(stderr,"Iterated 20 times with no solution (limit=%f)", limit); } gsl_matrix_free(G); gsl_matrix_free(G_LTP); gsl_vector_free(W); gsl_vector_free(y); gsl_vector_free(delta_y); gsl_multifit_linear_free(gsl_workspace); } fclose(fpLogFile); fprintf(stdout,"Freeing Matrices\n"); gsl_vector_free(x); gsl_vector_free(delta_x); gsl_vector_free(x_true); gsl_vector_free(x_error); gsl_vector_free(temp1); gsl_matrix_free(SolutionCovariance); gsl_matrix_free(T_ECEF2NED_44); for(iIndex=0;iIndex<MAX_SV;iIndex++) { gsl_vector_free(SVPos[iIndex]); } return 0; } void CalculateDOP(gsl_matrix *G, double *DOP) { gsl_matrix *GT; gsl_matrix *tempNN; gsl_matrix *V; gsl_vector *S; gsl_vector *Sinv; gsl_matrix *SinvMat; gsl_matrix *A; // = inv(GT*G); gsl_vector *SVDWork; gsl_matrix *U; int iReturnValue,iIndex; int iNumberMeasurements,iNumberStates; double var_x,var_y,var_z,var_dt; iNumberMeasurements = G->size1; iNumberStates = G->size2; GT = gsl_matrix_alloc(iNumberStates,iNumberMeasurements); tempNN = gsl_matrix_alloc(iNumberStates,iNumberStates); V = gsl_matrix_alloc(iNumberStates,iNumberStates); S = gsl_vector_alloc(iNumberStates); Sinv = gsl_vector_alloc(iNumberStates); SinvMat = gsl_matrix_alloc(iNumberStates,iNumberStates); A = gsl_matrix_alloc(iNumberStates,iNumberStates); SVDWork = gsl_vector_alloc(iNumberStates); U = gsl_matrix_alloc(iNumberStates,iNumberStates); // calculate DOP gsl_matrix_transpose_memcpy(GT,G); gsl_matrix_set_zero(tempNN); gsl_blas_dgemm (CblasNoTrans,CblasNoTrans, 1.0, GT, G, 1.0, tempNN); // take the SVD of GT*T (stored in TempNN) to find inverse - tempNN now contains 'U' iReturnValue = gsl_linalg_SV_decomp (tempNN,V,S,SVDWork); // get element wise inverse of S gsl_vector_set_all(Sinv,1.0); gsl_vector_div(Sinv, S); gsl_matrix_set_zero (SinvMat); for(iIndex=0;iIndex<iNumberStates;iIndex++) { gsl_matrix_set(SinvMat,iIndex,iIndex,gsl_vector_get(Sinv,iIndex)); } // inv(S)*UT gsl_matrix_memcpy(U,tempNN); gsl_matrix_set_zero (tempNN); gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0, SinvMat, U, 1.0, tempNN); // A = V * inv(S) * UT gsl_matrix_set_zero(A); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, V, tempNN, 1.0, A); var_x = gsl_matrix_get(A,0,0); var_y = gsl_matrix_get(A,1,1); var_z = gsl_matrix_get(A,2,2); var_dt = gsl_matrix_get(A,3,3); DOP[0] = sqrt(var_x+var_y+var_z+var_dt); DOP[1] = sqrt(var_x+var_y+var_z); DOP[2] = sqrt(var_x+var_y); DOP[3] = sqrt(var_z); DOP[4] = sqrt(var_dt); gsl_matrix_free(GT); gsl_matrix_free(tempNN); gsl_matrix_free(A); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(Sinv); gsl_matrix_free(U); gsl_vector_free(SVDWork); gsl_matrix_free(SinvMat); }
{ "alphanum_fraction": 0.6689590624, "avg_line_length": 25.1525076766, "ext": "c", "hexsha": "375d5fdd4ef5832668405b6429acc6fd62f3334f", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2019-11-14T08:30:11.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-01T20:17:26.000Z", "max_forks_repo_head_hexsha": "729c561ebf3b08d6dc9f57814c550a4724a386af", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "duncang/gpsins", "max_forks_repo_path": "src/gps_single.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "729c561ebf3b08d6dc9f57814c550a4724a386af", "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": "duncang/gpsins", "max_issues_repo_path": "src/gps_single.c", "max_line_length": 149, "max_stars_count": 2, "max_stars_repo_head_hexsha": "729c561ebf3b08d6dc9f57814c550a4724a386af", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "duncang/gpsins", "max_stars_repo_path": "src/gps_single.c", "max_stars_repo_stars_event_max_datetime": "2020-07-11T06:23:46.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T14:23:48.000Z", "num_tokens": 8377, "size": 24574 }
// Copyright (c) 2005 Stanford University (USA). // All rights reserved. // // This file is part of CGAL (www.cgal.org); 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. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Daniel Russel <drussel@alumni.princeton.edu> #ifndef CGAL_POLYNOMIAL_INTERNAL_GSL_NUMERIC_SOLVER_H #define CGAL_POLYNOMIAL_INTERNAL_GSL_NUMERIC_SOLVER_H #include <CGAL/Polynomial/basic.h> #include <CGAL/Polynomial/internal/numeric_solvers_support.h> #include <vector> #ifdef CGAL_POLYNOMIAL_USE_GSL #include <gsl/gsl_poly.h> #include <gsl/gsl_errno.h> namespace CGAL { namespace POLYNOMIAL { namespace internal { /*template <bool CLEAN> inline double gsl_max_error() { if (CLEAN) return .0000005; else return 0; }*/ template <bool CLEAN> inline void gsl_compute_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots_) { //double max_error=gsl_max_error<CLEAN>(); gsl_poly_complex_workspace *workspace; int degree= end-begin-1; workspace= gsl_poly_complex_workspace_alloc(degree+1); //! I can't use auto_ptr because it is an array double *roots= new double[2*degree]; /*for ( int i=0; i< 2*fn.degree(); ++i){ roots[i]=0; }*/ int ret = gsl_poly_complex_solve(begin, degree+1, workspace, roots); roots_.reserve(ret); if (ret!=GSL_SUCCESS) { std::cerr << "GSL solver did not converge on "; std::copy(begin, end, std::ostream_iterator<double>(std::cerr, " ")); std::cerr << std::endl; } double last= -std::numeric_limits<double>::infinity(); for ( int i=degree-1; i>=0; --i) { double r= roots[2*i]; double c= roots[2*i+1]; if (root_is_good(r, c, lb, ub)) { roots_.push_back(r); } else if (CLEAN && root_is_good(r,c, last, ub)) { last= r; } } std::sort(roots_.begin(), roots_.end(), std::greater<double>() ); delete roots; gsl_poly_complex_workspace_free(workspace); if (CLEAN) filter_solver_roots(begin,end, lb, ub, last, roots_); return; } template <bool CLEAN> inline void gsl_compute_cubic_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots_) { CGAL_Polynomial_precondition(begin[3] != 0); //double max_error=gsl_max_error<CLEAN>(); double r[3]; int num_roots= gsl_poly_solve_cubic(begin[2]/begin[3], begin[1]/begin[3], begin[0]/begin[3], &r[0],&r[1],&r[2]); roots_.reserve(num_roots); double last= -std::numeric_limits<double>::infinity(); // I want reverse sorted roots for (int i=num_roots-1; i>=0; --i) { if (r[i]> lb && r[i] < ub) roots_.push_back(r[i]); else if (CLEAN && r[i] <lb && r[i] > last){ last= r[i]; } } if (CLEAN) filter_solver_roots(begin, end, lb, ub, last, roots_); } inline void gsl_polynomial_compute_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots) { int degree= end-begin-1; switch( degree) { case -1: case 0: break; case 1: compute_linear_roots(begin,end, lb, ub, roots); break; case 2: compute_quadratic_roots(begin, end, lb, ub, roots); break; case 3: gsl_compute_cubic_roots<false>(begin, end, lb, ub, roots); break; default: gsl_compute_roots<false>(begin, end, lb, ub, roots); } } inline void gsl_polynomial_compute_cleaned_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots) { int degree= end-begin-1; switch( degree) { case -1: case 0: break; case 1: compute_linear_cleaned_roots(begin,end, lb, ub, roots); break; case 2: compute_quadratic_cleaned_roots(begin, end, lb, ub, roots); break; case 3: gsl_compute_cubic_roots<true>(begin, end, lb, ub, roots); break; default: gsl_compute_roots<true>(begin, end, lb, ub, roots); } } inline double gsl_evaluate_polynomial(const double *b, const double *e, double t) { if (b==e) return 0; /*double *d= new double[coefs.size()]; for (unsigned int i=0; i< coefs.size(); ++i){ d[i]= coefs[i]; }*/ double v= gsl_poly_eval(b, e-b, t); return v; } /* inline void gsl_polynomial_compute_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots){ CGAL_assertion(0&& no_gsl_support_built); } inline void gsl_polynomial_compute_cleaned_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots){ CGAL_assertion(0&& no_gsl_support_built); } inline double gsl_evaluate_polynomial(const double *b, const double *e, double t) { CGAL_assertion(0&& no_gsl_support_built); return std::numeric_limits<double>::nan(); } */ /*// GSL void gsl_polynomial_compute_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots); void gsl_polynomial_compute_cleaned_roots(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots);*/ struct GSL_numeric_solver { void operator()(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots) const { gsl_polynomial_compute_roots(begin, end, lb, ub, roots); } }; struct GSL_cleaned_numeric_solver { void operator()(const double *begin, const double *end, double lb, double ub, std::vector<double> &roots) const { gsl_polynomial_compute_cleaned_roots(begin, end, lb, ub, roots); } }; } } } //namespace CGAL::POLYNOMIAL::internal #endif // CGAL_POLYNOMIAL_USE_GSL #endif
{ "alphanum_fraction": 0.6467075279, "avg_line_length": 27.7860262009, "ext": "h", "hexsha": "6808909e1a27c243c20d416af9319309f2048ea6", "lang": "C", "max_forks_count": 34, "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Polynomial/internal/GSL_numeric_solver.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Polynomial/internal/GSL_numeric_solver.h", "max_line_length": 88, "max_stars_count": 187, "max_stars_repo_head_hexsha": "2b29c03cdac6f5e1ceac4cd2f15b594040ef909c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vipuserr/vipuserr-Geological-hazard", "max_stars_repo_path": "geo3d/include/CGAL/Polynomial/internal/GSL_numeric_solver.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "num_tokens": 1700, "size": 6363 }
/* This file forms part of hpGEM. This package has been developed over a number of years by various people at the University of Twente and a full list of contributors can be found at http://hpgem.org/about-the-code/team This code is distributed using BSD 3-Clause License. A copy of which can found below. Copyright (c) 2020, University of Twente All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HPGEM_MATRIXBLOCKS_H #define HPGEM_MATRIXBLOCKS_H #include <vector> #include <petsc.h> #include "LinearAlgebra/MiddleSizeMatrix.h" namespace DGMax { using namespace hpgem; /// A block from the global matrix, or a pair of blocks that are placed /// symmetrically. class MatrixBlocks { public: MatrixBlocks(std::vector<PetscInt> rowIndices, std::vector<PetscInt> columnIndices, LinearAlgebra::MiddleSizeMatrix block) : rowIndices_(std::move(rowIndices)), columnIndices_(std::move(columnIndices)), block1_(std::move(block)), pair_(false){}; MatrixBlocks(std::vector<PetscInt> rowIndices, std::vector<PetscInt> columnIndices, LinearAlgebra::MiddleSizeMatrix block1, LinearAlgebra::MiddleSizeMatrix block2) : rowIndices_(std::move(rowIndices)), columnIndices_(std::move(columnIndices)), block1_(std::move(block1)), block2_(std::move(block2)), pair_(true){}; /// Number of entries in the matrix block. If this is pair, then this gives /// the size of a single block. std::size_t getBlockSize() const { return rowIndices_.size() * columnIndices_.size(); } /// Whether this is a pair of blocks or a single block. bool isPair() const { return pair_; } /// \brief Load blocks into temporary storage for insertion. /// /// This stores the raw entries of the block in the storage space for use /// with insertBlocks(). The first getBlockSize() entries of the storage are /// used for storing the first matrix block. If this object is a pair then /// the subsequent getBlockSize() entries will be used for the second block. /// /// \param storage The storage to use, will be resized if necessary. void loadBlocks(std::vector<PetscScalar>& storage) const { // Make sure we have enough space std::size_t storageSize = getBlockSize(); std::size_t storageMultiplier = pair_ ? 2 : 1; if (storage.size() < storageMultiplier * storageSize) { storage.resize(storageMultiplier * storageSize); } // Copy data for (std::size_t i = 0; i < storageSize; ++i) { storage[i] = block1_[i]; } if (pair_) { for (std::size_t i = 0; i < storageSize; ++i) { storage[i + storageSize] = block2_[i]; } } } /// \brief Insert the block or blocks in a PetscMatrix. void insertBlocks(std::vector<PetscScalar>& storage, Mat mat) const { insertBlock(storage, false, mat); if (pair_) { insertBlock(storage, true, mat); } } private: /// The global indices for the rows std::vector<PetscInt> rowIndices_; /// The global indices for the columns std::vector<PetscInt> columnIndices_; /// The primary block LinearAlgebra::MiddleSizeMatrix block1_; /// The symmetrically placed block LinearAlgebra::MiddleSizeMatrix block2_; /// Whether this is a single block or a symmetrically placed pair. bool pair_; /// Helper function inserting a single block. void insertBlock(std::vector<PetscScalar>& storage, bool hermitianPart, Mat mat) const; /// Validate the correctnees void validate() const; }; } // namespace DGMax #endif // HPGEM_MATRIXBLOCKS_H
{ "alphanum_fraction": 0.6892173583, "avg_line_length": 37.6928571429, "ext": "h", "hexsha": "0c2a331b3719d0e0062451d01f1ed3341377db95", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-08-21T07:20:42.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-10T09:19:33.000Z", "max_forks_repo_head_hexsha": "b2f7ac6bdef3262af0c3e8559cb991357a96457f", "max_forks_repo_licenses": [ "BSD-3-Clause-Clear" ], "max_forks_repo_name": "hpgem/hpgem", "max_forks_repo_path": "applications/DG-Max/Utils/MatrixBlocks.h", "max_issues_count": 139, "max_issues_repo_head_hexsha": "b2f7ac6bdef3262af0c3e8559cb991357a96457f", "max_issues_repo_issues_event_max_datetime": "2022-03-10T20:58:14.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-06T12:42:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Clear" ], "max_issues_repo_name": "hpgem/hpgem", "max_issues_repo_path": "applications/DG-Max/Utils/MatrixBlocks.h", "max_line_length": 80, "max_stars_count": 5, "max_stars_repo_head_hexsha": "b2f7ac6bdef3262af0c3e8559cb991357a96457f", "max_stars_repo_licenses": [ "BSD-3-Clause-Clear" ], "max_stars_repo_name": "hpgem/hpgem", "max_stars_repo_path": "applications/DG-Max/Utils/MatrixBlocks.h", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:48:12.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-01T15:35:26.000Z", "num_tokens": 1172, "size": 5277 }
#ifndef __Rand_H__ #define __Rand_H__ #define RAND Rand::Instance() #include <gsl/gsl_rng.h> // GSL random number generator #include <gsl/gsl_randist.h> /* * Rand Singleton - interface to GSL rng (random number generator) * * Singletons and global variables are sometimes frowned-upon, but doing it this * way means the objects don't need to be passed around to all and sundry. * I think convenience and clarity sometimes trump dogma. */ class Rand { private: Rand() { m_Rng = NULL; }; Rand(Rand const&) = delete; Rand& operator = (Rand const&) = delete; static Rand* m_Instance; gsl_rng* m_Rng; // GSL random number generator unsigned long int m_Seed; public: static Rand* Instance(); void Initialise(); void Free(); unsigned long int CurrentSeed() { return m_Seed; } unsigned long int DefaultSeed() { return gsl_rng_default_seed; } unsigned long int Seed(const unsigned long p_Seed) { gsl_rng_set(m_Rng, p_Seed); m_Seed = p_Seed; return p_Seed; } double Random(); double Random(const double p_Lower, const double p_Upper); int RandomInt(const int p_Lower, const int p_Upper); int RandomInt(const int p_Upper) { return p_Upper < 0 ? 0 : RandomInt(0, p_Upper); } double RandomGaussian(const double p_Sigma); }; #endif // __Rand_H__
{ "alphanum_fraction": 0.5993527508, "avg_line_length": 29.1509433962, "ext": "h", "hexsha": "f0701820022338e5413cd8789cd5fe6e464d4575", "lang": "C", "max_forks_count": 34, "max_forks_repo_forks_event_max_datetime": "2022-03-23T00:50:08.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-05T03:36:57.000Z", "max_forks_repo_head_hexsha": "63e1aeef4ed37ff661b8118842ef73a4e9bea1fd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "avigna/COMPAS-1", "max_forks_repo_path": "src/Rand.h", "max_issues_count": 427, "max_issues_repo_head_hexsha": "63e1aeef4ed37ff661b8118842ef73a4e9bea1fd", "max_issues_repo_issues_event_max_datetime": "2022-03-25T08:52:28.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-04T01:54:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "avigna/COMPAS-1", "max_issues_repo_path": "src/Rand.h", "max_line_length": 133, "max_stars_count": 40, "max_stars_repo_head_hexsha": "63e1aeef4ed37ff661b8118842ef73a4e9bea1fd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "avigna/COMPAS-1", "max_stars_repo_path": "src/Rand.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T08:53:06.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-04T01:50:58.000Z", "num_tokens": 351, "size": 1545 }
/* ----------------------------------------------------------------------------- JAM_AXI_VEL_LOSINT Calculates integrand for line-of-sight integral required for first moment calculation. INPUTS zp : line-of-sight coordinate z' (integration variable) params : function parameters passed as a structure NOTES * Based on janis1_jeans_mge_los_integrand IDL code by Michele Cappellari. Laura L Watkins [lauralwatkins@gmail.com] This code is released under a BSD 2-clause license. If you use this code for your research, please cite: Watkins et al. 2013, MNRAS, 436, 2598 "Discrete dynamical models of omega Centauri" http://adsabs.harvard.edu/abs/2013MNRAS.436.2598W ----------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include "jam.h" #include "../mge/mge.h" double jam_axi_vel_losint(double zp, void *params) { struct params_losint *lp; struct params_mgeint mp; double xp, yp, si, ci, r, z, r2, z2, nu, intg, result, error, nu_i; double sign_kappa, sum; int i; // get parameters lp = params; xp = lp->xp; yp = lp->yp; // if the integrationFlag is already set, do not proceed if (*lp->integrationFlag!=0) { return 0.; } // intrinsic R and z si = sin(lp->incl); ci = cos(lp->incl); r = sqrt(pow(zp*si - yp*ci, 2) + pow(xp, 2)); // eqn 25 z = sqrt(pow(zp*ci + yp*si, 2)); // do some prep for the integrand to avoid repeat calculations r2 = r * r; z2 = z * z; // parameters for integrand function mp.r2 = r2; mp.z2 = z2; mp.pot = lp->pot; mp.s2p = lp->s2p; mp.e2p = lp->e2p; // perform integration gsl_integration_workspace *w = gsl_integration_workspace_alloc(1000); gsl_set_error_handler_off(); gsl_function F; F.function = &jam_axi_vel_mgeint; sum = 0.; for (i=0; i<lp->lum->ntotal; i++) { if (lp->kappa[i]==0.) sign_kappa = 0.; else sign_kappa = lp->kappa[i]/fabs(lp->kappa[i]); nu_i = lp->lum->area[i] * exp(-0.5/lp->s2l[i]*(r2+z2/lp->q2l[i])); mp.bani = lp->bani[i]; mp.s2l = lp->s2l[i]; mp.q2l = lp->q2l[i]; mp.s2q2l = lp->s2q2l[i]; F.params = &mp; *lp->integrationFlag += gsl_integration_qag(&F, 0., 1., 0., 1e-5, 1000, 6, w, &result, &error); sum += sign_kappa * pow(lp->kappa[i], 2) * nu_i * fabs(result); } gsl_integration_workspace_free(w); // check if the integration failed if (*lp->integrationFlag!=0) { return 0.; } // mge volume density nu = mge_dens(lp->lum, r, z); // keep track of kappa signs - see note 8 p77 of Cappellari 2008 intg = nu*sum/fabs(nu*sum)*sqrt(fabs(nu*sum)); intg *= pow(zp, lp->zpow); return intg; }
{ "alphanum_fraction": 0.5527440026, "avg_line_length": 28.4392523364, "ext": "c", "hexsha": "477498c004427fa754ebcaf77be672c1958a7991", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-02T13:33:21.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-25T09:30:07.000Z", "max_forks_repo_head_hexsha": "6ed576de012cc368f65acaf17432aa66a0933520", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "slzoutendijk/cjam", "max_forks_repo_path": "src/jam/jam_axi_vel_losint.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6ed576de012cc368f65acaf17432aa66a0933520", "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": "slzoutendijk/cjam", "max_issues_repo_path": "src/jam/jam_axi_vel_losint.c", "max_line_length": 80, "max_stars_count": 12, "max_stars_repo_head_hexsha": "6ed576de012cc368f65acaf17432aa66a0933520", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "slzoutendijk/cjam", "max_stars_repo_path": "src/jam/jam_axi_vel_losint.c", "max_stars_repo_stars_event_max_datetime": "2021-12-18T12:50:31.000Z", "max_stars_repo_stars_event_min_datetime": "2016-05-27T06:10:56.000Z", "num_tokens": 945, "size": 3043 }
#ifndef LVV_MULTIMIN_H #define LVV_MULTIMIN_H #include <stdlib.h> #include <iostream> using std::cerr; #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_multimin.h> #include <lvv/lvv.h> #include <lvv/math.h> namespace lvv { class f_minimizer { public: f_minimizer (const int N, double F(const gsl_vector*, void *), double *xa, double *ssa, void *var, bool _trace=false) : T (gsl_multimin_fminimizer_nmsimplex), trace(_trace), found(false), fmin(999999) { minex_func.n = N; minex_func.f = F; minex_func.params = var; mk_gsl_vector x (xa,N);// this is auto on stack(temp), will be copied in minimizer, // so we are fine when it will go out of scope mk_gsl_vector ss(ssa, N); //gv_x = gsl_vector_alloc(N); for (int i=0; i<N; i++) gsl_vector_set(gv_x, i, xa [i]); //gv_ss = gsl_vector_alloc(N); for (int i=0; i<N; i++) gsl_vector_set(gv_ss, i, ssa[i]); minimizer = gsl_multimin_fminimizer_alloc(T, N); gsl_multimin_fminimizer_set(minimizer, &minex_func, &x , &ss); //gsl_multimin_fminimizer_set(minimizer, &minex_func, gv_x, gv_ss); xmin = minimizer->x->data; if (trace) cout << "# minimizer: " << gsl_multimin_fminimizer_name (minimizer) << endl; }; ~f_minimizer () { gsl_multimin_fminimizer_free(minimizer); /* gsl_vector_free(gv_x); gsl_vector_free(gv_ss) ;*/ }; void find_min (double characteristic_size, int max_iter) { int test_status=GSL_CONTINUE; // test_status: GSL_SUCCESS==0; GSL_CONTINUE==-2; if (trace) FMT("# Itr %10t Y %20t Step %30t X[0..]\n"); for ( iter=0; iter<max_iter && (test_status==GSL_CONTINUE); ++iter ) { int iterate_status = gsl_multimin_fminimizer_iterate(minimizer); if (iterate_status) { cerr << "error: FMinimizer: in gsl_multimin_fminimizer_iterate()\n"; break; } double size = gsl_multimin_fminimizer_size(minimizer); test_status = gsl_multimin_test_size(size, characteristic_size); if (test_status == GSL_SUCCESS) { found=true; fmin=minimizer->fval; if (trace ) cout << "converged to minimum at\n"; } if (trace) { FMT("%5d %10.5d %10.5d") %iter %(minimizer->fval) %size; for (unsigned i=0; i < minimizer->x->size; ++i) FMT("%10.5d") %gsl_vector_get(minimizer->x, i); cout << endl; } } } const gsl_multimin_fminimizer_type *T; gsl_multimin_fminimizer *minimizer; gsl_multimin_function minex_func; bool trace; bool found; double *xmin; double fmin; gsl_vector *gv_x; gsl_vector *gv_ss; int iter; }; } // namespace #endif // LVV_MULTIMIN_H
{ "alphanum_fraction": 0.6276978417, "avg_line_length": 31.2359550562, "ext": "h", "hexsha": "9abb437794040b886210ef854900638defd96ba2", "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": "b610a089103853e7cf970efde2ce4bed9f505090", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lvv/lvvlib", "max_forks_repo_path": ".old/nelder-mead-min.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b610a089103853e7cf970efde2ce4bed9f505090", "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": "lvv/lvvlib", "max_issues_repo_path": ".old/nelder-mead-min.h", "max_line_length": 133, "max_stars_count": 13, "max_stars_repo_head_hexsha": "b610a089103853e7cf970efde2ce4bed9f505090", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lvv/lvvlib", "max_stars_repo_path": ".old/nelder-mead-min.h", "max_stars_repo_stars_event_max_datetime": "2020-09-14T23:13:14.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-05T12:26:16.000Z", "num_tokens": 859, "size": 2780 }
/* * This file contains functions used to call sequential MKL/BLAS/LAPACK routines * * Authors : Sebastien Cayrols * : Olivier Tissot * Email : sebastien.cayrols@[(gmail.com) | (inria.fr)] * : olivier.tissot@inria.fr */ /******************************************************************************/ /* INCLUDE */ /******************************************************************************/ /* STD */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> /* MKL/LAPACK */ #ifdef LAPACKEACTIVATE #include <lapacke.h> #include <cblas.h> #endif /* MPI */ #include <mpi.h> /* CPaLAMeM */ //#include "cpalamem_macro.h" #undef TIMERACTIVATE #include "cplm_utils.h" #include "cplm_timing.h" #include "cplm_matcsr.h" #include "cplm_kernels.h" #include "cplm_QS.h" //#include "cpalamem_instrumentation.h" /******************************************************************************/ /******************************************************************************/ /* CODE */ /******************************************************************************/ int CPLM_MatDenseKernelCholesky(CPLM_Mat_Dense_t* C_io) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; int matrix_layout = 0; int order = 0; int lda = 0; char uplo = 0; CPLM_ASSERT(C_io != NULL); CPLM_ASSERT(C_io->val != NULL); matrix_layout = (C_io->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; uplo = 'U'; order = C_io->info.n; lda = C_io->info.lda; ierr = LAPACKE_dpotrf( matrix_layout, uplo, order, C_io->val, lda);CPLM_CHKERR(ierr); if (ierr > 0) { CPLM_Abort("The matrix is not SPD!"); } CPLM_END_TIME CPLM_POP return ierr; } //TODO Remove malloc and explain why H int CPLM_MatDenseKernelQR( CPLM_Mat_Dense_t* A_io, CPLM_Mat_Dense_t* H_io, int index_i, int index_j) //to be verified { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; int matrix_layout = -1; double *tau = NULL; tau = malloc(A_io->info.N*sizeof(double)); CPLM_ASSERT(tau != NULL); matrix_layout = (A_io->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; ierr = LAPACKE_dgeqrf( matrix_layout, A_io->info.M, A_io->info.N, A_io->val, A_io->info.lda, tau);CPLM_CHKERR(ierr); if(H_io->val != NULL)//[Q] why test on val and not on H alone? { ierr = CPLM_MatDenseTriangularFillBlock( A_io, H_io, index_i, index_j, A_io->info.N);CPLM_CHKERR(ierr); } ierr = LAPACKE_dorgqr( matrix_layout, A_io->info.M, A_io->info.N, A_io->info.N, A_io->val, A_io->info.lda, tau);CPLM_CHKERR(ierr); free(tau); CPLM_END_TIME CPLM_POP return ierr; } int CPLM_MatDenseKernelLowerTriangularLeftSolve(CPLM_Mat_Dense_t* L, CPLM_Mat_Dense_t* B) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; int matrix_layout = 0; int m = 0; int nrhs = 0; char uplo = 'L'; // L is lower triangular char trans = 'N'; // No transpose, no conjugacy char diag = 'N'; // No unitary CPLM_ASSERT(L != NULL); CPLM_ASSERT(L->val != NULL); CPLM_ASSERT(B != NULL); CPLM_ASSERT(B->val != NULL); matrix_layout = (L->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; m = B->info.m; nrhs = B->info.n; ierr = LAPACKE_dtrtrs(matrix_layout, uplo, trans, diag, m, nrhs, L->val, L->info.lda, B->val, B->info.lda);CPLM_CHKERR(ierr); CPLM_END_TIME CPLM_POP return ierr; } int CPLM_MatDenseKernelUpperTriangularLeftSolve(CPLM_Mat_Dense_t* R, CPLM_Mat_Dense_t* B) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; int matrix_layout = -1; int m = 0; int nrhs = 0; char uplo = 'U'; // R is upper triangular char trans = 'N'; // No transpose, no conjugacy char diag = 'N'; // No unitary CPLM_ASSERT(R != NULL); CPLM_ASSERT(R->val != NULL); CPLM_ASSERT(B != NULL); CPLM_ASSERT(B->val != NULL); matrix_layout = (R->info.stor_type == ROW_MAJOR) ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; m = B->info.m; nrhs = B->info.n; ierr = LAPACKE_dtrtrs(matrix_layout, uplo, trans, diag, m, nrhs, R->val, R->info.lda, B->val, B->info.lda);CPLM_CHKERR(ierr); CPLM_END_TIME CPLM_POP return ierr; } //#ifdef MKLACTIVATE //B is triangular int CPLM_MatDenseDtrmm(CPLM_Mat_Dense_t *A_in , CPLM_Mat_Dense_t *B_io , char side , char uplo , char trans , char diag) { CPLM_PUSH int ierr = 0; CBLAS_LAYOUT matrix_layout = -1; CBLAS_DIAG blasDiag = CblasNonUnit; CBLAS_SIDE blasSide = CblasLeft; CBLAS_UPLO blasUPLO = CblasUpper; CBLAS_TRANSPOSE blasTrans = CblasTrans; CPLM_ASSERT(A_in->val != NULL); CPLM_ASSERT(B_io->val != NULL); blasDiag = (diag == 'U') ? CblasUnit : CblasNonUnit; blasSide = (side == 'R') ? CblasRight : CblasLeft; blasUPLO = (uplo == 'L') ? CblasLower : CblasUpper; blasTrans = (trans == 'T') ? CblasTrans : CblasNoTrans; matrix_layout = (A_in->info.stor_type == ROW_MAJOR) ? CblasRowMajor : CblasColMajor; cblas_dtrmm(matrix_layout, blasSide, blasUPLO, blasTrans, blasDiag, A_in->info.m, A_in->info.n, 1.0, A_in->val, A_in->info.lda, B_io->val, B_io->info.lda); CPLM_POP return ierr; } //#else // #ifdef LAPACKEACTIVATE // int CPLM_MatDenseDtrmm(CPLM_Mat_Dense_t *A_in , // CPLM_Mat_Dense_t *B_io , // char side , // char uplo , // char trans , // char diag) // { // CPLM_PUSH // int ierr = 0; // // CPLM_ASSERT(A_in->val != NULL); // CPLM_ASSERT(B_io->val != NULL); // // if(A_in->info.stor_type == ROW_MAJOR) // { // CPLM_Abort("Do not call trmm with row major"); // } // // dtrmm( // side, // uplo, // trans, // diag, // A_in->info.m, // A_in->info.n, // 1.0, // A_in->val, // A_in->info.lda, // B_io->val, // B_io->info.lda); // CPLM_POP // return ierr; // } // #endif //#endif // C=alpha A^{transa} * B^{transb} + beta C int CPLM_MatDenseKernelMatMult(CPLM_Mat_Dense_t* A, char ptransa, CPLM_Mat_Dense_t* B, char ptransb, CPLM_Mat_Dense_t* C, double alpha, double beta) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; CBLAS_TRANSPOSE transa; CBLAS_TRANSPOSE transb; // Allocate memory if needed if (C->val == NULL) { int Crow, Ccol, CrowGlob, CcolGlob; CrowGlob = (ptransa == 'N') ? A->info.M : A->info.N; Crow = (ptransa == 'N') ? A->info.m : A->info.n; CcolGlob = (ptransb == 'N') ? B->info.N : B->info.M; Ccol = (ptransb == 'N') ? B->info.n : B->info.m; ierr = CPLM_MatDenseSetInfo(C, CrowGlob, CcolGlob, Crow, Ccol, A->info.stor_type); // We use A storage type but this // is arbitrary CPLM_CHKERR(ierr); ierr = CPLM_MatDenseMalloc(C); CPLM_CHKERR(ierr); } transa = (ptransa == 'N') ? CblasNoTrans : CblasTrans; transb = (ptransb == 'N') ? CblasNoTrans : CblasTrans; // BLAS parameters CBLAS_LAYOUT layout = (A->info.stor_type == ROW_MAJOR) ? CblasRowMajor : CblasColMajor; int nbColOpA = (transa == CblasNoTrans) ? A->info.n : A->info.m; cblas_dgemm (layout, transa, transb, C->info.m, C->info.n, nbColOpA, alpha, A->val, A->info.lda, B->val, B->info.lda, beta, C->val, C->info.lda);CPLM_CHKERR(ierr); CPLM_END_TIME CPLM_POP return ierr; } int CPLM_MatDenseKernelUpperTriangularRightSolve(CPLM_Mat_Dense_t* R, CPLM_Mat_Dense_t* B) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; CBLAS_LAYOUT matrix_layout = -1; #ifdef MKLACTIVATE MKL_INT m = 0; MKL_INT nrhs = 0; #elif defined(LAPACKEACTIVATE) int m = 0; int nrhs = 0; #endif double alpha = 1e0; CPLM_ASSERT(R != NULL); CPLM_ASSERT(R->val != NULL); CPLM_ASSERT(B != NULL); CPLM_ASSERT(B->val != NULL); matrix_layout = (R->info.stor_type == ROW_MAJOR) ? CblasRowMajor : CblasColMajor; m = B->info.m; nrhs = B->info.n; cblas_dtrsm(matrix_layout, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, m, nrhs, alpha, R->val, R->info.lda, B->val, B->info.lda); CPLM_END_TIME CPLM_POP return ierr; } // y = beta*y + alpha*A*x int CPLM_MatDenseKernelMatVec(CPLM_Mat_Dense_t* A_in, double* x_in, double* y_io, double alpha, double beta) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; CBLAS_LAYOUT layout = -1; CPLM_ASSERT(A_in != NULL); CPLM_ASSERT(x_in != NULL); CPLM_ASSERT(y_io != NULL); CPLM_ASSERT(A_in->val != NULL); /* if (*y_io == NULL) */ /* { */ /* y_io = malloc(A_in->info.m*sizeof(double)); */ /* } */ // BLAS parameters layout = (A_in->info.stor_type == ROW_MAJOR) ? CblasRowMajor : CblasColMajor; cblas_dgemv(layout, CblasNoTrans, A_in->info.m, A_in->info.n, alpha, A_in->val, A_in->info.lda, x_in, 1, // increment for the elements of x beta, y_io, 1); // increment of the elements of y CPLM_END_TIME CPLM_POP return ierr; } int CPLM_MatDenseKernelSumColumns(CPLM_Mat_Dense_t* A_in, double* sumCol) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; CPLM_ASSERT(A_in->val != NULL); CPLM_ASSERT(sumCol != NULL); double* ones = (double*) malloc(A_in->info.n*sizeof(double)); for (int i = 0; i < A_in->info.n; ++i) ones[i] = 1.E0; ierr = CPLM_MatDenseKernelMatVec(A_in, ones, sumCol, 1.0, 0.0);CPLM_CHKERR(ierr); if (ones != NULL) free(ones); CPLM_END_TIME CPLM_POP return ierr; } #ifdef MKLACTIVATE // C = A + B using mkl int CPLM_MatDenseKernelMatAdd(CPLM_Mat_Dense_t* A_in, CPLM_Mat_Dense_t* B_in, CPLM_Mat_Dense_t* C_out, double alpha, double beta) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; char ordering = 0; char transa = 0; char transb = 0; if(!CPLM_MatDenseIsSameLocalInfo(A_in,B_in)) { CPLM_MatDensePrintfInfo("A info",A_in); CPLM_MatDensePrintfInfo("B info",B_in); CPLM_Abort("A and B do not have the same structure"); } // Allocate memory if needed if(C_out->val == NULL) { ierr = CPLM_MatDenseInit(C_out, A_in->info);CPLM_CHKERR(ierr); ierr = CPLM_MatDenseMalloc(C_out);CPLM_CHKERR(ierr); } // BLAS parameters ordering = (A_in->info.stor_type == ROW_MAJOR) ? 'R' : 'C'; transa = 'N'; transb = 'N'; mkl_domatadd (ordering, transa, transb, A_in->info.m, A_in->info.n, alpha, A_in->val, A_in->info.lda, beta, B_in->val, B_in->info.lda, C_out->val, C_out->info.lda); CPLM_END_TIME CPLM_POP return ierr; } int CPLM_MatCSRKernelMatDenseMult(CPLM_Mat_CSR_t *A_in, CPLM_Mat_Dense_t *B_in, CPLM_Mat_Dense_t *C_io, double alpha, double beta) { CPLM_PUSH CPLM_BEGIN_TIME CPLM_OPEN_TIMER int ierr = 0; char matdescra[6]; char trans = 'N'; CPLM_ASSERT(A_in != NULL); CPLM_ASSERT(B_in != NULL); CPLM_ASSERT(C_io != NULL); CPLM_ASSERT(A_in->val != NULL); CPLM_ASSERT(B_in->val != NULL); matdescra[0] = 'G'; matdescra[1] = 'L';//ignored if G matdescra[2] = 'N';//ignored if G matdescra[3] = 'C'; if(C_io->val == NULL) { ierr = CPLM_MatDenseSetInfo(C_io, A_in->info.m, B_in->info.n, A_in->info.m, B_in->info.n, B_in->info.stor_type);CPLM_CHKERR(ierr); ierr = CPLM_MatDenseMalloc(C_io);CPLM_CHKERR(ierr); } #ifdef DEBUG CPLM_MatCSRPrintf2D("M1",A_in); CPLM_MatDensePrintf2D("* M2",B_in); #endif CPLM_TIC(step1, "ConvertTo1BasedIndexing") // If COL_MAJOR we need to use 1-base indexes (don't ask why...) if (B_in->info.stor_type == COL_MAJOR) { matdescra[3] = 'F'; CPLM_MatCSRConvertTo1BasedIndexing(A_in); } CPLM_TAC(step1) CPLM_TIC(step2, "Call SpBLAS") mkl_dcsrmm(&trans, &A_in->info.m, &B_in->info.n, &A_in->info.n, &alpha, matdescra, A_in->val, A_in->colInd, A_in->rowPtr, &(A_in->rowPtr[1]), B_in->val, &(B_in->info.lda), &beta, C_io->val, &C_io->info.lda); CPLM_TAC(step2) // Back to 0-base indexes :) CPLM_TIC(step3, "ConvertTo0BasedIndexing") if (B_in->info.stor_type == COL_MAJOR) { CPLM_MatCSRConvertTo0BasedIndexing(A_in); } CPLM_TAC(step3) #ifdef DEBUG CPLM_MatDensePrintf2D("= ",C_io); #endif CPLM_CLOSE_TIMER CPLM_END_TIME CPLM_POP return ierr; } int CPLM_MatCSRKernelGenMatDenseMult(double *val_in, int *colInd_in, int *rowPtrB_in, int *rowPtrE_in, int nrowA_in, int ncolA_in, CPLM_Mat_Dense_t *B_in, CPLM_Mat_Dense_t *C_io, double alpha, double beta) { CPLM_PUSH CPLM_BEGIN_TIME CPLM_OPEN_TIMER int ierr = 0; char matdescra[6]; matdescra[0] = 'G'; matdescra[1] = 'L';//ignored if G matdescra[2] = 'N';//ignored if G char trans = 'N'; CPLM_ASSERT(C_io->val != NULL); if (B_in->info.stor_type == COL_MAJOR) matdescra[3] = 'F'; else matdescra[3] = 'C'; CPLM_TIC(step1, "Call SpBLAS") mkl_dcsrmm(&trans, &nrowA_in, &B_in->info.n, &ncolA_in, &alpha, matdescra, val_in, colInd_in, rowPtrB_in, rowPtrE_in, B_in->val, &B_in->info.lda, &beta, C_io->val, &C_io->info.lda); CPLM_TAC(step1) CPLM_CLOSE_TIMER CPLM_END_TIME CPLM_POP return ierr; } void CPLM_MatCSRPARDISOSetParameters(MKL_INT* iparam_io) { CPLM_PUSH CPLM_ASSERT(iparam_io != NULL); memset(iparam_io,0,64*sizeof(MKL_INT)); iparam_io[0] = 1; // Non standard solver iparam_io[1] = 2; // Metis permutation to reduce fill-in iparam_io[4] = 0; // Return Metis permutation iparam_io[9] = 13; // Pivot perturbation iparam_io[24] = 0; // Sequential forward and backward solve iparam_io[26] = 0; // Check A iparam_io[34] = 1; // C-style array indexing (starts from 0) // iparam_io[17] = -1; // iparam_io[18] = -1; CPLM_POP } int CPLM_MatCSRPARDISOFree(CPLM_Mat_CSR_t* A_in, _MKL_DSS_HANDLE_t pardisoHandle_io, MKL_INT* iparam_in, MKL_INT mtype_in) { CPLM_PUSH MKL_INT maxfct = 1; MKL_INT mnum = 1; MKL_INT phase = -1; MKL_INT n = A_in->info.m; MKL_INT nrhs = 0; MKL_INT msglvl = 0; MKL_INT error = 0; MKL_INT iDummy = -1; double dDummy = -1e0; pardiso(pardisoHandle_io, &maxfct, &mnum, &mtype_in, &phase, &n, &dDummy, A_in->rowPtr, A_in->colInd, &iDummy, &nrhs, iparam_in, &msglvl, &dDummy, // b: not needed here &dDummy, // x: not needed here &error); CPLM_POP return error; } int CPLM_MatCSRPARDISOFactorization( CPLM_Mat_CSR_t* A_in, _MKL_DSS_HANDLE_t pardisoHandle_out, MKL_INT* iparam_in, MKL_INT mtype_in, MKL_INT* perm_out) { CPLM_PUSH CPLM_BEGIN_TIME MKL_INT maxfct = 1; MKL_INT mnum = 1; MKL_INT phase = 12; MKL_INT n = A_in->info.m; MKL_INT nrhs = 0; MKL_INT msglvl = 0; MKL_INT error = 0; double dDummy = -1e0; CPLM_ASSERT(A_in != NULL); CPLM_ASSERT(A_in->val != NULL); CPLM_ASSERT(pardisoHandle_out != NULL); CPLM_ASSERT(iparam_in != NULL); // CPLM_ASSERT(perm_out != NULL); pardiso(pardisoHandle_out, &maxfct, &mnum, &mtype_in, &phase, &n, A_in->val, A_in->rowPtr, A_in->colInd, perm_out, // the permutation returned by PARDISO &nrhs, iparam_in, &msglvl, &dDummy, // b: not needed here &dDummy, // x: not needed here &error); CPLM_END_TIME CPLM_POP return error; } int CPLM_MatCSRPARDISOGeneralSolve(CPLM_Mat_CSR_t* A_in, CPLM_Mat_Dense_t* B_in, CPLM_Mat_Dense_t* X_out, MKL_INT phase, _MKL_DSS_HANDLE_t pardisoHandle_in, MKL_INT* iparam_in, MKL_INT mtype_in, MKL_INT* perm_in) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; MKL_INT maxfct = 1; MKL_INT mnum = 1; MKL_INT n = 0; MKL_INT nrhs = 0; MKL_INT msglvl = 0; MKL_INT error = 0; CPLM_ASSERT(A_in != NULL); CPLM_ASSERT(B_in != NULL); CPLM_ASSERT(X_out != NULL); CPLM_ASSERT(A_in->val != NULL); CPLM_ASSERT(B_in->val != NULL); CPLM_ASSERT(pardisoHandle_in != NULL); CPLM_ASSERT(iparam_in != NULL); // CPLM_ASSERT(perm_in != NULL); if (X_out->val == NULL) { X_out->info = B_in->info; ierr = CPLM_MatDenseMalloc(X_out);CPLM_CHKERR(ierr); } else if (!CPLM_MatDenseIsSameLocalInfo(X_out,B_in)) { X_out->info = B_in->info; ierr = CPLM_MatDenseRealloc(X_out);CPLM_CHKERR(ierr); } n = (MKL_INT) A_in->info.m; nrhs = (MKL_INT) B_in->info.n; pardiso(pardisoHandle_in, &maxfct, &mnum, &mtype_in, &phase, &n, A_in->val, A_in->rowPtr, A_in->colInd, perm_in, &nrhs, iparam_in, &msglvl, B_in->val, X_out->val, &error); CPLM_END_TIME CPLM_POP return error || ierr; } int CPLM_MatCSRPARDISOSolve( CPLM_Mat_CSR_t* A_in, CPLM_Mat_Dense_t* B_in, CPLM_Mat_Dense_t* X_out, _MKL_DSS_HANDLE_t pardisoHandle_in, MKL_INT* iparam_in, MKL_INT mtype_in, MKL_INT* perm_in) { CPLM_PUSH MKL_INT phase = 33; int ierr = CPLM_MatCSRPARDISOGeneralSolve( A_in, B_in, X_out, phase, pardisoHandle_in, iparam_in, mtype_in, perm_in); CPLM_POP return ierr; } int CPLM_MatCSRPARDISOSolveForward(CPLM_Mat_CSR_t* A_in, CPLM_Mat_Dense_t* B_in, CPLM_Mat_Dense_t* X_out, _MKL_DSS_HANDLE_t pardisoHandle_in, MKL_INT* iparam_in, MKL_INT mtype_in, MKL_INT* perm_in) { CPLM_PUSH MKL_INT phase = 331; int ierr = CPLM_MatCSRPARDISOGeneralSolve( A_in, B_in, X_out, phase, pardisoHandle_in, iparam_in, mtype_in, perm_in); if (ierr != 0) { CPLM_Abort("PARDISO Solve forward"); } CPLM_POP return ierr; } int CPLM_MatCSRPARDISOSolveBackward( CPLM_Mat_CSR_t* A_in, CPLM_Mat_Dense_t* B_in, CPLM_Mat_Dense_t* X_out, _MKL_DSS_HANDLE_t pardisoHandle_in, MKL_INT* iparam_in, MKL_INT mtype_in, MKL_INT* perm_in) { CPLM_PUSH MKL_INT phase = 333; int ierr = CPLM_MatCSRPARDISOGeneralSolve( A_in, B_in, X_out, phase, pardisoHandle_in, iparam_in, mtype_in, perm_in); if (ierr != 0) { CPLM_Abort("PARDISO Solve backward"); } CPLM_POP return ierr; } #endif int CPLM_MatDenseNorm(CPLM_Mat_Dense_t *A_in, const char type, double *norm) { CPLM_PUSH int ierr = 0; int major = (A_in->info.stor_type == COL_MAJOR) ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR; *norm = LAPACKE_dlange(major, type, A_in->info.m, A_in->info.n, A_in->val, A_in->info.lda); CPLM_POP return ierr; } int CPLM_MatDenseMatDotProd(CPLM_Mat_Dense_t* A, CPLM_Mat_Dense_t* B, CPLM_Mat_Dense_t* C, MPI_Comm comm) { CPLM_PUSH CPLM_BEGIN_TIME int ierr = 0; // Do local dot product ierr = CPLM_MatDenseKernelMatDotProd(A, B, C); // Sum local dot products in place (no mem alloc needed) ierr = MPI_Allreduce(MPI_IN_PLACE, C->val, C->info.nval, MPI_DOUBLE, MPI_SUM, comm);CPLM_checkMPIERR(ierr,"MatDenseMatDotProd::MPI_Allreduce"); CPLM_END_TIME CPLM_POP return ierr; } /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /* HANDLER */ /******************************************************************************/ /* void CPLM_MatDenseSVDHandler(int ierr) { if (ierr > 0) { CPLM_eprintf("the eigensolver did not converge!"); } else if (ierr < 0) { CPLM_eprintf("parameter %d has an illegal value!", -ierr + 1); } } */
{ "alphanum_fraction": 0.4774004591, "avg_line_length": 25.2912912913, "ext": "c", "hexsha": "3269027a064936109e98df63d62cfd7f0b20b209", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-10-05T11:22:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-17T22:41:41.000Z", "max_forks_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "W-Wuxian/preAlps", "max_forks_repo_path": "utils/cplm_light/cplm_kernels.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:11:37.000Z", "max_issues_repo_issues_event_min_datetime": "2019-03-14T16:11:37.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "W-Wuxian/preAlps", "max_issues_repo_path": "utils/cplm_light/cplm_kernels.c", "max_line_length": 145, "max_stars_count": 6, "max_stars_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "W-Wuxian/preAlps", "max_stars_repo_path": "utils/cplm_light/cplm_kernels.c", "max_stars_repo_stars_event_max_datetime": "2022-02-25T17:42:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-28T12:30:06.000Z", "num_tokens": 7055, "size": 25266 }
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team, * check out http://www.gromacs.org for more information. * Copyright (c) 2012,2013, by the GROMACS development team, led by * David van der Spoel, Berk Hess, Erik Lindahl, and including many * others, as listed in the AUTHORS file in the top-level source * directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <math.h> #include <string.h> #include <stdlib.h> #include "statutil.h" #include "sysstuff.h" #include "typedefs.h" #include "smalloc.h" #include "macros.h" #include "gmx_fatal.h" #include "vec.h" #include "copyrite.h" #include "futil.h" #include "readinp.h" #include "statutil.h" #include "txtdump.h" #include "gstat.h" #include "xvgr.h" #include "physics.h" #include "gmx_ana.h" enum { epAuf, epEuf, epAfu, epEfu, epNR }; enum { eqAif, eqEif, eqAfi, eqEfi, eqAui, eqEui, eqAiu, eqEiu, eqNR }; static char *eep[epNR] = { "Af", "Ef", "Au", "Eu" }; static char *eeq[eqNR] = { "Aif", "Eif", "Afi", "Efi", "Aui", "Eui", "Aiu", "Eiu" }; typedef struct { int nreplica; /* Number of replicas in the calculation */ int nframe; /* Number of time frames */ int nstate; /* Number of states the system can be in, e.g. F,I,U */ int nparams; /* Is 2, 4 or 8 */ gmx_bool *bMask; /* Determine whether this replica is part of the d2 comp. */ gmx_bool bSum; gmx_bool bDiscrete; /* Use either discrete folding (0/1) or a continuous */ /* criterion */ int nmask; /* Number of replicas taken into account */ real dt; /* Timestep between frames */ int j0, j1; /* Range of frames used in calculating delta */ real **temp, **data, **data2; int **state; /* State index running from 0 (F) to nstate-1 (U) */ real **beta, **fcalt, **icalt; real *time, *sumft, *sumit, *sumfct, *sumict; real *params; real *d2_replica; } t_remd_data; #ifdef HAVE_LIBGSL #include <gsl/gsl_multimin.h> static char *itoa(int i) { static char ptr[12]; sprintf(ptr, "%d", i); return ptr; } static char *epnm(int nparams, int index) { static char buf[32], from[8], to[8]; int nn, ni, ii; range_check(index, 0, nparams); if ((nparams == 2) || (nparams == 4)) { return eep[index]; } else if ((nparams > 4) && (nparams % 4 == 0)) { return eeq[index]; } else { gmx_fatal(FARGS, "Don't know how to handle %d parameters", nparams); } return NULL; } static gmx_bool bBack(t_remd_data *d) { return (d->nparams > 2); } static real is_folded(t_remd_data *d, int irep, int jframe) { if (d->state[irep][jframe] == 0) { return 1.0; } else { return 0.0; } } static real is_unfolded(t_remd_data *d, int irep, int jframe) { if (d->state[irep][jframe] == d->nstate-1) { return 1.0; } else { return 0.0; } } static real is_intermediate(t_remd_data *d, int irep, int jframe) { if ((d->state[irep][jframe] == 1) && (d->nstate > 2)) { return 1.0; } else { return 0.0; } } static void integrate_dfdt(t_remd_data *d) { int i, j; double beta, ddf, ddi, df, db, fac, sumf, sumi, area; d->sumfct[0] = 0; d->sumict[0] = 0; for (i = 0; (i < d->nreplica); i++) { if (d->bMask[i]) { if (d->bDiscrete) { ddf = 0.5*d->dt*is_folded(d, i, 0); ddi = 0.5*d->dt*is_intermediate(d, i, 0); } else { ddf = 0.5*d->dt*d->state[i][0]; ddi = 0.0; } d->fcalt[i][0] = ddf; d->icalt[i][0] = ddi; d->sumfct[0] += ddf; d->sumict[0] += ddi; } } for (j = 1; (j < d->nframe); j++) { if (j == d->nframe-1) { fac = 0.5*d->dt; } else { fac = d->dt; } sumf = sumi = 0; for (i = 0; (i < d->nreplica); i++) { if (d->bMask[i]) { beta = d->beta[i][j]; if ((d->nstate <= 2) || d->bDiscrete) { if (d->bDiscrete) { df = (d->params[epAuf]*exp(-beta*d->params[epEuf])* is_unfolded(d, i, j)); } else { area = (d->data2 ? d->data2[i][j] : 1.0); df = area*d->params[epAuf]*exp(-beta*d->params[epEuf]); } if (bBack(d)) { db = 0; if (d->bDiscrete) { db = (d->params[epAfu]*exp(-beta*d->params[epEfu])* is_folded(d, i, j)); } else { gmx_fatal(FARGS, "Back reaction not implemented with continuous"); } ddf = fac*(df-db); } else { ddf = fac*df; } d->fcalt[i][j] = d->fcalt[i][j-1] + ddf; sumf += ddf; } else { ddf = fac*((d->params[eqAif]*exp(-beta*d->params[eqEif])* is_intermediate(d, i, j)) - (d->params[eqAfi]*exp(-beta*d->params[eqEfi])* is_folded(d, i, j))); ddi = fac*((d->params[eqAui]*exp(-beta*d->params[eqEui])* is_unfolded(d, i, j)) - (d->params[eqAiu]*exp(-beta*d->params[eqEiu])* is_intermediate(d, i, j))); d->fcalt[i][j] = d->fcalt[i][j-1] + ddf; d->icalt[i][j] = d->icalt[i][j-1] + ddi; sumf += ddf; sumi += ddi; } } } d->sumfct[j] = d->sumfct[j-1] + sumf; d->sumict[j] = d->sumict[j-1] + sumi; } if (debug) { fprintf(debug, "@type xy\n"); for (j = 0; (j < d->nframe); j++) { fprintf(debug, "%8.3f %12.5e\n", d->time[j], d->sumfct[j]); } fprintf(debug, "&\n"); } } static void sum_ft(t_remd_data *d) { int i, j; double fac; for (j = 0; (j < d->nframe); j++) { d->sumft[j] = 0; d->sumit[j] = 0; if ((j == 0) || (j == d->nframe-1)) { fac = d->dt*0.5; } else { fac = d->dt; } for (i = 0; (i < d->nreplica); i++) { if (d->bMask[i]) { if (d->bDiscrete) { d->sumft[j] += fac*is_folded(d, i, j); d->sumit[j] += fac*is_intermediate(d, i, j); } else { d->sumft[j] += fac*d->state[i][j]; } } } } } static double calc_d2(t_remd_data *d) { int i, j; double dd2, d2 = 0, dr2, tmp; integrate_dfdt(d); if (d->bSum) { for (j = d->j0; (j < d->j1); j++) { if (d->bDiscrete) { d2 += sqr(d->sumft[j]-d->sumfct[j]); if (d->nstate > 2) { d2 += sqr(d->sumit[j]-d->sumict[j]); } } else { d2 += sqr(d->sumft[j]-d->sumfct[j]); } } } else { for (i = 0; (i < d->nreplica); i++) { dr2 = 0; if (d->bMask[i]) { for (j = d->j0; (j < d->j1); j++) { tmp = sqr(is_folded(d, i, j)-d->fcalt[i][j]); d2 += tmp; dr2 += tmp; if (d->nstate > 2) { tmp = sqr(is_intermediate(d, i, j)-d->icalt[i][j]); d2 += tmp; dr2 += tmp; } } d->d2_replica[i] = dr2/(d->j1-d->j0); } } } dd2 = (d2/(d->j1-d->j0))/(d->bDiscrete ? d->nmask : 1); return dd2; } static double my_f(const gsl_vector *v, void *params) { t_remd_data *d = (t_remd_data *) params; double penalty = 0; int i; for (i = 0; (i < d->nparams); i++) { d->params[i] = gsl_vector_get(v, i); if (d->params[i] < 0) { penalty += 10; } } if (penalty > 0) { return penalty; } else { return calc_d2(d); } } static void optimize_remd_parameters(FILE *fp, t_remd_data *d, int maxiter, real tol) { real size, d2; int iter = 0; int status = 0; int i; const gsl_multimin_fminimizer_type *T; gsl_multimin_fminimizer *s; gsl_vector *x, *dx; gsl_multimin_function my_func; my_func.f = &my_f; my_func.n = d->nparams; my_func.params = (void *) d; /* Starting point */ x = gsl_vector_alloc (my_func.n); for (i = 0; (i < my_func.n); i++) { gsl_vector_set (x, i, d->params[i]); } /* Step size, different for each of the parameters */ dx = gsl_vector_alloc (my_func.n); for (i = 0; (i < my_func.n); i++) { gsl_vector_set (dx, i, 0.1*d->params[i]); } T = gsl_multimin_fminimizer_nmsimplex; s = gsl_multimin_fminimizer_alloc (T, my_func.n); gsl_multimin_fminimizer_set (s, &my_func, x, dx); gsl_vector_free (x); gsl_vector_free (dx); printf ("%5s", "Iter"); for (i = 0; (i < my_func.n); i++) { printf(" %12s", epnm(my_func.n, i)); } printf (" %12s %12s\n", "NM Size", "Chi2"); do { iter++; status = gsl_multimin_fminimizer_iterate (s); if (status != 0) { gmx_fatal(FARGS, "Something went wrong in the iteration in minimizer %s", gsl_multimin_fminimizer_name(s)); } d2 = gsl_multimin_fminimizer_minimum(s); size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, tol); if (status == GSL_SUCCESS) { printf ("Minimum found using %s at:\n", gsl_multimin_fminimizer_name(s)); } printf ("%5d", iter); for (i = 0; (i < my_func.n); i++) { printf(" %12.4e", gsl_vector_get (s->x, i)); } printf (" %12.4e %12.4e\n", size, d2); } while ((status == GSL_CONTINUE) && (iter < maxiter)); gsl_multimin_fminimizer_free (s); } static void preprocess_remd(FILE *fp, t_remd_data *d, real cutoff, real tref, real ucut, gmx_bool bBack, real Euf, real Efu, real Ei, real t0, real t1, gmx_bool bSum, gmx_bool bDiscrete, int nmult) { int i, j, ninter; real dd, tau_f, tau_u; ninter = (ucut > cutoff) ? 1 : 0; if (ninter && (ucut <= cutoff)) { gmx_fatal(FARGS, "You have requested an intermediate but the cutoff for intermediates %f is smaller than the normal cutoff(%f)", ucut, cutoff); } if (!bBack) { d->nparams = 2; d->nstate = 2; } else { d->nparams = 4*(1+ninter); d->nstate = 2+ninter; } d->bSum = bSum; d->bDiscrete = bDiscrete; snew(d->beta, d->nreplica); snew(d->state, d->nreplica); snew(d->bMask, d->nreplica); snew(d->d2_replica, d->nreplica); snew(d->sumft, d->nframe); snew(d->sumit, d->nframe); snew(d->sumfct, d->nframe); snew(d->sumict, d->nframe); snew(d->params, d->nparams); snew(d->fcalt, d->nreplica); snew(d->icalt, d->nreplica); /* convert_times(d->nframe,d->time); */ if (t0 < 0) { d->j0 = 0; } else { for (d->j0 = 0; (d->j0 < d->nframe) && (d->time[d->j0] < t0); d->j0++) { ; } } if (t1 < 0) { d->j1 = d->nframe; } else { for (d->j1 = 0; (d->j1 < d->nframe) && (d->time[d->j1] < t1); d->j1++) { ; } } if ((d->j1-d->j0) < d->nparams+2) { gmx_fatal(FARGS, "Start (%f) or end time (%f) for fitting inconsistent. Reduce t0, increase t1 or supply more data", t0, t1); } fprintf(fp, "Will optimize from %g to %g\n", d->time[d->j0], d->time[d->j1-1]); d->nmask = d->nreplica; for (i = 0; (i < d->nreplica); i++) { snew(d->beta[i], d->nframe); snew(d->state[i], d->nframe); snew(d->fcalt[i], d->nframe); snew(d->icalt[i], d->nframe); d->bMask[i] = TRUE; for (j = 0; (j < d->nframe); j++) { d->beta[i][j] = 1.0/(BOLTZ*d->temp[i][j]); dd = d->data[i][j]; if (bDiscrete) { if (dd <= cutoff) { d->state[i][j] = 0; } else if ((ucut > cutoff) && (dd <= ucut)) { d->state[i][j] = 1; } else { d->state[i][j] = d->nstate-1; } } else { d->state[i][j] = dd*nmult; } } } sum_ft(d); /* Assume forward rate constant is half the total time in this * simulation and backward is ten times as long */ if (bDiscrete) { tau_f = d->time[d->nframe-1]; tau_u = 4*tau_f; d->params[epEuf] = Euf; d->params[epAuf] = exp(d->params[epEuf]/(BOLTZ*tref))/tau_f; if (bBack) { d->params[epEfu] = Efu; d->params[epAfu] = exp(d->params[epEfu]/(BOLTZ*tref))/tau_u; if (ninter > 0) { d->params[eqEui] = Ei; d->params[eqAui] = exp(d->params[eqEui]/(BOLTZ*tref))/tau_u; d->params[eqEiu] = Ei; d->params[eqAiu] = exp(d->params[eqEiu]/(BOLTZ*tref))/tau_u; } } else { d->params[epAfu] = 0; d->params[epEfu] = 0; } } else { d->params[epEuf] = Euf; if (d->data2) { d->params[epAuf] = 0.1; } else { d->params[epAuf] = 20.0; } } } static real tau(real A, real E, real T) { return exp(E/(BOLTZ*T))/A; } static real folded_fraction(t_remd_data *d, real tref) { real tauf, taub; tauf = tau(d->params[epAuf], d->params[epEuf], tref); taub = tau(d->params[epAfu], d->params[epEfu], tref); return (taub/(tauf+taub)); } static void print_tau(FILE *gp, t_remd_data *d, real tref) { real tauf, taub, ddd, fff, DG, DH, TDS, Tm, Tb, Te, Fb, Fe, Fm; int i, np = d->nparams; ddd = calc_d2(d); fprintf(gp, "Final value for Chi2 = %12.5e (%d replicas)\n", ddd, d->nmask); tauf = tau(d->params[epAuf], d->params[epEuf], tref); fprintf(gp, "%s = %12.5e %s = %12.5e (kJ/mole)\n", epnm(np, epAuf), d->params[epAuf], epnm(np, epEuf), d->params[epEuf]); if (bBack(d)) { taub = tau(d->params[epAfu], d->params[epEfu], tref); fprintf(gp, "%s = %12.5e %s = %12.5e (kJ/mole)\n", epnm(np, epAfu), d->params[epAfu], epnm(np, epEfu), d->params[epEfu]); fprintf(gp, "Equilibrium properties at T = %g\n", tref); fprintf(gp, "tau_f = %8.3f ns, tau_b = %8.3f ns\n", tauf/1000, taub/1000); fff = taub/(tauf+taub); DG = BOLTZ*tref*log(fff/(1-fff)); DH = d->params[epEfu]-d->params[epEuf]; TDS = DH-DG; fprintf(gp, "Folded fraction F = %8.3f\n", fff); fprintf(gp, "Unfolding energies: DG = %8.3f DH = %8.3f TDS = %8.3f\n", DG, DH, TDS); Tb = 260; Te = 420; Tm = 0; Fm = 0; Fb = folded_fraction(d, Tb); Fe = folded_fraction(d, Te); while ((Te-Tb > 0.001) && (Fm != 0.5)) { Tm = 0.5*(Tb+Te); Fm = folded_fraction(d, Tm); if (Fm > 0.5) { Fb = Fm; Tb = Tm; } else if (Fm < 0.5) { Te = Tm; Fe = Fm; } } if ((Fb-0.5)*(Fe-0.5) <= 0) { fprintf(gp, "Melting temperature Tm = %8.3f K\n", Tm); } else { fprintf(gp, "No melting temperature detected between 260 and 420K\n"); } if (np > 4) { char *ptr; fprintf(gp, "Data for intermediates at T = %g\n", tref); fprintf(gp, "%8s %10s %10s %10s\n", "Name", "A", "E", "tau"); for (i = 0; (i < np/2); i++) { tauf = tau(d->params[2*i], d->params[2*i+1], tref); ptr = epnm(d->nparams, 2*i); fprintf(gp, "%8s %10.3e %10.3e %10.3e\n", ptr+1, d->params[2*i], d->params[2*i+1], tauf/1000); } } } else { fprintf(gp, "Equilibrium properties at T = %g\n", tref); fprintf(gp, "tau_f = %8.3f\n", tauf); } } static void dump_remd_parameters(FILE *gp, t_remd_data *d, const char *fn, const char *fn2, const char *rfn, const char *efn, const char *mfn, int skip, real tref, output_env_t oenv) { FILE *fp, *hp; int i, j, np = d->nparams; real rhs, tauf, taub, fff, DG; real *params; const char *leg[] = { "Measured", "Fit", "Difference" }; const char *mleg[] = { "Folded fraction", "DG (kJ/mole)"}; char **rleg; real fac[] = { 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03 }; #define NFAC asize(fac) real d2[NFAC]; double norm; integrate_dfdt(d); print_tau(gp, d, tref); norm = (d->bDiscrete ? 1.0/d->nmask : 1.0); if (fn) { fp = xvgropen(fn, "Optimized fit to data", "Time (ps)", "Fraction Folded", oenv); xvgr_legend(fp, asize(leg), leg, oenv); for (i = 0; (i < d->nframe); i++) { if ((skip <= 0) || ((i % skip) == 0)) { fprintf(fp, "%12.5e %12.5e %12.5e %12.5e\n", d->time[i], d->sumft[i]*norm, d->sumfct[i]*norm, (d->sumft[i]-d->sumfct[i])*norm); } } ffclose(fp); } if (!d->bSum && rfn) { snew(rleg, d->nreplica*2); for (i = 0; (i < d->nreplica); i++) { snew(rleg[2*i], 32); snew(rleg[2*i+1], 32); sprintf(rleg[2*i], "\\f{4}F(t) %d", i); sprintf(rleg[2*i+1], "\\f{12}F \\f{4}(t) %d", i); } fp = xvgropen(rfn, "Optimized fit to data", "Time (ps)", "Fraction Folded", oenv); xvgr_legend(fp, d->nreplica*2, (const char**)rleg, oenv); for (j = 0; (j < d->nframe); j++) { if ((skip <= 0) || ((j % skip) == 0)) { fprintf(fp, "%12.5e", d->time[j]); for (i = 0; (i < d->nreplica); i++) { fprintf(fp, " %5f %9.2e", is_folded(d, i, j), d->fcalt[i][j]); } fprintf(fp, "\n"); } } ffclose(fp); } if (fn2 && (d->nstate > 2)) { fp = xvgropen(fn2, "Optimized fit to data", "Time (ps)", "Fraction Intermediate", oenv); xvgr_legend(fp, asize(leg), leg, oenv); for (i = 0; (i < d->nframe); i++) { if ((skip <= 0) || ((i % skip) == 0)) { fprintf(fp, "%12.5e %12.5e %12.5e %12.5e\n", d->time[i], d->sumit[i]*norm, d->sumict[i]*norm, (d->sumit[i]-d->sumict[i])*norm); } } ffclose(fp); } if (mfn) { if (bBack(d)) { fp = xvgropen(mfn, "Melting curve", "T (K)", "", oenv); xvgr_legend(fp, asize(mleg), mleg, oenv); for (i = 260; (i <= 420); i++) { tauf = tau(d->params[epAuf], d->params[epEuf], 1.0*i); taub = tau(d->params[epAfu], d->params[epEfu], 1.0*i); fff = taub/(tauf+taub); DG = BOLTZ*i*log(fff/(1-fff)); fprintf(fp, "%5d %8.3f %8.3f\n", i, fff, DG); } ffclose(fp); } } if (efn) { snew(params, d->nparams); for (i = 0; (i < d->nparams); i++) { params[i] = d->params[i]; } hp = xvgropen(efn, "Chi2 as a function of relative parameter", "Fraction", "Chi2", oenv); for (j = 0; (j < d->nparams); j++) { /* Reset all parameters to optimized values */ fprintf(hp, "@type xy\n"); for (i = 0; (i < d->nparams); i++) { d->params[i] = params[i]; } /* Now modify one of them */ for (i = 0; (i < NFAC); i++) { d->params[j] = fac[i]*params[j]; d2[i] = calc_d2(d); fprintf(gp, "%s = %12g d2 = %12g\n", epnm(np, j), d->params[j], d2[i]); fprintf(hp, "%12g %12g\n", fac[i], d2[i]); } fprintf(hp, "&\n"); } ffclose(hp); for (i = 0; (i < d->nparams); i++) { d->params[i] = params[i]; } sfree(params); } if (!d->bSum) { for (i = 0; (i < d->nreplica); i++) { fprintf(gp, "Chi2[%3d] = %8.2e\n", i, d->d2_replica[i]); } } } #endif /*HAVE_LIBGSL*/ int gmx_kinetics(int argc, char *argv[]) { const char *desc[] = { "[TT]g_kinetics[tt] reads two [TT].xvg[tt] files, each one containing data for N replicas.", "The first file contains the temperature of each replica at each timestep,", "and the second contains real values that can be interpreted as", "an indicator for folding. If the value in the file is larger than", "the cutoff it is taken to be unfolded and the other way around.[PAR]", "From these data an estimate of the forward and backward rate constants", "for folding is made at a reference temperature. In addition,", "a theoretical melting curve and free energy as a function of temperature", "are printed in an [TT].xvg[tt] file.[PAR]", "The user can give a max value to be regarded as intermediate", "([TT]-ucut[tt]), which, when given will trigger the use of an intermediate state", "in the algorithm to be defined as those structures that have", "cutoff < DATA < ucut. Structures with DATA values larger than ucut will", "not be regarded as potential folders. In this case 8 parameters are optimized.[PAR]", "The average fraction foled is printed in an [TT].xvg[tt] file together with the fit to it.", "If an intermediate is used a further file will show the build of the intermediate and the fit to that process.[PAR]", "The program can also be used with continuous variables (by setting", "[TT]-nodiscrete[tt]). In this case kinetics of other processes can be", "studied. This is very much a work in progress and hence the manual", "(this information) is lagging behind somewhat.[PAR]", "In order to compile this program you need access to the GNU", "scientific library." }; static int nreplica = 1; static real tref = 298.15; static real cutoff = 0.2; static real ucut = 0.0; static real Euf = 10; static real Efu = 30; static real Ei = 10; static gmx_bool bHaveT = TRUE; static real t0 = -1; static real t1 = -1; static real tb = 0; static real te = 0; static real tol = 1e-3; static int maxiter = 100; static int skip = 0; static int nmult = 1; static gmx_bool bBack = TRUE; static gmx_bool bSplit = TRUE; static gmx_bool bSum = TRUE; static gmx_bool bDiscrete = TRUE; t_pargs pa[] = { { "-time", FALSE, etBOOL, {&bHaveT}, "Expect a time in the input" }, { "-b", FALSE, etREAL, {&tb}, "First time to read from set" }, { "-e", FALSE, etREAL, {&te}, "Last time to read from set" }, { "-bfit", FALSE, etREAL, {&t0}, "Time to start the fit from" }, { "-efit", FALSE, etREAL, {&t1}, "Time to end the fit" }, { "-T", FALSE, etREAL, {&tref}, "Reference temperature for computing rate constants" }, { "-n", FALSE, etINT, {&nreplica}, "Read data for this number of replicas. Only necessary when files are written in xmgrace format using @type and & as delimiters." }, { "-cut", FALSE, etREAL, {&cutoff}, "Cut-off (max) value for regarding a structure as folded" }, { "-ucut", FALSE, etREAL, {&ucut}, "Cut-off (max) value for regarding a structure as intermediate (if not folded)" }, { "-euf", FALSE, etREAL, {&Euf}, "Initial guess for energy of activation for folding (kJ/mol)" }, { "-efu", FALSE, etREAL, {&Efu}, "Initial guess for energy of activation for unfolding (kJ/mol)" }, { "-ei", FALSE, etREAL, {&Ei}, "Initial guess for energy of activation for intermediates (kJ/mol)" }, { "-maxiter", FALSE, etINT, {&maxiter}, "Max number of iterations" }, { "-back", FALSE, etBOOL, {&bBack}, "Take the back reaction into account" }, { "-tol", FALSE, etREAL, {&tol}, "Absolute tolerance for convergence of the Nelder and Mead simplex algorithm" }, { "-skip", FALSE, etINT, {&skip}, "Skip points in the output [TT].xvg[tt] file" }, { "-split", FALSE, etBOOL, {&bSplit}, "Estimate error by splitting the number of replicas in two and refitting" }, { "-sum", FALSE, etBOOL, {&bSum}, "Average folding before computing [GRK]chi[grk]^2" }, { "-discrete", FALSE, etBOOL, {&bDiscrete}, "Use a discrete folding criterion (F <-> U) or a continuous one" }, { "-mult", FALSE, etINT, {&nmult}, "Factor to multiply the data with before discretization" } }; #define NPA asize(pa) FILE *fp; real dt_t, dt_d, dt_d2; int nset_t, nset_d, nset_d2, n_t, n_d, n_d2, i; const char *tfile, *dfile, *dfile2; t_remd_data remd; output_env_t oenv; t_filenm fnm[] = { { efXVG, "-f", "temp", ffREAD }, { efXVG, "-d", "data", ffREAD }, { efXVG, "-d2", "data2", ffOPTRD }, { efXVG, "-o", "ft_all", ffWRITE }, { efXVG, "-o2", "it_all", ffOPTWR }, { efXVG, "-o3", "ft_repl", ffOPTWR }, { efXVG, "-ee", "err_est", ffOPTWR }, { efLOG, "-g", "remd", ffWRITE }, { efXVG, "-m", "melt", ffWRITE } }; #define NFILE asize(fnm) CopyRight(stderr, argv[0]); parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_BE_NICE | PCA_TIME_UNIT, NFILE, fnm, NPA, pa, asize(desc), desc, 0, NULL, &oenv); #ifdef HAVE_LIBGSL please_cite(stdout, "Spoel2006d"); if (cutoff < 0) { gmx_fatal(FARGS, "cutoff should be >= 0 (rather than %f)", cutoff); } tfile = opt2fn("-f", NFILE, fnm); dfile = opt2fn("-d", NFILE, fnm); dfile2 = opt2fn_null("-d2", NFILE, fnm); fp = ffopen(opt2fn("-g", NFILE, fnm), "w"); remd.temp = read_xvg_time(tfile, bHaveT, opt2parg_bSet("-b", NPA, pa), tb, opt2parg_bSet("-e", NPA, pa), te, nreplica, &nset_t, &n_t, &dt_t, &remd.time); printf("Read %d sets of %d points in %s, dt = %g\n\n", nset_t, n_t, tfile, dt_t); sfree(remd.time); remd.data = read_xvg_time(dfile, bHaveT, opt2parg_bSet("-b", NPA, pa), tb, opt2parg_bSet("-e", NPA, pa), te, nreplica, &nset_d, &n_d, &dt_d, &remd.time); printf("Read %d sets of %d points in %s, dt = %g\n\n", nset_d, n_d, dfile, dt_d); if ((nset_t != nset_d) || (n_t != n_d) || (dt_t != dt_d)) { gmx_fatal(FARGS, "Files %s and %s are inconsistent. Check log file", tfile, dfile); } if (dfile2) { remd.data2 = read_xvg_time(dfile2, bHaveT, opt2parg_bSet("-b", NPA, pa), tb, opt2parg_bSet("-e", NPA, pa), te, nreplica, &nset_d2, &n_d2, &dt_d2, &remd.time); printf("Read %d sets of %d points in %s, dt = %g\n\n", nset_d2, n_d2, dfile2, dt_d2); if ((nset_d2 != nset_d) || (n_d != n_d2) || (dt_d != dt_d2)) { gmx_fatal(FARGS, "Files %s and %s are inconsistent. Check log file", dfile, dfile2); } } else { remd.data2 = NULL; } remd.nreplica = nset_d; remd.nframe = n_d; remd.dt = 1; preprocess_remd(fp, &remd, cutoff, tref, ucut, bBack, Euf, Efu, Ei, t0, t1, bSum, bDiscrete, nmult); optimize_remd_parameters(fp, &remd, maxiter, tol); dump_remd_parameters(fp, &remd, opt2fn("-o", NFILE, fnm), opt2fn_null("-o2", NFILE, fnm), opt2fn_null("-o3", NFILE, fnm), opt2fn_null("-ee", NFILE, fnm), opt2fn("-m", NFILE, fnm), skip, tref, oenv); if (bSplit) { printf("Splitting set of replicas in two halves\n"); for (i = 0; (i < remd.nreplica); i++) { remd.bMask[i] = FALSE; } remd.nmask = 0; for (i = 0; (i < remd.nreplica); i += 2) { remd.bMask[i] = TRUE; remd.nmask++; } sum_ft(&remd); optimize_remd_parameters(fp, &remd, maxiter, tol); dump_remd_parameters(fp, &remd, "test1.xvg", NULL, NULL, NULL, NULL, skip, tref, oenv); for (i = 0; (i < remd.nreplica); i++) { remd.bMask[i] = !remd.bMask[i]; } remd.nmask = remd.nreplica - remd.nmask; sum_ft(&remd); optimize_remd_parameters(fp, &remd, maxiter, tol); dump_remd_parameters(fp, &remd, "test2.xvg", NULL, NULL, NULL, NULL, skip, tref, oenv); for (i = 0; (i < remd.nreplica); i++) { remd.bMask[i] = FALSE; } remd.nmask = 0; for (i = 0; (i < remd.nreplica/2); i++) { remd.bMask[i] = TRUE; remd.nmask++; } sum_ft(&remd); optimize_remd_parameters(fp, &remd, maxiter, tol); dump_remd_parameters(fp, &remd, "test1.xvg", NULL, NULL, NULL, NULL, skip, tref, oenv); for (i = 0; (i < remd.nreplica); i++) { remd.bMask[i] = FALSE; } remd.nmask = 0; for (i = remd.nreplica/2; (i < remd.nreplica); i++) { remd.bMask[i] = TRUE; remd.nmask++; } sum_ft(&remd); optimize_remd_parameters(fp, &remd, maxiter, tol); dump_remd_parameters(fp, &remd, "test1.xvg", NULL, NULL, NULL, NULL, skip, tref, oenv); } ffclose(fp); view_all(oenv, NFILE, fnm); thanx(stderr); #else fprintf(stderr, "This program should be compiled with the GNU scientific library. Please install the library and reinstall GROMACS.\n"); #endif /*HAVE_LIBGSL*/ return 0; }
{ "alphanum_fraction": 0.4635273725, "avg_line_length": 31.9621421976, "ext": "c", "hexsha": "dce1cb7bec0068f6672b7089803cda297135c232", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_path": "gromacs-4.6.5/src/tools/gmx_kinetics.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "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": "farajilab/gifs_release", "max_issues_repo_path": "gromacs-4.6.5/src/tools/gmx_kinetics.c", "max_line_length": 151, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_path": "gromacs-4.6.5/src/tools/gmx_kinetics.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "num_tokens": 10576, "size": 34615 }
/* ** conversions: p->z, z->p, t->z ** ** G.Lohmann, April 2007 */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_errno.h> #define ABS(x) ((x) > 0 ? (x) : -(x)) /* ** convert t to p values */ double t2p(double t,double df) { double a,b,x; extern double gsl_sf_beta_inc(double,double,double); x = df/(df+(t*t)); if (x < 0 || x > 1) return 1; a = 0.5*df; b = 0.5; return 0.5 * gsl_sf_beta_inc(a,b,x); } /* ** convert t to z values */ double t2z(double t,double df) { double p=0,z=0; double a,b,x; extern double gsl_sf_beta_inc(double,double,double); /* t to p */ x = df/(df+(t*t)); if (x <= 0 || x > 1) return 0; a = 0.5*df; b = 0.5; p = 0.5 * gsl_sf_beta_inc(a,b,x); /* p to z */ z = gsl_cdf_ugaussian_Qinv(p); return z; } /* ** approximation: convert t to p values */ float t2z_approx(float t,float df) { float z=0,u; u = df*log(1.0+t*t/df)*(1.0-0.5/df); if (u <= 0) return 0; z = sqrt(u); return z; } /* ** convert p to t values */ double p2t(double px,double df) { double p,t0,t1,t,step=0.00001; t = 0; t0 = 0; t1 = 20; while (ABS(t0-t1) > step) { t = (t0 + t1)*0.5; p = t2p(t,df); if (p < px) t1 = t; else t0 = t; } p = t2p(t,df); return t; } /* ** convert z to p values */ double z2p(double z) { if (z < 0) return gsl_cdf_ugaussian_Q(-z); else return gsl_cdf_ugaussian_Q(z); } /* ** convert p to z values */ double p2z(double p) { return gsl_cdf_ugaussian_Qinv(p); }
{ "alphanum_fraction": 0.5601710446, "avg_line_length": 13.5289256198, "ext": "c", "hexsha": "28bd7a1062073adfbbb5604cd49e6b11f5c1b7f0", "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/lib_via/StatsConversions.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/lib_via/StatsConversions.c", "max_line_length": 54, "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/lib_via/StatsConversions.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": 636, "size": 1637 }
/** \file real-compressor.c */ #ifndef __COMPLEARN_REALCOMPRESSOR_H #define __COMPLEARN_REALCOMPRESSOR_H #define COMPLEARN_REAL_COMPRESSOR_TYPE (real_compressor_get_type ()) #define COMPLEARN_TYPE_REAL_COMPRESSOR (real_compressor_get_type ()) #define COMPLEARN_REAL_COMPRESSOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressor)) #define IS_COMPLEARN_REAL_COMPRESSOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), COMPLEARN_REAL_COMPRESSOR_TYPE)) #define COMPLEARN_REAL_COMPRESSOR_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE((inst), COMPLEARN_REAL_COMPRESSOR_TYPE, CompLearnRealCompressorIface)) #include <glib.h> #include <glib-object.h> #include <glib/garray.h> #include <gsl/gsl_matrix.h> #define COMPLEARN_ERROR 1 #define COMPLEARN_ERROR_NO_COMPRESSOR_SET 100 typedef struct _CompLearnRealCompressor CompLearnRealCompressor; typedef struct _CompLearnRealCompressorIface CompLearnRealCompressorIface; struct _CompLearnRealCompressorIface { GTypeInterface parent; GString *(*compress)(CompLearnRealCompressor *self, const GString *input); GString *(*decompress)(CompLearnRealCompressor *self, const GString *input); GString *(*blurb)(CompLearnRealCompressor *self); GString *(*canonical_extension)(CompLearnRealCompressor *self); GString *(*name)(CompLearnRealCompressor *self); GString *(*compressor_version)(CompLearnRealCompressor *self); GString *(*binding_version)(CompLearnRealCompressor *self); gboolean (*is_threadsafe)(CompLearnRealCompressor *self); gboolean (*is_compressible)(CompLearnRealCompressor *self, const GString *input); gboolean (*is_decompressible)(CompLearnRealCompressor *self, const GString *input); gboolean (*is_just_size)(CompLearnRealCompressor *self); gboolean (*is_hash_function)(CompLearnRealCompressor *self); GString *(*hash)(CompLearnRealCompressor *self, const GString *input); gboolean (*is_operational)(CompLearnRealCompressor *self); gboolean (*is_private_property)(CompLearnRealCompressor *self, const char *propname); gdouble (*compressed_size)(CompLearnRealCompressor *self, const GString *input); guint64 (*window_size)(CompLearnRealCompressor *self); CompLearnRealCompressor *(*clone)(CompLearnRealCompressor *self); }; GType real_compressor_get_type(void); /// Compress the string by the compressor /// \param[in] self is a pointer to compressor /// \param[in] input is a pointer to a GString which must be compressed /// \return a pointer to compressed string GString *real_compressor_compress(CompLearnRealCompressor *self,const GString *input); GString *real_compressor_hash(CompLearnRealCompressor *self,const GString *input); /// Decompress the string by the compressor /// \param[in] self is pointer to compressor /// \param[in] input is a pointer to a GString which must be decompressed /// \return a pointer to decompressed string GString *real_compressor_decompress(CompLearnRealCompressor *self,const GString *input); /// Calculate size of the compressed string /// \param[in] self is a pointer to a compressor /// \param[in] input is a pointer to string which must be compress /// \return size of compressed string in bits gdouble real_compressor_compressed_size(CompLearnRealCompressor *self,const GString *input); /// Return a short text description of this compressor /// \param[in] self is a pointer to a compressor GString *real_compressor_blurb(CompLearnRealCompressor *self); GString *real_compressor_name(CompLearnRealCompressor *self); /// Display the compressor version /// param[in] is a pointer to compressor /// \return a GString holding a 3-part version GString *real_compressor_compressor_version(CompLearnRealCompressor *self); /// Display the compressor binding version /// \param[in] is a pointer to compressor /// \return a GString holding a 3-part version GString *real_compressor_binding_version(CompLearnRealCompressor *self); /// This function checks whether the string is compressible by the compressor /// \param[in] self is a pointer to compressor /// \param[in] input is a pointer to GString which is under test /// \return true for every string gboolean real_compressor_is_compressible(CompLearnRealCompressor *self, const GString *input); /// Check whether the string is decompressible by the compressor /// \param[in] self is a pointer to compressor /// \param[in] input is a pointer to string which is under test gboolean real_compressor_is_decompressible(CompLearnRealCompressor *self, const GString *input); gboolean real_compressor_is_private_property(CompLearnRealCompressor *self, const char *input); guint64 real_compressor_window_size(CompLearnRealCompressor *self); gboolean real_compressor_is_threadsafe(CompLearnRealCompressor *self); gboolean real_compressor_is_just_size(CompLearnRealCompressor *self); gboolean real_compressor_is_hash_function(CompLearnRealCompressor *self); GString *real_compressor_canonical_extension(CompLearnRealCompressor *rc); gboolean real_compressor_is_operational(CompLearnRealCompressor *self); CompLearnRealCompressor *real_compressor_clone(CompLearnRealCompressor *self); #define SET_DEFAULT_PROPS(groupname, clt, mobj) \ do { \ GParamSpec **gps, **cur; \ g_assert(mobj != NULL); \ if (complearn_environment_get_nameable(groupname) == NULL) { \ complearn_environment_register_nameable(groupname, G_OBJECT(mobj)); \ break; \ } \ gps =g_object_class_list_properties(G_OBJECT_CLASS(clt(mobj)), NULL); \ for (cur = gps; *cur; cur += 1) { \ GValue v = {0,}; \ g_value_init(&v, (*cur)->value_type); \ g_param_value_set_default(*cur, &v); \ g_object_set_property(G_OBJECT(mobj), (*cur)->name, &v); \ complearn_environment_register_property(G_OBJECT(mobj), (*cur), &v); \ } } while(0) #define SET_DEFAULT_COMPRESSOR_PROPS(groupname, clt, mobj) \ do { \ SET_DEFAULT_PROPS(groupname, clt, mobj); \ if (complearn_environment_get_nameable(groupname) == NULL) { \ complearn_environment_register_compressor(mobj); \ } \ } while (0); #endif #define G_LOG_LEVEL_NOTICE G_LOG_LEVEL_USER_SHIFT #define g_notice(...) g_log(G_LOG_DOMAIN, G_LOG_LEVEL_NOTICE, __VA_ARGS__) void real_compressor_interface_init (gpointer g_iface, gpointer iface_data);
{ "alphanum_fraction": 0.7897845172, "avg_line_length": 49.7222222222, "ext": "c", "hexsha": "f2d36ae62bfc1f6c6b6297528178f442284fb8de", "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": "doxy/real-compressor.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": "doxy/real-compressor.c", "max_line_length": 155, "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": "doxy/real-compressor.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": 1568, "size": 6265 }
/* ** Read design file ** ** G.Lohmann, MPI-KYB 2018 */ #include <viaio/Vlib.h> #include <viaio/VImage.h> #include <viaio/mu.h> #include <viaio/option.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_blas.h> typedef struct TrialStruct { int id; float onset; float duration; float height; } Trial; extern void printmat(gsl_matrix *R,char *str); extern void printvec(gsl_vector *x,char *str); int test_ascii(int val) { if (val >= 'a' && val <= 'z') return 1; if (val >= 'A' && val <= 'Z') return 1; if (val >= '0' && val <= '9') return 1; if (val == ' ') return 1; if (val == '-') return 1; if (val == '+') return 1; if (val == '.') return 1; if (val == '\0') return 1; if (val == '\n') return 1; if (val == '\r') return 1; if (val == '\t') return 1; if (val == '\v') return 1; return 0; } int line_empty(char *buf,int len) { int i; for (i=0; i<len; i++) { if (buf[i] != ' ' && buf[i] != '\0' && buf[i] != '\n') return 0; } return 1; } int CheckBuffer(char *buf,int len) { int j; if(strlen(buf) < 1) return 0; if (buf[0] == '%' || buf[0] == '#' || buf[0] == '/') return 0; /* comment */ for (j=0; j<len; j++) { if (buf[j] == '\v') buf[j] = ' '; /* remove tabs */ if (buf[j] == '\t') buf[j] = ' '; } if (line_empty(buf,len) > 0) return 0; return 1; } int VistaFormat(char *buf,int len) { if (strncmp(buf,"V-data",6) == 0) return 1; return 0; } /* parse design file */ Trial *ReadDesign(VString designfile,int *numtrials,int *nevents) { FILE *fp=NULL; int i,j,id,len=4096; float onset=0,duration=0,height=0; char *buf = (char *)VCalloc(len,sizeof(char)); fp = fopen(designfile,"r"); if (!fp) VError(" error opening design file %s",designfile); int ntrials=0; while (!feof(fp)) { for (j=0; j<len; j++) buf[j] = '\0'; if (fgets(buf,len,fp) == NULL) break; if (VistaFormat(buf,len) > 1) VError(" Design file must be a text file"); if (CheckBuffer(buf,len) < 1) continue; if (! test_ascii((int)buf[0])) VError(" File %s: line %d begins with an illegal character (%c)",designfile,ntrials,buf[0]); ntrials++; } *numtrials = ntrials; Trial *trial = (Trial *) VCalloc(ntrials+1,sizeof(Trial)); i = (*nevents) = 0; rewind(fp); while (!feof(fp)) { for (j=0; j<len; j++) buf[j] = '\0'; if (fgets(buf,len,fp) == NULL) break; if (CheckBuffer(buf,len) < 1) continue; int nch = sscanf(buf,"%d %f %f %f",&id,&onset,&duration,&height); if (nch > 0 && nch != 4) VError(" line %d: illegal input format",i+1); if (duration < 0.5 && duration >= -0.0001) duration = 0.5; trial[i].id = id; trial[i].onset = onset; trial[i].duration = duration; trial[i].height = height; i++; if (id > (*nevents)) (*nevents) = id; } fclose(fp); return trial; } Trial *CopyTrials(Trial *trial,int numtrials) { int i; Trial *newtrial = (Trial *) VCalloc(numtrials,sizeof(Trial)); for (i=0; i<numtrials; i++) { newtrial[i].id = trial[i].id; newtrial[i].onset = trial[i].onset; newtrial[i].duration = trial[i].duration; newtrial[i].height = trial[i].height; } return newtrial; } /* concatenate trials from all runs */ Trial *ConcatenateTrials(Trial **trial,int *numtrials,float *run_duration,int dlists,int sumtrials) { int i,j; Trial *alltrials = (Trial *) VCalloc(sumtrials,sizeof(Trial)); int ii=0; float add=0; for (i=0; i<dlists; i++) { for (j=0; j<numtrials[i]; j++) { alltrials[ii].id = trial[i][j].id; alltrials[ii].onset = trial[i][j].onset + add; alltrials[ii].duration = trial[i][j].duration; alltrials[ii].height = trial[i][j].height; ii++; } add += run_duration[i]; } return alltrials; } /* check if trial labels are complete and positive */ void CheckTrialLabels(Trial *trial,int numtrials) { int i,j; int maxlabel = -1; for (i=0; i<numtrials; i++) { j = trial[i].id; if (j > maxlabel) maxlabel = j; if (j < 1) VError(" trial[%d] has illegal label %d",i,j); } int *tmp = (int *) VCalloc(maxlabel+1,sizeof(int)); for (i=0; i<numtrials; i++) { j = trial[i].id; tmp[j]++; } for (i=1; i<=maxlabel; i++) { if (tmp[i] < 1) VError(" Label %d missing in design file",i); if (tmp[i] < 4) VWarning(" Label %d has too few trials (%d) for random permutations",i,tmp[i]); } VFree(tmp); }
{ "alphanum_fraction": 0.5709556389, "avg_line_length": 24.1010638298, "ext": "c", "hexsha": "ebce82618e3fdf8a8c6f287bf8cbd161e59a29d3", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/vlisa_precoloring/Design.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/vlisa_precoloring/Design.c", "max_line_length": 127, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/vlisa_precoloring/Design.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": 1554, "size": 4531 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <petsc.h> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #include "common-driver-utils.h" /* writes out file1 1) its, residual, time 2) a summary of results file2 1) solver configuration */ PetscErrorCode BSSCR_solver_output( KSP ksp, PetscInt monitor_index, const char res_file[], const char solver_conf[] ) { PetscViewer v; MPI_Comm comm; PetscInt i,nargs; char **args; PetscObjectGetComm( (PetscObject)ksp, &comm ); PetscViewerASCIIOpen( comm, res_file, &v ); BSSCR_GeneratePetscHeader_for_viewer( v ); PetscViewerASCIIPrintf( v, "\n"); BSSCR_KSPLogSolve( v, monitor_index, ksp ); BSSCR_BSSCR_KSPLogSolveSummary( v, monitor_index, ksp ); Stg_PetscViewerDestroy(&v ); ////////////////////////////////////////////////////////// PetscObjectGetComm( (PetscObject)ksp, &comm ); PetscViewerASCIIOpen( comm, solver_conf, &v ); BSSCR_GeneratePetscHeader_for_viewer( v ); PetscViewerASCIIPrintf( v, "\n\nSolver configuration: \n"); PetscViewerASCIIPrintf( v, "\n1) Command line arguments supplied: \n"); PetscViewerASCIIPushTab(v); PetscGetArgs( &nargs, &args ); for( i=0; i<nargs; i++ ) { PetscViewerASCIIPrintf( v, "[%d]: %s \n", i, args[i] ); } PetscViewerASCIIPopTab(v); PetscViewerASCIIPrintf( v, "\n2) Petsc KSPView(): \n"); KSPView( ksp, v ); Stg_PetscViewerDestroy(&v ); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "BSSCR_KSPLogConvergenceRate" PetscErrorCode BSSCR_KSPLogConvergenceRate(PetscViewer v,PetscInt monitor_index, KSP ksp) { PetscInt i; PetscReal *rlog; PetscLogDouble *log; PetscInt nits; PetscReal rho; BSSCR_KSPLogGetResidualTimeHistory(ksp,monitor_index, &nits,&rlog,&log); PetscViewerASCIIPrintf( v, "#-----------------------------------------------------------------------------------------------------------------------\n"); PetscViewerASCIIPrintf( v, "# it |r| |r_0| |r|/|r_0| -log10(r/r0) rho |rn|/|r0|^{1/n} \n" ); PetscViewerASCIIPrintf( v, "#-----------------------------------------------------------------------------------------------------------------------\n"); rho = 0.0; i = 0; PetscViewerASCIIPrintf( v, "%1.4d %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e\n", i, rlog[i],rlog[0],rlog[i]/rlog[0],-log10(rlog[i]/rlog[0]), rho, 0.0 ); for( i=1; i<nits; i++ ) { rho = (-log10(rlog[i]/rlog[0]))-(-log10(rlog[i-1]/rlog[0])); PetscViewerASCIIPrintf( v, "%1.4d %14.12e %14.12e %14.12e %14.12e %14.12e %14.12e \n", i, rlog[i],rlog[0],rlog[i]/rlog[0],-log10(rlog[i]/rlog[0]), rho, pow(rlog[i]/rlog[0], 1.0/(double)i) ); } PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.5159310143, "avg_line_length": 33.8712871287, "ext": "c", "hexsha": "5eada56943e4fd292aa7cad9eedb43b8e855649c", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/solver_output.c", "max_issues_count": 561, "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/solver_output.c", "max_line_length": 158, "max_stars_count": 116, "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/solver_output.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "num_tokens": 1172, "size": 3421 }
#include <stdio.h> //printf #include <string.h> //memset #include <time.h> //time #include <cblas.h> //cblas_scopy, cblas_sscal, cblas_sgemm #include <sys/times.h> //times #include <unistd.h> //sysconf #include <math.h> //fabsf #include <xmmintrin.h> //_mm_malloc #define ALIGN 16 float* gen_matrix(int order, float range){ float* m = _mm_malloc(order * order * sizeof(float), ALIGN); srand(time(NULL)); for(int i = 0; i < order * order; ++i) m[i] = ((float)rand() / (float)(RAND_MAX)) * range; return m; } void transpose_matrix(float* m, int order){ for(int i = 0; i < order; ++i) for(int j = i; j < order; ++j){ float tmp = m[i * order + j]; m[i * order + j] = m[j * order + i]; m[j * order + i] = tmp; } } void print_matrix(float* m, int order, FILE* out){ fprintf(out, "Order: %d\n", order); for(int i = 0; i < order; ++i){ for(int j = 0; j < order; ++j) fprintf(out, "%.4f ", m[i * order + j]); fprintf(out, "\n"); } fprintf(out, "\n"); } void get_matrix_norms(float* m, int order, float* l1_norm, float* max_norm){ *l1_norm = 0; *max_norm = 0; for(int i = 0; i < order; ++i){ float row_sum = 0; float col_sum = 0; for(int j = 0; j < order; ++j){ row_sum += fabs(m[i * order + j]); col_sum += fabs(m[j * order + i]); } if(*l1_norm < col_sum) *l1_norm = col_sum; if(*max_norm < row_sum) *max_norm = row_sum; } } float* get_identity_matrix(int order){ float* m = _mm_malloc(order * order * sizeof(float), ALIGN); memset(m, 0, order * order * sizeof(float)); for(int i = 0; i < order; ++i) m[i * order + i] = 1; return m; } float* invert_matrix(float* A, int order, int iter_number){ float* B = _mm_malloc(order * order * sizeof(float), ALIGN); cblas_scopy(order * order, A, 1, B, 1); transpose_matrix(B, order); float l1_norm, max_norm; get_matrix_norms(A, order, &l1_norm, &max_norm); cblas_sscal(order * order, 1.0 / (l1_norm * max_norm), B, 1); float* R = get_identity_matrix(order); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, order, order, order, -1, B, order, A, order, 1, R, order); float* R_1_deg = _mm_malloc(order * order * sizeof(float), ALIGN); cblas_scopy(order * order, R, 1, R_1_deg, 1); float* tmp = NULL; float* inv_A = get_identity_matrix(order); for(int i = 0; i < iter_number; ++i){ tmp = _mm_malloc(order * order * sizeof(float), ALIGN); cblas_saxpy(order * order, 1, R, 1, inv_A, 1); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, order, order, order, 1, R, order, R_1_deg, order, 0, tmp, order); _mm_free(R); R = tmp; } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, order, order, order, 1, inv_A, order, B, order, 0.0, tmp, order); _mm_free(inv_A); inv_A = tmp; _mm_free(B); _mm_free(R_1_deg); return inv_A; } int main(){ FILE* input = fopen("input.txt", "r"); FILE* output = fopen("output.txt", "w"); int N = 0, M = 0; fscanf(input, "%d%d", &N, &M); float* A = gen_matrix(N, 5.0); time_t start_real = time(NULL); float* inv_A = invert_matrix(A, N, M); time_t finish_real = time(NULL); float* rez = _mm_malloc(N * N * sizeof(float), ALIGN); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, 1, inv_A, N, A, N, 0, rez, N); print_matrix(rez, N, output); printf("Total real time: %ld sec.\n", finish_real - start_real); _mm_free(A); _mm_free(inv_A); _mm_free(rez); fclose(input); fclose(output); return 0; }
{ "alphanum_fraction": 0.5692834563, "avg_line_length": 33.8928571429, "ext": "c", "hexsha": "75fe4a97069673b58d7e329731cf66d1375bd197", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-09-29T08:17:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-29T08:17:38.000Z", "max_forks_repo_head_hexsha": "2175f07ff325e754a0b5d19d760224af55a0e700", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "xp10rd/NSU-FIT", "max_forks_repo_path": "The 2nd course/Computers and devices/laboratory work #7/with_cblas/cblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2175f07ff325e754a0b5d19d760224af55a0e700", "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": "xp10rd/NSU-FIT", "max_issues_repo_path": "The 2nd course/Computers and devices/laboratory work #7/with_cblas/cblas.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "2175f07ff325e754a0b5d19d760224af55a0e700", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "xp10rd/NSU-FIT", "max_stars_repo_path": "The 2nd course/Computers and devices/laboratory work #7/with_cblas/cblas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1220, "size": 3796 }
/*========================================================== * arrayStxmWithMask.c - example in MATLAB External Interfaces * * Multiplies an input scalar (multiplier) * times a 1xN matrix (inMatrix) * and outputs a 1xN matrix (outMatrix) * * The calling syntax is: * * outMatrix = arrayStxmWithMask(multiplier, inMatrix) * * This is a MEX-file for MATLAB. * Copyright 2007-2012 The MathWorks, Inc. * *========================================================*/ /* Compiled with * mex -lgsl -lgslcblas ./toolbox/nanodiffraction/mex/mex_pca.c */ #include "mex.h" /* #include <stdio.h> */ #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #define PI 3.14159265 /* The computational routine */ void pca(double *x, double *mask, double *qx, double *qy, double *w, double *phi, mwSize m, mwSize n) { /* % first order moments tr = sum(dat(:)); % calculate covariance cov_qx_qx= sum(sum(dat.*qy.^2))./tr; cov_mix = sum(sum(dat.*qy.*qz))./tr; % Mischterm cov_qy_qy= sum(sum(dat.*qz.^2))./tr; % covariance matrix A=[cov_qx_qx cov_mix; cov_mix cov_qy_qy]; % solve eigenvalue problem (V: Eigenvectoren, D: % Diagonalmatrix) [V,D] = eig(A); */ mwSize col; mwSize row; double tr = 0; /* total sum of x */ for (row=0; row<m; row++) { for (col=0; col<n; col++) { x[row*m + col] = x[row*m + col] * mask[row*m + col]; tr += x[row*m + col]; } } /* covariance matrix */ double cov_qx = 0; double cov_mixed = 0; double cov_qy = 0; /* total sum of x */ for (row=0; row<m; row++) { for (col=0; col<n; col++) { cov_qx += x[row*m + col] * pow(qx[row*m + col],2); cov_qy += x[row*m + col] * pow(qy[row*m + col],2); cov_mixed += x[row*m + col] * qx[row*m + col] * qy[row*m + col]; } } double data[] = {cov_qx/tr , cov_mixed/tr, cov_mixed/tr, cov_qy/tr }; gsl_matrix_view mv = gsl_matrix_view_array (data, 2, 2); gsl_vector *eval = gsl_vector_alloc (2); gsl_matrix *evec = gsl_matrix_alloc (2, 2); gsl_eigen_symmv_workspace * ws = gsl_eigen_symmv_alloc (2); gsl_eigen_symmv (&mv.matrix, eval, evec, ws); gsl_eigen_symmv_free (ws); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_DESC); /* get eigenvalues and eigenvectors (assuming they are sorted) */ double eval_i = gsl_vector_get (eval, 0); double eval_j = gsl_vector_get (eval, 1); gsl_vector_view evec_i = gsl_matrix_column (evec, 0); double xcomp = gsl_vector_get (&evec_i.vector, 0); double ycomp = gsl_vector_get (&evec_i.vector, 1); /* anisotropy */ *w = (eval_i - eval_j) / (eval_i + eval_j); /* orientation */ *phi = atan2(ycomp,xcomp) * 180.0 / PI; if (*phi < 0){ *phi += 180; } gsl_vector_free (eval); gsl_matrix_free (evec); /* debugging information */ /* printf ("%g\t%g\t%g\n", cov_qx/tr, cov_mixed/tr, cov_qy/tr ); printf ("eigenvalue 1 = %g\n", eval_i); printf ("eigenvalue 2 = %g\n", eval_j); printf ("eigenvector = \n"); gsl_vector_fprintf (stdout, &evec_i.vector, "%g"); printf ("x = %g\n", xcomp); printf ("y = %g\n", ycomp); printf ("w = %g\n", *w); printf ("phi = %g\n", *phi); */ } /* The gateway function */ void mexFunction( int nlhs, mxArray *plhs[], /* output variables */ int nrhs, const mxArray *prhs[]) /* input variables */ { /* double placeholder; */ /* input scalar */ double *inData; /* 1xN input matrix */ double *inMask; /* 1xN input matrix */ double *qx; /* 1xN input matrix */ double *qy; /* 1xN input matrix */ size_t M; /* size of matrix */ size_t N; /* size of matrix */ double *w; /* output scalar or matrix */ double *phi; /* output scalar or matrix */ /* check for proper number of arguments */ if(nrhs!=4) { mexErrMsgIdAndTxt("MyToolbox:arrayStxmWithMask:nrhs","Four inputs required."); } if(nlhs!=2) { mexErrMsgIdAndTxt("MyToolbox:arrayStxmWithMask:nlhs","Two outputs required."); } /* get the value of the scalar input */ /* qrMin = mxGetScalar(prhs[1]); */ /* create a pointer to the data */ inData = mxGetPr(prhs[0]); inMask = mxGetPr(prhs[1]); qx = mxGetPr(prhs[2]); qy = mxGetPr(prhs[3]); /* get dimensions of the input data matrix */ M = mxGetM(prhs[0]); N = mxGetN(prhs[0]); /* create the output matrix */ plhs[0] = mxCreateDoubleScalar(0); plhs[1] = mxCreateDoubleScalar(0); /* get a pointer to the real data in the output matrix */ w = mxGetPr(plhs[0]); phi = mxGetPr(plhs[1]); /* call the computational routine */ pca(inData,inMask,qx,qy,w,phi,(mwSize)M,(mwSize)N); }
{ "alphanum_fraction": 0.5418125243, "avg_line_length": 28.2527472527, "ext": "c", "hexsha": "ba51a7b9093f4558f0eabc15ffe67c04cf9aae83", "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": "e8fb6602b7e07a104fbca06ace12b479c662cf70", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "irpgoe/nanodiffraction", "max_forks_repo_path": "mex/old/mex_pca.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e8fb6602b7e07a104fbca06ace12b479c662cf70", "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": "irpgoe/nanodiffraction", "max_issues_repo_path": "mex/old/mex_pca.c", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "e8fb6602b7e07a104fbca06ace12b479c662cf70", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "irpgoe/nanodiffraction", "max_stars_repo_path": "mex/old/mex_pca.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1540, "size": 5142 }
#ifndef NETWORK_CANUDPRECEIVER_H #define NETWORK_CANUDPRECEIVER_H #include <cstdint> #include <gsl/gsl> #include <QObject> #include "tincan/canrawframe.h" #include "network/udpasyncreceiver.h" namespace network { class Can_udp_receiver final : public QObject, public udp::Async_receiver { Q_OBJECT public: Can_udp_receiver() = default; Can_udp_receiver(const Can_udp_receiver&) = delete; Can_udp_receiver(Can_udp_receiver&&) = delete; Can_udp_receiver& operator=(const Can_udp_receiver&) = delete; Can_udp_receiver& operator=(Can_udp_receiver&&) = delete; void handle_receive(gsl::span<std::uint8_t> buffer) override; signals: void received_frame(std::uint64_t, tin::Can_raw_frame); }; } // namespace network #endif // NETWORK_CANUDPRECEIVER_H
{ "alphanum_fraction": 0.7680412371, "avg_line_length": 20.4210526316, "ext": "h", "hexsha": "c8e0455aeb8649a42437bd6005a4fb5ee83ce82a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-08-30T07:57:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-23T11:05:16.000Z", "max_forks_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jwkpeter/tincan", "max_forks_repo_path": "src/network/canudpreceiver.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "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": "jwkpeter/tincan", "max_issues_repo_path": "src/network/canudpreceiver.h", "max_line_length": 73, "max_stars_count": 9, "max_stars_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mwkpe/tincan", "max_stars_repo_path": "src/network/canudpreceiver.h", "max_stars_repo_stars_event_max_datetime": "2022-02-18T08:03:40.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-09T10:22:26.000Z", "num_tokens": 197, "size": 776 }
#include "utils.h" #include <assert.h> #include "stdio.h" #include "string.h" #include "cosmosis/datablock/c_datablock.h" #include <gsl/gsl_math.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> gsl_spline * spline_from_arrays(int n, double * x, double *y) { gsl_spline * output = gsl_spline_alloc(gsl_interp_akima, n); assert (output!=NULL); gsl_spline_init(output,x,y,n); return output; } DATABLOCK_STATUS save_spline(c_datablock * block, const char * section, const char * n_name, const char * x_name, const char * y_name, gsl_spline * s) { DATABLOCK_STATUS status = 0; if (strlen(n_name)>0){ status |= c_datablock_put_int(block, section, n_name, s->size); } if (strlen(x_name)>0){ status |= c_datablock_put_double_array_1d(block, section, x_name, s->x, s->size); } status |= c_datablock_put_double_array_1d(block, section, y_name, s->y, s->size); return status; } void reverse(double * x, int n) { for (int i=0; i<n/2; i++){ double tmp = x[i]; x[i] = x[n-1-i]; x[n-1-i] = tmp; } } static double identity_function(double x, double y, double z, void * a) { return z; } Interpolator2D * load_interpolator_chi_function(c_datablock * block, gsl_spline * chi_of_z_spline, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { int nk, nz, nP; double *k=NULL, *z=NULL; double **P=NULL; int status = 0; status = c_datablock_get_double_grid(block, section, k_name, &nk, &k, z_name, &nz, &z, P_name, &P); if (status){ fprintf(stderr, "Could not load interpolator for P(k). Error %d\n",status); return NULL; } //read only P(k,z) and not P(k,0) since the growth factor will be inside the kernels for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ P[j][i] = function(k[j], z[0], P[j][0], args); } } // What we have now is P(k, z). // We can optionally convert to P(k, chi) // If so we loop, lookup, and replace if (chi_of_z_spline){ for (int i=0; i<nz; i++){ double zi = z[i]; double chi_i = gsl_spline_eval(chi_of_z_spline, zi, NULL); z[i] = chi_i; } } if (status) return NULL; Interpolator2D * interp = init_interp_2d_akima_grid(k, z, P, nk, nz); deallocate_2d_double(&P, nk); free(k); free(z); return interp; } Interpolator2D * load_interpolator_chi(c_datablock * block, gsl_spline * chi_of_z_spline, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function(block, chi_of_z_spline, section, k_name, z_name, P_name, identity_function, NULL); } Interpolator2D * load_interpolator_function(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { return load_interpolator_chi_function(block, NULL, section, k_name, z_name, P_name, function, args); } Interpolator2D * load_interpolator(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function(block, NULL, section, k_name, z_name, P_name, identity_function, NULL); } // this is for the scale dependent growth rate from here---------------- Interpolator2D * load_interpolator_chi_function2(c_datablock * block, gsl_spline * chi_of_z_spline, gsl_spline * z_of_chi_spline, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { int nk, nz, nT; double *k=NULL, *z=NULL; double **P=NULL; int status = 0; status = c_datablock_get_double_grid(block, section, k_name, &nk, &k, z_name, &nz, &z, P_name, &P); double a[nk][nz],*pp[nk],**dTdz=NULL; for(int j=0;j<nk;j++){ pp[j]=&a[j][0];}//for the derivative dTdz=pp; double b[nk][nz],*ppp[nk],**f=NULL; for(int j=0;j<nk;j++){ ppp[j]=&b[j][0];}//for f(k,z) f=ppp; double c[nk][nz],*pppp[nk],**T=NULL; for(int j=0;j<nk;j++){ pppp[j]=&c[j][0];}//for the T(k,z) T=pppp; if (status){ fprintf(stderr, "Could not load interpolator for T(k). Error %d\n",status); return NULL; } for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ P[j][i] = function(k[j], z[i], P[j][i], args); } } //this is to take T(k,z) for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ T[j][i] = sqrt(P[j][i]/P[j][0]); } } //derivative dT/dz for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ //forward differences if(i==0){ dTdz[j][i] = (T[j][i+1]-T[j][i])/(z[i+1]-z[i]); } //central differences if(0<i && i<(nz-1)){ dTdz[j][i] = (T[j][i+1]-T[j][i-1])/(2.*(z[i+1]-z[i])); } //backward differences if(i==(nz-1)){ dTdz[j][i] = (T[j][i]-T[j][i-1])/(z[i]-z[i-1]); } } } //printf("ok with derivative\n"); //this is to take f(k,z) for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ f[j][i] = -((z[i]+1.)/T[j][i])*dTdz[j][i]; } } // What we have now is f(k, z). // We can optionally convert to f(k, z(chi)) // If so we loop, lookup, and replace if (chi_of_z_spline){ for (int i=0; i<nz; i++){ //int j=0; //my modification double zi = z[i]; //// j instead of i double chi_i = gsl_spline_eval(chi_of_z_spline, zi, NULL); //double z_i = gsl_spline_eval(z_of_chi_spline, chi_i, NULL); z[i] = chi_i; } } Interpolator2D * interp2 = init_interp_2d_akima_grid(k, z, f, nk, nz); return interp2; } Interpolator2D * load_interpolator_chi2(c_datablock * block, gsl_spline * chi_of_z_spline, gsl_spline * z_of_chi_spline, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function2(block, chi_of_z_spline, z_of_chi_spline, section, k_name, z_name, P_name, identity_function, NULL); } Interpolator2D * load_interpolator_function2(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { return load_interpolator_chi_function2(block, NULL, NULL, section, k_name, z_name, P_name, function, args); } Interpolator2D * load_interpolator2(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function2(block, NULL, NULL, section, k_name, z_name, P_name, identity_function, NULL); } // to here--------------------------------------- // here write the scale dependent growth factor Interpolator2D * load_interpolator_chi_function3(c_datablock * block, gsl_spline * chi_of_z_spline, gsl_spline * z_of_chi_spline, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { int nk, nz, nT; double *k=NULL, *z=NULL; double **P=NULL; int status = 0; status = c_datablock_get_double_grid(block, section, k_name, &nk, &k, z_name, &nz, &z, P_name, &P); double b[nk][nz],*ppp[nk],**D=NULL; for(int j=0;j<nk;j++){ ppp[j]=&b[j][0];}//for D(k,z) D=ppp; if (status){ fprintf(stderr, "Could not load interpolator for P_nl(k). Error %d\n",status); return NULL; } for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ P[j][i] = function(k[j], z[i], P[j][i], args); } } //printf("ok with derivative\n"); //this is to take D(k,z) for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ D[j][i] = sqrt(P[j][i]/P[j][0]); } } // What we have now is D(k, z). // We can optionally convert to D(k, z(chi)) // If so we loop, lookup, and replace if (chi_of_z_spline){ for (int i=0; i<nz; i++){ //int j=0; //my modification double zi = z[i]; //// j instead of i double chi_i = gsl_spline_eval(chi_of_z_spline, zi, NULL); //double z_i = gsl_spline_eval(z_of_chi_spline, chi_i, NULL); z[i] = chi_i; } } //printf("ok with z_of_chi\n"); Interpolator2D * interp3 = init_interp_2d_akima_grid(k, z, D, nk, nz); return interp3; } Interpolator2D * load_interpolator_chi3(c_datablock * block, gsl_spline * chi_of_z_spline, gsl_spline * z_of_chi_spline, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function3(block, chi_of_z_spline, z_of_chi_spline, section, k_name, z_name, P_name, identity_function, NULL); } Interpolator2D * load_interpolator_function3(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { return load_interpolator_chi_function3(block, NULL, NULL, section, k_name, z_name, P_name, function, args); } Interpolator2D * load_interpolator3(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function3(block, NULL, NULL, section, k_name, z_name, P_name, identity_function, NULL); } //-------------------to here //-----------------here is the scale dependent galaxy bias accounting for neutrinos Interpolator2D * load_interpolator_chi_function4(c_datablock * block, gsl_spline * chi_of_z_spline, gsl_spline * z_of_chi_spline, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { int nk, nz, nT; double *k=NULL, *z=NULL; double **P=NULL; int status = 0; status = c_datablock_get_double_grid(block, section, k_name, &nk, &k, z_name, &nz, &z, P_name, &P); double bb[nk][nz],*pppp[nk],**Bias=NULL; for(int j=0;j<nk;j++){ pppp[j]=&bb[j][0];}//for b(k,z) Bias=pppp; double bbL[nk][nz],*ppppL[nk],**bL=NULL; for(int j=0;j<nk;j++){ ppppL[j]=&bbL[j][0];}//for bL(k,z) bL=ppppL; double bbS[nk][nz],*ppppS[nk],**bS=NULL; for(int j=0;j<nk;j++){ ppppS[j]=&bbS[j][0];}//for bS(k,z) bS=ppppS; if (status){ fprintf(stderr, "Could not load interpolator for P_nl(k). Error %d\n",status); return NULL; } for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ P[j][i] = function(k[j], z[i], P[j][i], args); } } int status7=0; double omega_m; status7 = c_datablock_get_double(block, COSMOLOGICAL_PARAMETERS_SECTION, "omega_m", &omega_m); double Om = omega_m; int status8=0; double omega_vh2; status8 = c_datablock_get_double(block, COSMOLOGICAL_PARAMETERS_SECTION, "omnuh2", &omega_vh2); double Ovh2 = omega_vh2; int status9=0; double hs; status9 = c_datablock_get_double(block, COSMOLOGICAL_PARAMETERS_SECTION, "h0", &hs); double hubble = hs; double fv = (Ovh2/(hubble * hubble))/Om; double mv = Ovh2 * 93.14; //this is Sum(mv)/1eV in h/Mpc but for one massive neutrino only Sum(mv)=mv // this the neutrino free streaming scale in h/Mpc //for (int i=0; i<nz; i++){ // kfs[0][i] = 0.82 * sqrt(1.0 - Om + Om * (1.0 + z[i]) * (1.0 + z[i]) * (1.0 + z[i]))/((1.0 + z[i]) * (1.0 + z[i])) * mv; //} double knr; knr = 0.018 * sqrt(Om) * sqrt(mv); double constant=1.0; //this is to take b(k,z) for (int j=0; j<nk; j++){ for (int i=0; i<nz; i++){ bL[j][i] = constant/sqrt(P[0][i]/P[0][0]); bS[j][i] = constant/sqrt(P[0][i]/P[0][0]) - constant/sqrt(P[0][i]/P[0][0]) * fv; Bias[j][i] = bL[j][i] + (bS[j][i] - bL[j][i]) * 0.5 * (tanh(log(pow(k[j]/(knr),5.0)))+1.0) ; } } // What we have now is b(k, z). // We can optionally convert to b(k, z(chi)) // If so we loop, lookup, and replace if (chi_of_z_spline){ for (int i=0; i<nz; i++){ //int j=0; //my modification double zi = z[i]; //// j instead of i double chi_i = gsl_spline_eval(chi_of_z_spline, zi, NULL); //double z_i = gsl_spline_eval(z_of_chi_spline, chi_i, NULL); z[i] = chi_i; } } //printf("ok with z_of_chi\n"); Interpolator2D * interp4 = init_interp_2d_akima_grid(k, z, Bias, nk, nz); return interp4; } Interpolator2D * load_interpolator_chi4(c_datablock * block, gsl_spline * chi_of_z_spline, gsl_spline * z_of_chi_spline, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function4(block, chi_of_z_spline, z_of_chi_spline, section, k_name, z_name, P_name, identity_function, NULL); } Interpolator2D * load_interpolator_function4(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name, interp2d_modifier_function function, void * args ) { return load_interpolator_chi_function4(block, NULL, NULL, section, k_name, z_name, P_name, function, args); } Interpolator2D * load_interpolator4(c_datablock * block, const char * section, const char * k_name, const char * z_name, const char * P_name) { return load_interpolator_chi_function4(block, NULL, NULL, section, k_name, z_name, P_name, identity_function, NULL); } //------------------to here gsl_spline * load_spline(c_datablock * block, const char * section, const char * x_name, const char * y_name) { int status = 0 ; int nx, ny; double *x, *y; status |= c_datablock_get_double_array_1d(block, section, x_name, &x, &nx); if (status) return NULL; status |= c_datablock_get_double_array_1d(block, section, y_name, &y, &ny); if (status){ free(x); return NULL; } gsl_spline * output = NULL; if (x[1]<x[0]) {reverse(x, nx); reverse(y, ny);} if (nx==ny) output=spline_from_arrays(nx, x, y); else {fprintf(stderr, "Non-matching array sizes %s=%d, %s=%d\n", x_name, nx, y_name, ny);} free(x); free(y); return output; } /* gsl_spline2d * load_gsl_interpolator_chi(c_datablock * block, gsl_spline * chi_of_z_spline, const char * section, const char * k_name, const char * z_name, const char * P_name, ) { int nk, nz, nP; double *k=NULL, *z=NULL; double **P=NULL; int status = 0; status = c_datablock_get_double_grid(block, section, k_name, &nk, &k, z_name, &nz, &z, P_name, &P); if (status){ fprintf(stderr, "Could not load interpolator for P(k). Error %d\n",status); return NULL; } // What we have now is P(k, z). // We can optionally convert to P(k, chi) // If so we loop, lookup, and replace if (chi_of_z_spline){ for (int i=0; i<nz; i++){ double zi = z[i]; double chi_i = gsl_spline_eval(chi_of_z_spline, zi, NULL); z[i] = chi_i; } } if (status) return NULL; const gsl_interp2d_type *T = gsl_interp2d_bicubic; gsl_spline2d *spline = gsl_spline2d_alloc(T, nz, nk); gsl_interp_accel *xacc = gsl_interp_accel_alloc(); gsl_interp_accel *yacc = gsl_interp_accel_alloc(); gsl_spline_init Interpolator2D * interp = init_interp_2d_akima_grid(k, z, P, nk, nz); deallocate_2d_double(&P, nk); free(k); free(z); return interp; } */
{ "alphanum_fraction": 0.6452002415, "avg_line_length": 24.5180921053, "ext": "c", "hexsha": "b10b0ef5d35fd4b4b49bd20cb6048233fa74d213", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "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": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/utils.c", "max_line_length": 139, "max_stars_count": 1, "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/utils.c", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "num_tokens": 4900, "size": 14907 }
static char help[] = "Unstructured 2D FEM solution of nonlinear Poisson problem. Option prefix un_.\n" "Equation is\n" " - div( a(u,x,y) grad u ) = f(u,x,y)\n" "on arbitrary 2D polygonal domain, with boundary data g_D(x,y), g_N(x,y).\n" "Functions a(), f(), g_D(), g_N(), and u_exact() are given as formulas.\n" "Input files in PETSc binary format contain node coordinates, elements, Neumann\n" "boundary segments and boundary flags. Allows non-homogeneous Dirichlet and/or\n" "Neumann boundary conditions. Five different solution cases are implemented.\n\n"; #include <petsc.h> #include "../quadrature.h" #include "um.h" #include "cases.h" //STARTCTX typedef struct { UM *mesh; int solncase, quaddegree; double (*a_fcn)(double, double, double); double (*f_fcn)(double, double, double); double (*gD_fcn)(double, double); double (*gN_fcn)(double, double); double (*uexact_fcn)(double, double); PetscLogStage readstage, setupstage, solverstage, resstage, jacstage; //STRIP } unfemCtx; //ENDCTX //STARTFEM double chi(int L, double xi, double eta) { const double z[3] = {1.0 - xi - eta, xi, eta}; return z[L]; } const double dchi[3][2] = {{-1.0,-1.0},{ 1.0, 0.0},{ 0.0, 1.0}}; // evaluate v(xi,eta) on reference element using local node numbering double eval(const double v[3], double xi, double eta) { double sum = 0.0; int L; for (L = 0; L < 3; L++) sum += v[L] * chi(L,xi,eta); return sum; } double InnerProd(const double V[2], const double W[2]) { return V[0] * W[0] + V[1] * W[1]; } //ENDFEM extern PetscErrorCode FillExact(Vec, unfemCtx*); extern PetscErrorCode FormFunction(SNES, Vec, Vec, void*); extern PetscErrorCode FormPicard(SNES, Vec, Mat, Mat, void*); extern PetscErrorCode Preallocation(Mat, unfemCtx*); int main(int argc,char **argv) { PetscErrorCode ierr; PetscBool viewmesh = PETSC_FALSE, viewsoln = PETSC_FALSE, noprealloc = PETSC_FALSE, savepintbinary = PETSC_FALSE, savepintmatlab = PETSC_FALSE; char root[256] = "", nodesname[256], issname[256], solnname[256], pintname[256] = ""; int savepintlevel = -1, levels; UM mesh; unfemCtx user; SNES snes; KSP ksp; PC pc; PCType pctype; Mat A; Vec r, u, uexact; double err, h_max; PetscInitialize(&argc,&argv,NULL,help); ierr = PetscLogStageRegister("Read mesh ", &user.readstage); CHKERRQ(ierr); //STRIP ierr = PetscLogStageRegister("Set-up ", &user.setupstage); CHKERRQ(ierr); //STRIP ierr = PetscLogStageRegister("Solver ", &user.solverstage); CHKERRQ(ierr); //STRIP ierr = PetscLogStageRegister("Residual eval ", &user.resstage); CHKERRQ(ierr); //STRIP ierr = PetscLogStageRegister("Jacobian eval ", &user.jacstage); CHKERRQ(ierr); //STRIP user.quaddegree = 1; user.solncase = 0; ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "un_", "options for unfem", ""); CHKERRQ(ierr); ierr = PetscOptionsInt("-case", "exact solution cases: 0=linear, 1=nonlinear, 2=nonhomoNeumann, 3=chapter3, 4=koch", "unfem.c",user.solncase,&(user.solncase),NULL); CHKERRQ(ierr); ierr = PetscOptionsString("-gamg_save_pint_binary", "filename under which to save interpolation operator (Mat) in PETSc binary format", "unfem.c",pintname,pintname,sizeof(pintname),&savepintbinary); CHKERRQ(ierr); ierr = PetscOptionsString("-gamg_save_pint_matlab", "filename under which to save interpolation operator (Mat) in ascii Matlab format", "unfem.c",pintname,pintname,sizeof(pintname),&savepintmatlab); CHKERRQ(ierr); ierr = PetscOptionsInt("-gamg_save_pint_level", "saved interpolation operator is between L-1 and L where this option sets L; defaults to finest levels", "unfem.c",savepintlevel,&savepintlevel,NULL); CHKERRQ(ierr); ierr = PetscOptionsString("-mesh", "file name root of mesh stored in PETSc binary with .vec,.is extensions", "unfem.c",root,root,sizeof(root),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-noprealloc", "do not perform preallocation before matrix assembly", "unfem.c",noprealloc,&noprealloc,NULL); CHKERRQ(ierr); ierr = PetscOptionsInt("-quaddegree", "quadrature degree (1,2,3)", "unfem.c",user.quaddegree,&(user.quaddegree),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-view_mesh", "view loaded mesh (nodes and elements) at stdout", "unfem.c",viewmesh,&viewmesh,NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-view_solution", "view solution u(x,y) to binary file; uses root name of mesh plus .soln\nsee petsc2tricontour.py to view graphically", "unfem.c",viewsoln,&viewsoln,NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); // determine filenames if (strlen(root) == 0) { SETERRQ(PETSC_COMM_WORLD,4,"no mesh name root given; rerun with '-un_mesh foo'"); } strcpy(nodesname, root); strncat(nodesname, ".vec", 4); strcpy(issname, root); strncat(issname, ".is", 3); // set source/boundary functions and exact solution user.a_fcn = &a_lin; user.f_fcn = &f_lin; user.uexact_fcn = &uexact_lin; user.gD_fcn = &gD_lin; user.gN_fcn = &gN_lin; switch (user.solncase) { case 0 : break; case 1 : user.a_fcn = &a_nonlin; user.f_fcn = &f_nonlin; break; case 2 : user.gN_fcn = &gN_linneu; break; case 3 : user.a_fcn = &a_square; user.f_fcn = &f_square; user.uexact_fcn = &uexact_square; user.gD_fcn = &gD_square; user.gN_fcn = NULL; // seg fault if ever called break; case 4 : user.a_fcn = &a_koch; user.f_fcn = &f_koch; user.uexact_fcn = NULL; // seg fault if ever called user.gD_fcn = &gD_koch; user.gN_fcn = NULL; // seg fault if ever called break; default : SETERRQ(PETSC_COMM_WORLD,1,"other solution cases not implemented"); } PetscLogStagePush(user.readstage); //STARTREADMESH // read mesh object of type UM ierr = UMInitialize(&mesh); CHKERRQ(ierr); ierr = UMReadNodes(&mesh,nodesname); CHKERRQ(ierr); ierr = UMReadISs(&mesh,issname); CHKERRQ(ierr); ierr = UMStats(&mesh, &h_max, NULL, NULL, NULL); CHKERRQ(ierr); user.mesh = &mesh; //ENDREADMESH PetscLogStagePop(); if (viewmesh) { PetscViewer stdoutviewer; ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&stdoutviewer); CHKERRQ(ierr); ierr = UMViewASCII(&mesh,stdoutviewer); CHKERRQ(ierr); } PetscLogStagePush(user.setupstage); //STARTMAININITIAL // configure Vecs and SNES ierr = VecCreate(PETSC_COMM_WORLD,&r); CHKERRQ(ierr); ierr = VecSetSizes(r,PETSC_DECIDE,mesh.N); CHKERRQ(ierr); ierr = VecSetFromOptions(r); CHKERRQ(ierr); ierr = VecDuplicate(r,&u); CHKERRQ(ierr); ierr = VecSet(u,0.0); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetFunction(snes,r,FormFunction,&user); CHKERRQ(ierr); // reset default KSP and PC ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr); ierr = KSPSetType(ksp,KSPCG); CHKERRQ(ierr); ierr = KSPGetPC(ksp,&pc); CHKERRQ(ierr); ierr = PCSetType(pc,PCICC); CHKERRQ(ierr); // setup matrix for Picard iteration, including preallocation ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr); ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,mesh.N,mesh.N); CHKERRQ(ierr); ierr = MatSetFromOptions(A); CHKERRQ(ierr); ierr = MatSetOption(A,MAT_SYMMETRIC,PETSC_TRUE); CHKERRQ(ierr); if (noprealloc) { ierr = MatSetUp(A); CHKERRQ(ierr); } else { ierr = Preallocation(A,&user); CHKERRQ(ierr); } ierr = SNESSetJacobian(snes,A,A,FormPicard,&user); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); PetscLogStagePop(); //STRIP // solve PetscLogStagePush(user.solverstage); //STRIP ierr = SNESSolve(snes,NULL,u);CHKERRQ(ierr); //ENDMAININITIAL PetscLogStagePop(); // report if PC is GAMG ierr = PCGetType(pc,&pctype); CHKERRQ(ierr); if (strcmp(pctype,"gamg") == 0) { ierr = PCMGGetLevels(pc,&levels); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, " PC is GAMG with %d levels\n",levels); CHKERRQ(ierr); } // save Pint from GAMG if requested if (strlen(pintname) > 0) { Mat pint; PetscViewer viewer; if (strcmp(pctype,"gamg") != 0) { SETERRQ(PETSC_COMM_WORLD,2,"option -un_gamg_save_pint set but PC is not of type PCGAMG"); } if (savepintlevel >= levels) { SETERRQ(PETSC_COMM_WORLD,3,"invalid level given in -un_gamg_save_pint_level"); } if (savepintbinary && savepintmatlab) { SETERRQ(PETSC_COMM_WORLD,4,"only one of -un_gamg_save_pint_binary OR -un_gamg_save_pint_matlab is allowed"); } if (savepintlevel <= 0) { savepintlevel = levels - 1; } ierr = PCMGGetInterpolation(pc,savepintlevel,&pint); CHKERRQ(ierr); if (savepintbinary) { ierr = PetscPrintf(PETSC_COMM_WORLD, " saving interpolation operator on levels %d->%d in binary format to %s ...\n", savepintlevel-1,savepintlevel,pintname); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,pintname,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr); ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, " saving interpolation operator on levels %d->%d in ascii format to %s ...\n", savepintlevel-1,savepintlevel,pintname); CHKERRQ(ierr); ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,pintname,&viewer); CHKERRQ(ierr); ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr); } ierr = MatView(pint,viewer); CHKERRQ(ierr); } // if exact solution available, report numerical error if (user.uexact_fcn) { ierr = VecDuplicate(r,&uexact); CHKERRQ(ierr); ierr = FillExact(uexact,&user); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact ierr = VecNorm(u,NORM_INFINITY,&err); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "case %d result for N=%d nodes with h = %.3e : |u-u_ex|_inf = %.2e\n", user.solncase,mesh.N,h_max,err); CHKERRQ(ierr); VecDestroy(&uexact); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, "case %d result for N=%d nodes with h = %.3e ... done\n", user.solncase,mesh.N,h_max); CHKERRQ(ierr); } // save solution in PETSc binary if requested if (viewsoln) { strcpy(solnname, root); strncat(solnname, ".soln", 5); ierr = PetscPrintf(PETSC_COMM_WORLD, "writing solution in binary format to %s ...\n",solnname); CHKERRQ(ierr); ierr = UMViewSolutionBinary(&mesh,solnname,u); CHKERRQ(ierr); } // clean-up VecDestroy(&u); VecDestroy(&r); MatDestroy(&A); SNESDestroy(&snes); UMDestroy(&mesh); return PetscFinalize(); } PetscErrorCode FillExact(Vec uexact, unfemCtx *ctx) { PetscErrorCode ierr; const Node *aloc; double *auexact; int i; ierr = UMGetNodeCoordArrayRead(ctx->mesh,&aloc); CHKERRQ(ierr); ierr = VecGetArray(uexact,&auexact); CHKERRQ(ierr); for (i = 0; i < ctx->mesh->N; i++) { auexact[i] = ctx->uexact_fcn(aloc[i].x,aloc[i].y); } ierr = VecRestoreArray(uexact,&auexact); CHKERRQ(ierr); ierr = UMRestoreNodeCoordArrayRead(ctx->mesh,&aloc); CHKERRQ(ierr); return 0; } //STARTRESIDUAL PetscErrorCode FormFunction(SNES snes, Vec u, Vec F, void *ctx) { PetscErrorCode ierr; unfemCtx *user = (unfemCtx*)ctx; const Quad2DTri q = symmgauss[user->quaddegree-1]; const int *ae, *ans, *abf, *en; const Node *aloc; const double *au; int p, na, nb, k, l, r; double *aF, unode[3], gradu[2], gradpsi[3][2], uquad[4], aquad[4], fquad[4], dx, dy, dx1, dx2, dy1, dy2, detJ, ls, xmid, ymid, sint, xx, yy, psi, ip, sum; PetscLogStagePush(user->resstage); //STRIP ierr = VecSet(F,0.0); CHKERRQ(ierr); ierr = VecGetArray(F,&aF); CHKERRQ(ierr); ierr = UMGetNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr); ierr = ISGetIndices(user->mesh->bf,&abf); CHKERRQ(ierr); // Neumann boundary segment contributions (if any) if (user->mesh->P > 0) { ierr = ISGetIndices(user->mesh->ns,&ans); CHKERRQ(ierr); for (p = 0; p < user->mesh->P; p++) { na = ans[2*p+0]; nb = ans[2*p+1]; // nodes at end of segment dx = aloc[na].x-aloc[nb].x; dy = aloc[na].y-aloc[nb].y; ls = sqrt(dx * dx + dy * dy); // length of segment // midpoint rule; psi_na=psi_nb=0.5 at midpoint of segment xmid = 0.5*(aloc[na].x+aloc[nb].x); ymid = 0.5*(aloc[na].y+aloc[nb].y); sint = 0.5 * ls * user->gN_fcn(xmid,ymid); // nodes could be Dirichlet if (abf[na] != 2) aF[na] -= sint; if (abf[nb] != 2) aF[nb] -= sint; } ierr = ISRestoreIndices(user->mesh->ns,&ans); CHKERRQ(ierr); } // element contributions and Dirichlet node residuals ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr); ierr = ISGetIndices(user->mesh->e,&ae); CHKERRQ(ierr); for (k = 0; k < user->mesh->K; k++) { // element geometry and hat function gradients en = ae + 3*k; // en[0], en[1], en[2] are nodes of element k dx1 = aloc[en[1]].x - aloc[en[0]].x; dx2 = aloc[en[2]].x - aloc[en[0]].x; dy1 = aloc[en[1]].y - aloc[en[0]].y; dy2 = aloc[en[2]].y - aloc[en[0]].y; detJ = dx1 * dy2 - dx2 * dy1; for (l = 0; l < 3; l++) { gradpsi[l][0] = ( dy2 * dchi[l][0] - dy1 * dchi[l][1]) / detJ; gradpsi[l][1] = (-dx2 * dchi[l][0] + dx1 * dchi[l][1]) / detJ; } // u and grad u on element gradu[0] = 0.0; gradu[1] = 0.0; for (l = 0; l < 3; l++) { if (abf[en[l]] == 2) // enforces symmetry unode[l] = user->gD_fcn(aloc[en[l]].x,aloc[en[l]].y); else unode[l] = au[en[l]]; gradu[0] += unode[l] * gradpsi[l][0]; gradu[1] += unode[l] * gradpsi[l][1]; } // function values at quadrature points on element for (r = 0; r < q.n; r++) { uquad[r] = eval(unode,q.xi[r],q.eta[r]); xx = aloc[en[0]].x + dx1 * q.xi[r] + dx2 * q.eta[r]; yy = aloc[en[0]].y + dy1 * q.xi[r] + dy2 * q.eta[r]; aquad[r] = user->a_fcn(uquad[r],xx,yy); fquad[r] = user->f_fcn(uquad[r],xx,yy); } // residual contribution for each node of element for (l = 0; l < 3; l++) { if (abf[en[l]] == 2) { // set Dirichlet residual xx = aloc[en[l]].x; yy = aloc[en[l]].y; aF[en[l]] = au[en[l]] - user->gD_fcn(xx,yy); } else { sum = 0.0; for (r = 0; r < q.n; r++) { psi = chi(l,q.xi[r],q.eta[r]); ip = InnerProd(gradu,gradpsi[l]); sum += q.w[r] * ( aquad[r] * ip - fquad[r] * psi ); } aF[en[l]] += fabs(detJ) * sum; } } } ierr = ISRestoreIndices(user->mesh->e,&ae); CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr); ierr = ISRestoreIndices(user->mesh->bf,&abf); CHKERRQ(ierr); ierr = UMRestoreNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr); ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr); PetscLogStagePop(); //STRIP return 0; } //ENDRESIDUAL PetscErrorCode FormPicard(SNES snes, Vec u, Mat A, Mat P, void *ctx) { PetscErrorCode ierr; unfemCtx *user = (unfemCtx*)ctx; const Quad2DTri q = symmgauss[user->quaddegree-1]; const int *ae, *abf, *en; const Node *aloc; const double *au; double unode[3], gradpsi[3][2], uquad[4], aquad[4], v[9], dx1, dx2, dy1, dy2, detJ, xx, yy, sum; int n, k, l, m, r, cr, cv, row[3]; PetscLogStagePush(user->jacstage); //STRIP ierr = MatZeroEntries(P); CHKERRQ(ierr); ierr = ISGetIndices(user->mesh->bf,&abf); CHKERRQ(ierr); for (n = 0; n < user->mesh->N; n++) { if (abf[n] == 2) { v[0] = 1.0; ierr = MatSetValues(P,1,&n,1,&n,v,ADD_VALUES); CHKERRQ(ierr); } } ierr = ISGetIndices(user->mesh->e,&ae); CHKERRQ(ierr); ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr); ierr = UMGetNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr); for (k = 0; k < user->mesh->K; k++) { en = ae + 3*k; // en[0], en[1], en[2] are nodes of element k // geometry of element dx1 = aloc[en[1]].x - aloc[en[0]].x; dx2 = aloc[en[2]].x - aloc[en[0]].x; dy1 = aloc[en[1]].y - aloc[en[0]].y; dy2 = aloc[en[2]].y - aloc[en[0]].y; detJ = dx1 * dy2 - dx2 * dy1; // gradients of hat functions and u on element for (l = 0; l < 3; l++) { gradpsi[l][0] = ( dy2 * dchi[l][0] - dy1 * dchi[l][1]) / detJ; gradpsi[l][1] = (-dx2 * dchi[l][0] + dx1 * dchi[l][1]) / detJ; if (abf[en[l]] == 2) unode[l] = user->gD_fcn(aloc[en[l]].x,aloc[en[l]].y); else unode[l] = au[en[l]]; } // function values at quadrature points on element for (r = 0; r < q.n; r++) { uquad[r] = eval(unode,q.xi[r],q.eta[r]); xx = aloc[en[0]].x + dx1 * q.xi[r] + dx2 * q.eta[r]; yy = aloc[en[0]].y + dy1 * q.xi[r] + dy2 * q.eta[r]; aquad[r] = user->a_fcn(uquad[r],xx,yy); } // generate 3x3 element stiffness matrix (3x3 is max size but may be smaller) cr = 0; cv = 0; // cr = count rows; cv = value counter for all entries for (l = 0; l < 3; l++) { if (abf[en[l]] != 2) { row[cr++] = en[l]; for (m = 0; m < 3; m++) { if (abf[en[m]] != 2) { sum = 0.0; for (r = 0; r < q.n; r++) { sum += q.w[r] * aquad[r] * InnerProd(gradpsi[l],gradpsi[m]); } v[cv++] = fabs(detJ) * sum; } } } } // insert element stiffness matrix ierr = MatSetValues(P,cr,row,cr,row,v,ADD_VALUES); CHKERRQ(ierr); } ierr = ISRestoreIndices(user->mesh->e,&ae); CHKERRQ(ierr); ierr = ISRestoreIndices(user->mesh->bf,&abf); CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr); ierr = UMRestoreNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (A != P) { ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } ierr = MatSetOption(P,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE); CHKERRQ(ierr); PetscLogStagePop(); //STRIP return 0; } /* Note that nnz[n] is the number of nonzeros in row n. It equals one for Dirichlet rows, one more than the number of incident triangles for an interior point, and two more than the number of incident triangles for Neumann boundary nodes. */ //STARTPREALLOC PetscErrorCode Preallocation(Mat J, unfemCtx *user) { PetscErrorCode ierr; const int *ae, *abf, *en; int *nnz, n, k, l; nnz = (int *)malloc(sizeof(int)*(user->mesh->N)); ierr = ISGetIndices(user->mesh->bf,&abf); CHKERRQ(ierr); for (n = 0; n < user->mesh->N; n++) nnz[n] = (abf[n] == 1) ? 2 : 1; ierr = ISGetIndices(user->mesh->e,&ae); CHKERRQ(ierr); for (k = 0; k < user->mesh->K; k++) { en = ae + 3*k; // en[0], en[1], en[2] are nodes of element k for (l = 0; l < 3; l++) if (abf[en[l]] != 2) nnz[en[l]] += 1; } ierr = ISRestoreIndices(user->mesh->e,&ae); CHKERRQ(ierr); ierr = ISRestoreIndices(user->mesh->bf,&abf); CHKERRQ(ierr); ierr = MatSeqAIJSetPreallocation(J,-1,nnz); CHKERRQ(ierr); free(nnz); return 0; } //ENDPREALLOC
{ "alphanum_fraction": 0.5718275193, "avg_line_length": 41.263671875, "ext": "c", "hexsha": "37fdead61538d62835913426be4c4aa1d7f5e0e0", "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/ch10/unfem.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/ch10/unfem.c", "max_line_length": 129, "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/ch10/unfem.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6473, "size": 21127 }
/* linalg/householder.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007, 2010 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> double gsl_linalg_householder_transform (gsl_vector * v) { /* replace v[0:n-1] with a householder vector (v[0:n-1]) and coefficient tau that annihilate v[1:n-1] */ const size_t n = v->size ; if (n == 1) { return 0.0; /* tau = 0 */ } else { double alpha, beta, tau ; gsl_vector_view x = gsl_vector_subvector (v, 1, n - 1) ; double xnorm = gsl_blas_dnrm2 (&x.vector); if (xnorm == 0) { return 0.0; /* tau = 0 */ } alpha = gsl_vector_get (v, 0) ; beta = - (alpha >= 0.0 ? +1.0 : -1.0) * hypot(alpha, xnorm) ; tau = (beta - alpha) / beta ; { double s = (alpha - beta); if (fabs(s) > GSL_DBL_MIN) { gsl_blas_dscal (1.0 / s, &x.vector); gsl_vector_set (v, 0, beta) ; } else { gsl_blas_dscal (GSL_DBL_EPSILON / s, &x.vector); gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, &x.vector); gsl_vector_set (v, 0, beta) ; } } return tau; } } int gsl_linalg_householder_hm (double tau, const gsl_vector * v, gsl_matrix * A) { /* applies a householder transformation v,tau to matrix m */ if (tau == 0.0) { return GSL_SUCCESS; } #ifdef USE_BLAS { gsl_vector_const_view v1 = gsl_vector_const_subvector (v, 1, v->size - 1); gsl_matrix_view A1 = gsl_matrix_submatrix (A, 1, 0, A->size1 - 1, A->size2); size_t j; for (j = 0; j < A->size2; j++) { double wj = 0.0; gsl_vector_view A1j = gsl_matrix_column(&A1.matrix, j); gsl_blas_ddot (&A1j.vector, &v1.vector, &wj); wj += gsl_matrix_get(A,0,j); { double A0j = gsl_matrix_get (A, 0, j); gsl_matrix_set (A, 0, j, A0j - tau * wj); } gsl_blas_daxpy (-tau * wj, &v1.vector, &A1j.vector); } } #else { size_t i, j; for (j = 0; j < A->size2; j++) { /* Compute wj = Akj vk */ double wj = gsl_matrix_get(A,0,j); for (i = 1; i < A->size1; i++) /* note, computed for v(0) = 1 above */ { wj += gsl_matrix_get(A,i,j) * gsl_vector_get(v,i); } /* Aij = Aij - tau vi wj */ /* i = 0 */ { double A0j = gsl_matrix_get (A, 0, j); gsl_matrix_set (A, 0, j, A0j - tau * wj); } /* i = 1 .. M-1 */ for (i = 1; i < A->size1; i++) { double Aij = gsl_matrix_get (A, i, j); double vi = gsl_vector_get (v, i); gsl_matrix_set (A, i, j, Aij - tau * vi * wj); } } } #endif return GSL_SUCCESS; } int gsl_linalg_householder_mh (double tau, const gsl_vector * v, gsl_matrix * A) { /* applies a householder transformation v,tau to matrix m from the right hand side in order to zero out rows */ if (tau == 0) return GSL_SUCCESS; /* A = A - tau w v' */ #ifdef USE_BLAS { gsl_vector_const_view v1 = gsl_vector_const_subvector (v, 1, v->size - 1); gsl_matrix_view A1 = gsl_matrix_submatrix (A, 0, 1, A->size1, A->size2-1); size_t i; for (i = 0; i < A->size1; i++) { double wi = 0.0; gsl_vector_view A1i = gsl_matrix_row(&A1.matrix, i); gsl_blas_ddot (&A1i.vector, &v1.vector, &wi); wi += gsl_matrix_get(A,i,0); { double Ai0 = gsl_matrix_get (A, i, 0); gsl_matrix_set (A, i, 0, Ai0 - tau * wi); } gsl_blas_daxpy(-tau * wi, &v1.vector, &A1i.vector); } } #else { size_t i, j; for (i = 0; i < A->size1; i++) { double wi = gsl_matrix_get(A,i,0); for (j = 1; j < A->size2; j++) /* note, computed for v(0) = 1 above */ { wi += gsl_matrix_get(A,i,j) * gsl_vector_get(v,j); } /* j = 0 */ { double Ai0 = gsl_matrix_get (A, i, 0); gsl_matrix_set (A, i, 0, Ai0 - tau * wi); } /* j = 1 .. N-1 */ for (j = 1; j < A->size2; j++) { double vj = gsl_vector_get (v, j); double Aij = gsl_matrix_get (A, i, j); gsl_matrix_set (A, i, j, Aij - tau * wi * vj); } } } #endif return GSL_SUCCESS; } int gsl_linalg_householder_hv (double tau, const gsl_vector * v, gsl_vector * w) { /* applies a householder transformation v to vector w */ const size_t N = v->size; if (tau == 0) return GSL_SUCCESS ; { /* compute d = v'w */ double d0 = gsl_vector_get(w,0); double d1, d; gsl_vector_const_view v1 = gsl_vector_const_subvector(v, 1, N-1); gsl_vector_view w1 = gsl_vector_subvector(w, 1, N-1); gsl_blas_ddot (&v1.vector, &w1.vector, &d1); d = d0 + d1; /* compute w = w - tau (v) (v'w) */ { double w0 = gsl_vector_get (w,0); gsl_vector_set (w, 0, w0 - tau * d); } gsl_blas_daxpy (-tau * d, &v1.vector, &w1.vector); } return GSL_SUCCESS; } int gsl_linalg_householder_hm1 (double tau, gsl_matrix * A) { /* applies a householder transformation v,tau to a matrix being build up from the identity matrix, using the first column of A as a householder vector */ if (tau == 0) { size_t i,j; gsl_matrix_set (A, 0, 0, 1.0); for (j = 1; j < A->size2; j++) { gsl_matrix_set (A, 0, j, 0.0); } for (i = 1; i < A->size1; i++) { gsl_matrix_set (A, i, 0, 0.0); } return GSL_SUCCESS; } /* w = A' v */ #ifdef USE_BLAS { gsl_matrix_view A1 = gsl_matrix_submatrix (A, 1, 0, A->size1 - 1, A->size2); gsl_vector_view v1 = gsl_matrix_column (&A1.matrix, 0); size_t j; for (j = 1; j < A->size2; j++) { double wj = 0.0; /* A0j * v0 */ gsl_vector_view A1j = gsl_matrix_column(&A1.matrix, j); gsl_blas_ddot (&A1j.vector, &v1.vector, &wj); /* A = A - tau v w' */ gsl_matrix_set (A, 0, j, - tau * wj); gsl_blas_daxpy(-tau*wj, &v1.vector, &A1j.vector); } gsl_blas_dscal(-tau, &v1.vector); gsl_matrix_set (A, 0, 0, 1.0 - tau); } #else { size_t i, j; for (j = 1; j < A->size2; j++) { double wj = 0.0; /* A0j * v0 */ for (i = 1; i < A->size1; i++) { double vi = gsl_matrix_get(A, i, 0); wj += gsl_matrix_get(A,i,j) * vi; } /* A = A - tau v w' */ gsl_matrix_set (A, 0, j, - tau * wj); for (i = 1; i < A->size1; i++) { double vi = gsl_matrix_get (A, i, 0); double Aij = gsl_matrix_get (A, i, j); gsl_matrix_set (A, i, j, Aij - tau * vi * wj); } } for (i = 1; i < A->size1; i++) { double vi = gsl_matrix_get(A, i, 0); gsl_matrix_set(A, i, 0, -tau * vi); } gsl_matrix_set (A, 0, 0, 1.0 - tau); } #endif return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5125166284, "avg_line_length": 24.3205882353, "ext": "c", "hexsha": "65a6385cc91be94a7959a8831939e19c2ac82d27", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/linalg/householder.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/linalg/householder.c", "max_line_length": 91, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/linalg/householder.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 2681, "size": 8269 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "monotonic.h" #include <memcached/dockey.h> #include <memcached/types.h> #include <nlohmann/json_fwd.hpp> #include <platform/sized_buffer.h> #include <gsl/gsl> #include <unordered_map> #include <vector> namespace Collections { // The reserved name of the system owned, default collection. const char* const _DefaultCollectionIdentifier = "_default"; static cb::const_char_buffer DefaultCollectionIdentifier( _DefaultCollectionIdentifier); const char* const _DefaultScopeIdentifier = "_default"; static cb::const_char_buffer DefaultScopeIdentifier(_DefaultScopeIdentifier); // SystemEvent keys or parts which will be made into keys const char* const SystemSeparator = ":"; // Note this never changes const char* const CollectionEventPrefixWithSeparator = "_collection:"; const char* const ScopeEventPrefixWithSeparator = "_scope:"; // Couchstore private file name for manifest data const char CouchstoreManifest[] = "_local/collections_manifest"; // Length of the string excluding the zero terminator (i.e. strlen) const size_t CouchstoreManifestLen = sizeof(CouchstoreManifest) - 1; using ManifestUid = WeaklyMonotonic<uint64_t>; // Map used in summary stats using Summary = std::unordered_map<CollectionID, uint64_t>; struct ManifestUidNetworkOrder { ManifestUidNetworkOrder(ManifestUid uid) : uid(htonll(uid)) { } ManifestUid to_host() const { return ntohll(uid); } ManifestUid::value_type uid; }; static_assert(sizeof(ManifestUidNetworkOrder) == 8, "ManifestUidNetworkOrder must have fixed size of 8 bytes as " "written to disk."); /** * Return a ManifestUid from a C-string. * A valid ManifestUid is a C-string where each character satisfies * std::isxdigit and can be converted to a ManifestUid by std::strtoull. * * @param uid C-string uid * @param len a length for validation purposes * @throws std::invalid_argument if uid is invalid */ ManifestUid makeUid(const char* uid, size_t len = 16); /** * Return a ManifestUid from a std::string * A valid ManifestUid is a std::string where each character satisfies * std::isxdigit and can be converted to a ManifestUid by std::strtoull. * * @param uid std::string * @throws std::invalid_argument if uid is invalid */ static inline ManifestUid makeUid(const std::string& uid) { return makeUid(uid.c_str()); } /** * Return a CollectionID from a C-string. * A valid CollectionID is a C-string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul. * * @param uid C-string uid * @throws std::invalid_argument if uid is invalid */ static inline CollectionID makeCollectionID(const char* uid) { // CollectionID is 8 characters max and smaller than a ManifestUid return gsl::narrow_cast<CollectionID>(makeUid(uid, 8)); } /** * Return a CollectionID from a std::string * A valid CollectionID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * * @param uid std::string * @throws std::invalid_argument if uid is invalid */ static inline CollectionID makeCollectionID(const std::string& uid) { return makeCollectionID(uid.c_str()); } /** * Return a ScopeID from a C-string. * A valid CollectionID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * @param uid C-string uid * @return std::invalid_argument if uid is invalid */ static inline ScopeID makeScopeID(const char* uid) { // ScopeId is 8 characters max and smaller than a ManifestUid return gsl::narrow_cast<ScopeID>(makeUid(uid, 8)); } /** * Return a ScopeID from a std::string * A valid ScopeID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * @param uid std::string * @return std::invalid_argument if uid is invalid */ static inline ScopeID makeScopeID(const std::string& uid) { return makeScopeID(uid.c_str()); } /** * The metadata of a single collection * * Default construction yields the default collection */ struct CollectionMetaData { ScopeID sid{ScopeID::Default}; // The scope that the collection belongs to CollectionID cid{CollectionID::Default}; // The collection's ID std::string name{_DefaultCollectionIdentifier}; // The collection's name cb::ExpiryLimit maxTtl; // The collection's maxTTL bool operator==(const CollectionMetaData& other) const { return sid == other.sid && cid == other.cid && name == other.name && maxTtl == other.maxTtl; } }; /** * All of the data a system event needs */ struct CreateEventData { ManifestUid manifestUid; // The Manifest which generated the event CollectionMetaData metaData; // The data of the new collection }; struct DropEventData { ManifestUid manifestUid; // The Manifest which generated the event ScopeID sid; // The scope that the collection belonged to CollectionID cid; // The collection the event belongs to }; struct CreateScopeEventData { ManifestUid manifestUid; // The Manifest which generated the event ScopeID sid; // The scope id std::string name; // The scope name }; struct DropScopeEventData { ManifestUid manifestUid; // The Manifest which generated the event ScopeID sid; // The scope the event belongs to }; /** * All of the data a DCP create event message will transmit in the value of the * message. This is the layout to be used on the wire and is in the correct * byte order */ struct CreateEventDcpData { CreateEventDcpData(const CreateEventData& ev) : manifestUid(ev.manifestUid), sid(ev.metaData.sid), cid(ev.metaData.cid) { } /// The manifest uid stored in network byte order ready for sending ManifestUidNetworkOrder manifestUid; /// The scope id stored in network byte order ready for sending ScopeIDNetworkOrder sid; /// The collection id stored in network byte order ready for sending CollectionIDNetworkOrder cid; // The size is sizeof(manifestUid) + sizeof(cid) + sizeof(sid) // (msvc won't allow that expression) constexpr static size_t size{16}; }; /** * All of the data a DCP create event message will transmit in the value of a * DCP system event message (when the collection is created with a TTL). This is * the layout to be used on the wire and is in the correct byte order */ struct CreateWithMaxTtlEventDcpData { CreateWithMaxTtlEventDcpData(const CreateEventData& ev) : manifestUid(ev.manifestUid), sid(ev.metaData.sid), cid(ev.metaData.cid), maxTtl(htonl(gsl::narrow_cast<uint32_t>( ev.metaData.maxTtl.get().count()))) { } /// The manifest uid stored in network byte order ready for sending ManifestUidNetworkOrder manifestUid; /// The scope id stored in network byte order ready for sending ScopeIDNetworkOrder sid; /// The collection id stored in network byte order ready for sending CollectionIDNetworkOrder cid; /// The collection's maxTTL value (in network byte order) uint32_t maxTtl; // The size is sizeof(manifestUid) + sizeof(cid) + sizeof(sid) + // sizeof(maxTTL) (msvc won't allow that expression) constexpr static size_t size{20}; }; /** * All of the data a DCP drop event message will transmit in the value of the * message. This is the layout to be used on the wire and is in the correct * byte order */ struct DropEventDcpData { DropEventDcpData(const DropEventData& data) : manifestUid(data.manifestUid), sid(data.sid), cid(data.cid) { } /// The manifest uid stored in network byte order ready for sending ManifestUidNetworkOrder manifestUid; /// The scope id stored in network byte order ready for sending ScopeIDNetworkOrder sid; /// The collection id stored in network byte order ready for sending CollectionIDNetworkOrder cid; // The size is sizeof(manifestUid) + sizeof(cid) (msvc won't allow that // expression) constexpr static size_t size{16}; }; /** * All of the data a DCP create scope event message will transmit in the value * of the message. This is the layout to be used on the wire and is in the * correct byte order */ struct CreateScopeEventDcpData { CreateScopeEventDcpData(const CreateScopeEventData& data) : manifestUid(data.manifestUid), sid(data.sid) { } /// The manifest uid stored in network byte order ready for sending ManifestUidNetworkOrder manifestUid; /// The scope id stored in network byte order ready for sending ScopeIDNetworkOrder sid; constexpr static size_t size{12}; }; /** * All of the data a DCP drop scope event message will transmit in the value of * the message. This is the layout to be used on the wire and is in the correct * byte order */ struct DropScopeEventDcpData { DropScopeEventDcpData(const DropScopeEventData& data) : manifestUid(data.manifestUid), sid(data.sid) { } /// The manifest uid stored in network byte order ready for sending ManifestUidNetworkOrder manifestUid; /// The collection id stored in network byte order ready for sending ScopeIDNetworkOrder sid; constexpr static size_t size{12}; }; /** * All unknown_collection errors should be accompanied by a error context * value which includes the manifest ID which was what the collection lookup * failed against. * @return json for use in setErrorJsonExtras */ nlohmann::json getUnknownCollectionErrorContext(uint64_t manifestUid); /** * For creation of collection SystemEvents - The SystemEventFactory * glues the CollectionID into the event key (so create of x doesn't * collide with create of y). This method yields the 'keyExtra' parameter * * @param collection The value to turn into a string * @return the keyExtra parameter to be passed to SystemEventFactory */ std::string makeCollectionIdIntoString(CollectionID collection); /** * For creation of scope SystemEvents - The SystemEventFactory * glues the ScopeID into the event key (so create of x doesn't * collide with create of y). This method yields the 'keyExtra' parameter * * @param sid The ScopeId to turn into a string * @return the keyExtra parameter to be passed to SystemEventFactory */ std::string makeScopeIdIntoString(ScopeID sid); /** * For creation of collection SystemEvents - The SystemEventFactory * glues the CollectionID into the event key (so create of x doesn't * collide with create of y). This method basically reverses * makeCollectionIdIntoString so we can get a CollectionID from a * SystemEvent key * * @param key DocKey from a SystemEvent * @param separator the separator between the SystemEvent prefix and the * CollectionID * @return the ID which was in the event */ CollectionID getCollectionIDFromKey( const DocKey& key, const char* separator = Collections::SystemSeparator); /// Same as getCollectionIDFromKey but for events changing scopes ScopeID getScopeIDFromKey(const DocKey& key, const char* separator = Collections::SystemSeparator); /** * Callback function for processing against dropped collections in an ephemeral * vb, returns true if the key at seqno should be dropped */ using IsDroppedEphemeralCb = std::function<bool(const DocKey&, int64_t)>; } // end namespace Collections
{ "alphanum_fraction": 0.7263693849, "avg_line_length": 35.9203539823, "ext": "h", "hexsha": "cfc39b5183b0b6c86252ae23dce7e6fa7168ce5f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_path": "engines/ep/src/collections/collections_types.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "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": "paolococchi/kv_engine", "max_issues_repo_path": "engines/ep/src/collections/collections_types.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_path": "engines/ep/src/collections/collections_types.h", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "num_tokens": 2820, "size": 12177 }
#include <math.h> #include <string.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <fastpm/libfastpm.h> #include <fastpm/prof.h> #include <fastpm/lightcone.h> #include <fastpm/logging.h> #include <gsl/gsl_linalg.h> #include "pmpfft.h" #include "pmghosts.h" static void _matrix_invert(double (*matrix)[4], double (*matrix_inv)[4], int matrix_size) //square matrix.. //matrix_size fixed to 4 { double temp[16]; memcpy(temp, matrix, sizeof(double) * 16); gsl_matrix_view m = gsl_matrix_view_array(temp, matrix_size, matrix_size); gsl_matrix_view inv = gsl_matrix_view_array(&matrix_inv[0][0],matrix_size, matrix_size); gsl_permutation * p = gsl_permutation_alloc (matrix_size); int signum; gsl_linalg_LU_decomp (&m.matrix, p, &signum); gsl_linalg_LU_invert (&m.matrix, p, &inv.matrix); gsl_permutation_free (p); } void fastpm_lc_init(FastPMLightCone * lc) { gsl_set_error_handler_off(); // Turn off GSL error handler /* Allocation */ lc->horizon = malloc(sizeof(FastPMHorizon)); fastpm_horizon_init(lc->horizon, lc->cosmology); _matrix_invert(lc->glmatrix,lc->glmatrix_inv,4); } void fastpm_lc_destroy(FastPMLightCone * lc) { fastpm_horizon_destroy(lc->horizon); free(lc->horizon); } void fastpm_usmesh_init(FastPMUSMesh * mesh, FastPMLightCone * lc, double target_volume, FastPMStore * source, size_t np_upper, double (*tileshifts)[3], int ntiles, double amin, double amax) { mesh->target_volume = target_volume; mesh->source = source; mesh->amin = amin; mesh->amax = amax; mesh->lc = lc; mesh->tileshifts = malloc(sizeof(tileshifts[0]) * ntiles); mesh->ntiles = ntiles; mesh->np_before = 0; memcpy(mesh->tileshifts, tileshifts, sizeof(tileshifts[0]) * ntiles); mesh->event_handlers = NULL; mesh->p = malloc(sizeof(FastPMStore)); /* for saving the density with particles */ fastpm_store_init(mesh->p, source->name, np_upper, COLUMN_ID | COLUMN_POS | COLUMN_VEL | COLUMN_MASK | COLUMN_AEMIT, FASTPM_MEMORY_HEAP ); mesh->p->meta.M0 = source->meta.M0; // FIXME: change this for ncdm mass defn? } void fastpm_usmesh_destroy(FastPMUSMesh * mesh) { fastpm_destroy_event_handlers(&mesh->event_handlers); fastpm_store_destroy(mesh->p); free(mesh->tileshifts); free(mesh->p); } struct funct_params { FastPMLightCone *lc; FastPMStore * p; FastPMDriftFactor * drift; ptrdiff_t i; double tileshift[4]; double a1; double a2; void * context; }; static double funct(double a, void *params) { struct funct_params *Fp = (struct funct_params *) params; FastPMLightCone *lc = Fp->lc; FastPMStore * p = Fp->p; FastPMDriftFactor * drift = Fp->drift; ptrdiff_t i = Fp->i; int d; double xi[4]; double xo[4]; xi[3] = 1; if(p->v) { fastpm_drift_one(drift, p, i, xi, a); } else { for(d = 0; d < 3; d ++) { xi[d] = p->x[i][d]; } } for(d = 0; d < 4; d ++) { xi[d] += Fp->tileshift[d]; } /* transform the coordinate */ fastpm_gldot(lc->glmatrix, xi, xo); double distance = fastpm_lc_distance(lc, xo); /* XXX: may need to worry about periodic boundary */ return distance - lc->speedfactor * HorizonDistance(a, lc->horizon); } double fastpm_lc_distance(FastPMLightCone * lc, double x[3]) { double distance; if (lc->fov <= 0) { distance = x[2]; } else { distance = 0; int d; for (d = 0; d < 3; d ++) { distance += x[d] * x[d]; } distance = sqrt(distance); } return distance; } static int _fastpm_usmesh_intersect_one(FastPMUSMesh * mesh, struct funct_params * params, ptrdiff_t i, double * solution) { params->i = i; return fastpm_horizon_solve(mesh->lc->horizon, params->context, solution, params->a1, params->a2, funct, params); } static double zangle(double * x) { double dxy = 0; double dz = x[2]; dxy = x[0] * x[0] + x[1] * x[1]; double rt = atan2(sqrt(dxy), dz) / M_PI * 180.; if (rt < 0) rt += 360.; return rt; } /* is a vector in the i-th octant. * The ordering of octants is in C ordering, with * the Z-axis the fast changing direction. * * Thus [0, 4) are x > 0. * * The tolerance is in the same unit as the vector. * */ static int _in_octant(int i, double vec[3], double tol) { static const int signs[][3] = { {1, 1, 1}, {1, 1, -1}, {1, -1, 1}, {1, -1, -1}, {-1, 1, 1}, {-1, 1, -1}, {-1, -1, 1}, {-1, -1, -1}, }; int d; for(d = 0; d < 3; d ++) { double s = vec[d] * signs[i][d]; if(s < -tol) { return 0; } } return 1; } int fastpm_lc_inside(FastPMLightCone * lc, double vec[3]) { if(lc->fov > 0) { int r; if(lc->fov < 360) { r = zangle(vec) <= lc->fov * 0.5; } else { r = 1; } if(r) { double norm = 0; int d; for(d = 0; d < 3; d ++) { norm += vec[d] * vec[d]; } norm = sqrt(norm); int i; for(i = 0; i < 8; i ++) { if(lc->octants[i] && _in_octant(i, vec, lc->tol * norm)) return 1; } return 0; } else { return 0; } } else { /* smesh takes care of this */ return 1; } } /* Compute an approximate AABB of all particles * based on position at two times, assuming linear motion. * */ static void fastpm_compute_bbox(FastPMStore * p, FastPMDriftFactor * drift, double a1, double a2, double padding, double xmin[3], double xmax[3], MPI_Comm comm ) { ptrdiff_t i; for(int d = 0; d < 3; d ++) { xmin[d] = 1e20; xmax[d] = -1e20; } for(i = 0; i < p->np; i ++) { int d; for(d = 0; d < 3; d ++) { double xo[3]; fastpm_drift_one(drift, p, i, xo, a1); if(xo[d] < xmin[d]) xmin[d] = xo[d]; if(xo[d] > xmax[d]) xmax[d] = xo[d]; fastpm_drift_one(drift, p, i, xo, a2); if(xo[d] < xmin[d]) xmin[d] = xo[d]; if(xo[d] > xmax[d]) xmax[d] = xo[d]; } } // It is sufficient not doing a reduce; each rank can cull its own // volume. // MPI_Allreduce(MPI_IN_PLACE, xmin, 3, MPI_DOUBLE, MPI_MIN, comm); // MPI_Allreduce(MPI_IN_PLACE, xmax, 3, MPI_DOUBLE, MPI_MAX, comm); for(int d = 0; d < 3; d ++) { xmin[d] -= padding; xmax[d] += padding; } } #include "spherebox.h" void rotate_vec3(vec3 v3, double glmatrix[4][4], int translate) { double xi[4]; double xo[4]; for(int d = 0; d < 3; d ++) { xi[d] = v3.v[d]; } if(translate) xi[3] = 1; else xi[3] = 0; fastpm_gldot(glmatrix, xi, xo); for(int d = 0; d < 3; d ++) { v3.v[d] = xo[d]; } } /* * if a shell in (radius1, radius2) intersects a AABB box at xmin to xmax. * * Apply glmatrix and tileshift to the AABB first to transform it to the intended location. * */ int fastpm_shell_intersects_bbox( double xmin[3], double xmax[3], double glmatrix[4][4], double tileshift[3], double radius1, double radius2 ) { box bbox = make_box(xmin, xmax); /* rotate all planes, and apply tileshift */ for(int i = 0; i < 6; i ++) { rotate_vec3(bbox.planes[i].position, glmatrix, 1); rotate_vec3(bbox.planes[i].direction, glmatrix, 0); for(int d = 0; d < 3; d ++) { bbox.planes[i].position.v[d] += tileshift[d]; } } for(int i = 0; i < 8; i ++) { rotate_vec3(bbox.corners[i], glmatrix, 1); for(int d = 0; d < 3; d ++) { bbox.corners[i].v[d] += tileshift[d]; } } sphere s1 = make_sphere0(radius1); if (box_inside_sphere(bbox, s1)) return 0; sphere s2 = make_sphere0(radius2); if (sphere_outside_box(s2, bbox)) return 0; return 1; } /* FIXME: * the function shall take ai, af as input, * * the function shall be able to interpolate potential as * well as position and velocity. * We need a more general representation of '*drift' and '*kick'. * * */ static int fastpm_usmesh_intersect_tile(FastPMUSMesh * mesh, double * tileshift, double a1, double a2, FastPMDriftFactor * drift, FastPMKickFactor * kick, FastPMStore * p, FastPMStore * pout ) { FastPMLightCone * lc = mesh->lc; struct funct_params params = { .lc = lc, .drift = drift, .p = p, .i = 0, .a1 = a1, .a2 = a2, }; int a1_is_outside = (params.a1 > mesh->amax) || (params.a1 < mesh->amin); int a2_is_outside = (params.a2 > mesh->amax) || (params.a2 < mesh->amin); if(a1_is_outside && a2_is_outside) { return 0; } { int d; for(d = 0; d < 3; d ++) { params.tileshift[d] = tileshift[d]; } } params.tileshift[3] = 0; ptrdiff_t i; #pragma omp parallel firstprivate(params) { params.context = fastpm_horizon_solve_start(); #pragma omp for for(i = 0; i < p->np; i ++) { double a_emit = 0; if(0 == _fastpm_usmesh_intersect_one(mesh, &params, i, &a_emit)) continue; /* the event is outside the region we care, skip */ if(a_emit > mesh->amax || a_emit < mesh->amin) continue; double xi[4]; double xo[4]; int d; xi[3] = 1; if(p->v) { /* can we drift? if we are using a fixed grid there is no v. */ fastpm_drift_one(drift, p, i, xi, a_emit); } else { for(d = 0; d < 3; d ++) { xi[d] = p->x[i][d]; } } for(d = 0; d < 4; d ++) { xi[d] += params.tileshift[d]; } /* transform the coordinate */ fastpm_gldot(lc->glmatrix, xi, xo); /* does it fall into the field of view? */ if(!fastpm_lc_inside(lc, xo)) continue; /* A solution is found */ /* move the particle and store it. */ ptrdiff_t next; #pragma omp atomic capture next = pout->np++; if(next >= pout->np_upper) { continue; } /* copy the position if desired */ if(pout->x) { for(d = 0; d < 3; d ++) { pout->x[next][d] = xo[d]; } } float vo[4]; float vi[4]; if(p->v) { /* can we kick? if we are using a fixed grid there is no v */ fastpm_kick_one(kick, p, i, vi, a_emit); vi[3] = 0; /* transform the coordinate */ fastpm_gldotf(lc->glmatrix, vi, vo); if(pout->v) { for(d = 0; d < 3; d ++) { /* convert to peculiar velocity a dx / dt in kms */ pout->v[next][d] = vo[d] * HubbleConstant / a_emit; } } } if(pout->id) pout->id[next] = p->id[i]; if(pout->aemit) pout->aemit[next] = a_emit; if(pout->mask) pout->mask[next] = p->mask[i]; double potfactor = 1.5 * lc->cosmology->Omega_cdm / (HubbleDistance * HubbleDistance); /* convert to dimensionless potential */ if(pout->potential) pout->potential[next] = p->potential[i] / a_emit * potfactor; if(pout->tidal) { for(d = 0; d < 6; d++) { pout->tidal[next][d] = p->tidal[i][d] / a_emit * potfactor; } } } fastpm_horizon_solve_end(params.context); } if(pout->np >= pout->np_upper) { fastpm_raise(-1, "Too many particles in the light cone; limit = %td, wanted = %td\n", pout->np_upper, pout->np); } return 0; } void fastpm_usmesh_emit(FastPMUSMesh * mesh, int whence) { /* a portion of light cone is ready between a0 and a1 */ FastPMLCEvent lcevent[1]; lcevent->p = mesh->p; lcevent->ai = mesh->ai; lcevent->af = mesh->af; lcevent->whence = whence; fastpm_emit_event(mesh->event_handlers, FASTPM_EVENT_LC_READY, FASTPM_EVENT_STAGE_AFTER, (FastPMEvent*) lcevent, mesh); } int fastpm_usmesh_intersect(FastPMUSMesh * mesh, FastPMDriftFactor * drift, FastPMKickFactor * kick, double a1, double a2, int whence, MPI_Comm comm) { { double t1 = a1, t2 = a2; a1 = fmin(t1, t2); a2 = fmax(t1, t2); } CLOCK(intersect); if (whence == TIMESTEP_START) { mesh->ai = a1; mesh->af = a1; fastpm_info("usmesh start event from %0.4f to %0.4f.\n", mesh->ai, mesh->af); mesh->np_before = 0; fastpm_usmesh_emit(mesh, whence); } else if (whence == TIMESTEP_CUR) { double xmin[3] = {0}; double xmax[3] = {0}; double padding = 0.5; /* rainwoodman: add a 500 Kpc/h padding; need a better estimate. */ fastpm_compute_bbox(mesh->source, drift, a1, a2, padding, xmin, xmax, comm); fastpm_info("usmesh: bounding box computed for a = (%g, %g), AABB = [ %g %g %g ] - [ %g %g %g]", a1, a2, xmin[0], xmin[1], xmin[2], xmax[0], xmax[1], xmax[2] ); /* for each tile */ int t; ENTER(intersect); fastpm_info("usmesh intersection from %0.4f to %0.4f with %d tiles.\n", a1, a2, mesh->ntiles); double r1 = mesh->lc->speedfactor * HorizonDistance(a1, mesh->lc->horizon); double r2 = mesh->lc->speedfactor * HorizonDistance(a2, mesh->lc->horizon); double volume = 4 * M_PI / 3 * (pow(r1, 3) - pow(r2, 3)); int steps = (int) ((volume / mesh->target_volume) + 0.5); if(steps == 0) steps = 1; double da = (a1 - a2) / steps; for(int i = 0; i < steps; i ++) { double ai = a1 + da * i; double af = (i + 1 == steps)?a2 : a1 + da * (i + 1); fastpm_info("usmesh: intersection step %d / %d a = %g %g .\n", i, steps, ai, af); int ntiles = 0; for(t = 0; t < mesh->ntiles; t ++) { /* for spherical geometry, skip if the tile does not intersects the lightcone. */ if(mesh->lc->fov > 0 && !fastpm_shell_intersects_bbox( xmin, xmax, mesh->lc->glmatrix, &mesh->tileshifts[t][0], r2, r1)) { continue; } fastpm_usmesh_intersect_tile(mesh, &mesh->tileshifts[t][0], ai, af, drift, kick, mesh->source, mesh->p); /*Store particle to get density*/ ntiles ++; } double ntiles_max, ntiles_min, ntiles_mean; MPIU_stats(comm, ntiles, "<->", &ntiles_min, &ntiles_mean, &ntiles_max); fastpm_info("usmesh: number of bounding box intersects shell r = (%g %g), min = %g max = %g, mean=%g", r2, r1, ntiles_min, ntiles_max, ntiles_mean); LEAVE(intersect); mesh->af = af; if(MPIU_Any(comm, mesh->p->np > 0.5 * mesh->p->np_upper)) { fastpm_info("usmesh cur event from %0.4f to %0.4f.\n", mesh->ai, mesh->af); fastpm_usmesh_emit(mesh, whence); mesh->np_before += mesh->p->np; /* now purge the store. */ mesh->p->np = 0; mesh->ai = mesh->af; } } } else if (whence == TIMESTEP_END) { mesh->af = a2; fastpm_info("usmesh end event from %0.4f to %0.4f.\n", mesh->ai, mesh->af); fastpm_usmesh_emit(mesh, whence); mesh->np_before += mesh->p->np; /* now purge the store. */ mesh->p->np = 0; mesh->ai = mesh->af; } return 0; }
{ "alphanum_fraction": 0.5128526272, "avg_line_length": 28.5153061224, "ext": "c", "hexsha": "1230a22028697d4125b688fcc47117b88a0a09b2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/libfastpm/lightcone-usmesh.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/libfastpm/lightcone-usmesh.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/libfastpm/lightcone-usmesh.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4893, "size": 16767 }
#ifndef LIC_CALL_STACK_FRAME #define LIC_CALL_STACK_FRAME #include <stack> #include <gsl/gsl> #include "format/Opcodes.h" #include "loader/MethodDefinition.h" #include "EvaluationStack.h" namespace lic { class CallStackFrame { public: CallStackFrame(MethodDefinition& method, gsl::span<TypedValue> args, Opcode* returnAddress); CallStackFrame(MethodDefinition& method, TypedValue& thisRef, gsl::span<TypedValue> args, Opcode* returnAddress); MethodDefinition& Method(); TypedValue& Arg(size_t index); TypedValue& Local(size_t index); EvaluationStack& Stack(); Opcode* ReturnAddress() const; private: MethodDefinition& method; std::vector<TypedValue> args; std::vector<TypedValue> locals; EvaluationStack stack; Opcode* returnAddress; }; } #endif // !LIC_CALL_STACK_FRAME
{ "alphanum_fraction": 0.7415458937, "avg_line_length": 21.7894736842, "ext": "h", "hexsha": "ce37797f5cc4133019c329905c678708ce50beaa", "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": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_path": "src/interpreter/CallStackFrame.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "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": "roberthusak/lic", "max_issues_repo_path": "src/interpreter/CallStackFrame.h", "max_line_length": 117, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_path": "src/interpreter/CallStackFrame.h", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "num_tokens": 196, "size": 828 }
#pragma once #include <gsl/gsl>
{ "alphanum_fraction": 0.6764705882, "avg_line_length": 6.8, "ext": "h", "hexsha": "5246ae4c8d35bb690b270bf2151fdd92f5bbfffd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "DakkyDaWolf/OpenGL", "max_forks_repo_path": "build/Test/pch.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "DakkyDaWolf/OpenGL", "max_issues_repo_path": "build/Test/pch.h", "max_line_length": 18, "max_stars_count": null, "max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "DakkyDaWolf/OpenGL", "max_stars_repo_path": "build/Test/pch.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10, "size": 34 }
#if !defined(SM_H) #define SM_H #include <gsl/gsl_matrix.h> /** * @brief Class describing the Standard Model * * This class holds all the parameters specifying the Standard Model, and * methods to access them in convenient ways. * */ class SM { public: /// Default value for EM coupling \f$ \alpha_{\rm{EM}}(M_Z) \f$ const static double alpha = 1./127.934; /// Default value for EM coupling at low energy const static double alpha0 = 1./137.0359997; /// Default value for the Fermi constant \f$ G_F \f$ (\f$ \rm{GeV}^{-2} \f$) const static double GF = 1.16637E-5; /// Default value for \f$ M_Z \f$ (GeV) const static double MZ = 91.15349; /// Default value for \f$ M_W \f$ (GeV) const static double MW = 80.36951; /// Default value for the strong coupling \f$ \alpha_s(M_Z) \f$ const static double alpha_s = 0.119; /// Default value for total width \f$ \Gamma_Z \f$ (GeV) const static double GammaZ = 2.49581; /// Default value for total width \f$ \Gamma_W \f$ (GeV) const static double GammaW = 2.08856; /// Default value for quark pole mass \f$ m_d \f$ (GeV) const static double md_p = 0.0; /// Default value for quark pole mass \f$ m_u \f$ (GeV) const static double mu_p = 0.0; /// Default value for quark pole mass \f$ m_s \f$ (GeV) const static double ms_p = 0.1; // Scale for strange quark mass (GeV) const static double Q_ms = 2.0; /// Default value for quark pole mass \f$ m_c \f$ (GeV) const static double mc_p = 1.42; /// Default value for quark pole mass \f$ m_b \f$ (GeV) const static double mb_p = 4.75; /// Default value for quark pole mass \f$ m_t \f$ (GeV) const static double mt_p = 172.5; /// Default value for electron pole mass \f$ m_e \f$ (GeV) const static double me_p = 0.510998918E-3; /// Default value for muon pole mass \f$ m_\mu \f$ (GeV) const static double mmu_p = 0.105658367; /// Default value for tau pole mass \f$ m_\tau \f$ (GeV) const static double mtau_p = 1.77684; // PDG booklet 2012 /// Default value for CKM matrix element \f$ V_{ud} \f$ const static double Vud = 0.97427; /// Default value for CKM matrix element \f$ V_{us} \f$ const static double Vus = 0.22534; /// Default value for CKM matrix element \f$ V_{ub} \f$ const static double Vub = 0.00351; /// Default value for CKM matrix element \f$ V_{cd} \f$ const static double Vcd = 0.22520; /// Default value for CKM matrix element \f$ V_{cs} \f$ const static double Vcs = 0.97334; /// Default value for CKM matrix element \f$ V_{cb} \f$ const static double Vcb = 0.0412; /// Default value for CKM matrix element \f$ V_{td} \f$ const static double Vtd = 0.00867; /// Default value for CKM matrix element \f$ V_{ts} \f$ const static double Vts = 0.0404; /// Default value for CKM matrix element \f$ V_{tb} \f$ const static double Vtb = 0.999146; /** * @brief Default constructor initializing the Standard Model with default parameter * values * * This constructor initializes a new SM object with default parameters. The * values used as defaults are specified by public constants in this class. */ SM(); /** * @brief Sets the EM coupling \f$ \alpha \f$ * * @param alpha_in New value for \f$ \alpha(M_Z) \f$ */ void set_alpha(double alpha_in); /** * @brief Sets the EM coupling \f$ \alpha_0 \f at low energy$ * * @param alpha_in New value for \f$ \alpha(Q^2=0) \f$ */ void set_alpha0(double alpha_in); /** * @brief Sets the Fermi constant \f$ G_F \f$ * * @param GF_in New value for \f$ G_F \f$ (\f$ GeV^{-2} \f$) */ void set_GF(double GF_in); /** * @brief Sets \f$ M_Z \f$ * * @param MZ_in New value for \f$ M_Z \f$ */ void set_MZ(double MZ_in); /** * @brief Sets \f$ M_W \f$ * * @param MW_in New value for \f$ M_W \f$ */ void set_MW(double MW_in); /** * @brief Sets \f$ \gamma_Z \f$ * * @param GammaZ_in New value for \f$ \Gamma_Z \f$ */ void set_gamma_Z(double GammaZ_in); /** * @brief Sets \f$ \gamma_W \f$ * * @param GammaW_in New value for \f$ \Gamma_W \f$ */ void set_gamma_W(double GammaW_in); /** * @brief Sets the strong coupling \f$ \alpha_s \f$ * * @param alpha_s_in New value for \f$ \alpha_s(M_Z) \f$ */ void set_alpha_s(double alpha_s_in); /** * @brief Current value of \f$ \alpha \f$ * * @returns Value of \f$ \alpha \f$ */ double get_alpha(); double get_alpha0(); /** * @brief Current value of \f$ G_F \f$ * * @returns Value of \f$ G_F \f$ (\f$ \rm{GeV}^{-2} \f$) */ double get_GF(); /** * @brief Current value of \f$ \sin\theta_W \f$ * * @returns Value of \f$ \sin\theta_W \f$ */ double get_sintw(); /** * @brief Current value of \f$ \cos\theta_W \f$ * * @returns Value of \f$ \cos\theta_W \f$ */ double get_costw(); /** * @brief Current value of weak SU(2) coupling \f$ g \f$ * * @returns Value of \f$ g \f$ */ double get_g(); /** * @brief Current value of hypercharge U(1) coupling \f$ g' \f$ * * @returns Value of \f$ g' \f$ */ double get_gprime(); /** * @brief Current value of EM coupling \f$ e \f$ * * @returns Value of \f$ g' \f$ */ double get_e(); /** * @brief Current value of \f$ \alpha_s \f$ * * @returns Value of \f$ \alpha_s \f$ */ double get_alpha_s(); /** * @brief Current value of \f$ M_W \f$ * * @returns Value of \f$ M_W \f$ (GeV) */ double get_MW(); /** * @brief Current value of \f$ \Gamma_W \f$ * * @returns Value of \f$ \Gamma_W \f$ (GeV) */ double get_gamma_W(); /** * @brief Current value of \f$ M_Z \f$ * * @returns Value of \f$ M_Z \f$ (GeV) */ double get_MZ(); /** * @brief Current value of \f$ \Gamma_Z \f$ * * @returns Value of \f$ \Gamma_Z \f$ (GeV) */ double get_gamma_Z(); /** * @brief Current value of the vev \f$ v=1/\sqrt{\sqrt{2}G_F} \f$ * * @returns Value of \f$ v \f$ (GeV) */ double get_v(); /** * @brief Current value of the vev squared \f$ v^2=1/(\sqrt{2}G_F) \f$ * * @returns Value of \f$ v^2 \f$ (\f$ \rm{GeV}^2 \f$) */ double get_v2(); /** * @brief Vector boson mass * * This method returns the mass of a given vector boson. The numbering * convention used throughout 2HDMC is such that (1 = photon, 2 = Z0, 3 = W+). * * @param v Index (1-3) for the vector boson * * @returns Value of \f$ m_V \f$ (GeV) */ double get_vmass(int v); /** * @brief Vector boson width * * This method returns the decay width of a given vector boson. The numbering * convention is such that (1 = photon, 2 = Z0, 3 = W+). * * @param v Index (1-3) for the vector boson * * @returns Value of \f$ \Gamma_V \f$ (GeV) */ double get_gamma_V(int v); /** * @brief Sets the CKM matrix to a 3x3 unit matrix * * This method sets the CKM matrix to a 3x3 unit matrix, i.e. eliminating * all charged current interactions between different generations. */ void set_diagonal_CKM(); /** * @brief Full CKM matrix * * This method can be used to retrieve the full CKM matrix as a gsl_matrix. * * @returns CKM matrix * * @see get_MD, get_MU, get_ML, get_CKM_element */ gsl_matrix* get_CKM_matrix(); /** * @brief Element of the CKM matrix * * This method can be used to retrieve a certain element of the CKM matrix. * * @param i Row index (1,2,3 = u,c,t) of CKM matrix element * @param j Column index (1,2,3 = d,s,b) of CKM matrix element * @returns The requested CKM element * * @see get_CKM */ double get_CKM_element(int i, int j); /** * @brief Sets the pole mass of a lepton * * This method sets the pole mass of lepton \a l to the supplied value. * * @param l Index of lepton (1,2,3 = \f$ e,\mu,\tau \f$) * @param lmass_in New mass of lepton */ void set_lmass_pole(int l, double lmass_in); /** * @brief Sets the pole mass of a quark * * This method sets the pole mass of quark \a q to the supplied value. * * @param q Index of quark (1,2,3,4,5,6 = \f$ d,u,s,c,b,t \f$) * @param qmass_in New mass of quark */ void set_qmass_pole(int q, double qmass_in); void set_qmass_msbar(int flav, double qmass_in); /** * @brief Sets the pole mass of a down-type quark * * This method sets the pole mass of quark \a d to the supplied value. * * @param d Index of quark (1,2,3 = \f$ d,s,b \f$) * @param dmass_in New mass of quark */ void set_dmass_pole(int d, double dmass_in); /** * @brief Sets the pole mass of an up-type quark * * This method sets the pole mass of quark \a u to the supplied value. * * @param u Index of quark (1,2,3 = \f$ u,c,t \f$) * @param umass_in New mass of quark */ void set_umass_pole(int u, double umass_in); /** * @brief Quark pole mass * * @param q Index (1,2,3,4,5,6 = \f$ d,u,s,c,b,t \f$) of quark * * @returns The pole mass \f$ m_q \f$ */ double get_qmass_pole(int q); /** * @brief Down-type quark pole mass * * @param d Index (1,2,3 = \f$ d,s,b \f$) of down-type quark * * @returns Quark pole mass \f$ m_d \f$ */ double get_dmass_pole(int d); /** * @brief Up-type quark pole mass * * @param u Index (1,2,3 = \f$ u,c,t \f$) of up-type quark * * @returns Quark pole mass \f$ m_u \f$ */ double get_umass_pole(int u); /** * @brief Lepton pole mass * * @param l Index (1,2,3 = \f$ e,\mu,\tau \f$) of lepton * * @returns The pole mass \f$ m_l \f$ */ double get_lmass_pole(int l); /** * @brief Mass matrix for down-type quarks * * This method can be used to retrieve, in matrix form, the current pole masses * used for the down-type quarks. The masses are returned as the diagonal * elements of a 3x3 gsl_matrix that must be allocated by the user. * * @returns Diagonal mass matrix for the down-type quarks * * @see get_MU, get_ML, get_CKM */ gsl_matrix* get_MD(); /** * @brief Mass matrix for up-type quarks * * This method can be used to retrieve, in matrix form, the current pole masses * used for the up-type quarks. The masses are returned as the diagonal * elements of a 3x3 gsl_matrix that must be allocated by the user. * * @returns Diagonal mass matrix for the up-type quarks * * @see get_MD, get_ML, get_CKM */ gsl_matrix* get_MU(); /** * @brief Mass matrix for leptons * * This method can be used to retrieve, in matrix form, the current pole masses * used for the leptons. The masses are returned as the diagonal * elements of a 3x3 gsl_matrix that must be allocated by the user. * * @returns Diagonal mass matrix for the leptons * * @see get_MD, get_MU, get_CKM */ gsl_matrix* get_ML(); /** * @brief Quark \f$ \overline{\rm{MS}}\f$ mass * * This method determines the \f$ \overline{\rm{MS}}\f$ mass \f$ \overline{m}_q(\overline{m}_q) \f$ * * @param q Index (1,2,3,4,5,6 = \f$ d,u,s,c,b,t \f$) of quark * * @returns Quark \f$ \overline{\rm{MS}}\f$ mass \f$ \overline{m}_q(\overline{m}_q) \f$ * * @see run_qmass_MSbar */ double get_qmass_MSbar(int q); /** * @brief Down-type quark \f$ \overline{\rm{MS}}\f$ mass * * This method determines the \f$ \overline{\rm{MS}}\f$ mass \f$ \overline{m}_d(\overline{m}_d) \f$ * * @param d Index (1,2,3 = \f$ d,s,b \f$) of down-type quark * * @returns Quark \f$ \overline{\rm{MS}}\f$ mass \f$ \overline{m}_d(\overline{m}_d) \f$ * * @see get_umass_MSbar, run_qmass_MSbar */ double get_dmass_MSbar(int d); /** * @brief Up-type quark \f$ \overline{\rm{MS}}\f$ mass * * This method determines the \f$ \overline{\rm{MS}}\f$ mass \f$ \overline{m}_u(\overline{m}_u) \f$ * * @param u Index (1,2,3 = \f$ u,c,t \f$) of up-type quark * * @returns Quark \f$ \overline{\rm{MS}}\f$ mass \f$ \overline{m}_u(\overline{m}_u) \f$ * * @see get_dmass_MSbar, run_qmass_MSbar */ double get_umass_MSbar(int u); /** * @brief Evaluates running quark masses * * This method evaluates the running quark_mass \a quark_mass, initially specified * at the input scale \a Qinit, at the new scale \a Qfin. The calculation is performed * in the \f$ \overline{\rm{MS}} \f$ scheme with variable number of active * flavours and threshold matching. * * @param quark_mass The input value for the running quark mass * @param Qinit Starting scale * @param Qfin Final scale at which the mass is to be evaluated * @param mtop \f$ \overline{\rm{MS}} \f$ top mass (for thresholds) * @param mbot \f$ \overline{\rm{MS}} \f$ bottom mass (for thresholds) * * @returns The running mass at the scale \a Qfin */ double run_qmass_MSbar(double quark_mass, double Qinit, double Qfin, double mtop, double mbot); /** * @brief Evaluates the running strong coupling * * This method evaluates the running strong coupling \f$ \alpha_s \f$ in the * \f$ \overline{\rm{MS}} \f$ scheme at the scale specified by \a Q. * * @param Q Scale at which to evaluate the running coupling * @param mtop \f$ \overline{\rm{MS}} \f$ top mass (for thresholds) * @param mbot \f$ \overline{\rm{MS}} \f$ bottom mass (for thresholds) * * @returns The strong coupling \f$ \alpha_s \f$ at the scale \a Q */ double run_alphas_MSbar(double Q, double mtop, double mbot); /** * @brief Number of active flavours * * This method returns the number of active quark flavours to be used at * a certain mass scale when decoupling the heavier quarks. The thresholds * are determined from the quark \f$ \overline{\rm{MS}} \f$ masses. * * @param M The scale for which the number of flavours is desired * * @returns The number of quark flavours active at this scale */ int get_Nactivef(double M); /** * @brief %SM width of the top quark * * Calculates the width of the top quark in the %SM, i.e. no contributions from * \f$ t\to H^+ b \f$ decays etc. are included. * * @returns The top width \f$ \Gamma_t \f$ */ double get_gamma_top(); double get_gamma_tWd(int d); // --- These masses are for compatibility test with HDECAY --- // Scale for HD quark masses (HD) const static double Q_HD = 5.0; // switch for HD quark masses (HD) const static bool b_HD = false; /// Default value for running quark mass at 5 GeV \f$ m_s(5) \f$ (GeV) const static double ms_5 = 0.08160951656; /// Default value for running quark mass at 5 GeV \f$ m_c(5) \f$ (GeV) const static double mc_5 = 0.8960809463; /// Default value for running quark mass at 5 GeV \f$ m_b(5) \f$ (GeV) const static double mb_5 = 4.310679848; /// Default value for running quark mass at 5 GeV \f$ m_t(5) \f$ (GeV) const static double mt_5 = 246.5552058; // ------------------------------------------------------------- private: // Internal variables which store the current values of the SM parameters double m_alpha; double m_alpha0; double m_GF; double m_s2tW; double m_alpha_s; double m_md_p[3]; double m_mu_p[3]; double m_ml_p[3]; double m_MW; double m_MZ; double m_GammaW; double m_GammaZ; double m_CKM[3][3]; double m_qmass_ms[7]; // Support functions for the running mass calculation double m_threshold(double as); double RQ(double as, int nf, int loops); double QCD_beta(int c, int nf); void clear_lookup(); }; #endif
{ "alphanum_fraction": 0.6166420924, "avg_line_length": 26.7106164384, "ext": "h", "hexsha": "6bbd352ae85c89cab08828313f8eb904a604fd14", "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": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_forks_repo_path": "src/SM.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "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": "shiggs90/2HDMC-NLO-master-wei", "max_issues_repo_path": "src/SM.h", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_stars_repo_path": "src/SM.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5293, "size": 15599 }
/* rng/rand48.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_sys.h> #include <gsl/gsl_rng.h> /* This is the Unix rand48() generator. The generator returns the upper 32 bits from each term of the sequence, x_{n+1} = (a x_n + c) mod m using 48-bit unsigned arithmetic, with a = 0x5DEECE66D , c = 0xB and m = 2^48. The seed specifies the upper 32 bits of the initial value, x_1, with the lower 16 bits set to 0x330E. The theoretical value of x_{10001} is 244131582646046. The period of this generator is ? FIXME (probably around 2^48). */ static inline void rand48_advance (void *vstate); static unsigned long int rand48_get (void *vstate); static double rand48_get_double (void *vstate); static void rand48_set (void *state, unsigned long int s); static const unsigned short int a0 = 0xE66D ; static const unsigned short int a1 = 0xDEEC ; static const unsigned short int a2 = 0x0005 ; static const unsigned short int c0 = 0x000B ; typedef struct { unsigned short int x0, x1, x2; } rand48_state_t; static inline void rand48_advance (void *vstate) { rand48_state_t *state = (rand48_state_t *) vstate; /* work with unsigned long ints throughout to get correct integer promotions of any unsigned short ints */ const unsigned long int x0 = (unsigned long int) state->x0 ; const unsigned long int x1 = (unsigned long int) state->x1 ; const unsigned long int x2 = (unsigned long int) state->x2 ; unsigned long int a ; a = a0 * x0 + c0 ; state->x0 = (a & 0xFFFF) ; a >>= 16 ; /* although the next line may overflow we only need the top 16 bits in the following stage, so it does not matter */ a += a0 * x1 + a1 * x0 ; state->x1 = (a & 0xFFFF) ; a >>= 16 ; a += a0 * x2 + a1 * x1 + a2 * x0 ; state->x2 = (a & 0xFFFF) ; } static unsigned long int rand48_get (void *vstate) { unsigned long int x1, x2; rand48_state_t *state = (rand48_state_t *) vstate; rand48_advance (state) ; x2 = (unsigned long int) state->x2; x1 = (unsigned long int) state->x1; return (x2 << 16) + x1; } static double rand48_get_double (void * vstate) { rand48_state_t *state = (rand48_state_t *) vstate; rand48_advance (state) ; return (ldexp((double) state->x2, -16) + ldexp((double) state->x1, -32) + ldexp((double) state->x0, -48)) ; } static void rand48_set (void *vstate, unsigned long int s) { rand48_state_t *state = (rand48_state_t *) vstate; if (s == 0) /* default seed */ { state->x0 = 0x330E ; state->x1 = 0xABCD ; state->x2 = 0x1234 ; } else { state->x0 = 0x330E ; state->x1 = s & 0xFFFF ; state->x2 = (s >> 16) & 0xFFFF ; } return; } static const gsl_rng_type rand48_type = {"rand48", /* name */ 0xffffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (rand48_state_t), &rand48_set, &rand48_get, &rand48_get_double }; const gsl_rng_type *gsl_rng_rand48 = &rand48_type;
{ "alphanum_fraction": 0.6593207156, "avg_line_length": 26.7847222222, "ext": "c", "hexsha": "f01a351f0210a6c9298cd7d3100e6190ee2e2e32", "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/rng/rand48.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/rng/rand48.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/rng/rand48.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": 1164, "size": 3857 }
#pragma once #include "CesiumUtility/Library.h" #include <cmath> #include <cstdint> #include <gsl/narrow> #include <initializer_list> #include <map> #include <optional> #include <stdexcept> #include <string> #include <string_view> #include <type_traits> #include <variant> #include <vector> namespace CesiumUtility { struct JsonValueMissingKey : public std::runtime_error { JsonValueMissingKey(const std::string& key) : std::runtime_error(key + " is not present in Object") {} }; struct JsonValueNotRealValue : public std::runtime_error { JsonValueNotRealValue() : std::runtime_error("this->value was not double, uint64_t or int64_t") {} }; template <typename T, typename U> constexpr T losslessNarrowOrDefault(U u, T defaultValue) noexcept { constexpr const bool is_different_signedness = (std::is_signed<T>::value != std::is_signed<U>::value); const T t = gsl::narrow_cast<T>(u); if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{})))) { return defaultValue; } return t; } /** * @brief A generic implementation of a value in a JSON structure. * * Instances of this class are used to represent the common `extras` field * of glTF elements that extend the the {@link ExtensibleObject} class. */ class CESIUMUTILITY_API JsonValue final { public: /** * @brief The type to represent a `null` JSON value. */ using Null = std::nullptr_t; /** * @brief The type to represent a `Bool` JSON value. */ using Bool = bool; /** * @brief The type to represent a `String` JSON value. */ using String = std::string; /** * @brief The type to represent an `Object` JSON value. */ using Object = std::map<std::string, JsonValue>; /** * @brief The type to represent an `Array` JSON value. */ using Array = std::vector<JsonValue>; /** * @brief Default constructor. */ JsonValue() : value() {} /** * @brief Creates a `null` JSON value. */ JsonValue(std::nullptr_t) : value(nullptr) {} /** * @brief Creates a `Number` JSON value. * * NaN and ±Infinity are represented as {@link JsonValue::Null}. */ JsonValue(double v) { if (std::isnan(v) || std::isinf(v)) { value = nullptr; } else { value = v; } } /** * @brief Creates a `std::int64_t` JSON value (Widening conversion from * std::int8_t). */ JsonValue(std::int8_t v) : value(static_cast<std::int64_t>(v)) {} /** * @brief Creates a `std::uint64_t` JSON value (Widening conversion from * std::uint8_t). */ JsonValue(std::uint8_t v) : value(static_cast<std::uint64_t>(v)) {} /** * @brief Creates a `std::int64_t` JSON value (Widening conversion from * std::int16_t). */ JsonValue(std::int16_t v) : value(static_cast<std::int64_t>(v)) {} /** * @brief Creates a `std::uint64_t` JSON value (Widening conversion from * std::uint16_t). */ JsonValue(std::uint16_t v) : value(static_cast<std::uint64_t>(v)) {} /** * @brief Creates a `std::int64_t` JSON value (Widening conversion from * std::int32_t). */ JsonValue(std::int32_t v) : value(static_cast<std::int64_t>(v)) {} /** * @brief Creates a `std::uint64_t` JSON value (Widening conversion from * std::uint32_t). */ JsonValue(std::uint32_t v) : value(static_cast<std::uint64_t>(v)) {} /** * @brief Creates a `std::int64_t` JSON value. */ JsonValue(std::int64_t v) : value(v) {} /** * @brief Creates a `std::uint64_t` JSON value. */ JsonValue(std::uint64_t v) : value(v) {} /** * @brief Creates a `Bool` JSON value. */ JsonValue(bool v) : value(v) {} /** * @brief Creates a `String` JSON value. */ JsonValue(const std::string& v) : value(v) {} /** * @brief Creates a `String` JSON value. */ JsonValue(std::string&& v) : value(std::move(v)) {} /** * @brief Creates a `String` JSON value. */ JsonValue(const char* v) : value(std::string(v)) {} /** * @brief Creates an `Object` JSON value with the given properties. */ JsonValue(const std::map<std::string, JsonValue>& v) : value(v) {} /** * @brief Creates an `Object` JSON value with the given properties. */ JsonValue(std::map<std::string, JsonValue>&& v) : value(std::move(v)) {} /** * @brief Creates an `Array` JSON value with the given elements. */ JsonValue(const std::vector<JsonValue>& v) : value(v) {} /** * @brief Creates an `Array` JSON value with the given elements. */ JsonValue(std::vector<JsonValue>&& v) : value(std::move(v)) {} /** * @brief Creates an JSON value from the given initializer list. */ JsonValue(std::initializer_list<JsonValue> v) : value(std::vector<JsonValue>(v)) {} /** * @brief Creates an JSON value from the given initializer list. */ JsonValue(std::initializer_list<std::pair<const std::string, JsonValue>> v) : value(std::map<std::string, JsonValue>(v)) {} [[nodiscard]] const JsonValue* getValuePtrForKey(const std::string& key) const; [[nodiscard]] JsonValue* getValuePtrForKey(const std::string& key); /** * @brief Gets a typed value corresponding to the given key in the * object represented by this instance. * * If this instance is not a {@link JsonValue::Object}, returns * `nullptr`. If the key does not exist in this object, returns * `nullptr`. If the named value does not have the type T, returns * nullptr. * * @tparam T The expected type of the value. * @param key The key for which to retrieve the value from this object. * @return A pointer to the requested value, or nullptr if the value * cannot be obtained as requested. */ template <typename T> const T* getValuePtrForKey(const std::string& key) const { const JsonValue* pValue = this->getValuePtrForKey(key); if (!pValue) { return nullptr; } return std::get_if<T>(&pValue->value); } /** * @brief Gets a typed value corresponding to the given key in the * object represented by this instance. * * If this instance is not a {@link JsonValue::Object}, returns * `nullptr`. If the key does not exist in this object, returns * `nullptr`. If the named value does not have the type T, returns * nullptr. * * @tparam T The expected type of the value. * @param key The key for which to retrieve the value from this object. * @return A pointer to the requested value, or nullptr if the value * cannot be obtained as requested. */ template <typename T> T* getValuePtrForKey(const std::string& key) { JsonValue* pValue = this->getValuePtrForKey(key); return std::get_if<T>(&pValue->value); } /** * @brief Converts the numerical value corresponding to the given key * to the provided numerical template type. * If this instance is not a {@link JsonValue::Object}, throws * `std::bad_variant_access`. If the key does not exist in this object, throws * `JsonValueMissingKey`. If the named value does not have a numerical type T, * throws `JsonValueNotRealValue`, if the named value cannot be converted from * `double` / `std::uint64_t` / `std::int64_t` without precision loss, throws * `gsl::narrowing_error` * @tparam To The expected type of the value. * @param key The key for which to retrieve the value from this object. * @return The converted value. * @throws If unable to convert the converted value for one of the aforementioned reasons. * @remarks Compilation will fail if type 'To' is not an integral / float / double type. */ template < typename To, typename std::enable_if< std::is_integral<To>::value || std::is_floating_point<To>::value>::type* = nullptr> [[nodiscard]] To getSafeNumericalValueForKey(const std::string& key) const { const Object& pObject = std::get<Object>(this->value); const auto it = pObject.find(key); if (it == pObject.end()) { throw JsonValueMissingKey(key); } return it->second.getSafeNumber<To>(); } /** * @brief Converts the numerical value corresponding to the given key * to the provided numerical template type. * * If this instance is not a {@link JsonValue::Object}, the key does not exist * in this object, or the named value does not have a numerical type that can * be represented as T without precision loss, then the default value is * returned. * * @tparam To The expected type of the value. * @param key The key for which to retrieve the value from this object. * @return The converted value. * @throws If unable to convert the converted value for one of the * aforementioned reasons. * @remarks Compilation will fail if type 'To' is not an integral / float / * double type. */ template < typename To, typename std::enable_if< std::is_integral<To>::value || std::is_floating_point<To>::value>::type* = nullptr> [[nodiscard]] To getSafeNumericalValueOrDefaultForKey( const std::string& key, To defaultValue) const { const Object& pObject = std::get<Object>(this->value); const auto it = pObject.find(key); if (it == pObject.end()) { return defaultValue; } return it->second.getSafeNumberOrDefault<To>(defaultValue); } /** * @brief Determines if this value is an Object and has the given key. * * @param key The key. * @return true if this value contains the key. false if it is not an object * or does not contain the given key. */ [[nodiscard]] inline bool hasKey(const std::string& key) const { const Object* pObject = std::get_if<Object>(&this->value); if (!pObject) { return false; } return pObject->find(key) != pObject->end(); } /** * @brief Gets the numerical quantity from the value casted to the `To` * type. This function should be used over `getDouble()` / `getUint64()` / * `getInt64()` if you plan on casting that type into another smaller type or * different type. * @returns The converted type if it can be cast without precision loss. * @throws If the underlying value is not a numerical type or it cannot be * converted without precision loss. */ template < typename To, typename std::enable_if< std::is_integral<To>::value || std::is_floating_point<To>::value>::type* = nullptr> [[nodiscard]] To getSafeNumber() const { const std::uint64_t* uInt = std::get_if<std::uint64_t>(&this->value); if (uInt) { return gsl::narrow<To>(*uInt); } const std::int64_t* sInt = std::get_if<std::int64_t>(&this->value); if (sInt) { return gsl::narrow<To>(*sInt); } const double* real = std::get_if<double>(&this->value); if (real) { return gsl::narrow<To>(*real); } throw JsonValueNotRealValue(); } /** * @brief Gets the numerical quantity from the value casted to the `To` * type or returns defaultValue if unable to do so. * @returns The converted type if it can be cast without precision loss * or `defaultValue` if it cannot be converted safely. */ template < typename To, typename std::enable_if< std::is_integral<To>::value || std::is_floating_point<To>::value>::type* = nullptr> [[nodiscard]] To getSafeNumberOrDefault(To defaultValue) const noexcept { const std::uint64_t* uInt = std::get_if<std::uint64_t>(&this->value); if (uInt) { return losslessNarrowOrDefault<To>(*uInt, defaultValue); } const std::int64_t* sInt = std::get_if<std::int64_t>(&this->value); if (sInt) { return losslessNarrowOrDefault<To>(*sInt, defaultValue); } const double* real = std::get_if<double>(&this->value); if (real) { return losslessNarrowOrDefault<To>(*real, defaultValue); } return defaultValue; } /** * @brief Gets the object from the value. * @return The object. * @throws std::bad_variant_access if the underlying type is not a * JsonValue::Object */ [[nodiscard]] inline const JsonValue::Object& getObject() const { return std::get<JsonValue::Object>(this->value); } /** * @brief Gets the string from the value. * @return The string. * @throws std::bad_variant_access if the underlying type is not a * JsonValue::String */ [[nodiscard]] inline const JsonValue::String& getString() const { return std::get<String>(this->value); } /** * @brief Gets the array from the value. * @return The arrayj. * @throws std::bad_variant_access if the underlying type is not a * JsonValue::Array */ [[nodiscard]] inline const JsonValue::Array& getArray() const { return std::get<JsonValue::Array>(this->value); } /** * @brief Gets the bool from the value. * @return The bool. * @throws std::bad_variant_access if the underlying type is not a * JsonValue::Bool */ [[nodiscard]] inline bool getBool() const { return std::get<bool>(this->value); } /** * @brief Gets the double from the value. * @return The double. * @throws std::bad_variant_access if the underlying type is not a double */ [[nodiscard]] inline double getDouble() const { return std::get<double>(this->value); } /** * @brief Gets the std::uint64_t from the value. * @return The std::uint64_t. * @throws std::bad_variant_access if the underlying type is not a * std::uint64_t */ [[nodiscard]] std::uint64_t getUint64() const { return std::get<std::uint64_t>(this->value); } /** * @brief Gets the std::int64_t from the value. * @return The std::int64_t. * @throws std::bad_variant_access if the underlying type is not a * std::int64_t */ [[nodiscard]] std::int64_t getInt64() const { return std::get<std::int64_t>(this->value); } /** * @brief Gets the bool from the value or returns defaultValue * @return The bool or defaultValue if this->value is not a bool. */ [[nodiscard]] inline bool getBoolOrDefault(bool defaultValue) const { const auto* v = std::get_if<bool>(&this->value); if (v) { return *v; } return defaultValue; } /** * @brief Gets the string from the value or returns defaultValue * @return The string or defaultValue if this->value is not a string. */ [[nodiscard]] inline const JsonValue::String getStringOrDefault(String defaultValue) const { const auto* v = std::get_if<JsonValue::String>(&this->value); if (v) { return *v; } return defaultValue; } /** * @brief Gets the double from the value or returns defaultValue * @return The double or defaultValue if this->value is not a double. */ [[nodiscard]] inline double getDoubleOrDefault(double defaultValue) const { const auto* v = std::get_if<double>(&this->value); if (v) { return *v; } return defaultValue; } /** * @brief Gets the uint64_t from the value or returns defaultValue * @return The uint64_t or defaultValue if this->value is not a uint64_t. */ [[nodiscard]] inline std::uint64_t getUint64OrDefault(std::uint64_t defaultValue) const { const auto* v = std::get_if<std::uint64_t>(&this->value); if (v) { return *v; } return defaultValue; } /** * @brief Gets the int64_t from the value or returns defaultValue * @return The int64_t or defaultValue if this->value is not a int64_t. */ [[nodiscard]] inline std::int64_t getInt64OrDefault(std::int64_t defaultValue) const { const auto* v = std::get_if<std::int64_t>(&this->value); if (v) { return *v; } return defaultValue; } /** * @brief Returns whether this value is a `null` value. */ [[nodiscard]] inline bool isNull() const noexcept { return std::holds_alternative<Null>(this->value); } /** * @brief Returns whether this value is a `double`, `std::uint64_t` or * `std::int64_t`. Use this function in conjunction with `getNumber` for * safely casting to arbitrary types */ [[nodiscard]] inline bool isNumber() const noexcept { return isDouble() || isUint64() || isInt64(); } /** * @brief Returns whether this value is a `Bool` value. */ [[nodiscard]] inline bool isBool() const noexcept { return std::holds_alternative<Bool>(this->value); } /** * @brief Returns whether this value is a `String` value. */ [[nodiscard]] inline bool isString() const noexcept { return std::holds_alternative<String>(this->value); } /** * @brief Returns whether this value is an `Object` value. */ [[nodiscard]] inline bool isObject() const noexcept { return std::holds_alternative<Object>(this->value); } /** * @brief Returns whether this value is an `Array` value. */ [[nodiscard]] inline bool isArray() const noexcept { return std::holds_alternative<Array>(this->value); } /** * @brief Returns whether this value is a `double` value. */ [[nodiscard]] inline bool isDouble() const noexcept { return std::holds_alternative<double>(this->value); } /** * @brief Returns whether this value is a `std::uint64_t` value. */ [[nodiscard]] inline bool isUint64() const noexcept { return std::holds_alternative<std::uint64_t>(this->value); } /** * @brief Returns whether this value is a `std::int64_t` value. */ [[nodiscard]] inline bool isInt64() const noexcept { return std::holds_alternative<std::int64_t>(this->value); } /** * @brief The actual value. * * The type of the value may be queried with the `isNull`, `isDouble`, * `isBool`, `isString`, `isObject`, `isUint64`, `isInt64`, `isNumber`, and * `isArray` functions. * * The actual value may be obtained with the `getNumber`, `getBool`, * and `getString` functions for the respective types. For * `Object` values, the properties may be accessed with the * `getValueForKey` functions. */ std::variant< Null, double, std::uint64_t, std::int64_t, Bool, String, Object, Array> value; }; } // namespace CesiumUtility
{ "alphanum_fraction": 0.6465978699, "avg_line_length": 29.3220064725, "ext": "h", "hexsha": "52748dc5ff07cb94be61faebed67ca507446647f", "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": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "zrkcode/cesium-native", "max_forks_repo_path": "CesiumUtility/include/CesiumUtility/JsonValue.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "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": "zrkcode/cesium-native", "max_issues_repo_path": "CesiumUtility/include/CesiumUtility/JsonValue.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "zrkcode/cesium-native", "max_stars_repo_path": "CesiumUtility/include/CesiumUtility/JsonValue.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4795, "size": 18121 }
#pragma once #include <errno.h> // errno #include <fcntl.h> // open, write #include <unistd.h> // getpid #include <sstream> #include <boost/filesystem.hpp> #include <gsl/gsl_util> #include "do_persistence.h" #include "error_macros.h" // RAII wrapper for creating, writing and deleting the file that will // contain the port number for the REST interface. class RestPortAdvertiser { public: RestPortAdvertiser(uint16_t port) { // We cannot remove the port file on shutdown because we have already dropped permissions. // Clean it up now when we are still running as root. _DeleteOlderPortFiles(); std::stringstream ss; ss << docli::GetRuntimeDirectory() << '/' << _restPortFileNamePrefix << '.' << getpid(); _outFilePath = ss.str(); // If file already exists, it is truncated. Probably from an old instance that terminated abnormally. // Allow file to only be read by others. int fd = open(_outFilePath.data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH); if (fd == -1) { THROW_HR_MSG(E_FAIL, "Failed to open file %s, errno: %d", _outFilePath.data(), errno); } try { const auto writeStr = std::to_string(port) + '\n'; const auto cbWrite = gsl::narrow_cast<ssize_t>(writeStr.size() * sizeof(char)); const ssize_t written = write(fd, writeStr.data(), cbWrite); if (written != cbWrite) { THROW_HR_MSG(E_FAIL, "Failed to write port, written: %zd, errno: %d", written, errno); } } catch (...) { (void)close(fd); throw; } (void)close(fd); } const std::string& OutFilePath() const { return _outFilePath; } private: void _DeleteOlderPortFiles() try { auto& runtimeDirectory = docli::GetRuntimeDirectory(); for (boost::filesystem::directory_iterator itr(runtimeDirectory); itr != boost::filesystem::directory_iterator(); ++itr) { auto& dirEntry = itr->path(); if (dirEntry.filename().string().find(_restPortFileNamePrefix) != std::string::npos) { boost::system::error_code ec; boost::filesystem::remove(dirEntry, ec); if (ec) { DoLogWarning("Failed to delete old port file (%d, %s) %s", ec.value(), ec.message().data(), dirEntry.string().data()); } } } } CATCH_LOG() std::string _outFilePath; static constexpr const char* const _restPortFileNamePrefix = "restport"; };
{ "alphanum_fraction": 0.5864774001, "avg_line_length": 34.3205128205, "ext": "h", "hexsha": "3767db9ab52f65cb9dd1f683534d25f6e42bd81e", "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": "8966861204e09961f0db33728e500cd7346cd5dd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "QPC-database/do-client", "max_forks_repo_path": "client-lite/src/ipc/rest_port_advertiser.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8966861204e09961f0db33728e500cd7346cd5dd", "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": "QPC-database/do-client", "max_issues_repo_path": "client-lite/src/ipc/rest_port_advertiser.h", "max_line_length": 138, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8966861204e09961f0db33728e500cd7346cd5dd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "QPC-database/do-client", "max_stars_repo_path": "client-lite/src/ipc/rest_port_advertiser.h", "max_stars_repo_stars_event_max_datetime": "2021-07-06T14:12:34.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-06T14:12:34.000Z", "num_tokens": 624, "size": 2677 }
/* 10 Sept 08: Process_Error_Code is now static and thus private to this library. */ #include <cblas.h> #include "lbl.h" #include "ma57.h" #ifdef __cplusplus extern "C" { /* To prevent C++ compilers from mangling symbols */ #endif /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Process_Error_Code" static int Process_Error_Code( Ma57_Data *ma57, int nerror ) { LOGMSG( " [%3d]", nerror ); /* Take appropriate action according to error code */ /* Inflation factors are from the MA57 spec sheet */ switch( nerror ) { case 0: break; /* Warnings */ case 1: LOGMSG( " Found and ignored %d indices out of range.\n", ma57->info[2] ); break; case 2: LOGMSG( " Found and summed %d duplicate entries.\n", ma57->info[3] ); break; case 3: LOGMSG( " Found duplicate and out-of-range indices.\n" ); break; case 4: LOGMSG( " Matrix has rank %d, deficient.\n", ma57->info[24] ); break; case 5: LOGMSG( " Found %d pivot sign changes in definite matrix.\n", ma57->info[25] ); break; case 8: LOGMSG( " Infinity norm of solution found to be zero.\n" ); break; case 10: LOGMSG( " Insufficient real space. Increased LFACT to %d.\n", ma57->lfact ); break; case 11: LOGMSG( " Insufficient integer space. Increased LIFACT to %d.\n", ma57->lifact ); break; /* Errors */ case -1: LOGMSG( " Value of n is out of range: %d.\n", ma57->info[1] ); break; case -2: LOGMSG( " Value of nz is out of range: %d.\n", ma57->info[1] ); break; case -3: LOGMSG( " Adjusted size of array FACT to %d.\n", ma57->lfact ); break; case -4: LOGMSG( " Adjusting size of array IFACT to %d.\n", ma57->lifact ); break; case -5: LOGMSG( " Small pivot encountered at pivot step %d. Threshold = %lf.\n", ma57->info[1], ma57->cntl[1] ); case -6: LOGMSG( " Change in pivot sign detected at pivot step %d.\n", ma57->info[1] ); break; case -7: LOGMSG( " Erroneous sizing of array FACT or IFACT.\n" ); break; case -8: LOGMSG( " Iterative refinement failed to converge.\n" ); break; case -9: LOGMSG( " Error in user-supplied permutation array in component %d.\n", ma57->info[1] ); break; case -10: LOGMSG( " Unknown pivoting strategy: %d\n.", ma57->info[1] ); break; case -11: LOGMSG( " Size of RHS must be %d. Received %d.\n", ma57->n, ma57->info[1] ); break; case -12: LOGMSG( " Invalid value of JOB (%d).\n", ma57->info[1] ); break; case -13: LOGMSG( " Invalid number of iterative refinement steps (%d).\n", ma57->info[1] ); break; case -14: LOGMSG( " Failed to estimate condition number.\n" ); break; case -15: LOGMSG( " LKEEP has value %d, less than minimum allowed.\n", ma57->info[1] ); break; case -16: LOGMSG( " Invalid number of RHS (%d).\n", ma57->info[1] ); break; case -17: LOGMSG( " Increasing size of LWORK to %d.\n", ma57->lwork ); break; case -18: LOGMSG( " MeTiS library not available or not found.\n" ); break; default: LOGMSG( " Unrecognized flag from Factorize()." ); nerror = -30; } return nerror; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "MA57_Initialize" Ma57_Data *Ma57_Initialize( int nz, int n, FILE *logfile ) { /* Call initialize subroutine MA57ID and set defaults */ Ma57_Data *ma57 = (Ma57_Data *)LBL_Calloc( 1, sizeof(Ma57_Data) ); ma57->logfile = logfile; LOGMSG( " MA57 :: Initializing..." ); ma57->n = n; ma57->nz = nz; ma57->fetched = 0; ma57->irn = (int *)LBL_Calloc( nz, sizeof(int) ); ma57->jcn = (int *)LBL_Calloc( nz, sizeof(int) ); ma57->lkeep = 5*n + nz + imax(n,nz) + 42 + n; // Add n to suggested val. ma57->keep = (int *)LBL_Calloc( ma57->lkeep, sizeof(int) ); ma57->iwork = (int *)LBL_Calloc( 5*n, sizeof(int) ); ma57->work = NULL; // Will be initialized in Ma57_Solve() LOGMSG( " Calling ma57id..." ); MA57ID( ma57->cntl, ma57->icntl ); // Initialize all parameters // Ensure some default parameters are appropriate ma57->icntl[0] = -1; // Stream for error messages. ma57->icntl[1] = -1; // Stream for warning messages. ma57->icntl[2] = -1; // Stream for monitoring printing. ma57->icntl[3] = -1; // Stream for printing of statistics. ma57->icntl[4] = 0; // Verbosity: 0=none, 1=errors, 2=1+warnings, // 3=2+monitor, 4=3+input,output ma57->icntl[5] = 5; // Pivot selection strategy: // 0: AMD using MC47 // 1: User-supplied pivot sequence // 2: AMD with dense row strategy // 3: MD as in MA27 // 4: MeTiS // 5: Automatic (4 with fallback on 2) ma57->icntl[6] = 1; // Numerical pivoting strategy // 1: Do pivoting using value in cntl(1) // 2: No pivoting; exit on sign change or zero // 3: No pivoting; exit if pivot modulus < cntl(2) // 4: No pivoting; alter pivots to have same sign ma57->icntl[7] = 1; // Memory will be re-allocated if necessary ma57->icntl[15] = 0; // No need to scale system before factorizing ma57->fetched = 0; LOGMSG( " done\n"); return ma57; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Analyze" int Ma57_Analyze( Ma57_Data *ma57 ) { int finished = 0, error; LOGMSG( " MA57 :: Analyzing..." ); /* Unpack data structure and call MA57AD */ while( !finished ) { LOGMSG( "\n Calling ma57ad... " ); MA57AD( &(ma57->n), &(ma57->nz), ma57->irn, ma57->jcn, &(ma57->lkeep), ma57->keep, ma57->iwork, ma57->icntl, ma57->info, ma57->rinfo ); error = ma57->info[0]; if( !error ) finished = 1; else { error = Process_Error_Code( ma57, error ); if( error != -3 && error != -4 && error != -8 && error != -14 ) return error; } } // Allocate data for Factorize() ma57->lfact = ceil( LFACT_GROW * ma57->info[8] ); ma57->fact = (double *)LBL_Calloc( ma57->lfact, sizeof(double) ); ma57->lifact = ceil( LIFACT_GROW * ma57->info[9] ); ma57->ifact = (int *)LBL_Calloc( ma57->lifact, sizeof(int) ); LBL_Free( ma57->iwork ); ma57->iwork = (int *)LBL_Calloc( ma57->n, sizeof(int) ); ma57->work = NULL; LOGMSG( " done\n"); return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Factorize" int Ma57_Factorize( Ma57_Data *ma57, double A[] ) { // To ensure consistency with the MA27 interface, the user must pass // the array A, *including* its zero-th element. Internally, A+1 is // passed to MA57. double *newFact; int *newIfact; int newSize, one = 1, zero = 0; int finished = 0, error; LOGMSG( " MA57 :: Factorizing...\n" ); /* Unpack data structure and call MA57BD */ while( !finished ) { LOGMSG( " Calling ma57bd... " ); MA57BD( &(ma57->n), &(ma57->nz), A, ma57->fact, &(ma57->lfact), ma57->ifact, &(ma57->lifact), &(ma57->lkeep), ma57->keep, ma57->iwork, ma57->icntl, ma57->cntl, ma57->info, ma57->rinfo ); error = ma57->info[0]; if( !error ) { finished = 1; } else { error = Process_Error_Code( ma57, error ); if( error == -3 || error == 10 ) { /* Resize real workspace */ newSize = (error == 10) ? ma57->lfact : ma57->info[16]; newSize = ceil( LFACT_GROW * newSize ); LOGMSG(" Resizing real workspace for factors to %d", newSize); newFact = (double *)LBL_Calloc( newSize, sizeof(double) ); MA57ED( &(ma57->n), &zero, ma57->keep, ma57->fact, &(ma57->lfact), newFact, &newSize, ma57->ifact, &(ma57->lifact), NULL, &zero, ma57->info ); LBL_Free( ma57->fact ); ma57->fact = newFact; newFact = NULL; ma57->lfact = newSize; } else if( error == -4 || error == 11 ) { /* Resize integer workspace */ newSize = (error == 11) ? ma57->lifact : ma57->info[17]; newSize = ceil( LIFACT_GROW * newSize ); LOGMSG(" Resizing int workspace for factors to %d", newSize); newIfact = (int *)LBL_Calloc( newSize, sizeof(int) ); MA57ED( &(ma57->n), &one, ma57->keep, ma57->fact, &(ma57->lfact), NULL, &zero, ma57->ifact, &(ma57->lifact), newIfact, &newSize, ma57->info ); LBL_Free( ma57->ifact ); ma57->ifact = newIfact; newIfact = NULL; ma57->lifact = newSize; } else { finished = 1; if( error < 0 ) return error; } } } LOGMSG("\n"); LOGMSG(" %-23s: %6i %-28s: %6i\n", "No. of 2x2 pivots" , ma57->info[21], "Pivot step for modification" , ma57->info[26]); LOGMSG(" %-28s: %6i %-28s: %6i\n", "No. of negative e-vals" , ma57->info[23], "No. of entries in factor" , ma57->info[13]); LOGMSG(" %-28s: %6i %-28s: %6i\n", "Rank of factorization" , ma57->info[24], "No. of pivot sign changes" , ma57->info[25]); LOGMSG(" done\n"); return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Solve" int Ma57_Solve( Ma57_Data *ma57, double x[] ) { int one = 1, finished = 0, error; LOGMSG( " MA57 :: Solving..." ); ma57->job = 1; ma57->lrhs = ma57->n; ma57->nrhs = 1; ma57->lwork = ma57->n * ma57->nrhs; if( !ma57->work ) { LOGMSG("\n Sizing work array to size %d ", ma57->lwork); ma57->work = (double *)LBL_Calloc( ma57->lwork, sizeof(double) ); } while( !finished ) { LOGMSG( "\n Calling ma57cd... " ); /* Unpack data structure and call MA57CD */ MA57CD( &(ma57->job), &(ma57->n), ma57->fact, &(ma57->lfact), ma57->ifact, &(ma57->lifact), &ma57->nrhs, x, &(ma57->lrhs), ma57->work, &(ma57->lwork), ma57->iwork, ma57->icntl, ma57->info ); error = ma57->info[0]; if( error == -17 ) { LBL_Free( ma57->work ); ma57->lwork = ceil( 1.2 * ma57->lwork ); LOGMSG("\n Resizing work array to size %d ", ma57->lwork); ma57->work = (double *)LBL_Calloc( ma57->lwork, sizeof(double) ); } else finished = 1; if( error ) error = Process_Error_Code( ma57, error ); } LOGMSG( " done\n" ); return error; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Refine" int Ma57_Refine( Ma57_Data *ma57, double x[], double rhs[], double A[], int maxitref, int job ) { int error; LOGMSG( " MA57 :: Performing iterative refinement..." ); ma57->job = job; /* For values of 'job' that demand the presence of the residual, * it should be placed by the user in ma57->residual prior to calling * this function. */ /* Allocate work space */ ma57->icntl[8] = imax( 1, maxitref ); // Number of refinement iterations ma57->icntl[9] = 1; // Return estimates of condition number LBL_Free( ma57->iwork ); ma57->iwork = (int *)LBL_Calloc( ma57->n, sizeof(int) ); LBL_Free( ma57->work ); ma57->lwork = ma57->n; if( ma57->icntl[8] > 1 ) { ma57->lwork += 2 * ma57->n; if( ma57->icntl[9] > 0 ) ma57->lwork += 2 * ma57->n; } ma57->work = (double *)LBL_Calloc( ma57->lwork, sizeof(double) ); ma57->residual = (double *)LBL_Calloc( ma57->n, sizeof(double) ); /* Perform iterative refinement */ MA57DD( &(ma57->job), &(ma57->n), &(ma57->nz), A, ma57->irn, ma57->jcn, ma57->fact, &(ma57->lfact), ma57->ifact, &(ma57->lifact), rhs, x, ma57->residual, ma57->work, ma57->iwork, ma57->icntl, ma57->cntl, ma57->info, ma57->rinfo ); error = ma57->info[0]; if( error ) error = Process_Error_Code(ma57, ma57->info[0]); LOGMSG( " done\n" ); return error; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_Finalize" void Ma57_Finalize( Ma57_Data *ma57 ) { /* Free allocated memory */ LOGMSG( " MA57 :: Deallocating data arrays..." ); LBL_Free( ma57->irn ); LBL_Free( ma57->jcn ); LBL_Free( ma57->keep ); LBL_Free( ma57->iwork ); LBL_Free( ma57->fact ); LBL_Free( ma57->ifact ); LBL_Free( ma57->work ); if( ma57->residual ) LBL_Free(ma57->residual); LOGMSG( " done.\n" ); free(ma57); return; } /* ================================================================= */ /* Currently, this routine doesn't do error checking on the allowable parameter values. */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_set_int_parm" void Ma57_set_int_parm( Ma57_Data *ma57, int parm, int val ) { switch (parm) { case MA57_I_PIV_SELECTION: ma57->icntl[MA57_I_PIV_SELECTION] = val; LOGMSG(" Set %-20s = %10d\n","I_PIV_SELECTION",val); break; case MA57_I_PIV_NUMERICAL: ma57->icntl[MA57_I_PIV_NUMERICAL] = val; LOGMSG(" Set %-20s = %10d\n","I_PIV_NUMERICAL",val); break; case MA57_I_SCALING: ma57->icntl[MA57_I_SCALING] = val; LOGMSG(" Set %-20s = %10d\n","I_SCALING",val); break; } return; } /* ================================================================= */ /* Currently, this routine doesn't do error checking on the allowable parameter values. */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_set_real_parm" void Ma57_set_real_parm( Ma57_Data *ma57, int parm, double val ) { switch (parm) { case MA57_D_PIV_THRESH: ma57->cntl[MA57_D_PIV_THRESH] = val; LOGMSG(" Set %-20s = %10.2e\n","D_PIV_THRESH",val); break; case MA57_D_PIV_NONZERO: ma57->cntl[MA57_D_PIV_NONZERO] = val; LOGMSG(" Set %-20s = %10.2e\n","D_PIV_NONZERO",val); break; } return; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_get_int_parm" int Ma57_get_int_parm( Ma57_Data *ma57, int parm ) { switch (parm) { case MA57_I_PIV_SELECTION: return ma57->icntl[MA57_I_PIV_SELECTION]; case MA57_I_PIV_NUMERICAL: return ma57->icntl[MA57_I_PIV_NUMERICAL]; case MA57_I_SCALING: return ma57->icntl[MA57_I_SCALING]; } return 0; } /* ================================================================= */ #ifdef __FUNCT__ #undef __FUNCT__ #endif #define __FUNCT__ "Ma57_get_real_parm" double Ma57_get_real_parm( Ma57_Data *ma57, int parm ) { switch (parm) { case MA57_D_PIV_THRESH: return ma57->cntl[MA57_D_PIV_THRESH]; case MA57_D_PIV_NONZERO: return ma57->cntl[MA57_D_PIV_NONZERO]; } return 0.0; } /* ================================================================= */ #ifdef __cplusplus } /* Closing brace for extern "C" block */ #endif
{ "alphanum_fraction": 0.5205853777, "avg_line_length": 30.4962962963, "ext": "c", "hexsha": "6b1014f9d0dfdf905abb48eb14cf57ae7170a05c", "lang": "C", "max_forks_count": 30, "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_path": "externals/lbl/src/ma57_lib.c", "max_issues_count": 381, "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_path": "externals/lbl/src/ma57_lib.c", "max_line_length": 80, "max_stars_count": 137, "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_path": "externals/lbl/src/ma57_lib.c", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "num_tokens": 4861, "size": 16468 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <gsl/span> #include "core/common/common.h" #include "core/optimizer/graph_transformer.h" namespace onnxruntime { struct FreeDimensionOverride; /** @Class FreeDimensionOverrideTransformer Transformer that overrides free dimensions in the graph with the specific value that matches the denotation for that dimension. */ class FreeDimensionOverrideTransformer : public GraphTransformer { public: explicit FreeDimensionOverrideTransformer(gsl::span<const FreeDimensionOverride> overrides_to_apply); private: Status ApplyImpl(Graph& graph, bool& modified, int graph_level) const override; std::map<std::string, int64_t> dimension_override_by_denotation_; }; } // namespace onnxruntime
{ "alphanum_fraction": 0.7992656059, "avg_line_length": 25.53125, "ext": "h", "hexsha": "d92ac47a08455c5f01f65a7a755a18285e2f0c68", "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": "9ed85987e3cc4c76cdbbec0f1aa84be7660adb43", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mohammad1ta/onnxruntime", "max_forks_repo_path": "onnxruntime/core/optimizer/free_dim_override_transformer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9ed85987e3cc4c76cdbbec0f1aa84be7660adb43", "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": "mohammad1ta/onnxruntime", "max_issues_repo_path": "onnxruntime/core/optimizer/free_dim_override_transformer.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "9ed85987e3cc4c76cdbbec0f1aa84be7660adb43", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mohammad1ta/onnxruntime", "max_stars_repo_path": "onnxruntime/core/optimizer/free_dim_override_transformer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 165, "size": 817 }
#include <stdio.h> #include <stdlib.h> #include <cblas.h> #include <math.h> #include "../inc/knnring.h" // Application Entry Point knnresult kNN(double * X, double * Y, int n, int m, int d, int k) { // Calculate distances matrix D - D is row-major and nxm double* tempD = calculateD(X, Y, n, m, d, k); double* D = calloc(m*n, sizeof(double)); // Transpose D to mxn //cblas_dimatcopy(CblasRowMajor, CblasTrans, n, m, 1.0, D, m, n); double* identityMat = calloc(n*n, sizeof(double)); for(int f=0; f<n; f++) identityMat[f*n + f] = 1; cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, n, 1, tempD, m, identityMat, n, 0, D, n); // Free memory free(identityMat); free(tempD); // Create results struct knnresult results; results.k = k; results.m = m; results.ndist = calloc(m*k, sizeof(double)); results.nidx = calloc(m*k, sizeof(int)); // Create ids array for the X array int* ids = calloc(n, sizeof(int)); // K-Select using quickselect to find k smallest distances for each point of Y for(int j = 0; j < m; j++){ // Re-set ids vector before executing quickselect each time for(int i = 0; i < n; i++) ids[i] = i; // Call quickselect on the row of D to sort it up to its k-th element kselect(D + j * n, ids, n, k); // Quicksort the results quickSort(D + j * n, ids, 0, n-1); // Write results (point id and distance) for(int l = 0; l < k; l++){ results.ndist[j * k + l] = D[j * n + l]; results.nidx[j * k + l] = ids[l]; } } // Free memory and return results free(ids); return results; } // Function used to calculate D = sqrt(sum(X.^2,2) -2* X*Y.' + sum(Y.^2,2).'); double* calculateD(double * X, double * Y, int n, int m, int d, int k){ // Temporary variable double temp = 0; // Distance matrix for results double* D = calloc(n*m, sizeof(double)); // Euclidean norm vectors double* normX = calloc(n, sizeof(double)); double* normY = calloc(m, sizeof(double)); // Matrice to store -2*X*Y' double* XY = calloc(n*m, sizeof(double)); // Calculate -2*XY (https://software.intel.com/en-us/mkl-tutorial-c-multiplying-matrices-using-dgemm) cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, m, d, -2, X, d, Y, d, 0, XY, m); // Calculate sum(X.^2,2), sum(Y.^2,2) for(int i = 0; i < n; i++){ temp = cblas_dnrm2(d, X+i*d, 1); normX[i] = temp * temp; } for(int i = 0; i < m; i++){ temp = cblas_dnrm2(d, Y+i*d, 1); normY[i] = temp * temp; } // XY = sum(X.^2,2) -2* X*Y.' for (int i=0; i<n; i++) for(int j=0; j<m; j++) XY[i*m+j] += normX[i] + normY[j]; // D = sqrt(sum(X.^2,2) -2* X*Y.' + sum(Y.^2,2).'); for(int i = 0; i < n*m; i++) D[i] = sqrt(fabs(XY[i])); // Free memory free(normX); free(normY); free(XY); return D; } // A utility function to swap two elements void swap_double(double *a, double *b){ double t = *a; *a = *b; *b = t; } // A utility function to swap two elements void swap_int(int *a, int *b){ int t = *a; *a = *b; *b = t; } // QuickSort Partition function. low and high are the range of indexes in arr where partition should work int partition (double arr[], int *ids, int low, int high){ // Select a pivot and initialize flag to position of smallest element before pivot double pivot = arr[high]; int i = (low - 1); // Go through the array examining each element for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot, increment i and swap it out with the one currently pointed by i if (arr[j] < pivot) { i++; // Swap distances and corresponding point ids swap_double(&arr[i], &arr[j]); swap_int(&ids[i], &ids[j]); } } // Finally place pivot in its correct position in the array and return the position as the middle point swap_double(&arr[i + 1], &arr[high]); swap_int(&ids[i + 1], &ids[high]); return (i + 1); } // Returns the median using the QuickSelect algorithm double kselect(double arr[], int *ids, int length, int k){ return quickSelect(arr, ids, length, k); } // Returns the idx-th element of arr when arr is sorted. idx is the index (starting from 1) of the point we want to find when the array is sorted. double quickSelect(double arr[], int *ids, int length, int idx){ // Check to end recursion if (length == 1){ return arr[0]; } // Select last array element as pivot double pivot = arr[length - 1]; // Get index of pivot after we partition the array int pivotIndex = partition(arr, ids, 0, length - 1); // Create the higher and lower arrays that occur after partitioning in QuickSort fashion int lowerLength = pivotIndex; pivotIndex++; int higherLength = (length - (lowerLength + 1)); // At this point pivotIndex, lowerLength and higherLength all start from 1 not 0 // Variable to store result of following recursive calls double result = 0; // This means that the point we're looking (median in our case) is in the lower partition if (idx <= lowerLength){ result = quickSelect(arr, ids, lowerLength, idx); } // This means that idx-th element is our pivot point else if(idx == pivotIndex){ result = pivot; } // This means that the median is in the higher partition else{ result = quickSelect(arr + pivotIndex, ids + pivotIndex, higherLength, idx - pivotIndex); } // Return result return result; } // Simple quicksort implementation that also sorts the ids array according to the way the main array was sorted void quickSort(double arr[], int *ids, int low, int high) { if (low < high) { // idx is the partition point int idx = partition(arr, ids, low, high); // Divide and conquer quickSort(arr, ids, low, idx - 1); quickSort(arr, ids, idx + 1, high); } }
{ "alphanum_fraction": 0.6151902998, "avg_line_length": 28.0094339623, "ext": "c", "hexsha": "a67eb8ec71b4a34f42f85f1fdaae3a1c5cd5499c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b426495643705e5616dd526327ba23934d6d1285", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CedArctic/knn_mpi", "max_forks_repo_path": "src/knnring_sequential.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b426495643705e5616dd526327ba23934d6d1285", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CedArctic/knn_mpi", "max_issues_repo_path": "src/knnring_sequential.c", "max_line_length": 146, "max_stars_count": null, "max_stars_repo_head_hexsha": "b426495643705e5616dd526327ba23934d6d1285", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CedArctic/knn_mpi", "max_stars_repo_path": "src/knnring_sequential.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1778, "size": 5938 }
#ifndef __GSL_PERMUTE_MATRIX_H__ #define __GSL_PERMUTE_MATRIX_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <gsl/gsl_permute_matrix_complex_long_double.h> #include <gsl/gsl_permute_matrix_complex_double.h> #include <gsl/gsl_permute_matrix_complex_float.h> #include <gsl/gsl_permute_matrix_long_double.h> #include <gsl/gsl_permute_matrix_double.h> #include <gsl/gsl_permute_matrix_float.h> #include <gsl/gsl_permute_matrix_ulong.h> #include <gsl/gsl_permute_matrix_long.h> #include <gsl/gsl_permute_matrix_uint.h> #include <gsl/gsl_permute_matrix_int.h> #include <gsl/gsl_permute_matrix_ushort.h> #include <gsl/gsl_permute_matrix_short.h> #include <gsl/gsl_permute_matrix_uchar.h> #include <gsl/gsl_permute_matrix_char.h> #endif /* __GSL_PERMUTE_MATRIX_H__ */
{ "alphanum_fraction": 0.8053830228, "avg_line_length": 27.6, "ext": "h", "hexsha": "4710f1465cae35ec9f9dccb5e2d8c81248cee972", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_matrix.h", "max_line_length": 55, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_matrix.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": 272, "size": 966 }
/*insert GNU extensions*/ #define _GNU_SOURCE /*in particular, use of NAN extension*/ /* used by <errno.h> */ extern int errno; /* GSL ----------- */ #include <gsl/gsl_vector.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> /* --------------- */ #define GET(x,i) gsl_vector_get(x,i) #define SET(x,i,y) gsl_vector_set(x,i,y) struct multimin_params { double step_size; double tol; unsigned maxiter; double epsabs; double maxsize; unsigned method; unsigned verbosity; }; void multimin(size_t,double *,double *, const unsigned *,const double *,const double *, void (*) (const size_t,const double *,void *,double *), void (*) (const size_t,const double *, void *,double *), void (*) (const size_t,const double *, void *,double *,double *), void *, const struct multimin_params);
{ "alphanum_fraction": 0.6655172414, "avg_line_length": 23.5135135135, "ext": "h", "hexsha": "d88f271f4180bfdb4e4c1a74573ec8015c886ff8", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_path": "multimin.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_path": "multimin.h", "max_line_length": 67, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_path": "multimin.h", "max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z", "num_tokens": 226, "size": 870 }
#ifndef SOURCE_LINGAUSS_H_ #define SOURCE_LINGAUSS_H_ // *** source/lin_gauss.h *** // Author: Kevin Wolz, date: 06/2018 // // This program defines the class "LinGauss" describing linear Gaussian models. #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <stdlib.h> #include <sys/stat.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_integration.h> #include "utils.h" class LinGauss { public: unsigned int datdim_; unsigned int pardim_; // Ensures that g_matrix_, covar_matrix_, prior_matrix_, prior_param_values_, // data_mean_values_ are initialized and != 0. bool initialized_; // Ensures that cover_matrix_ is inverted and stored in inv_cover_matrix_. bool inverted_; // Ensures that this instance of LinGauss is initialized and fisher_matrix_ // is calculated. bool fisherized_; gsl_matrix* g_matrix_; // design matrix of the model gsl_matrix* covar_matrix_; // data covariance matrix gsl_matrix* inv_covar_matrix_; // inverse data covariance matrix gsl_matrix* fisher_matrix_; // Fisher matrix gsl_matrix* prior_matrix_; // prior precision matrix gsl_vector* prior_param_values_; // prior fiducial parameter values gsl_vector* param_values_; // ML estimator values gsl_vector* data_mean_values_; // mean of the data vector LinGauss(unsigned int num_data, unsigned int num_params); void DisallocateMembers(); void CalculateFisherMatrix(); void CalculateMlEstimator(gsl_vector* data); double CalculateChisquared(gsl_vector* data, gsl_vector* params); }; #endif // SOURCE_LINGAUSS_H_
{ "alphanum_fraction": 0.7589336358, "avg_line_length": 31.4821428571, "ext": "h", "hexsha": "edbadb77b2734deb02fc0ad889303c350e08f6ea", "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": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kevguitar/Robustness", "max_forks_repo_path": "source/lin_gauss.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "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": "kevguitar/Robustness", "max_issues_repo_path": "source/lin_gauss.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kevguitar/Robustness", "max_stars_repo_path": "source/lin_gauss.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 463, "size": 1763 }
#pragma once #include <renderer/Shading.h> #include <renderer/VertexSpecification.h> #include <gsl/span> #include <cassert> namespace ad { namespace graphics { struct GenericDrawer { VertexArrayObject mVertexArray; Program mProgram; std::size_t mVertexCount{0}; std::size_t mInstanceCount{1}; template <class T_vertex> VertexBufferObject addVertexBuffer( const std::initializer_list<AttributeDescription> & aAttributes, gsl::span<T_vertex> aVertices) { if (mVertexCount) { assert(static_cast<std::size_t>(aVertices.size()) == mVertexCount); } else { mVertexCount = aVertices.size(); } return loadVertexBuffer(mVertexArray, aAttributes, sizeof(T_vertex), sizeof(T_vertex)*aVertices.size(), aVertices.data()); } void render() const { glBindVertexArray(mVertexArray); glUseProgram(mProgram); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, mVertexCount, mInstanceCount); } }; } // namespace graphics } // namespace ad
{ "alphanum_fraction": 0.5495011512, "avg_line_length": 23.6909090909, "ext": "h", "hexsha": "997337dfc002e2c161fbfe54d833bee0b3c87869", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-03-18T10:56:05.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-18T10:56:05.000Z", "max_forks_repo_head_hexsha": "6dcc18e4fe21ecd833799bf7338305bbc3600041", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ShredEagle/graphics", "max_forks_repo_path": "src/app/prototypes/chader/GenericDrawer.h", "max_issues_count": 27, "max_issues_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_issues_repo_issues_event_max_datetime": "2022-03-04T13:35:29.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-03T11:34:41.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Adnn/Graphics", "max_issues_repo_path": "src/app/prototypes/chader/GenericDrawer.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Adnn/Graphics", "max_stars_repo_path": "src/app/prototypes/chader/GenericDrawer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 247, "size": 1303 }
/** * @file coroutine/linux.h * @author github.com/luncliff (luncliff@gmail.com) * @copyright CC BY 4.0 */ #ifndef COROUTINE_SYSTEM_WRAPPER_H #define COROUTINE_SYSTEM_WRAPPER_H #if !(defined(__linux__)) #error "expect Linux platform for this file" #endif #include <sys/epoll.h> // for Linux epoll #include <coroutine/return.h> #include <gsl/gsl> /** * @defgroup Linux */ namespace coro { /** * @brief RAII wrapping for epoll file descriptor * @ingroup Linux */ class epoll_owner final { int64_t epfd; public: /** * @brief create a fd with `epoll`. Throw if the function fails. * @see kqeueue * @throw system_error */ epoll_owner() noexcept(false); /** * @brief close the current epoll file descriptor */ ~epoll_owner() noexcept; epoll_owner(const epoll_owner&) = delete; epoll_owner(epoll_owner&&) = delete; epoll_owner& operator=(const epoll_owner&) = delete; epoll_owner& operator=(epoll_owner&&) = delete; public: /** * @brief bind the fd to epoll * @param fd * @param req * @see epoll_ctl * @throw system_error */ void try_add(uint64_t fd, epoll_event& req) noexcept(false); /** * @brief unbind the fd to epoll * @param fd * @see epoll_ctl */ void remove(uint64_t fd); /** * @brief fetch all events for the given kqeueue descriptor * @param wait_ms millisecond to wait * @param list * @return ptrdiff_t * @see epoll_wait * @throw system_error * * Timeout is not an error for this function */ ptrdiff_t wait(uint32_t wait_ms, gsl::span<epoll_event> list) noexcept(false); public: /** * @brief return temporary awaitable object for given event * @param req input for `change` operation * @see change * * There is no guarantee of reusage of returned awaiter object * When it is awaited, and `req.udata` is null(0), * the value is set to `coroutine_handle<void>` * * ```cpp * auto edge_in_async(epoll_owner& ep, int64_t fd) -> frame_t { * epoll_event req{}; * req.events = EPOLLET | EPOLLIN | EPOLLONESHOT; * req.data.ptr = nullptr; * co_await ep.submit(fd, req); * } * ``` */ [[nodiscard]] auto submit(int64_t fd, epoll_event& req) noexcept { class awaiter final : public suspend_always { epoll_owner& ep; int64_t fd; epoll_event& req; public: constexpr awaiter(epoll_owner& _ep, int64_t _fd, epoll_event& _req) : ep{_ep}, fd{_fd}, req{_req} { } public: void await_suspend(coroutine_handle<void> coro) noexcept(false) { if (req.data.ptr == nullptr) req.data.ptr = coro.address(); return ep.try_add(fd, req); } }; return awaiter{*this, fd, req}; } }; /** * @brief RAII + stateful `eventfd` * @see https://github.com/grpc/grpc/blob/master/src/core/lib/iomgr/is_epollexclusive_available.cc * @ingroup Linux * * If the object is signaled(`set`), * the bound `epoll_owner` will yield suspended coroutine through `epoll_event`'s user data. * * Its object can be `co_await`ed multiple times */ class event final { uint64_t state; public: event() noexcept(false); ~event() noexcept; event(const event&) = delete; event(event&&) = delete; event& operator=(const event&) = delete; event& operator=(event&&) = delete; uint64_t fd() const noexcept; bool is_set() const noexcept; void set() noexcept(false); void reset() noexcept(false); }; /** * @brief Bind the given `event`(`eventfd`) to `epoll_owner`(Epoll) * * @param ep epoll_owner * @param efd event * @see event * @return awaitable struct for the binding * @ingroup Linux */ auto wait_in(epoll_owner& ep, event& efd) { class awaiter : epoll_event { epoll_owner& ep; event& efd; public: /** * @brief Prepares one-time registration */ awaiter(epoll_owner& _ep, event& _efd) noexcept : epoll_event{}, ep{_ep}, efd{_efd} { this->events = EPOLLET | EPOLLIN | EPOLLONESHOT; } bool await_ready() const noexcept { return efd.is_set(); } /** * @brief Wait for `write` to given `eventfd` */ void await_suspend(coroutine_handle<void> coro) noexcept(false) { this->data.ptr = coro.address(); return ep.try_add(efd.fd(), *this); } /** * @brief Reset the given event object when resumed */ void await_resume() noexcept { return efd.reset(); } }; return awaiter{ep, efd}; } } // namespace coro #endif // COROUTINE_SYSTEM_WRAPPER_H
{ "alphanum_fraction": 0.5911210217, "avg_line_length": 26.1005291005, "ext": "h", "hexsha": "b6b45fe249e33da7d1117ca53ffb13db9a5b1af4", "lang": "C", "max_forks_count": 29, "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:36:55.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-26T14:03:47.000Z", "max_forks_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "lanza/coroutine", "max_forks_repo_path": "interface/coroutine/linux.h", "max_issues_count": 35, "max_issues_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_issues_repo_issues_event_max_datetime": "2022-01-27T01:10:02.000Z", "max_issues_repo_issues_event_min_datetime": "2018-11-09T04:38:20.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "lanza/coroutine", "max_issues_repo_path": "interface/coroutine/linux.h", "max_line_length": 98, "max_stars_count": 368, "max_stars_repo_head_hexsha": "c90caab988f96997f5bc1bd6f1958b80524fa14a", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "lanza/coroutine", "max_stars_repo_path": "interface/coroutine/linux.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-22T22:57:04.000Z", "num_tokens": 1265, "size": 4933 }