Search is not available for this dataset
text
string
meta
dict
#include "lah.h" #ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */ #include <lapacke.h> lah_Return lah_LU(lah_mat *A, lah_index setZero, lapack_int *ipiv) { lah_index i = 0; lah_index j = 0; lapack_int res = 1; if (A == NULL || A->nR != A->nC) return lahReturnParameterError; /* matrix_layout = LAH_LAPACK_LAYOUT(A); lda = (matrix_layout == LAPACK_COL_MAJOR) ? A->nR : A->nC; */ res = GETRF(LAH_LAPACK_LAYOUT, A->nR, A->nC, A->data, LAH_LEADING_DIM(A), ipiv); /* Set rest of matrix to zero, if setZero == 1 */ if (setZero) { for (i = 0; i < A->nR; i++) { for(j = i + 1; j < A->nC; ++j) LAH_ENTRY(A, i , j) = 0.0; } } return (res == 0) ? lahReturnOk : lahReturnExternError; } #endif
{ "alphanum_fraction": 0.5471014493, "avg_line_length": 25.875, "ext": "c", "hexsha": "63259cef4298bc6a749f5f67024671d54c8e6e58", "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": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_path": "Source/lah_LU.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "maj0e/linear-algebra-helpers", "max_issues_repo_path": "Source/lah_LU.c", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_path": "Source/lah_LU.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 282, "size": 828 }
#include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_ieee_utils.h> int main (void) { double x = 1, oldsum = 0, sum = 0; int i = 0; gsl_ieee_env_setup (); /* read GSL_IEEE_MODE */ do { i++; oldsum = sum; sum += x; x = x / i; printf ("i=%2d sum=%.18f error=%g\n", i, sum, sum - M_E); if (i > 30) break; } while (sum != oldsum); return 0; }
{ "alphanum_fraction": 0.4644444444, "avg_line_length": 14.5161290323, "ext": "c", "hexsha": "04f837db288132d5a51f226134678fd5263bd851", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieeeround.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieeeround.c", "max_line_length": 49, "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/ieeeround.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": 154, "size": 450 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mpi.h> #include "parmt_mtsearch.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "iscl/array/array.h" #include "iscl/memory/memory.h" #include "iscl/signal/convolve.h" int parmt_computeStackedCrossCorrelation_MPI( const MPI_Comm comm, const int npgrns, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, const int ldm, const int nmt, const double *__restrict__ mt, const int npts, const double *__restrict__ data, const int lxc, double *__restrict__ xc) { double *xcwork; int ierr, lx; ierr = 0; lx = npts + npgrns - 1; xcwork = memory_calloc64f(lxc); ierr = parmt_computeStackedCrossCorrelation(npgrns, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, ldm, nmt, mt, npts, data, lx, xcwork); MPI_Allreduce(xcwork, xc, lxc, MPI_DOUBLE, MPI_SUM, comm); memory_free64f(&xcwork); return ierr; } //============================================================================// /*! * @brief This is an alignment tool intended to optimize the lag by computing * * \f[ * x_c = \frac{1}{n_{mt}} \sum_{i=1}^{n_{mt}} \textbf{u}_i \textbf{d} * \f] * * where the \f$ \star \f$ implies a normalized cross-correlation. * * @param[in] npgrns number of points in Green's functions * @param[in] Gxx Green's functions scaled by \f$ m_{xx} \f$ [npgrns] * @param[in] Gyy Green's functions scaled by \f$ m_{yy} \f$ [npgrns] * @param[in] Gzz Green's functions scaled by \f$ m_{zz} \f$ [npgrns] * @param[in] Gxy Green's functions scaled by \f$ m_{xy} \f$ [npgrns] * @param[in] Gxz Green's functions scaled by \f$ m_{xz} \f$ [npgrns] * @param[in] Gyz Green's functions scaled by \f$ m_{yz} \f$ [npgrns] * @param[in] ldm leading dimension of moment tensors (>= 6) * @param[in] nmt number of moment tensors * @param[in] mt moment tensors. the i'th moment tensor begins at * i*ldm and the moment tensor terms are packed * \f$ \{ m_{xx}, m_{yy}, m_{zz}, * m_{xy}, m_{xz}, m_{yz} \f$. * @param[in] npts number of points in signal * @param[in] data Observed data. This is an array of dimension [npts]. * @param[in] lxc max size of xc (should be >= npts + npgrns - 1) * * @param[out] xc stack of the observed and synthetic cross-correlations * [lxc]. the C indexed lag is computed: * npts - 1 + argmax(xc) * where the argmax takes values [0,lx-1] * * @result 0 indicates success * * @author Ben Baker * * @copyright ISTI distributed under Apache 2 * */ int parmt_computeStackedCrossCorrelation( const int npgrns, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, const int ldm, const int nmt, const double *__restrict__ mt, const int npts, const double *__restrict__ data, const int lxc, double *__restrict__ xc) { const char *fcnm = "parmt_computedStackedCrossCorrelation\0"; double *Gmat, *Gxc, *xcorr, *xcw; double m6[8] __attribute__((aligned(64))); double dscal __attribute__((aligned(64))) = 0.0; double gscal __attribute__((aligned(64))) = 0.0; double xscal __attribute__((aligned(64))) = 0.0; double est __attribute__((aligned(64))) = 0.0; int i, ierr, j, lc; lc = npts + npgrns - 1; if (npts < 1 || npgrns < 1 || Gxx == NULL || Gyy == NULL || Gzz == NULL || Gxy == NULL || Gxz == NULL || Gyz == NULL || data == NULL) { if (npts < 1){fprintf(stderr, "%s: no data points\n", __func__);} if (npgrns < 1){fprintf(stderr, "%s: no grns fns points\n", __func__);} if (data == NULL){fprintf(stderr, "%s: data is NULL\n", __func__);} if (Gxx == NULL){fprintf(stderr, "%s: Gxx is NULL\n", __func__);} if (Gyy == NULL){fprintf(stderr, "%s: Gyy is NULL\n", __func__);} if (Gzz == NULL){fprintf(stderr, "%s: Gzz is NULL\n", __func__);} if (Gxy == NULL){fprintf(stderr, "%s: Gxy is NULL\n", __func__);} if (Gxz == NULL){fprintf(stderr, "%s: Gxz is NULL\n", __func__);} if (Gyz == NULL){fprintf(stderr, "%s: Gyz is NULL\n", __func__);} return -1; } if (lc > lxc) { fprintf(stderr, "%s: Error xc is too small\n", __func__); return -1; } if (ldm < 6 || nmt < 1 || mt == NULL) { if (ldm < 6){fprintf(stderr, "%s: ldm must be >= 6\n", __func__);} if (nmt < 1){fprintf(stderr, "%s: no moment tensors\n", __func__);} if (mt == NULL){fprintf(stderr, "%s: mt is NULL\n", __func__);} return -1; } // Set space and correlate data with columns of G xcorr = memory_calloc64f(lc); Gmat = memory_calloc64f(8*npgrns); Gxc = memory_calloc64f(8*lc); dscal = cblas_dnrm2(npts, data, 1); dscal = dscal*dscal; #ifdef __INTEL_COMPILER __assume_aligned(Gxc, 64); __assume_aligned(Gmat, 64); __assume_aligned(xcorr, 64); __assume_aligned(xc, 64); #endif for (i=0; i<6; i++) { if (i == 0) { cblas_dcopy(npgrns, Gxx, 1, &Gmat[i], 8); ierr = signal_convolve_correlate64f_work(npts, data, npgrns, Gxx, CONVCOR_FULL, lc, xcorr); } else if (i == 1) { cblas_dcopy(npgrns, Gyy, 1, &Gmat[i], 8); ierr = signal_convolve_correlate64f_work(npts, data, npgrns, Gyy, CONVCOR_FULL, lc, xcorr); } else if (i == 2) { cblas_dcopy(npgrns, Gzz, 1, &Gmat[i], 8); ierr = signal_convolve_correlate64f_work(npts, data, npgrns, Gzz, CONVCOR_FULL, lc, xcorr); } else if (i == 3) { cblas_dcopy(npgrns, Gxy, 1, &Gmat[i], 8); ierr = signal_convolve_correlate64f_work(npts, data, npgrns, Gxy, CONVCOR_FULL, lc, xcorr); } else if (i == 4) { cblas_dcopy(npgrns, Gxz, 1, &Gmat[i], 8); ierr = signal_convolve_correlate64f_work(npts, data, npgrns, Gxz, CONVCOR_FULL, lc, xcorr); } else if (i == 5) { cblas_dcopy(npgrns, Gyz, 1, &Gmat[i], 8); ierr = signal_convolve_correlate64f_work(npts, data, npgrns, Gyz, CONVCOR_FULL, lc, xcorr); } if (ierr != 0) { fprintf(stderr, "%s: Error correlating Greens fn: %d\n", __func__, i+1); return -1; } cblas_dcopy(lc, xcorr, 1, &Gxc[i], 8); } array_zeros64f_work(lxc, xc); // Compute \f$ x_c = \sum_{i=1}^{n_{mt}} G \textbf{m} \star \textbf{d} \f$ #pragma omp parallel shared(Gxc, Gmat, mt, lc, xc) \ firstprivate (dscal, xcorr) \ private (est, gscal, xscal, i, j, m6, xcw) default(none) { xcw = memory_calloc64f(lxc); #ifdef __INTEL_COMILER __assume_aligned(xcw, 64); #endif #pragma omp for for (i=0; i<nmt; i++) { m6[0] = mt[ldm*i ]; m6[1] = mt[ldm*i+1]; m6[2] = mt[ldm*i+2]; m6[3] = mt[ldm*i+3]; m6[4] = mt[ldm*i+4]; m6[5] = mt[ldm*i+5]; // compute the energy in the synthetic gscal = 0.0; for (j=0; j<npgrns; j++) { est = Gmat[8*j+0]*m6[0] + Gmat[8*j+1]*m6[1] + Gmat[8*j+2]*m6[2] + Gmat[8*j+3]*m6[3] + Gmat[8*j+4]*m6[4] + Gmat[8*j+5]*m6[5]; gscal = gscal + est*est; } xscal = 1.0/sqrt(dscal*gscal); // compute the normalized cross-correlation for (j=0; j<lc; j++) { est = Gxc[8*j+0]*m6[0] + Gxc[8*j+1]*m6[1] + Gxc[8*j+2]*m6[2] + Gxc[8*j+3]*m6[3] + Gxc[8*j+4]*m6[4] + Gxc[8*j+5]*m6[5]; xcw[j] = xcw[j] + xscal*est; } //cblas_dgemv(CblasRowMajor, CblasNoTrans, // lc, 6, 1.0, G, 8, &mt[8*i], 1, 1.0, xcw, 1); } #pragma omp critical #pragma omp simd for (i=0; i<lxc; i++) { xc[i] = xc[i] + xcw[i]; } memory_free64f(&xcw); } // normalize by the number of moment tensors cblas_dscal(lc, 1.0/(double) nmt, xc, 1); // free memory memory_free64f(&Gxc); memory_free64f(&Gmat); memory_free64f(&xcorr); return 0; }
{ "alphanum_fraction": 0.4762422207, "avg_line_length": 38.785440613, "ext": "c", "hexsha": "9d62e7993c4c2021d71487e0a48e6533443cd435", "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": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "src/stackedCrossCorrelation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "src/stackedCrossCorrelation.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "src/stackedCrossCorrelation.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2899, "size": 10123 }
#include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> int main (void) { int i; double xi, yi; double x[10], y[10]; printf ("#m=0,S=2\n"); for (i = 0; i < 10; i++) { x[i] = i + 0.5 * sin (i); y[i] = i + cos (i * i); printf ("%g %g\n", x[i], y[i]); } printf ("#m=1,S=0\n"); { gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 10); gsl_spline_init (spline, x, y, 10); for (xi = x[0]; xi < x[9]; xi += 0.01) { double yi = gsl_spline_eval (spline, xi, acc); printf ("%g %g\n", xi, yi); } gsl_spline_free (spline); gsl_interp_accel_free(acc); } }
{ "alphanum_fraction": 0.5365853659, "avg_line_length": 19.475, "ext": "c", "hexsha": "39aec03f5f812915b6bceff8ca08e6b4a1c831eb", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/demo.c", "max_line_length": 67, "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/interpolation/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 277, "size": 779 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /* * * * Filename: posit.c * * Description: Determine the positivity violation of the Redfield dynamics * on a given initial pure state * * Version: 1.0 * Created: 20/07/2014 09:59:35 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include "initial.h" #include "funcs.h" #include <stdlib.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> /* * FUNCTION * Name: main * Description: * */ int main ( int argc, char *argv[] ) { double o_eff = gsl_hypot(OMEGA, D); /* sigma^z eigenstates, Bloch vectorial form */ double z_minus[] = { 1, 0, -OMEGA/o_eff, -D/o_eff }; double z_plus[] = { 1, 0, OMEGA/o_eff, D/o_eff }; gsl_vector* z_m = gsl_vector_calloc(4); gsl_vector* z_p = gsl_vector_calloc(4); int i; for ( i = 0; i < 4; i++ ) { gsl_vector_set( z_m, i, z_minus[i] ); gsl_vector_set( z_p, i, z_plus[i] ); } /* parameters */ double r, theta; return EXIT_SUCCESS; } /* ---------- end of function main ---------- */ /* * FUNCTION * Name: state_matrix * Description: return the density patrix of the pure state |psi><psi| * */ gsl_matrix_complex* state_matrix ( double r, double theta ) { gsl_matrix_complex* psi = gsl_matrix_complex_calloc (2, 2); gsl_matrix_complex_set ( psi, 1, 1, gsl_complex_rect(r*r, 0) ); gsl_matrix_complex_set ( psi, 1, 2, gsl_complex_rect(r*sqrt(1-r*r)*cos(theta), r*sqrt(1-r*r)*sin(theta)) ); gsl_matrix_complex_set ( psi, 2, 1, gsl_complex_rect(r*sqrt(1-r*r)*cos(theta), -r*sqrt(1-r*r)*sin(theta)) ); gsl_matrix_complex_set ( psi, 2, 2, gsl_complex_rect(1-r*r, 0) ); return psi; } /* ----- end of function state_matrix ----- */ /* * FUNCTION * Name: rotate * Description: return the density matrix in the rotated frame of reference * of an angle OMEGA*t * */ gsl_matrix_complex* rotate ( gsl_matrix_complex* m, double t ) { /* copy m into a working matrix M */ gsl_matrix_complex* M = gsl_matrix_complex_calloc ( 2, 2); gsl_matrix_complex_memcpy( M, m ); /* rotation matrix */ gsl_matrix_complex* Rot = gsl_matrix_complex_calloc( 2, 2 ); gsl_matrix_complex_set ( Rot, 1, 1, gsl_complex_rect( cos(OMEGA*t/2), 0) ); gsl_matrix_complex_set ( Rot, 1, 2, gsl_complex_rect( -sin(OMEGA*t/2), 0)); gsl_matrix_complex_set ( Rot, 2, 1, gsl_complex_rect( sin(OMEGA*t/2), 0) ); gsl_matrix_complex_set ( Rot, 2, 2, gsl_complex_rect( cos(OMEGA*t/2), 0) ); /* inverse of Rot: * * first perform the LU decomposition of Rot: */ gsl_permutation* perm = gsl_permutation_calloc(2); int signum; gsl_matrix_complex* Rot_lu = gsl_matrix_complex_calloc( 2, 2 ); gsl_matrix_complex_memcpy ( Rot_lu, Rot ); gsl_linalg_complex_LU_decomp ( Rot_lu, perm, &signum); /* then calculate Rot_inv: */ gsl_matrix_complex* Rot_inv = gsl_matrix_complex_calloc( 2, 2 ); gsl_linalg_complex_LU_invert ( Rot_lu, perm, Rot_inv ); /* Finally calculate Rot * m * Rot_inv */ gsl_blas_zgemm ( CblasNoTrans, CblasNoTrans, gsl_complex_rect(1.,0), Rot, M, gsl_complex_rect(0,0), M ); gsl_blas_zgemm ( CblasNoTrans, CblasNoTrans, gsl_complex_rect(1.,0), M, Rot_inv, gsl_complex_rect(0,0), M ); return (M); } /* ----- end of function rotate ----- */ /* * FUNCTION * Name: D_psi * Description: the matrix D[|psi><psi|] * */ gsl_matrix_complex* D_psi ( gsl_matrix_complex* dpsi ) { gsl_matrix_complex* dp = gsl_matrix_complex_calloc(2, 2); return (dp); } /* ----- end of function D_psi ----- */
{ "alphanum_fraction": 0.6774193548, "avg_line_length": 32.35625, "ext": "c", "hexsha": "1ebc0142a79170df13506afbc2e86f26ba08bddd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "posit.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "posit.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "posit.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1490, "size": 5177 }
/*This program evaluates the differential equations for a photon's geodesic in a perturbed spacetime in SPHERICAL coordinates.*/ /*This program solves the particular case for flat FRW perturbed spacetime with metric: $g_{ab} = {[g]}_{ab} + h_{ab}$. Where ${[g]}_{ab}$ corresponds to the flat FRW metric and $h_{ab}$ corresponds to the perturbation in the conformal Newtonian gauge. A Plummer potential with adequate parameters have been used to simulate the perturbation. The equations are written in the form $\frac{d(x or p)^{\alpha}}{d\lambda}=f(x^{\alpha},p^{\alpha})$ and the indice $\alpha$ runs from 0 to 3. Where $p^{\alpha}={\dot{x}}^{\alpha}$. The coordinates for the photon's geodesics are: (ct,r,\theta,\phi) = (x0,x1,x2,x3).*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> //GSL error management module #include <gsl/gsl_spline.h> //GSL interpolation module #define A 10.0 //Distance parameter of the perturbations #define G 43007.01 //Gravitational constant #define M 0.0 //Mass of the perturbation #define C 299792.458 //Speed of light #define NLINES 100000 //Number of lines in geodesic_solution.dat file #define NSTEPS 40000000 //Number of steps for solving geodesics #define NLINESFRW 10000 //Number of lines in frw.dat file #define DLAMBDA 0.01 //Geodesics parameter step typedef long double mydbl; /*Interpolation of function inside *spline object evaluated at an abscisa 'x'. Argument *spline is a pointer to a spline object which stores the type of interpolation to be made. x is the independent variable where the function is evaluated. *acc is a pointer to a lookup object for interpolations.*/ double interpolator(gsl_spline *spline, double x, gsl_interp_accel *acc) { double a = gsl_spline_eval(spline, x, acc); //Interpolates data to abcisa x using method in spline and acceleration object acc return a; //Return value of interpolated function at x } /*Function for the gravitational potential to be used. Potential for Plummer model.*/ mydbl potential(mydbl r) { return -G*M/(sqrtl(A*A + r*r)); } /*Derivative of potential respecto to radial coordinate.*/ mydbl der_potential(mydbl r) { return G*M*r/(powl(A*A+r*r, 1.5)); } /*Function of the 0th momentum component differential equation for the geodesics. ${p0}^{dot} = f0(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_0(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl f = -(2.0/(C*C))*der_potential(r)*p0*pr/(1.0 + 2.0*potential(r)/(C*C)) - (1.0 - 2.0*potential(r)/(C*C))*((a*adot)/C)*(pr*pr + r*r*(powl(sinl(theta),2.0)*pphi*pphi + ptheta*ptheta))/(1.0 + 2.0*potential(r)/(C*C)); return f; } /*Function of the 1th (radial) momentum component differential equation for the geodesics. ${p1}^{dot} = f1(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl f = - (der_potential(r)*p0*p0)/(a*a*C*C*(1.0 - 2.0*potential(r)/(C*C))) - (2.0*adot*p0*pr)/(C*a) + r*(ptheta*ptheta + sinl(theta)*sinl(theta)*pphi*pphi) - (der_potential(r)/(C*C))*(powl(r,2.0)*(powl(ptheta,2.0) + powl(sinl(theta)*pphi,2.0)) - pr*pr)/(1.0 - 2.0*potential(r)/(C*C)); return f; } /*Function of the 2th (polar) momentum component differential equation for the geodesics. ${p2}^{dot} = f2(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_theta(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl f = 0.5*sinl(2.0*theta)*pphi*pphi + 2.0*((der_potential(r)/powl(C,2.0))/(1.0 - 2.0*potential(r)/(C*C)) - 1.0/r)*pr*ptheta - (2.0*adot*p0*ptheta)/(C*a); return f; } /*Function of the 3th (azimuthal) momentum component differential equation for the geodesics. ${p3}^{dot} = f3(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_phi(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl f = 2.0*( (der_potential(r)/powl(C,2.0))/(1.0 - 2.0*potential(r)/(C*C)) - 1.0/r)*pr*pphi - 2.0*(1.0/tanl(theta))*ptheta*pphi - (2.0*adot*p0*pphi)/(a*C); return f; } /*Function for solving the geodesics differential equations using 4th order Runge-Kutta method. Arguments are pointer so variables in that memory addresses are changed every time this function is called.*/ void runge_kutta_4(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl *x0, mydbl *x1, mydbl *x2, mydbl *x3, mydbl *p0, mydbl *p1, mydbl *p2, mydbl *p3, mydbl *lambda) { /*Increment in the variables of the differential equation we want to solve*/ mydbl dx0, dx1, dx2, dx3, dp0, dp1, dp2, dp3; /*dxi = (k1,j + 2*k2,j + 2*k3,j + k4,j)/6. In this sections the ki,j are declared with i=1,2,3,4.*/ mydbl k1x0, k1x1, k1x2, k1x3, k1p0, k1p1, k1p2, k1p3; mydbl k2x0, k2x1, k2x2, k2x3, k2p0, k2p1, k2p2, k2p3; mydbl k3x0, k3x1, k3x2, k3x3, k3p0, k3p1, k3p2, k3p3; mydbl k4x0, k4x1, k4x2, k4x3, k4p0, k4p1, k4p2, k4p3; /*This section calculates the k1 quantities*/ k1x0 = *p0*DLAMBDA; k1x1 = *p1*DLAMBDA; k1x2 = *p2*DLAMBDA; k3x0 = *p3*DLAMBDA; k1p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2); k1p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2); k1p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2); k1p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2); /*This section calculates the k2 quantities*/ k2x0 = DLAMBDA*(*p0 + 0.5*k1p0); k2x1 = DLAMBDA*(*p1 + 0.5*k1p1); k2x2 = DLAMBDA*(*p2 + 0.5*k1p2); k2x3 = DLAMBDA*(*p3 + 0.5*k1p3); k2p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2); k2p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2); k2p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2); k2p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2); /*This section calculates the k3 quantities*/ k3x0 = DLAMBDA*(*p0 + 0.5*k2p0); k3x1 = DLAMBDA*(*p1 + 0.5*k2p1); k3x2 = DLAMBDA*(*p2 + 0.5*k2p2); k3x3 = DLAMBDA*(*p3 + 0.5*k2p3); k3p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2); k3p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2); k3p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2); k3p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2); /*This section calculates the k4 quantities*/ k4x0 = DLAMBDA*(*p0 + k3p0); k4x1 = DLAMBDA*(*p1 + k3p1); k4x2 = DLAMBDA*(*p2 + k3p2); k4x3 = DLAMBDA*(*p3 + k3p3); k4p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2); k4p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2); k4p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2); k4p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2); /*Calculation of the increments*/ dx0 = (k1x0 + 2.0*k2x0 + 2.0*k3x0 + k4x0)/6.0; dx1 = (k1x1 + 2.0*k2x1 + 2.0*k3x1 + k4x1)/6.0; dx2 = (k1x2 + 2.0*k2x2 + 2.0*k3x2 + k4x2)/6.0; dx3 = (k1x3 + 2.0*k2x3 + 2.0*k3x3 + k4x3)/6.0; dp0 = (k1p0 + 2.0*k2p0 + 2.0*k3p0 + k4p0)/6.0; dp1 = (k1p1 + 2.0*k2p1 + 2.0*k3p1 + k4p1)/6.0; dp2 = (k1p2 + 2.0*k2p2 + 2.0*k3p2 + k4p2)/6.0; dp3 = (k1p3 + 2.0*k2p3 + 2.0*k3p3 + k4p3)/6.0; /*New values of the variables of the differential equation. Since we are using pointers, when called the routine the value of variable change.*/ *x0 = *x0 + dx0; *x1 = *x1 + dx1; *x2 = *x2 + dx2; *x3 = *x3 + dx3; *p0 = *p0 + dp0; *p1 = *p1 + dp1; *p2 = *p2 + dp2; *p3 = *p3 + dp3; /*Increment of parameter of geodesics*/ *lambda = *lambda + DLAMBDA; } /*To set the initial value of pr, it must hold $g_{\mu\nu}p^{\mu}p^{\nu} = 0$. This factor multiplies p0 to guarantee that p1 fulfill the null geodesic condition.*/ mydbl condition_factor(mydbl r, double a) { return (mydbl)(1.0/a)*sqrtl((1.0+2.0*potential(r)/(C*C))/(1.0 - 2.0*potential(r)/(C*C))); } /*$cp^{0}$ multiplied by this factor allows to obtain the energy for a local inertial observer in this spacetime.*/ mydbl energy_factor(mydbl r) { mydbl g = sqrtl(1.0 + 2.0*potential(r)/(C*C)); return g; } /*Violation of null geodesics condition $g_{\mu\nu}p^{\mu}p^{\nu} = 0$.*/ mydbl violation(mydbl r, mydbl theta, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, double a) { mydbl f = -(1.0+2.0*potential(r)/(C*C))*p0*p0 + a*a*(1.0-2.0*potential(r)/(C*C))*(pr*pr + r*r*(powl(sinl(theta),2.0)*pphi*pphi + ptheta*ptheta)); return f; } int main(void) { /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/ int i; //For array manipulation /*Pointer to scale_factor.dat file*/ FILE *frw; frw = fopen("scale_factor.dat","r"); /*Variables and arrays to read the data*/ double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW]; /*Reading the data*/ for(i=0; i<NLINESFRW; i++) { fscanf(frw,"%lf %lf %lf %lf", &cosmictime[i], &conftime, &scale_factor[i], &der_scale_factor[i]); } /*Free space in memory*/ fclose(frw); /*** Initializes objects for interpolation. 1 is for interpolation of scale factor, 2 is for interpolation of derivative of scale factor ***/ /*Allocate space in memory*/ gsl_interp_accel *acc1 = gsl_interp_accel_alloc(); //Acceleration type object (for index lookup) gsl_interp_accel *acc2 = gsl_interp_accel_alloc(); gsl_spline *spline1 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW); //Spline type object (define interpolation type and space in memory, works for both) gsl_spline *spline2 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW); /*Initializes objects for interpolation*/ gsl_spline_init(spline1, cosmictime, scale_factor, NLINESFRW); //Initializes spline object for data conf_time, scale_factor of size NLINES gsl_spline_init(spline2, cosmictime, der_scale_factor, NLINESFRW); //Initializes spline object for data conf_time, der_scale_factor of size NLINES /************************************************************************************/ /***SOLVES GEODESIC EQUATIONS FOR PERTURBED FRW UNIVERSE WITH STATIC PLUMMER POTENTIAL ***/ /*Initial conditions*/ mydbl ti = 7.0 ,x0, r = -200.0, theta = M_PI*0.5, phi = M_PI*0.5, p0 = 1.0e-3, pr, ptheta = 0.0, pphi = 0.0, lambda = 0.0, energy1, energy, v, difft, difference; double difftfrw, aem, aobs; x0 = C*ti; aem = interpolator(spline1, (double)(1.0*ti), acc1); pr = condition_factor(r, aem)*p0; energy1 = C*energy_factor(r)*p0; v = violation(r, theta, p0, pr, ptheta, pphi, aem); difft = (energy1 - energy1)/energy1; difftfrw = (aem/aem) - 1.0; difference = difft - (mydbl)(1.0*difftfrw); /*Pointer to file where solution of differential equation will be saved.*/ FILE *geodesic; geodesic = fopen("../geodesic_solution.dat","w"); /*Write line of initial values in file*/ fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le\n", lambda, x0, r, theta, phi, p0, pr, ptheta, pphi, energy1, v, difft, difftfrw, difference); long long int ii; /*Solution of the differential equation*/ for(ii=0; ii<(1+ NSTEPS); ii++) { runge_kutta_4(spline1, acc1, spline2, acc2, &x0, &r, &theta, &phi, &p0, &pr, &ptheta, &pphi, &lambda); if((ii%(NSTEPS/NLINES)) == 0) { energy = C*energy_factor(r)*p0; difft = (energy - energy1)/energy1; ti = x0/C; aobs = interpolator(spline1, (double)(1.0*ti), acc1); v = violation(r, theta, p0, pr, ptheta, pphi, aobs); difftfrw = (aem/aobs) - 1.0; difference = difft - (mydbl)(1.0*difftfrw); fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le\n", lambda, x0, r, theta, phi, p0, pr, ptheta, pphi, energy, v, difft, difftfrw, difference); } } /************************************************************************************/ /*** Releasing all used space in memory ***/ fclose(geodesic); //Close file storing the results gsl_spline_free(spline1); //Free memory of spline object gsl_spline_free(spline2); gsl_interp_accel_free(acc1); //Free memory of accel object gsl_interp_accel_free(acc2); }
{ "alphanum_fraction": 0.6591191495, "avg_line_length": 56.8078431373, "ext": "c", "hexsha": "0c286203e66dc9301b80a7553bad4fe86c094a9c", "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": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_forks_repo_path": "frw/frw_perturbed_spherical.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_issues_repo_issues_event_max_datetime": "2016-09-19T20:33:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-26T05:36:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_issues_repo_path": "frw/frw_perturbed_spherical.c", "max_line_length": 342, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_stars_repo_path": "frw/frw_perturbed_spherical.c", "max_stars_repo_stars_event_max_datetime": "2015-10-21T03:59:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-21T03:59:02.000Z", "num_tokens": 6059, "size": 14486 }
#ifndef _NAMASTER_H_ #define _NAMASTER_H_ #ifndef NO_DOXY #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include <complex.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include <fftw3.h> #endif //NO_DOXY #define NMT_MAX(a,b) (((a)>(b)) ? (a) : (b)) // maximum #define NMT_MIN(a,b) (((a)<(b)) ? (a) : (b)) // minimum #ifdef _SPREC typedef float flouble; typedef float complex fcomplex; #else //_SPREC typedef double flouble; typedef double complex fcomplex; #endif //_SPREC /*! \mainpage NaMaster C API * * Welcome to the documentation of NaMaster's C API. Navigate through the tabs above to learn more * about the different functionality implemented in the code. * * \section general_notes General notes * - Most users will prefer to use the python wrapper "pymaster", which mostly calls the C-based functions. * - NaMaster uses a "row-major" order to define the ordering of power spectra into vectors. E.g. the cross-correlation of two spin-2 fields 'a' and 'b' would give rise to 4 power spectra: Ea-Eb, Ea-Bb, Ba-Eb and Ba-Bb. These are stored into 1-dimensional arrays using exactly that order. For the case of a spin-0 - spin-2 correlation, the ordering is [T-E, T-B], where T is the spin-0 field and (E,B) are the harmonic components of the spin-2 field. * - The abbreviation MCM will often be used instead of "mode-coupling matrix". * - SHT will sometimes be used for "Spherical Harmonic Transform". In the context of flat-sky fields, this should be understood as a standard Fast Fourier Transform (FFT) (with appropriate trigonometric factors if dealing with spin-2 fields). * - FWHM will sometimes be used for "Full-width at half-max". * * \section more_info More info * * Please refer to the README and LICENSE files for further information on installation, * credits and licensing. Do not hesitate to contact the authors (preferably via github * issues on https://github.com/LSSTDESC/NaMaster) if you encounter any problems using * the code. */ /** * @brief Flat-sky bandpowers. * * This structure defines bandpowers for flat-sky power spectra. * These are currently defined only by band edges (assumed * flat weights within band). */ typedef struct { int n_bands; //!< Number of bandpowers stored flouble *ell_0_list; //!< Lower edge of each bandpower flouble *ell_f_list; //!< Upper edge of each bandpower } nmt_binning_scheme_flat; /** * @brief nmt_binning_scheme_flat constructor for constant bandpowers * * nmt_binning_scheme_flat constructor for bandpowers with * constant width \p nlb, from ell = 2 to ell = \p lmax. * @param nlb Constant band width * @param lmax Maximum multipole * @return Allocated binning structure. */ nmt_binning_scheme_flat *nmt_bins_flat_constant(int nlb,flouble lmax); /** * @brief nmt_binning_scheme_flat generic constructor. * * @param nell Number of bandpowers * @param l0 Lower edge of all bandpowers (should be allocated to nell elements). * @param lf Lower edge of all bandpowers (should be allocated to nell elements). * @return Allocated binning structure. */ nmt_binning_scheme_flat *nmt_bins_flat_create(int nell,flouble *l0,flouble *lf); /** * @brief nmt_binning_scheme_flat destructor */ void nmt_bins_flat_free(nmt_binning_scheme_flat *bin); /** * @brief Returns average of input power spectrum into bandpowers. * * @param bin nmt_binning_scheme_flat structure defining the bandpowers. * @param nl Number of elements in the input power spectra. * @param larr Array containing the \p nl multipoles at which the input power * spectrum is defined. * @param cls_in Array of \p ncls input power spectra. * @param cls_out Array of \p ncls averaged output power spectra. * Should be allocated to the number of bandpowers defined \p bin. * @param ncls Number of input/output power spectra. */ void nmt_bin_cls_flat(nmt_binning_scheme_flat *bin,int nl,flouble *larr,flouble **cls_in, flouble **cls_out,int ncls); /** * @brief Returns binned power spectra interpolated into an given set of multipoles. * * Nearest-neighbours interpolation is used. * @param bin nmt_binning_scheme_flat structure defining the bandpowers. * @param cls_in Array of \p ncls input power spectra. Must have the same number of * elements as bandpowers defined by \p bin. * @param nl Number of elements in the output power spectra. * @param larr Array containing the \p nl multipoles at which the output power * spectrum are requested. * @param cls_out Array of \p ncls interpolated output power spectra. * @param ncls Number of input/output power spectra. */ void nmt_unbin_cls_flat(nmt_binning_scheme_flat *bin,flouble **cls_in, int nl,flouble *larr,flouble **cls_out,int ncls); /** * @brief Returns effective multipoles. * * Returns the mid point of each bandpower defined in \p bin. * @param bin nmt_binning_scheme_flat structure defining the bandpowers. * @param larr Output array containing mid-points of the bandpowers. * Should be preallocated to the correct number of bandpowers. */ void nmt_ell_eff_flat(nmt_binning_scheme_flat *bin,flouble *larr); /** * @brief Fast bin-searching routine for flat-sky bandpowers * * Returns the bandpower index in which a given ell falls. The functions is designed * to be fast if a good guess for the bandpower index is supplied. A typical use would * be to iterate over ell values and pass, as a guess index, the index found in the * previous iteration. * @param bin nmt_binning_scheme_flat structure defining the bandpowers. * @param l Multipole for which you want the bandpower index. * @param il Guessed bandpower index. * @return Bandpower index. */ int nmt_bins_flat_search_fast(nmt_binning_scheme_flat *bin,flouble l,int il); /** * @brief Full-sky bandpowers. * * This structure defines bandpowers for full-sky power spectra. * Although a given multipole ell can only contribute to one bandpower, * the distribution of ells per bandpower and their relative weights * is left completely free. */ typedef struct { int n_bands; //!< Number of bandpowers. int *nell_list; //!< Number of multipoles belonging to each bandpower. int **ell_list; //!< List of multipoles in each bandpowers. flouble **w_list; //!< List of weights associated to each multipole in \p ell_list. flouble **f_ell; //!< Multiplicative ell factor int ell_max; //!< Maximum multipole included. } nmt_binning_scheme; /** * @brief nmt_binning_scheme constructor for constant bandpowers. * * nmt_binning_scheme constructor for bandpowers with constant * width \p nlb, from ell = 2 to ell = \p lmax. * @param nlb Constant band width * @param lmax Maximum multipole * @param is_l2 If not zero, will assume l*(l+1)/2pi weighting * @return Allocated binning structure. */ nmt_binning_scheme *nmt_bins_constant(int nlb,int lmax,int is_l2); /** * @brief nmt_binning_scheme generic constructor. * * @param nell Number of elements in all subsequent arrays. * @param bpws Array of bandpower indices. * @param ells Array of multipole values. This function collects all multipoles * into their associated bandpowers. * @param weights Array of weights associated to each multipole. Weights are * normalized to 1 within each bandpower. * @param f_ell Array of ell-dependent prefactor (e.g. l*(l+1)/2pi is a typical choice). * Pass NULL if you don't want any prefactor. * normalized to 1 within each bandpower. * @param lmax Maximum multipole to consider. * @return Allocated binning structure. */ nmt_binning_scheme *nmt_bins_create(int nell,int *bpws,int *ells,flouble *weights, flouble *f_ell,int lmax); /** * @brief nmt_binning_scheme constructor from file * * Builds a nmt_binning_scheme structure from an ASCII file. * @param fname Path to file containing information to build bandpowers. * The file should contain three columns, corresponding to: * bandpower index, multipole and weight (in this order). * See definition of nmt_bins_create(). * @param lmax Maximum multipole to be considered. * @return Allocated binning structure. */ nmt_binning_scheme *nmt_bins_read(char *fname,int lmax); /** * @brief nmt_binning_scheme destructor */ void nmt_bins_free(nmt_binning_scheme *bin); /** * @brief Returns average of input power spectrum into bandpowers. * * @param bin nmt_binning_scheme structure defining the bandpowers. * @param cls_in Array of \p ncls input power spectra. They should be * defined in all ells that go into any bandpower defined by \p bin. * @param cls_out Array of \p ncls averaged output power spectra. * Should be allocated to the number of bandpowers defined \p bin. * @param ncls Number of input/output power spectra. */ void nmt_bin_cls(nmt_binning_scheme *bin,flouble **cls_in,flouble **cls_out,int ncls); /** * @brief Returns binned power spectra interpolated into output multipoles. * * Top-hat interpolation is used (i.e. a given ell is associated with the binned power * spectrum value at the bandpower that ell corresponds to). * @param bin nmt_binning_scheme structure defining the bandpowers. * @param cls_in Array of \p ncls input power spectra. Must have the same number of * elements as bandpowers defined by \p bin. * @param cls_out Array of \p ncls interpolated output power spectra. * @param ncls Number of input/output power spectra. */ void nmt_unbin_cls(nmt_binning_scheme *bin,flouble **cls_in,flouble **cls_out,int ncls); /** * @brief Returns effective multipoles. * * Return the weighted average multipole values within each bandpower defined by \p bin. * @param bin nmt_binning_scheme structure defining the bandpowers. * @param larr Output array containing the effective multipole in each bandpower. * Should be preallocated to the correct number of bandpowers. */ void nmt_ell_eff(nmt_binning_scheme *bin,flouble *larr); /** * @brief Flat-sky Fourier-space function * * Unlike multipoles in harmonic space, in the case of full-sky operations, * wavenumbers k in Fourier space for flat-sky fields are in general continuous * variables. This structure helps define functions of these continuous variables. */ typedef struct { int is_const; //!< If >0, this function is just a constant flouble x0; //!< Lower edge of spline interpolation flouble xf; //!< Upper edge of spline interpolation flouble y0; //!< Function will take this value for x < \p x0 flouble yf; //!< Function will take this value for x > \p xf gsl_spline *spl; //!< GSL spline interpolator. } nmt_k_function; /** * @brief nmt_k_function creator. * * @param nk Number of elements in input arrays. * @param karr k-values at which the input function is sampled. * @param farr Function values at k = \p karr. * @param y0 Constant function value below interpolation range. * @param yf Constant function value above interpolation range. * @param is_const If non-zero, will create a constant function. * In this case all previous arguments other than \p y0 are ignored * and the function will take this value for all k. */ nmt_k_function *nmt_k_function_alloc(int nk,flouble *karr,flouble *farr, flouble y0,flouble yf,int is_const); /** * @brief nmt_k_function destructor */ void nmt_k_function_free(nmt_k_function *f); /** * @brief nmt_k_function evaluator. * * Returns value of function at \p k. * @param f nmt_k_function to evaluate. * @param k Value of k for which you want f(k). * @param intacc GSL interpolation accelerator. If you don't want any, just pass a NULL pointer. */ flouble nmt_k_function_eval(nmt_k_function *f,flouble k,gsl_interp_accel *intacc); /** * @brief Flat-sky information. * * This structure contains all the information defining a given rectangular flat-sky patch. * The structure also contains information about the optimal way of sampling the Fourier * version of this patch into rings of |k|. */ typedef struct { int nx; //!< Number of grid points in the x dimension int ny; //!< Number of grid points in the y dimension long npix; //!< Total number of pixels (given by \p nx * \p ny flouble lx; //!< Length of the x dimension (in steradians) flouble ly; //!< Length of the y dimension (in steradians) flouble pixsize; //!< Pixel area (given by \p lx * \p ly / ( \p nx * \p ny)) int n_ell; //!< Number of |k|-values for Fourier-space sampling. flouble dell; //!< Width of the Fourier-space rings. This is found as min(2 &pi; / \p lx,2 &pi; / \p ly). flouble i_dell; //!< 1 / \p dell flouble *ell_min; //!< Array of \p n_ell values containing the lower edges of each of the |k| rings. // int *n_cells; } nmt_flatsky_info; /** * @brief nmt_flatsky_info constructor * * Builds nmt_flatsky_info from patch dimensions. * @param nx Number of grid points in the x dimension * @param ny Number of grid points in the y dimension * @param lx Length of the x dimension (in steradians) * @param ly Length of the y dimension (in steradians) * @return Allocated nmt_flatsky_info structure. */ nmt_flatsky_info *nmt_flatsky_info_alloc(int nx,int ny,flouble lx,flouble ly); /** * @brief nmt_flatsky_info destructor. */ void nmt_flatsky_info_free(nmt_flatsky_info *fs); /** * @brief Flat-sky field * * This structure contains all the information defining a spin-s flat-sky field. * This includes field values, masking, purification and contamination. */ typedef struct { nmt_flatsky_info *fs; //!< Structure defining patch geometry. long npix; //!< Number of pixels in all maps (also contained in \p fs). int pure_e; //!< >0 if E-modes have been purified. int pure_b; //!< >0 if B-modes have been purified. flouble *mask; //!< Field's mask (an array of \p npix values). fcomplex **a_mask; //!< Fourier transform of the mask. Only computed if E or B are purified. int spin; //!< field's spin (>=0). int nmaps; //!< Number of maps in the field (2 for spin-2, 1 for spin-0). flouble **maps; //!< Observed field values. When initialized, these maps are already multiplied by the mask, contaminant deprojected and purified if requested. fcomplex **alms; //!< Fourier-transfoms of the maps. int ntemp; //!< Number of contaminant templates flouble ***temp; //!< Contaminant template maps (mask-multiplied but NOT purified). fcomplex ***a_temp; //!< Fourier-transfomrs of template maps (mask-multiplied AND purified if requested). gsl_matrix *matrix_M; //!< Inverse contaminant covariance matrix (see scientific documentation or companion paper). nmt_k_function *beam; //!< Function defining a circularly-symmetric beam function. Power spectra will be beam-deconvolved. int lite; //!< lightweight field (no maps, temp, a_temp or a_mask) int mask_only; //!< this field only contains a mask, and beam. No alms, maps or anything else. } nmt_field_flat; /** * @brief nmt_field_flat destructor */ void nmt_field_flat_free(nmt_field_flat *fl); /** * @brief nmt_field_flat constructor * * Builds an nmt_field_flat structure from input maps and patch parameters. * @param nx Number of grid points in the x dimension. * @param ny Number of grid points in the y dimension. * @param lx Length of the x dimension (in steradians). * @param ly Length of the y dimension (in steradians). * @param mask Field's mask (an array of \p nx * \p ny values). * @param spin Field's spin. * @param maps Observed field values BEFORE multiplying by the mask (this is irrelevant for binary masks). * @param ntemp Number of contaminant templates affecting this field. * @param temp Contaminant template maps (again, NOT multiplied by the mask). * @param nl_beam Number of multipole values defining this field's beam. * @param l_beam Multipole values at which this field's beam is defined. * @param beam Beam values at ell = \p l_beam. Pass a NULL pointer if you don't want any beam (\p nl_beam and \p l_beam will be ignored). * @param pure_e Set to >0 if you want purified E-modes. * @param pure_b Set to >0 if you want purified B-modes. * @param tol_pinv Contaminant deprojection requires the inversion of the template covariance matrix. This could be ill-defined if some templates are linearly related. In this case we use a pseudo-inverse that accounts for this possibility in a consistent way. Effectively this is a singular-value decomposition. All eigenvalues that are smaller than \p tol_pinv the largest eigenvalue will be discarded. * @param masked_input if not 0, input maps and templates have already been masked. This is not advisable if using purification. * @param is_lite if not 0, only the map alms and the mask will be stored. You can then use this field to compute the standard pseudo-C_ell with deprojection and purification, but you won't be able to compute the deprojection bias or examine any maps. * @param mask_only if not 0, this field will only store a mask and a beam. You will be able to use it to compute the PCL and covariance mode coupling matrices, but that's it (no actual power spectra, deprojection biases etc.). */ nmt_field_flat *nmt_field_flat_alloc(int nx,int ny,flouble lx,flouble ly, flouble *mask,int spin,flouble **maps,int ntemp,flouble ***temp, int nl_beam,flouble *l_beam,flouble *beam, int pure_e,int pure_b,double tol_pinv,int masked_input, int is_lite,int mask_only); /** * @brief Gaussian realizations of flat-sky fields * * Generates a Gaussian realization of an arbitrary list of possibly-correlated * fields with different spins. * @param nx Number of grid points in the x dimension. * @param ny Number of grid points in the y dimension. * @param lx Length of the x dimension (in steradians). * @param ly Length of the y dimension (in steradians). * @param nfields Number of fields to generate. * @param spin_arr Array (size \p nfields) containing the spins of the fields to be generated. * @param nl_beam Number of multipoles at which the field beams are defined. * @param l_beam Array of multipoles at which the field beams are defined. * @param beam_fields Array of beams (one per field). * @param nl_cell Number of multipole values at which the input power spectra are provided. * @param l_cell Array of multipole values at which the input power spectra are provided. * @param cell_fields Array of input power spectra. Shape should be [\p n_cls][\p nl_cell], where \p n_cls is the number of power spectra needed to define all the fields. This should be \p n_cls = n_maps * (n_maps + 1) / 2, where n_maps is the total number of maps required (1 for each spin-0 field, 2 for each spin-2 field). Power spectra must be provided only for the upper-triangular part in row-major order (e.g. if n_maps is 3, there will be 6 power spectra ordered as [1-1,1-2,1-3,2-2,2-3,3-3]. * @param seed Seed for this particular realization. * @return Gaussian realization. */ flouble **nmt_synfast_flat(int nx,int ny,flouble lx,flouble ly,int nfields,int *spin_arr, int nl_beam,flouble *l_beam,flouble **beam_fields, int nl_cell,flouble *l_cell,flouble **cell_fields, int seed); /** * @brief E- or B-mode purifies a given pair of flat-sky (Q,U) maps. * * This function is mostly used internally by NaMaster, and its standalone use is discouraged. * @param fl nmt_field_flat containing information about what should be purified. * @param mask Sky mask (should be appropriately apodized - see scientific documentation). * @param walm0 Fourier transform of the mask. * @param maps_in Maps to be purified (should NOT be mask-multiplied). * @param maps_out Output purified maps. * @param alms Fourier transform of the output purified maps. */ void nmt_purify_flat(nmt_field_flat *fl,flouble *mask,fcomplex **walm0, flouble **maps_in,flouble **maps_out,fcomplex **alms); /** * @brief Curved-sky information. * * This structure contains all the information defining a given full-sky patch. * It describes either a HEALPix grid (in which case is_healpix!=0) or a CAR * patch (for is_healpix==0). If the latter, then the CAR pixelization must * conform to the Clenshaw-Curtis sampling. In this case the colatitude theta * must be sampled at N points going from 0 to pi (including both), separated * by an interval Dtheta = pi/(N-1). Not all iso-latitude rings must be stored * in the patch (i.e. ny!=N necessarily). See the documentation for * nmt_curvedsky_info_alloc for further information on the constraints that * some of the members of this structure must fulfill. */ typedef struct { int is_healpix; //!< is this HEALPix pixelization? long n_eq; //!< equivalent of nside, number of pixels in the equatorial ring int lmax_sht; //!< Maximum multipole to compute spherical harmonic transform int nx_short; //!< Number of grid points in the x dimension before completing the circle int nx; //!< Number of grid points in the phi dimension int ny; //!< Number of grid points in the theta dimension long npix; //!< Total number of pixels (given by \p nx * \p ny flouble Delta_theta; //!< pixel size in theta direction flouble Delta_phi; //!< pixel size in phi direction flouble phi0; // longitude of first pixel flouble theta0; // colatitude of last ring } nmt_curvedsky_info; /** * @brief Makes a copy of a nmt_curvedsky_info structure * * @param cs_in input structure to be copied. * @return copy of input nmt_curvedsky_info structure. */ nmt_curvedsky_info *nmt_curvedsky_info_copy(nmt_curvedsky_info *cs_in); /** * @brief nmt_curvedsky_info creator * * If generating a Clenshaw-Curtis grid, then Dtheta and Dphi must be (close to) * exact divisor of pi and 2pi respectively. Likewise, theta0 must be an integer * multiple of Dtheta, and the number of pixels in the theta direction must be * such that the map actually fits on the sphere (i.e. theta0-(ny-1)*Dtheta >=0). * @param is_healpix is this HEALPix pixelization. * @param nside if is_healpix, this should be the HEALPix Nside parameter. * @param lmax_sht maximum multipole up to which spherical harmonic transforms will be computed. * @param nx0 number of pixels in the phi direction. * @param ny0 number of pixels in the theta direction. * @param Dtheta pixel size in the theta direction. In radians. Must be positive. * @param Dphi pixel size in the phi direction. In radians, must be positive. * @param theta0 colatitude of the last ring in the map. In radians. * @param phi0 minimum azimuth covered by the map. In radians. * @return nmt_curvedsky_info struct. */ nmt_curvedsky_info *nmt_curvedsky_info_alloc(int is_healpix,long nside, int lmax_sht, int nx0,int ny0,flouble Dtheta,flouble Dphi, flouble phi0,flouble theta0); /** * @brief Compare two nmt_curvedsky_info structs. * * @return true (!=0) if both structs are equivalent, and false (0) if they aren't. */ int nmt_diff_curvedsky_info(nmt_curvedsky_info *c1, nmt_curvedsky_info *c2); /** * @brief Extend CAR map to cover the full circle. * * CAR maps only cover a particular part of the sky, but the SHT routines need as * input maps that are complete in the azimuth direction. This routine takes in * a raw CAR map with its corresponding nmt_curvedsky_info and returns the * phi-complete map (with zeros in all pixels outside the original map). * If the input map is in HEALPix, this routine just returns a copy of it. * @param cs curved sky geometry info. * @param map_in input incomplete map. * @return phi-complete map. */ flouble *nmt_extend_CAR_map(nmt_curvedsky_info *cs,flouble *map_in); /** * @brief Full-sky field * * This structure contains all the information defining a spin-s full-sky field. * This includes field values, masking, purification and contamination. */ typedef struct { nmt_curvedsky_info *cs; //!< pixelization parameters long npix; //!< Number of pixels in all maps long nalms; //!< Number of complex harmonic coefficients int lmax; //!< Maximum multipole used int pure_e; //!< >0 if E-modes have been purified int pure_b; //!< >0 if B-modes have been purified flouble *mask; //!< Field's mask (an array of \p npix values). fcomplex **a_mask; //!< Spherical transform of the mask. Only computed if E or B are purified. int spin; //!< field's spin (>=0). int nmaps; //!< Number of maps in the field (2 for spin-2, 1 for spin-0). flouble **maps; //!< Observed field values. When initialized, these maps are already multiplied by the mask, contaminant-deprojected and purified if requested. fcomplex **alms; //!< Spherical harmonic transfoms of the maps. int ntemp; //!< Number of contaminant templates flouble ***temp; //!< Contaminant template maps (mask-multiplied but NOT purified). fcomplex ***a_temp; //!< Spherical harmonic transfomrs of template maps (mask-multiplied AND purified if requested). gsl_matrix *matrix_M; //!< Inverse contaminant covariance matrix (see scientific documentation or companion paper). flouble *beam; //!< Field's beam (defined on all multipoles up to \p lmax). int lite; //!< lightweight field (no maps, temp, a_temp or a_mask) int mask_only; //!< this field only contains a mask, and beam. No alms, maps or anything else. } nmt_field; /** * @brief nmt_field destructor. */ void nmt_field_free(nmt_field *fl); /** * @brief nmt_field constructor * * Builds an nmt_field structure from input maps and resolution parameters. * @param cs curved sky geometry info. * @param mask Field's mask. * @param spin Field's spin. * @param maps Observed field values BEFORE multiplying by the mask (this is irrelevant for binary masks). * @param ntemp Number of contaminant templates affecting this field. * @param temp Contaminant template maps (again, NOT multiplied by the mask). * @param beam Harmonic coefficients of the beam (defined for all multipoles up to * the maximum multipole sampled by the map). Pass a NULL pointer if you don't want any beam. * @param pure_e Set to >0 if you want purified E-modes. * @param pure_b Set to >0 if you want purified B-modes. * @param n_iter_mask_purify E/B purification requires a number of harmonic-space operations on an appropriately apodized mask. This parameter sets the number of iterations requested to compute the spherical harmonic transform of the field's mask. Higher values will produce more accurate results (at the cost of computational time). * @param tol_pinv Contaminant deprojection requires the inversion of the template covariance matrix. This could be ill-defined if some templates are linearly related. In this case we use a pseudo-inverse that accounts for this possibility in a consistent way. Effectively this is a singular-value decomposition. All eigenvalues that are smaller than \p tol_pinv the largest eigenvalue will be discarded. * @param niter number of iterations when computing alms (for all transforms other than the mask's). * @param masked_input if not 0, input maps and templates have already been masked. This is not advisable if using purification. * @param is_lite if not 0, only the map alms and the mask will be stored. You can then use this field to compute the standard pseudo-C_ell with deprojection and purification, but you won't be able to compute the deprojection bias or examine any maps. * @param mask_only if not 0, this field will only store a mask and a beam. You will be able to use it to compute the PCL and covariance mode coupling matrices, but that's it (no actual power spectra, deprojection biases etc.). */ nmt_field *nmt_field_alloc_sph(nmt_curvedsky_info *cs,flouble *mask,int spin,flouble **maps, int ntemp,flouble ***temp,flouble *beam, int pure_e,int pure_b,int n_iter_mask_purify,double tol_pinv, int niter,int masked_input,int is_lite,int mask_only); /** * @brief nmt_field constructor from file. * * Builds an nmt_field structure from data written in files. * @param is_healpix is the map stored in healpix format? * @param fname_mask Path to FITS file containing the field's mask (single HEALPix map). * @param spin Field's spin. * @param fname_maps Path to FITS file containing the field's observed maps (1(2) maps if \p spin=0(!=0)). * @param fname_temp Path to FITS file containing the field's contaminant templates. If \p spin > 0, the file should contain an even number of files. Each consecutive pair of maps will be interpreted as the Q and U components of a given contaminant. Pass "none" if you don't want any contaminants. * @param fname_beam Path to ASCII file containing the field's beam. The file should contain two columns: l (multipole) and b_l (beam SHT at that multipole). Pass "none if you don't want a beam. * @param pure_e >0 if you want E-mode purification. * @param pure_b >0 if you want B-mode purification. * @param n_iter_mask_purify E/B purification requires a number of harmonic-space operations on an appropriately apodized mask. This parameter sets the number of iterations requested to compute the spherical harmonic transform of the field's mask. Higher values will produce more accurate results (at the cost of computational time). * @param tol_pinv Contaminant deprojection requires the inversion of the template covariance matrix. This could be ill-defined if some templates are linearly related. In this case we use a pseudo-inverse that accounts for this possibility in a consistent way. Effectively this is a singular-value decomposition. All eigenvalues that are smaller than \p tol_pinv the largest eigenvalue will be discarded. * @param niter number of iterations when computing alms (other than the mask's). */ nmt_field *nmt_field_read(int is_healpix,char *fname_mask,char *fname_maps,char *fname_temp, char *fname_beam,int spin,int pure_e,int pure_b, int n_iter_mask_purify,double tol_pinv,int niter); /** * @brief Gaussian realizations of full-sky fields * * Generates a Gaussian realization of an arbitrary list of possibly-correlated fields with different spins. * @param cs curved sky geometry info. * @param lmax Maximum multipole used. * @param nfields Number of fields to generate. * @param spin_arr Array (size \p nfields) containing the spins of the fields to be generated. * @param beam_fields Array of beams (one per field). Must be defined at all ell <= \p lmax. * @param cells Array of input power spectra (defined at all ell <= \p lmax). Shape should be [\p n_cls][\p lmax+1], where \p n_cls is the number of power spectra needed to define all the fields. This should be \p n_cls = n_maps * (n_maps + 1) / 2, where n_maps is the total number of maps required (1 for each spin-0 field, 2 for each spin-2 field). Power spectra must be provided only for the upper-triangular part in row-major order (e.g. if n_maps is 3, there will be 6 power spectra ordered as [1-1,1-2,1-3,2-2,2-3,3-3]. * @param seed Seed for this particular realization. * @return Gaussian realization. */ flouble **nmt_synfast_sph(nmt_curvedsky_info *cs,int nfields,int *spin_arr,int lmax, flouble **cells,flouble **beam_fields,int seed); /** * @brief E- or B-mode purifies a given pair of full-sky (Q,U) maps. * * This function is mostly used internally by NaMaster, and its standalone use is discouraged. * @param fl nmt_field containing information about what should be purified. * @param mask Sky mask (should be appropriately apodized - see scientific documentation). * @param walm0 Spherical harmonic transform of the mask. * @param maps_in Maps to be purified (should NOT be mask-multiplied). * @param maps_out Output purified maps. * @param alms Spherical harmonic transform of the output purified maps. * @param niter number of iterations when computing alms. */ void nmt_purify(nmt_field *fl,flouble *mask,fcomplex **walm0, flouble **maps_in,flouble **maps_out,fcomplex **alms,int niter); /** * @brief Apodize full-sky mask. * * Produces apodized version of a full-sky mask for a number of apodization schemes. * @param nside HEALPix resolution parameter. * @param mask_in Input mask to be apodized. * @param mask_out Output apodized mask. * @param aposize Apodization scale (in degrees). * @param apotype String defining the apodization procedure. Three values allowed: 'C1', 'C2' and 'Smooth'. These correspond to: * - \p apotype = "C1". All pixels are multiplied by a factor \f$f\f$, given by: *\f[ * f=\left\{ * \begin{array}{cc} * x-\sin(2\pi x)/(2\pi) & x<1\\ * 1 & {\rm otherwise} * \end{array} * \right., * \f] where \f$x=\sqrt{(1-\cos\theta)/(1-\cos(\theta_*))}\f$, \f$\theta_*\f$ is the apodization scale and \f$\theta\f$ is the angular separation between a pixel and the nearest masked pixel (i.e. where the mask takes a zero value). * - \p apotype = "C2". The same as the C1 case, but the function in this case is: *\f[ * f=\left\{ * \begin{array}{cc} * \frac{1}{2}\left[1-\cos(\pi x)\right] & x<1\\ * 1 & {\rm otherwise} * \end{array} * \right., * \f] * - \p apotype = "Smooth". This apodization is carried out in three steps: * -# All pixels within a disc of radius \f$2.5\theta_*\f$ of a masked pixel are masked. * -# The resulting map is smooth with a Gaussian window function with standard deviation \f$\sigma=\theta_*\f$. * -# One final pass is made through all pixels to ensure that all originally masked * pixels are still masked after the smoothing operation. */ void nmt_apodize_mask(long nside,flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype); /** * @brief Apodize flat-sky mask. * * Produces apodized version of a flat-sky mask for a number of apodization schemes. * @param nx Number of grid points in the x dimension * @param ny Number of grid points in the y dimension * @param lx Length of the x dimension (in steradians) * @param ly Length of the y dimension (in steradians) * @param mask_in Input mask to be apodized. * @param mask_out Output apodized mask. * @param aposize Apodization scale (in degrees). * @param apotype String defining the apodization procedure. See definitions of nmt_apodize_mask(). */ void nmt_apodize_mask_flat(int nx,int ny,flouble lx,flouble ly, flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype); /** * @brief Flat-sky mode-coupling matrix. * * Structure containing information about the mode-coupling matrix (MCM) for flat-sky pseudo-CLs. */ typedef struct { int ncls; //!< Number of power spectra (1, 2 or 4 depending of the spins of the fields being correlated. flouble ellcut_x[2]; //!< Range of ells in the x direction to be masked in Fourie space flouble ellcut_y[2]; //!< Range of ells in the y direction to be masked in Fourie space int pe1; //!< Is the E-mode component of the first field purified? int pe2; //!< Is the E-mode component of the second field purified? int pb1; //!< Is the B-mode component of the first field purified? int pb2; //!< Is the B-mode component of the second field purified? nmt_flatsky_info *fs; //!< Contains information about rectangular flat-sky patch. int is_teb; //!< Does it hold all MCM elements to compute all of spin0-spin0, 0-2 and 2-2 correlations? int *n_cells; //!< Number of unmasked Fourier-space grid points contributing to a given bandpower flouble **coupling_matrix_unbinned; //!< Unbinned MCM flouble **coupling_matrix_binned; //!< Binned MCM nmt_binning_scheme_flat *bin; //!< Bandpowers defining the binning flouble lmax; //!< Maximum k-mode used gsl_matrix *coupling_matrix_binned_gsl; //!< GSL version of MCM (prepared for inversion) gsl_permutation *coupling_matrix_perm; //!< Complements \p coupling_matrix_binned_gsl for inversion. } nmt_workspace_flat; /** * @brief nmt_workspace_flat destructor */ void nmt_workspace_flat_free(nmt_workspace_flat *w); /** * @brief Computes mode-coupling matrix. * * Computes MCM for a given pair of flat-sky fields. * @param fl1 nmt_field_flat structure defining the first field to correlate. * @param fl2 nmt_field_flat structure defining the second field to correlate. * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers. * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked. * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked. * if \p lmx_x < \p lmn_x, no Fourier-space masked is performed. * @param lmn_y Same as \p lmn_x for the y direction. * @param lmx_y Same as \p lmx_x for the y direction. * @param is_teb if !=0, all mode-coupling matrices (0-0,0-2,2-2) will be computed at the same time. */ nmt_workspace_flat *nmt_compute_coupling_matrix_flat(nmt_field_flat *fl1,nmt_field_flat *fl2, nmt_binning_scheme_flat *bin, flouble lmn_x,flouble lmx_x, flouble lmn_y,flouble lmx_y,int is_teb); /** * @brief Computes deprojection bias. * * Computes contaminant deprojection bias for a pair of fields. * See notes about power spectrum ordering in the main page of this documentation. * @param fl1 nmt_field_flat structure defining the first field to correlate. * @param fl2 nmt_field_flat structure defining the second field to correlate. * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers. * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked. * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked. * if \p lmx_x < \p lmn_x, no Fourier-space masked is performed. * @param lmn_y Same as \p lmn_x for the y direction. * @param lmx_y Same as \p lmx_x for the y direction. * @param nl_prop Number of multipoles over which the proposed power spectrum is defined. * @param l_prop Array of multipoles over which the proposed power spectrum is defined. * @param cl_proposal Proposed power spectrum. Should have shape [ncls][\p nl_prop], where \p ncls is the appropriate number of power spectra given the spins of the input fields (e.g. \p ncls = 2*2 = 4 if both fields have spin=2). * @param cl_bias Ouptput deprojection bias. Should be allocated to shape [ncls][nbpw], where \p ncls is defined above and \p nbpw is the number of bandpowers defined by \p bin. */ void nmt_compute_deprojection_bias_flat(nmt_field_flat *fl1,nmt_field_flat *fl2, nmt_binning_scheme_flat *bin, flouble lmn_x,flouble lmx_x,flouble lmn_y,flouble lmx_y, int nl_prop,flouble *l_prop,flouble **cl_proposal, flouble **cl_bias); /** * @brief Mode-couples an input power spectrum * * This function applies the effects of the mode-coupling the pseudo-CL estimator for a given * input power spectrum. This function should be used in conjunction with nmt_decouple_cl_l_flat() * to compute the theory prediction of the pseudo-CL estimator. See the scientific documentation * or the companion paper for further details on how this is done in particular for the flat-sky * approximation. * See notes about power spectrum ordering in the main page of this documentation. * @param w nmt_workspace_flat structure containing the mode-coupling matrix * @param nl Number of multipoles on which the input power spectrum is defined. * @param larr Array of multipoles on which the input power spectrum is defined. * @param cl_in Array of input power spectra. Should have shape [ncls][nl], where ncls is the appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2 for two spin-2 fields. * @param cl_out Array of output power spectra. Should have shape [ncls][nbpw], where ncls is defined above and nbpw is the number of bandpowers used to define \p w. */ void nmt_couple_cl_l_flat_fast(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in, flouble **cl_out); /** * @brief Mode-couples an input power spectrum * * Faster (but less accurate) version of nmt_couple_cl_l_flat_fast(). * @param w nmt_workspace_flat structure containing the mode-coupling matrix * @param nl Number of multipoles on which the input power spectrum is defined. * @param larr Array of multipoles on which the input power spectrum is defined. * @param cl_in Array of input power spectra. Should have shape [ncls][nl], where ncls is the appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2 for two spin-2 fields. * @param cl_out Array of output power spectra. Should have shape [ncls][nbpw], where ncls is defined above and nbpw is the number of bandpowers used to define \p w. */ void nmt_couple_cl_l_flat_quick(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in, flouble **cl_out); /** * @brief Inverts mode-coupling matrix * * Multiplies coupled power spectra by inverse mode-coupling matrix. * See notes about power spectrum ordering in the main page of this documentation. * @param w nmt_workspace_flat containing the mode-coupling matrix. * @param cl_in Input coupled power spectra. Should have shape [ncls][nbpw], where \p ncls is the appropriate number of power spectra given the fields used to define \p w (e.g. 4=2*2 for two spin-2 fields) and \p nbpw is the number of bandpowers used when defining \p w. * @param cl_noise_in Noise bias (same shape as \p cl_in). * @param cl_bias Deprojection bias (same shape as \p cl_in, see nmt_compute_deprojection_bias_flat()). * @param cl_out Mode-decoupled power spectrum (same shape as \p cl_in). */ void nmt_decouple_cl_l_flat(nmt_workspace_flat *w,flouble **cl_in,flouble **cl_noise_in, flouble **cl_bias,flouble **cl_out); /** * @brief Coupled pseudo-CL * * Computes the pseudo-CL power spectrum of two fields without accounting for the mode-coupling * matrix. * See notes about power spectrum ordering in the main page of this documentation. * @param fl1 nmt_field_flat structure defining the first field to correlate. * @param fl2 nmt_field_flat structure defining the second field to correlate. * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers. * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked. * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked. * if \p lmx_x < \p lmn_x, no Fourier-space masked is performed. * @param lmn_y Same as \p lmn_x for the y direction. * @param lmx_y Same as \p lmx_x for the y direction. * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], where \p ncls is the appropriate number of power spectra (e.g. 4=2*2 for two spin-2 fields), and \p nbpw is the number of bandpowers defined by \p bin. */ void nmt_compute_coupled_cell_flat(nmt_field_flat *fl1,nmt_field_flat *fl2, nmt_binning_scheme_flat *bin,flouble **cl_out, flouble lmn_x,flouble lmx_x,flouble lmn_y,flouble lmx_y); /** * @brief Computes pseudo-CL specrum. * * Wrapper function containing all the steps to compute a power spectrum. For performance * reasons, the blind use of this function is discouraged against a smarter combination of * nmt_workspace_flat structures and nmt_compute_coupled_cell_flat(). * See notes about power spectrum ordering in the main page of this documentation. * @param fl1 nmt_field_flat structure defining the first field to correlate. * @param fl2 nmt_field_flat structure defining the second field to correlate. * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers. * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked. * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked. * if \p lmx_x < \p lmn_x, no Fourier-space masked is performed. * @param lmn_y Same as \p lmn_x for the y direction. * @param lmx_y Same as \p lmx_x for the y direction. * @param w0 nmt_workspace_flat structure containing the mode-coupling matrix. If NULL, a new computation of the MCM will be carried out and stored in the output nmt_workspace_flat. Otherwise, \p w0 will be used and returned by this function. * @param nl_prop Number of multipoles over which the proposed power spectrum is defined. * @param l_prop Array of multipoles over which the proposed power spectrum is defined. * @param cl_prop Proposed power spectrum. Should have shape [ncls][\p nl_prop], where \p ncls is the appropriate number of power spectra given the spins of the input fields (e.g. \p ncls = 2*2 = 4 if both fields have spin=2). * @param cl_noise Noise bias. Should have shape [ncls][nbpw], where \p ncls is * defined above and \p nbpw is the number of bandpowers defined by \p bin. * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], where \p ncls is defined above and \p nbpw is the number of bandpowers defined by \p bin. * @return Newly allocated nmt_workspace_flat structure containing the mode-coupling matrix if \p w0 is NULL (will return \p w0 otherwise). */ nmt_workspace_flat *nmt_compute_power_spectra_flat(nmt_field_flat *fl1,nmt_field_flat *fl2, nmt_binning_scheme_flat *bin, flouble lmn_x,flouble lmx_x, flouble lmn_y,flouble lmx_y, nmt_workspace_flat *w0,flouble **cl_noise, int nl_prop,flouble *l_prop,flouble **cl_prop, flouble **cl_out); /** * @brief Full-sky mode-coupling matrix. * * Structure containing information about the mode-coupling matrix (MCM) for full-sky pseudo-CLs. */ typedef struct { int lmax; //!< Maximum multipole used int lmax_fields; //!< Resolution of fields being correlated. int lmax_mask; //!< Mask resolution int is_teb; //!< Does it hold all MCM elements to compute all of spin0-spin0, 0-2 and 2-2 correlations? int ncls; //!< Number of power spectra (1, 2 or 4 depending of the spins of the fields being correlated. nmt_curvedsky_info *cs; //!< curved sky geometry information. flouble *beam_prod; //!< Product of field beams. flouble *pcl_masks; //!< Pseudo-CL of the masks. flouble **coupling_matrix_unbinned; //!< Unbinned mode-coupling matrix nmt_binning_scheme *bin; //!< Bandpowers defining the binning gsl_matrix *coupling_matrix_binned; //!< GSL version of MCM (prepared for inversion) gsl_permutation *coupling_matrix_perm; //!< Complements \p coupling_matrix_binned_gsl for inversion. } nmt_workspace; typedef struct { int lmax; int lmax_mask; int npcl; int s1; int s2; int has_00; flouble ***xi_00; int has_0s; flouble ****xi_0s; int has_ss; flouble ****xi_pp; flouble ****xi_mm; int pure_e1; int pure_e2; int pure_b1; int pure_b2; int pure_any; int npure_0s; int npure_ss; } nmt_master_calculator; nmt_master_calculator *nmt_compute_master_coefficients(int lmax, int lmax_mask, int npcl, flouble **pcl_masks, int s1, int s2, int pure_e1, int pure_b1, int pure_e2, int pure_b2, int do_teb, int l_toeplitz, int l_exact, int dl_band); void nmt_master_calculator_free(nmt_master_calculator *c); /** * @brief Computes mode-coupling matrix. * * Computes MCM for a given pair of full-sky fields. * @param fl1 nmt_field structure defining the first field to correlate. * @param fl2 nmt_field structure defining the second field to correlate. * @param bin nmt_binning_scheme defining the power spectrum bandpowers. * @param is_teb if !=0, all mode-coupling matrices (0-0,0-2,2-2) will be computed at the same time. * @param niter number of iterations when computing alms. * @param lmax_mask maximum multipole to which the masks should be resolved. If smaller than the maximum multipole of fl1/fl2, it will be set to that. * @return Newly allocated nmt_workspace structure containing the mode-coupling matrix. */ nmt_workspace *nmt_compute_coupling_matrix(nmt_field *fl1,nmt_field *fl2,nmt_binning_scheme *bin, int is_teb,int niter,int lmax_mask, int l_toeplitz,int l_exact,int dl_band); /** * @brief Updates the mode coupling matrix with a new one.Saves nmt_workspace structure to file * * The new matrix must be provided as a single 1D array of size n_rows\f$^2\f$. * Here n_rows=n_cls * n_ell is the size of the flattened power spectra, where n_cls is the number * of power spectra (1, 2 or 4 for spin0-0, spin0-2 and spin2-2 correlations) and n_ells=lmax+1 * (by default lmax=3*nside-1 for HEALPix, and pi/dx for CAR (where dx is the minimum angular pixel size)). The ordering of the power spectra should be such that the * l-th element of the i-th power spectrum is stored with index l * n_cls + i. * @param w nmt_workspace to be updated. * @param n_rows size of the flattened power spectra. * @param new_matrix new mode-coupling matrix (flattened). */ void nmt_update_coupling_matrix(nmt_workspace *w,int n_rows,double *new_matrix); /** * @brief Updates the binning scheme associated to this workspace. * * Also rebins the MCM and re-inverts it. * @param w nmt_workspace to be updated. * @param bin new nmt_binning_scheme. */ void nmt_workspace_update_binning(nmt_workspace *w, nmt_binning_scheme *bin); /** * @brief Updates the beams associated to this workspace. * * Also recomputes the binned MCM and its inverse * @param w workspace. * @param nl1 Number of elements of b1. * @param b1 First field's beam (harmonic space). One element per multipole. * @param nl2 Number of elements of b1. * @param b2 Second field's beam (harmonic space). One element per multipole. */ void nmt_workspace_update_beams(nmt_workspace *w, int nl1,double *b1, int nl2,double *b2); /** * @brief nmt_workspace destructor */ void nmt_workspace_free(nmt_workspace *w); /** * @brief Computes deprojection bias. * * Computes contaminant deprojection bias for a pair of fields. * See notes about power spectrum ordering in the main page of this documentation. * @param fl1 nmt_field structure defining the first field to correlate. * @param fl2 nmt_field structure defining the second field to correlate. * @param cl_proposal Proposed power spectrum. Should have shape [ncls][lmax+1], where \p ncls is the appropriate number of power spectra given the spins of the input fields (e.g. \p ncls = 2*2 = 4 if both fields have spin=2). * @param cl_bias Ouptput deprojection bias. Should be allocated to shape [ncls][lmax+1], where \p ncls is defined above. * @param niter number of iterations when computing alms. */ void nmt_compute_deprojection_bias(nmt_field *fl1,nmt_field *fl2, flouble **cl_proposal,flouble **cl_bias,int niter); /** * @brief Noise bias from uncorrelated noise map * * Computes deprojection bias due to an source of uncorrelated noise given an input noise variance map. * See companion paper for more details. * @param fl1 nmt_field structure defining the properties of the field for which this noise bias applies. * @param map_var Noise variance map (should contain per-pixel noise variance). * @param cl_bias Ouptput noise bias. Should be allocated to shape [ncls][lmax+1], where \p ncls is the appropriate number of power spectra given the spins of the input fields (e.g. \p ncls = 2*2 = 4 if both fields have spin=2). * @param niter number of iterations when computing alms. */ void nmt_compute_uncorr_noise_deprojection_bias(nmt_field *fl1,flouble *map_var,flouble **cl_bias, int niter); /** * @brief Mode-couples an input power spectrum * * This function applies the effects of the mode-coupling the pseudo-CL estimator for a given * input power spectrum. This function should be used in conjunction with nmt_decouple_cl_l() * to compute the theory prediction of the pseudo-CL estimator. * See notes about power spectrum ordering in the main page of this documentation. * @param w nmt_workspace structure containing the mode-coupling matrix * @param cl_in Array of input power spectra. Should have shape [ncls][lmax+1], where ncls is the appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2 for two spin-2 fields). * @param cl_out Array of output power spectra. Should have shape [ncls][lmax+1], where ncls is defined above. */ void nmt_couple_cl_l(nmt_workspace *w,flouble **cl_in,flouble **cl_out); /** * @brief Inverts mode-coupling matrix * * Multiplies coupled power spectra by inverse mode-coupling matrix. * See notes about power spectrum ordering in the main page of this documentation. * @param w nmt_workspace containing the mode-coupling matrix. * @param cl_in Input coupled power spectra. Should have shape [ncls][lmax+1], where \p ncls is the appropriate number of power spectra given the fields used to define \p w (e.g. 4=2*2 for two spin-2 fields). * @param cl_noise_in Noise bias (same shape as \p cl_in). * @param cl_bias Deprojection bias (same shape as \p cl_in, see nmt_compute_deprojection_bias()). * @param cl_out Mode-decoupled power spectrum. Should have shape [ncls][nbpw], where ncls is defined above and nbpw is the number of bandpowers used to define \p w. */ void nmt_decouple_cl_l(nmt_workspace *w,flouble **cl_in,flouble **cl_noise_in, flouble **cl_bias,flouble **cl_out); /** * @brief Returns the bandpower window functions for this workspace. * * This function returns, in a flattened array, the bandpower window functions associated with the * mode-coupling matrix stored in this workspace. The effect of the PCL estimator on the unbinned * theory prediction can be fully accounted for by convolving it with these window functions. * @param w nmt_workspace containing the mode-coupling matrix. * @param bpw_win_out output 1D array allocated to the right size (n_cls * n_bpw * n_cls * (lmax+1)). */ void nmt_compute_bandpower_windows(nmt_workspace *w,double *bpw_win_out); /** * @brief Coupled pseudo-CL * * Computes the pseudo-CL power spectrum of two fields without accounting for the mode-coupling * matrix. This is essentially equivalent to running HEALPix's 'anafast' on the purified and * contaminant-deprojected input fields. * See notes about power spectrum ordering in the main page of this documentation. * @param fl1 nmt_field structure defining the first field to correlate. * @param fl2 nmt_field structure defining the second field to correlate. * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][lmax+1], where \p ncls is the appropriate number of power spectra (e.g. 4=2*2 for two spin-2 fields). */ void nmt_compute_coupled_cell(nmt_field *fl1,nmt_field *fl2,flouble **cl_out); /** * @brief Computes pseudo-CL specrum. * * Wrapper function containing all the steps to compute a power spectrum. For performance * reasons, the blind use of this function is discouraged against a smarter combination of * nmt_workspace structures and nmt_compute_coupled_cell(). * See notes about power spectrum ordering in the main page of this documentation. * @param fl1 nmt_field structure defining the first field to correlate. * @param fl2 nmt_field structure defining the second field to correlate. * @param bin nmt_binning_scheme defining the power spectrum bandpowers. * @param w0 nmt_workspace structure containing the mode-coupling matrix. If NULL, a new computation of the MCM will be carried out and stored in the output nmt_workspace. Otherwise, \p w0 will be used and returned by this function. * @param cl_proposal Proposed power spectrum. Should have shape [ncls][lmax+1], where \p ncls is the appropriate number of power spectra given the spins of the input fields (e.g. \p ncls = 2*2 = 4 if both fields have spin=2). * @param cl_noise Noise bias (same shape as \p cl_prop). * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], where \p ncls is defined above and \p nbpw is the number of bandpowers defined by \p bin. * @param niter number of iterations when computing alms. * @param lmax_mask maximum multipole to which the masks should be resolved. If smaller than the maximum multipole of fl1/fl2, it will be set to that. * @return Newly allocated nmt_workspace structure containing the mode-coupling matrix if \p w0 is NULL (will return \p w0 otherwise). */ nmt_workspace *nmt_compute_power_spectra(nmt_field *fl1,nmt_field *fl2, nmt_binning_scheme *bin,nmt_workspace *w0, flouble **cl_noise,flouble **cl_proposal,flouble **cl_out, int niter,int lmax_mask,int l_toeplitz, int l_exact,int dl_band); /** * @brief Flat-sky Gaussian covariance matrix * * Structure containing the information necessary to compute Gaussian covariance matrices * for the pseudo-CL spectra of two flat-sky spin-0 fields. * */ typedef struct { nmt_binning_scheme_flat *bin; //!< Bandpowers defining the binning flouble **xi00_1122; //!< First (a1b1-a2b2), 00, mode coupling matrix (see scientific documentation) flouble **xi00_1221; //!< Second (a1b2-a2b1), 00, mode coupling matrix (see scientific documentation) flouble **xi02_1122; //!< First (a1b1-a2b2), 02, mode coupling matrix (see scientific documentation) flouble **xi02_1221; //!< Second (a1b2-a2b1), 02, mode coupling matrix (see scientific documentation) flouble **xi22p_1122; //!< First (a1b1-a2b2), 22p, mode coupling matrix (see scientific documentation) flouble **xi22p_1221; //!< Second (a1b2-a2b1), 22p, mode coupling matrix (see scientific documentation) flouble **xi22m_1122; //!< First (a1b1-a2b2), 22m, mode coupling matrix (see scientific documentation) flouble **xi22m_1221; //!< Second (a1b2-a2b1), 22m, mode coupling matrix (see scientific documentation) } nmt_covar_workspace_flat; /** * @brief nmt_covar_workspace_flat destructor. */ void nmt_covar_workspace_flat_free(nmt_covar_workspace_flat *cw); /** * @brief nmt_covar_workspace_flat constructor * * Builds an nmt_covar_workspace_flat structure from two nmt_workspace_flat structures, corresponding * to the two sets of power spectra for which the covariance is required. * @param fla1 nmt_field_field for the first field going into the first (a-th) power spectrum. * @param fla2 nmt_field_field for the second field going into the first (a-th) power spectrum. * @param flb1 nmt_field_field for the first field going into the second (b-th) power spectrum. * @param flb2 nmt_field_field for the second field going into the second (b-th) power spectrum. * @param ba nmt_binning_scheme_flat used for the first power spectrum. * @param bb nmt_binning_scheme_flat used for the second power spectrum. */ nmt_covar_workspace_flat *nmt_covar_workspace_flat_init(nmt_field_flat *fla1,nmt_field_flat *fla2, nmt_binning_scheme_flat *ba, nmt_field_flat *flb1,nmt_field_flat *flb2, nmt_binning_scheme_flat *bb); /** * @brief Compute flat-sky Gaussian covariance matrix * * Computes the covariance matrix for two sets of power spectra given input predicted spectra * and two nmt_covar_workspace_flat structures. * @param cw nmt_covar_workspace_flat structure containing the information necessary to compute the covariance matrix. * @param spin_a field a spin. * @param spin_b field b spin. * @param spin_c field c spin. * @param spin_d field d spin. * @param wa nmt_workspace_flat structure containing the mode-coupling matrix for the first power spectra (between fields a and b). * @param wb nmt_workspace_flat structure containing the mode-coupling matrix for the second power spectra (between fields c and d). * @param nl Number of multipoles in which input power spectra are computed. * @param larr Array of multipoles in which input power spectra are computed. * @param clac Cross-power spectra between field 1 in the first set and field 1 in the second set (ac) * @param clad Cross-power spectra between field 1 in the first set and field 2 in the second set (ad) * @param clbc Cross-power spectra between field 2 in the first set and field 1 in the second set (bc) * @param clbd Cross-power spectra between field 2 in the first set and field 2 in the second set (bd) * @param covar_out flattened covariance matrix. Should be allocated to shape [ncls_1 * nbpw_1 * ncls_2 * nbpw_2], where nbpw_X and ncls_X are the number of bandpowers and different power spectra in the X-th set of fields. */ void nmt_compute_gaussian_covariance_flat(nmt_covar_workspace_flat *cw, int spin_a,int spin_b,int spin_c,int spin_d, nmt_workspace_flat *wa,nmt_workspace_flat *wb, int nl,flouble *larr, flouble **clac,flouble **clad, flouble **clbc,flouble **clbd,flouble *covar_out); /** * @brief Full-sky Gaussian covariance matrix * * Structure containing the information necessary to compute Gaussian covariance matrices * for the pseudo-CL spectra of two full-sky spin-0 fields. */ typedef struct { int lmax; //!< Maximum multipole for the first set of power spectra flouble **xi00_1122; //!< First (a1b1-a2b2), 00, mode coupling matrix (see scientific documentation) flouble **xi00_1221; //!< Second (a1b2-a2b1), 00, mode coupling matrix (see scientific documentation) flouble **xi02_1122; //!< First (a1b1-a2b2), 02, mode coupling matrix (see scientific documentation) flouble **xi02_1221; //!< Second (a1b2-a2b1), 02, mode coupling matrix (see scientific documentation) flouble **xi22p_1122; //!< First (a1b1-a2b2), 22+, mode coupling matrix (see scientific documentation) flouble **xi22p_1221; //!< Second (a1b2-a2b1), 22+, mode coupling matrix (see scientific documentation) flouble **xi22m_1122; //!< First (a1b1-a2b2), 22-, mode coupling matrix (see scientific documentation) flouble **xi22m_1221; //!< Second (a1b2-a2b1), 22-, mode coupling matrix (see scientific documentation) } nmt_covar_workspace; /** * @brief nmt_covar_workspace destructor. */ void nmt_covar_workspace_free(nmt_covar_workspace *cw); /** * @brief nmt_covar_workspace constructor * * Builds an nmt_covar_workspace structure from two pairs of nmt_field structures, corresponding * to the two sets of power spectra for which the covariance is required. * @param fla1 nmt_field for the first field going into the first (a-th) power spectrum. * @param fla2 nmt_field for the second field going into the first (a-th) power spectrum. * @param flb1 nmt_field for the first field going into the second (b-th) power spectrum. * @param flb2 nmt_field for the second field going into the second (b-th) power spectrum. * @param lmax maximum multipole up to which the coupling coefficients will be calculated. * @param niter number of iterations when computing alms. */ nmt_covar_workspace *nmt_covar_workspace_init(nmt_field *fla1,nmt_field *fla2, nmt_field *flb1,nmt_field *flb2, int lmax,int niter, int l_toeplitz,int l_exact,int dl_band); /** * @brief Compute full-sky Gaussian covariance matrix * * Computes the covariance matrix for two sets of power spectra given input predicted spectra * and a nmt_covar_workspace structure. * @param cw nmt_covar_workspace structure containing the information necessary to compute the covariance matrix. * @param spin_a field a spin. * @param spin_b field b spin. * @param spin_c field c spin. * @param spin_d field d spin. * @param wa nmt_workspace structure containing the mode-coupling matrix for the first power spectra. * @param wb nmt_workspace structure containing the mode-coupling matrix for the second power spectra. * @param clac Cross-power spectra between field 1 in the first set and field 1 in the second set (ac) All power spectra should be defined for all ell < lmax. * @param clad Cross-power spectra between field 1 in the first set and field 2 in the second set (ad) * @param clbc Cross-power spectra between field 2 in the first set and field 1 in the second set (bc) * @param clbd Cross-power spectra between field 2 in the first set and field 2 in the second set (bd) * @param covar_out flattened covariance matrix. Should be allocated to shape [ncls_1 * nbpw_1 * ncls_2 * nbpw_2], where nbpw_X and ncls_X are the number of bandpowers and different power spectra in the X-th set of fields. */ void nmt_compute_gaussian_covariance(nmt_covar_workspace *cw, int spin_a,int spin_b,int spin_c,int spin_d, nmt_workspace *wa,nmt_workspace *wb, flouble **clac,flouble **clad, flouble **clbc,flouble **clbd, flouble *covar_out); /** * @brief Compute full-sky Gaussian covariance matrix * * Computes the covariance matrix for two sets of power spectra given input predicted spectra * and a nmt_covar_workspace structure. Calculation done for the mode-coupled pseudo-Cls. * @param cw nmt_covar_workspace structure containing the information necessary to compute the covariance matrix. * @param spin_a field a spin. * @param spin_b field b spin. * @param spin_c field c spin. * @param spin_d field d spin. * @param wa nmt_workspace structure containing the mode-coupling matrix for the first power spectra. * @param wb nmt_workspace structure containing the mode-coupling matrix for the second power spectra. * @param clac Cross-power spectra between field 1 in the first set and field 1 in the second set (ac) All power spectra should be defined for all ell < lmax. * @param clad Cross-power spectra between field 1 in the first set and field 2 in the second set (ad) * @param clbc Cross-power spectra between field 2 in the first set and field 1 in the second set (bc) * @param clbd Cross-power spectra between field 2 in the first set and field 2 in the second set (bd) * @param covar_out flattened covariance matrix. Should be allocated to shape [ncls_1 * nbpw_1 * ncls_2 * nbpw_2], where nbpw_X and ncls_X are the number of bandpowers and different power spectra in the X-th set of fields. */ void nmt_compute_gaussian_covariance_coupled(nmt_covar_workspace *cw, int spin_a,int spin_b,int spin_c,int spin_d, nmt_workspace *wa,nmt_workspace *wb, flouble **clac,flouble **clad, flouble **clbc,flouble **clbd, flouble *covar_out); /** * @brief Saves nmt_workspace structure to file * * The output file uses the FITS standard. In combination with nmt_workspace_read_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future power spectrum computations. The same workspace can be used on any pair of fields * with the same masks. * @param w nmt_workspace to be saved. * @param fname Path to output file. */ void nmt_workspace_write_fits(nmt_workspace *w,char *fname); /** * @brief Builds nmt_workspace structure from file * * The input file uses the FITS standard. In combination with nmt_workspace_write_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future power spectrum computations. The same workspace can be used on any pair of fields * with the same masks. * @param fname Path to input file. */ nmt_workspace *nmt_workspace_read_fits(char *fname); /** * @brief Builds nmt_workspace_flat structure from file * * The input file uses the FITS standard. In combination with nmt_workspace_flat_write_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future power spectrum computations. The same workspace can be used on any pair of fields * with the same masks. * @param fname Path to input file. */ nmt_workspace_flat *nmt_workspace_flat_read_fits(char *fname); /** * @brief Saves nmt_workspace_flat structure to file * * The output file uses the FITS standard. In combination with nmt_workspace_flat_read_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future power spectrum computations. The same workspace can be used on any pair of fields * with the same masks. * @param w nmt_workspace_flat to be saved. * @param fname Path to output file. */ void nmt_workspace_flat_write_fits(nmt_workspace_flat *w,char *fname); /** * @brief Saves nmt_covar_workspace structure to file * * The output file uses the FITS standard. In combination with nmt_covar_workspace_read_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future covariance matrix computations. The same workspace can be used on any pair of power spectra * between fields with the same masks. * @param cw nmt_covar_workspace to be saved. * @param fname Path to output file. */ void nmt_covar_workspace_write_fits(nmt_covar_workspace *cw,char *fname); /** * @brief Builds nmt_covar_workspace structure from file * * The input file uses the FITS standard. In combination with nmt_covar_workspace_write_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future covariance matrix computations. The same workspace can be used on any pair of power spectra * between fields with the same masks. * @param fname Path to input file. */ nmt_covar_workspace *nmt_covar_workspace_read_fits(char *fname); /** * @brief Saves nmt_covar_workspace_flat structure to file * * The output file uses the FITS standard. In combination with nmt_covar_workspace_flat_read_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future covariance matrix computations. The same workspace can be used on any pair of power spectra * between fields with the same masks. * @param cw nmt_covar_workspace_flat to be saved. * @param fname Path to output file. */ void nmt_covar_workspace_flat_write_fits(nmt_covar_workspace_flat *cw,char *fname); /** * @brief Builds nmt_covar_workspace_flat structure from file * * The input file uses the FITS standard. In combination with nmt_covar_workspace_flat_write_fits(), * this can be used to save the information contained in a given workspace and reuse it for * future covariance matrix computations. The same workspace can be used on any pair of power spectra * between fields with the same masks. * @param fname Path to input file. */ nmt_covar_workspace_flat *nmt_covar_workspace_flat_read_fits(char *fname); #endif //_NAMASTER_H_
{ "alphanum_fraction": 0.7329121515, "avg_line_length": 50.4950704225, "ext": "h", "hexsha": "391c6a9126191b6e75b13a587a9e24e5f2f048bd", "lang": "C", "max_forks_count": 22, "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:28:48.000Z", "max_forks_repo_forks_event_min_datetime": "2018-08-16T21:15:48.000Z", "max_forks_repo_head_hexsha": "3707cf5d78688340f81d836f24a48435149d4df3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "LSSTDESC/NaMaster", "max_forks_repo_path": "src/namaster.h", "max_issues_count": 96, "max_issues_repo_head_hexsha": "3707cf5d78688340f81d836f24a48435149d4df3", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:38:23.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-20T07:35:37.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "LSSTDESC/NaMaster", "max_issues_repo_path": "src/namaster.h", "max_line_length": 165, "max_stars_count": 37, "max_stars_repo_head_hexsha": "3707cf5d78688340f81d836f24a48435149d4df3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "LSSTDESC/NaMaster", "max_stars_repo_path": "src/namaster.h", "max_stars_repo_stars_event_max_datetime": "2022-02-08T19:47:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-31T15:59:52.000Z", "num_tokens": 18078, "size": 71703 }
#ifndef __NEURALNETWORK_INCLUDED__ #define __NEURALNETWORK_INCLUDED__ #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #include <string> #include "Frame.h" using namespace std; struct Matrix { double* data; int rows; int cols; }; class NeuralNetwork { public: NeuralNetwork(string theta1_filename, string theta2_filename); ~NeuralNetwork(); double* predict(Frame* frame); private: Matrix theta1_; Matrix theta2_; }; Matrix read2DMatrixFromFile(string filename); double sigmoid(double x); #endif
{ "alphanum_fraction": 0.7540394973, "avg_line_length": 15.0540540541, "ext": "h", "hexsha": "b2385e4125ecf05c4b1f6c17fa371b94f5a2c271", "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": "175ba4d6f0fbb27a51d67342892014fa4eee02aa", "max_forks_repo_licenses": [ "Apache-2.0", "BSD-2-Clause" ], "max_forks_repo_name": "prateekralhan/Self-Driving-Car-wih-survillence-support-system", "max_forks_repo_path": "NeuralNetwork.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "175ba4d6f0fbb27a51d67342892014fa4eee02aa", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0", "BSD-2-Clause" ], "max_issues_repo_name": "prateekralhan/Self-Driving-Car-wih-survillence-support-system", "max_issues_repo_path": "NeuralNetwork.h", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "175ba4d6f0fbb27a51d67342892014fa4eee02aa", "max_stars_repo_licenses": [ "Apache-2.0", "BSD-2-Clause" ], "max_stars_repo_name": "prateekralhan/Self-Driving-Car-wih-survillence-support-system", "max_stars_repo_path": "NeuralNetwork.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 130, "size": 557 }
/* rng/default.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_errno.h> /* The initial defaults are defined in the file mt.c, so we can get access to the static parts of the default generator. */ const gsl_rng_type * gsl_rng_env_setup (void) { unsigned long int seed = 0; const char *p = getenv ("GSL_RNG_TYPE"); if (p) { const gsl_rng_type **t, **t0 = gsl_rng_types_setup (); gsl_rng_default = 0; /* check GSL_RNG_TYPE against the names of all the generators */ for (t = t0; *t != 0; t++) { if (strcmp (p, (*t)->name) == 0) { gsl_rng_default = *t; break; } } if (gsl_rng_default == 0) { int i = 0; fprintf (stderr, "GSL_RNG_TYPE=%s not recognized\n", p); fprintf (stderr, "Valid generator types are:\n"); for (t = t0; *t != 0; t++) { fprintf (stderr, " %18s", (*t)->name); if ((++i) % 4 == 0) { fputc ('\n', stderr); } } fputc ('\n', stderr); GSL_ERROR_VAL ("unknown generator", GSL_EINVAL, 0); } fprintf (stderr, "GSL_RNG_TYPE=%s\n", gsl_rng_default->name); } else { gsl_rng_default = gsl_rng_mt19937; } p = getenv ("GSL_RNG_SEED"); if (p) { seed = strtoul (p, 0, 0); fprintf (stderr, "GSL_RNG_SEED=%lu\n", seed); }; gsl_rng_default_seed = seed; return gsl_rng_default; }
{ "alphanum_fraction": 0.5867598684, "avg_line_length": 25.8723404255, "ext": "c", "hexsha": "4b0f80d8749ce6724e34f3ad4a9b17f25fc2d6b4", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/default.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/rng/default.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/rng/default.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": 658, "size": 2432 }
/* randist/gsl-randist.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_test.h> void error (const char * s); int main (int argc, char *argv[]) { size_t i,j; size_t n = 0; double mu = 0, nu = 0, nu1 = 0, nu2 = 0, sigma = 0, a = 0, b = 0, c = 0; double zeta = 0, sigmax = 0, sigmay = 0, rho = 0; double p = 0; double x = 0, y =0, z=0 ; unsigned int N = 0, t = 0, n1 = 0, n2 = 0 ; unsigned long int seed = 0 ; const char * name ; gsl_rng * r ; if (argc < 4) { printf ( "Usage: gsl-randist seed n DIST param1 param2 ...\n" "Generates n samples from the distribution DIST with parameters param1,\n" "param2, etc. Valid distributions are,\n\n"); printf( " beta\n" " binomial\n" " bivariate-gaussian\n" " cauchy\n" " chisq\n" " dir-2d\n" " dir-3d\n" " dir-nd\n" " erlang\n" " exponential\n" " exppow\n" " fdist\n" " flat\n" " gamma\n" " gaussian-tail\n" " gaussian\n" " geometric\n" " gumbel1\n" " gumbel2\n" " hypergeometric\n" " laplace\n" " landau\n" " levy\n" " levy-skew\n" " logarithmic\n" " logistic\n" " lognormal\n" " negative-binomial\n" " pareto\n" " pascal\n" " poisson\n" " rayleigh-tail\n" " rayleigh\n" " tdist\n" " ugaussian-tail\n" " ugaussian\n" " weibull\n") ; exit (0); } argv++ ; seed = atol (argv[0]); argc-- ; argv++ ; n = atol (argv[0]); argc-- ; argv++ ; name = argv[0] ; argc-- ; argc-- ; gsl_rng_env_setup() ; if (gsl_rng_default_seed != 0) { fprintf(stderr, "overriding GSL_RNG_SEED with command line value, seed = %ld\n", seed) ; } gsl_rng_default_seed = seed ; r = gsl_rng_alloc(gsl_rng_default) ; #define NAME(x) !strcmp(name,(x)) #define OUTPUT(x) for (i = 0; i < n; i++) { printf("%g\n", (x)) ; } #define OUTPUT1(a,x) for(i = 0; i < n; i++) { a ; printf("%g\n", x) ; } #define OUTPUT2(a,x,y) for(i = 0; i < n; i++) { a ; printf("%g %g\n", x, y) ; } #define OUTPUT3(a,x,y,z) for(i = 0; i < n; i++) { a ; printf("%g %g %g\n", x, y, z) ; } #define INT_OUTPUT(x) for (i = 0; i < n; i++) { printf("%d\n", (x)) ; } #define ARGS(x,y) if (argc != x) error(y) ; #define DBL_ARG(x) if (argc) { x=atof((++argv)[0]);argc--;} else {error( #x);}; #define INT_ARG(x) if (argc) { x=atoi((++argv)[0]);argc--;} else {error( #x);}; if (NAME("bernoulli")) { ARGS(1, "p = probability of success"); DBL_ARG(p) INT_OUTPUT(gsl_ran_bernoulli (r, p)); } else if (NAME("beta")) { ARGS(2, "a,b = shape parameters"); DBL_ARG(a) DBL_ARG(b) OUTPUT(gsl_ran_beta (r, a, b)); } else if (NAME("binomial")) { ARGS(2, "p = probability, N = number of trials"); DBL_ARG(p) INT_ARG(N) INT_OUTPUT(gsl_ran_binomial (r, p, N)); } else if (NAME("cauchy")) { ARGS(1, "a = scale parameter"); DBL_ARG(a) OUTPUT(gsl_ran_cauchy (r, a)); } else if (NAME("chisq")) { ARGS(1, "nu = degrees of freedom"); DBL_ARG(nu) OUTPUT(gsl_ran_chisq (r, nu)); } else if (NAME("erlang")) { ARGS(2, "a = scale parameter, b = order"); DBL_ARG(a) DBL_ARG(b) OUTPUT(gsl_ran_erlang (r, a, b)); } else if (NAME("exponential")) { ARGS(1, "mu = mean value"); DBL_ARG(mu) ; OUTPUT(gsl_ran_exponential (r, mu)); } else if (NAME("exppow")) { ARGS(2, "a = scale parameter, b = power (1=exponential, 2=gaussian)"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_exppow (r, a, b)); } else if (NAME("fdist")) { ARGS(2, "nu1, nu2 = degrees of freedom parameters"); DBL_ARG(nu1) ; DBL_ARG(nu2) ; OUTPUT(gsl_ran_fdist (r, nu1, nu2)); } else if (NAME("flat")) { ARGS(2, "a = lower limit, b = upper limit"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_flat (r, a, b)); } else if (NAME("gamma")) { ARGS(2, "a = order, b = scale"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_gamma (r, a, b)); } else if (NAME("gaussian")) { ARGS(1, "sigma = standard deviation"); DBL_ARG(sigma) ; OUTPUT(gsl_ran_gaussian (r, sigma)); } else if (NAME("gaussian-tail")) { ARGS(2, "a = lower limit, sigma = standard deviation"); DBL_ARG(a) ; DBL_ARG(sigma) ; OUTPUT(gsl_ran_gaussian_tail (r, a, sigma)); } else if (NAME("ugaussian")) { ARGS(0, "unit gaussian, no parameters required"); OUTPUT(gsl_ran_ugaussian (r)); } else if (NAME("ugaussian-tail")) { ARGS(1, "a = lower limit"); DBL_ARG(a) ; OUTPUT(gsl_ran_ugaussian_tail (r, a)); } else if (NAME("bivariate-gaussian")) { ARGS(3, "sigmax = x std.dev., sigmay = y std.dev., rho = correlation"); DBL_ARG(sigmax) ; DBL_ARG(sigmay) ; DBL_ARG(rho) ; OUTPUT2(gsl_ran_bivariate_gaussian (r, sigmax, sigmay, rho, &x, &y), x, y); } else if (NAME("dir-2d")) { OUTPUT2(gsl_ran_dir_2d (r, &x, &y), x, y); } else if (NAME("dir-3d")) { OUTPUT3(gsl_ran_dir_3d (r, &x, &y, &z), x, y, z); } else if (NAME("dir-nd")) { double *xarr; ARGS(1, "n1 = number of dimensions of hypersphere"); INT_ARG(n1) ; xarr = (double *)malloc(n1*sizeof(double)); for(i = 0; i < n; i++) { gsl_ran_dir_nd (r, n1, xarr) ; for (j = 0; j < n1; j++) { if (j) putchar(' '); printf("%g", xarr[j]) ; } putchar('\n'); } ; free(xarr); } else if (NAME("geometric")) { ARGS(1, "p = bernoulli trial probability of success"); DBL_ARG(p) ; INT_OUTPUT(gsl_ran_geometric (r, p)); } else if (NAME("gumbel1")) { ARGS(2, "a = order, b = scale parameter"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_gumbel1 (r, a, b)); } else if (NAME("gumbel2")) { ARGS(2, "a = order, b = scale parameter"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_gumbel2 (r, a, b)); } else if (NAME("hypergeometric")) { ARGS(3, "n1 = tagged population, n2 = untagged population, t = number of trials"); INT_ARG(n1) ; INT_ARG(n2) ; INT_ARG(t) ; INT_OUTPUT(gsl_ran_hypergeometric (r, n1, n2, t)); } else if (NAME("laplace")) { ARGS(1, "a = scale parameter"); DBL_ARG(a) ; OUTPUT(gsl_ran_laplace (r, a)); } else if (NAME("landau")) { ARGS(0, "no arguments required"); OUTPUT(gsl_ran_landau (r)); } else if (NAME("levy")) { ARGS(2, "c = scale, a = power (1=cauchy, 2=gaussian)"); DBL_ARG(c) ; DBL_ARG(a) ; OUTPUT(gsl_ran_levy (r, c, a)); } else if (NAME("levy-skew")) { ARGS(3, "c = scale, a = power (1=cauchy, 2=gaussian), b = skew"); DBL_ARG(c) ; DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_levy_skew (r, c, a, b)); } else if (NAME("logarithmic")) { ARGS(1, "p = probability"); DBL_ARG(p) ; INT_OUTPUT(gsl_ran_logarithmic (r, p)); } else if (NAME("logistic")) { ARGS(1, "a = scale parameter"); DBL_ARG(a) ; OUTPUT(gsl_ran_logistic (r, a)); } else if (NAME("lognormal")) { ARGS(2, "zeta = location parameter, sigma = scale parameter"); DBL_ARG(zeta) ; DBL_ARG(sigma) ; OUTPUT(gsl_ran_lognormal (r, zeta, sigma)); } else if (NAME("negative-binomial")) { ARGS(2, "p = probability, a = order"); DBL_ARG(p) ; DBL_ARG(a) ; INT_OUTPUT(gsl_ran_negative_binomial (r, p, a)); } else if (NAME("pareto")) { ARGS(2, "a = power, b = scale parameter"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_pareto (r, a, b)); } else if (NAME("pascal")) { ARGS(2, "p = probability, n = order (integer)"); DBL_ARG(p) ; INT_ARG(N) ; INT_OUTPUT(gsl_ran_pascal (r, p, N)); } else if (NAME("poisson")) { ARGS(1, "mu = scale parameter"); DBL_ARG(mu) ; INT_OUTPUT(gsl_ran_poisson (r, mu)); } else if (NAME("rayleigh")) { ARGS(1, "sigma = scale parameter"); DBL_ARG(sigma) ; OUTPUT(gsl_ran_rayleigh (r, sigma)); } else if (NAME("rayleigh-tail")) { ARGS(2, "a = lower limit, sigma = scale parameter"); DBL_ARG(a) ; DBL_ARG(sigma) ; OUTPUT(gsl_ran_rayleigh_tail (r, a, sigma)); } else if (NAME("tdist")) { ARGS(1, "nu = degrees of freedom"); DBL_ARG(nu) ; OUTPUT(gsl_ran_tdist (r, nu)); } else if (NAME("weibull")) { ARGS(2, "a = scale parameter, b = exponent"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_weibull (r, a, b)); } else { fprintf(stderr,"Error: unrecognized distribution: %s\n", name) ; } return 0 ; } void error (const char * s) { fprintf(stderr, "Error: arguments should be %s\n",s) ; exit (EXIT_FAILURE) ; }
{ "alphanum_fraction": 0.5476981968, "avg_line_length": 25.1316455696, "ext": "c", "hexsha": "aec5e7d0a18746d6a2a1236b7146e4bea48f57aa", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/gsl-randist.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/gsl-randist.c", "max_line_length": 88, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/gsl-randist.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": 3357, "size": 9927 }
#include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_poly.h> /* Find a minimum in x=[0,1] of the interpolating quadratic through * (0,f0) (1,f1) with derivative fp0 at x=0. The interpolating * polynomial is q(x) = f0 + fp0 * z + (f1-f0-fp0) * z^2 */ static double interp_quad (double f0, double fp0, double f1, double zl, double zh) { double fl = f0 + zl*(fp0 + zl*(f1 - f0 -fp0)); double fh = f0 + zh*(fp0 + zh*(f1 - f0 -fp0)); double c = 2 * (f1 - f0 - fp0); /* curvature */ double zmin = zl, fmin = fl; if (fh < fmin) { zmin = zh; fmin = fh; } if (c > 0) /* positive curvature required for a minimum */ { double z = -fp0 / c; /* location of minimum */ if (z > zl && z < zh) { double f = f0 + z*(fp0 + z*(f1 - f0 -fp0)); if (f < fmin) { zmin = z; fmin = f; }; } } return zmin; } /* Find a minimum in x=[0,1] of the interpolating cubic through * (0,f0) (1,f1) with derivatives fp0 at x=0 and fp1 at x=1. * * The interpolating polynomial is: * * c(x) = f0 + fp0 * z + eta * z^2 + xi * z^3 * * where eta=3*(f1-f0)-2*fp0-fp1, xi=fp0+fp1-2*(f1-f0). */ static double cubic (double c0, double c1, double c2, double c3, double z) { return c0 + z * (c1 + z * (c2 + z * c3)); } static void check_extremum (double c0, double c1, double c2, double c3, double z, double *zmin, double *fmin) { /* could make an early return by testing curvature >0 for minimum */ double y = cubic (c0, c1, c2, c3, z); if (y < *fmin) { *zmin = z; /* accepted new point*/ *fmin = y; } } static double interp_cubic (double f0, double fp0, double f1, double fp1, double zl, double zh) { double eta = 3 * (f1 - f0) - 2 * fp0 - fp1; double xi = fp0 + fp1 - 2 * (f1 - f0); double c0 = f0, c1 = fp0, c2 = eta, c3 = xi; double zmin, fmin; double z0, z1; zmin = zl; fmin = cubic(c0, c1, c2, c3, zl); check_extremum (c0, c1, c2, c3, zh, &zmin, &fmin); { int n = gsl_poly_solve_quadratic (3 * c3, 2 * c2, c1, &z0, &z1); if (n == 2) /* found 2 roots */ { if (z0 > zl && z0 < zh) check_extremum (c0, c1, c2, c3, z0, &zmin, &fmin); if (z1 > zl && z1 < zh) check_extremum (c0, c1, c2, c3, z1, &zmin, &fmin); } else if (n == 1) /* found 1 root */ { if (z0 > zl && z0 < zh) check_extremum (c0, c1, c2, c3, z0, &zmin, &fmin); } } return zmin; } static double interpolate (double a, double fa, double fpa, double b, double fb, double fpb, double xmin, double xmax, int order) { /* Map [a,b] to [0,1] */ double z, alpha, zmin, zmax; zmin = (xmin - a) / (b - a); zmax = (xmax - a) / (b - a); if (zmin > zmax) { double tmp = zmin; zmin = zmax; zmax = tmp; }; if (order > 2 && GSL_IS_REAL(fpb)) { z = interp_cubic (fa, fpa * (b - a), fb, fpb * (b - a), zmin, zmax); } else { z = interp_quad (fa, fpa * (b - a), fb, zmin, zmax); } alpha = a + z * (b - a); return alpha; } /* recommended values from Fletcher are rho = 0.01, sigma = 0.1, tau1 = 9, tau2 = 0.05, tau3 = 0.5 */ static int minimize (gsl_function_fdf * fn, double rho, double sigma, double tau1, double tau2, double tau3, int order, double alpha1, double *alpha_new) { double f0, fp0, falpha, falpha_prev, fpalpha, fpalpha_prev, delta, alpha_next; double alpha = alpha1, alpha_prev = 0.0; double a, b, fa, fb, fpa, fpb; const size_t bracket_iters = 100, section_iters = 100; size_t i = 0; GSL_FN_FDF_EVAL_F_DF (fn, 0.0, &f0, &fp0); falpha_prev = f0; fpalpha_prev = fp0; /* Avoid uninitialized variables morning */ a = 0.0; b = alpha; fa = f0; fb = 0.0; fpa = fp0; fpb = 0.0; /* Begin bracketing */ while (i++ < bracket_iters) { falpha = GSL_FN_FDF_EVAL_F (fn, alpha); /* Fletcher's rho test */ if (falpha > f0 + alpha * rho * fp0 || falpha >= falpha_prev) { a = alpha_prev; fa = falpha_prev; fpa = fpalpha_prev; b = alpha; fb = falpha; fpb = GSL_NAN; break; /* goto sectioning */ } fpalpha = GSL_FN_FDF_EVAL_DF (fn, alpha); /* Fletcher's sigma test */ if (fabs (fpalpha) <= -sigma * fp0) { *alpha_new = alpha; return GSL_SUCCESS; } if (fpalpha >= 0) { a = alpha; fa = falpha; fpa = fpalpha; b = alpha_prev; fb = falpha_prev; fpb = fpalpha_prev; break; /* goto sectioning */ } delta = alpha - alpha_prev; { double lower = alpha + delta; double upper = alpha + tau1 * delta; alpha_next = interpolate (alpha_prev, falpha_prev, fpalpha_prev, alpha, falpha, fpalpha, lower, upper, order); } alpha_prev = alpha; falpha_prev = falpha; fpalpha_prev = fpalpha; alpha = alpha_next; } /* Sectioning of bracket [a,b] */ while (i++ < section_iters) { delta = b - a; { double lower = a + tau2 * delta; double upper = b - tau3 * delta; alpha = interpolate (a, fa, fpa, b, fb, fpb, lower, upper, order); } falpha = GSL_FN_FDF_EVAL_F (fn, alpha); if ((a-alpha)*fpa <= GSL_DBL_EPSILON) { /* roundoff prevents progress */ return GSL_ENOPROG; }; if (falpha > f0 + rho * alpha * fp0 || falpha >= fa) { /* a_next = a; */ b = alpha; fb = falpha; fpb = GSL_NAN; } else { fpalpha = GSL_FN_FDF_EVAL_DF (fn, alpha); if (fabs(fpalpha) <= -sigma * fp0) { *alpha_new = alpha; return GSL_SUCCESS; /* terminate */ } if ( ((b-a) >= 0 && fpalpha >= 0) || ((b-a) <=0 && fpalpha <= 0)) { b = a; fb = fa; fpb = fpa; a = alpha; fa = falpha; fpa = fpalpha; } else { a = alpha; fa = falpha; fpa = fpalpha; } } } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5113636364, "avg_line_length": 25.1935483871, "ext": "c", "hexsha": "60677d63b358b9fc81e00eccc79eb6931dbfd3a5", "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/multimin/linear_minimize.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/multimin/linear_minimize.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/multimin/linear_minimize.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": 2127, "size": 6248 }
#pragma once #include <gsl/gsl> #include <halley/text/halleystring.h> #include "lua_reference.h" #include "halley/data_structures/hash_map.h" struct lua_State; namespace Halley { class Resources; class LuaState; class LuaState { public: LuaState(Resources& resources); ~LuaState(); const LuaReference* tryGetModule(const String& moduleName) const; const LuaReference& getModule(const String& moduleName) const; const LuaReference& getOrLoadModule(const String& moduleName); const LuaReference& loadModule(const String& moduleName, gsl::span<const gsl::byte> data); void unloadModule(const String& moduleName); void call(int nArgs, int nRets); lua_State* getRawState(); void pushCallback(LuaCallback&& callback); void pushErrorHandler(); void popErrorHandler(); void pushLuaState(lua_State* lua); void popLuaState(); String errorHandler(String message); private: lua_State* lua; Vector<lua_State*> pushedStates; Resources* resources; HashMap<String, LuaReference> modules; Vector<std::unique_ptr<LuaCallback>> closures; std::unique_ptr<LuaReference> errorHandlerRef; Vector<int> errorHandlerStackPos; LuaReference loadScript(const String& chunkName, gsl::span<const gsl::byte> data); void print(String string); const LuaReference& packageLoader(String moduleName); String printVariableAtTop(int maxDepth = 2, bool quote = true); }; class LuaStateOverrider { public: LuaStateOverrider(LuaState& state, lua_State* rawState); ~LuaStateOverrider(); private: LuaState& state; }; }
{ "alphanum_fraction": 0.7540038437, "avg_line_length": 24.390625, "ext": "h", "hexsha": "675369eb2e74dfda8394864220f615a61a258254", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/engine/lua/include/halley/lua/lua_state.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_path": "src/engine/lua/include/halley/lua/lua_state.h", "max_line_length": 92, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_path": "src/engine/lua/include/halley/lua/lua_state.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 380, "size": 1561 }
#ifndef _SPATIAL_CONVOLUTION_ #define _SPATIAL_CONVOLUTION_ #include "Mem_Alloc.h" #include "Time.h" #include "Global_Setting.h" //#include <cblas.h> extern int spatial_convolution_float32(float* input_ptr, float* kernel_ptr, float* output_ptr); extern int spatial_convolution_float32_mm(float* input_ptr, float* kernel_ptr, float* output_ptr); extern int spatial_convolution_float32_mm_blas(float* input_ptr, float* kernel_ptr, float* output_ptr); #endif // _SPATIAL_CONVOLUTION_
{ "alphanum_fraction": 0.8161157025, "avg_line_length": 34.5714285714, "ext": "h", "hexsha": "fab73e7e500a1b1420584c3649c2e29f106fffee", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-06-27T11:00:18.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-27T11:00:18.000Z", "max_forks_repo_head_hexsha": "d84bb3a285be184978a8a4185843ce860daa1866", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yeephycho/Fast_Spatial_Convolution", "max_forks_repo_path": "src/Spatial_Convolution.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d84bb3a285be184978a8a4185843ce860daa1866", "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": "yeephycho/Fast_Spatial_Convolution", "max_issues_repo_path": "src/Spatial_Convolution.h", "max_line_length": 103, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d84bb3a285be184978a8a4185843ce860daa1866", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yeephycho/Fast_Spatial_Convolution", "max_stars_repo_path": "src/Spatial_Convolution.h", "max_stars_repo_stars_event_max_datetime": "2018-06-27T11:00:18.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-27T11:00:18.000Z", "num_tokens": 122, "size": 484 }
/* Function in common for mlfit1, mlfitN, etc ... */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <stdint.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> #include "mlfit.h" #include "blit3.h" #ifndef verbose #define verbose 0 #endif double estimateNphot(double *V, size_t Vm) // V is a Vm x Vm matrix // The number of photons locally as sum(V-min(V)) { double s = 0; double minV = INFINITY; for(size_t kk=0; kk<Vm*Vm; kk++) s+=V[kk]; for(size_t kk=0; kk<Vm*Vm; kk++) minV = GSL_MIN(V[kk], minV); s = s-minV*Vm*Vm; //printf("estimateNphot: %f\n", s); return s; } int double_cmp(const void * a, const void * b) { if (*(const double*)a > *(const double*)b) { return 1; } else { if (*(const double*)a < *(const double*)b) { return -1; } else { return 0; } } } double estimateBGV(double *V, size_t Vm, size_t Vn, size_t Vp, double * D) // estimate the background level in V [VmxVnxVp] around the point D // (x,y,z) { int32_t radius = 7; double * ePixels = malloc(sizeof(double)*6*(2*radius+1)*(2*radius+1)); // a few more than we need int32_t x = nearbyint(D[0]); int32_t y = nearbyint(D[1]); int32_t z = nearbyint(D[2]); // Loop over the box, and copy the edge pixels to ePixels size_t nPixels = 0; for(int32_t zz = z-radius; zz<=z+radius; zz++) for(int32_t yy = y-radius; yy<=y+radius; yy++) for(int32_t xx = x-radius; xx<=x+radius; xx++) if((abs(zz-z)+abs(yy-y)+abs(xx-x)) == radius) if(xx>=0 && yy>=0 && zz>=0 && xx< (int32_t) Vm && yy<(int32_t) Vn && zz<(int32_t) Vp) ePixels[nPixels++] = V[xx + yy*Vm + zz*Vm*Vn]; #if verbose > 0 printf("%lu ePixels\n", nPixels); #endif double median = 0; if(nPixels>0) { qsort(ePixels, nPixels, sizeof(double), double_cmp); gsl_sort(ePixels, 1, nPixels); median = gsl_stats_median_from_sorted_data(ePixels, 1, nPixels); //median = (double) nPixels; #if verbose > 0 printf("Median: %f\n", median); #endif } else { median = 0;} free(ePixels); return(median); //return((double) q); } double estimateBG(double *V, size_t Vm) // Estimate the background level as the median of the edge pixels { size_t nEdge = 4*Vm-4; double * ePixels = malloc(nEdge*sizeof(double)); size_t pos = 0; for(uint32_t kk = 0; kk<Vm; kk++, pos++) // Left ePixels[pos] = V[kk]; for(uint32_t kk = 0; kk<Vm; kk++, pos++) // Right ePixels[pos] = V[kk+(Vm-1)*Vm]; for(uint32_t kk = 1; kk<Vm-1; kk++, pos++) // Top ePixels[pos] = V[Vm*kk]; for(uint32_t kk = 1; kk<Vm-1; kk++, pos++) // Bottom ePixels[pos] = (double) V[Vm-1+Vm*kk]; assert(pos == 4*Vm-4); if(0) { for(uint32_t kk = 0; kk<nEdge; kk++) printf("%2d :%f\n", kk, ePixels[kk]); printf("\n"); } // qsort(ePixels, nEdge, sizeof(double), double_cmp); if(0) { for(uint32_t kk = 0; kk<nEdge; kk++) printf("%2d %f\n", kk, ePixels[kk]); printf("\n"); } gsl_sort(ePixels, 1, nEdge); double median = gsl_stats_median_from_sorted_data(ePixels, 1, nEdge); // double mean = gsl_stats_mean(ePixels, 1, nEdge); #if verbose > 0 printf("Median: %f\n", median); #endif free(ePixels); return(median); } int getZLine(double *W, size_t Ws, double * V, size_t Vm, size_t Vn, size_t Vp, double *D) /* Copy a line from V into W. * The line will be D[x, y, z-hWs:z+hWs] * where hWs = (Ws-1)/2 and D = [x,y,z] * * returns 1 on failure (i.e. line is out of bounds) * returns 0 if ok. * * See also: getRegion */ { int64_t x = nearbyint(D[0]); int64_t y = nearbyint(D[1]); int64_t z = nearbyint(D[2]); size_t Ws2 = (Ws-1)/2; if(z+Ws2 >= Vp) return 1; if(z<(int64_t) Ws2) return 1; size_t pos = 0; for(size_t zz = z-Ws2; zz<=z+Ws2; zz++) { W[pos++] = V[x + y*Vm + zz*Vm*Vn]; } return 0; } int getRegion(double * W, size_t Ws, double * V, size_t Vm, size_t Vn, size_t Vp, double * D) // Get a 2D region for constant z or returns 0 if out of bounds // Vm, Vn, Vp is the centre of the region. { size_t Ws2 = (Ws-1)/2; size_t pos = 0; int64_t x = nearbyint(D[0]); int64_t y = nearbyint(D[1]); int64_t z = nearbyint(D[2]); #if verbose > 0 printf("getRegion round(D): (%lu %lu %lu)\n", x, y, z); printf("getRegion size(V) (%lu %lu %lu)\n", Vm, Vn, Vp); #endif if(x-(int64_t) Ws2 < 0) return 1; if(y-(int64_t) Ws2 < 0) return 1; if(x+(uint64_t) Ws2 >= Vm) return 1; if(y+(uint64_t) Ws2 >= Vn) return 1; if(z<0) return 1; if((size_t) z>=Vp) return 1; #if verbose > 1 printf("Region valid\n"); printf("%lu %lu %lu\n", Vm, Vn, Vp); #endif uint32_t zz = z; for(uint32_t yy = y-Ws2; yy<=y+Ws2; yy++) { for(uint32_t xx = x-Ws2; xx<=x+Ws2; xx++) { assert(xx<Vm); assert(yy<Vn); assert(zz<Vp); // printf("x %lu y %lu z %lu\n", x, y, z); W[pos++] = V[xx + yy*Vm + zz*Vm*Vn]; } } // showRegion(W, Ws); return 0; } void showRegion(double * W, size_t Ws) // Dump some quadratic region to the terminal { printf("Show region ...\n"); for(size_t xx = 0 ; xx<Ws; xx++) { for(size_t yy = 0; yy<Ws; yy++) { printf("%f ", W[yy*Ws+xx]); } printf("\n"); } }
{ "alphanum_fraction": 0.5801209373, "avg_line_length": 22.8103448276, "ext": "c", "hexsha": "68a323a1257bc8ab3dd17fd52ea28697203355d0", "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": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elgw/dotter", "max_forks_repo_path": "common/mex/mlfit.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "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": "elgw/dotter", "max_issues_repo_path": "common/mex/mlfit.c", "max_line_length": 99, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elgw/dotter", "max_stars_repo_path": "common/mex/mlfit.c", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "num_tokens": 1949, "size": 5292 }
#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_axpy (void) { const double flteps = 1e-4, dbleps = 1e-6; { int N = 1; float alpha = 0.0f; float X[] = { 0.018f }; int incX = 1; float Y[] = { -0.417f }; int incY = -1; float expected[] = { -0.417f }; cblas_saxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected[i], flteps, "saxpy(case 64)"); } }; }; { int N = 1; double alpha = 0; double X[] = { 0.071 }; int incX = 1; double Y[] = { -0.888 }; int incY = -1; double expected[] = { -0.888 }; cblas_daxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected[i], dbleps, "daxpy(case 65)"); } }; }; { int N = 1; float alpha[2] = {1.0f, 0.0f}; float X[] = { -0.542f, -0.362f }; int incX = 1; float Y[] = { -0.459f, -0.433f }; int incY = -1; float expected[] = { -1.001f, -0.795f }; cblas_caxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected[2*i], flteps, "caxpy(case 66) real"); gsl_test_rel(Y[2*i+1], expected[2*i+1], flteps, "caxpy(case 66) imag"); }; }; }; { int N = 1; double alpha[2] = {-1, 0}; double X[] = { 0.003, -0.514 }; int incX = 1; double Y[] = { -0.529, 0.743 }; int incY = -1; double expected[] = { -0.532, 1.257 }; cblas_zaxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected[2*i], dbleps, "zaxpy(case 67) real"); gsl_test_rel(Y[2*i+1], expected[2*i+1], dbleps, "zaxpy(case 67) imag"); }; }; }; { int N = 1; float alpha = 0.1f; float X[] = { 0.771f }; int incX = -1; float Y[] = { 0.507f }; int incY = 1; float expected[] = { 0.5841f }; cblas_saxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected[i], flteps, "saxpy(case 68)"); } }; }; { int N = 1; double alpha = -0.3; double X[] = { 0.029 }; int incX = -1; double Y[] = { -0.992 }; int incY = 1; double expected[] = { -1.0007 }; cblas_daxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected[i], dbleps, "daxpy(case 69)"); } }; }; { int N = 1; float alpha[2] = {-0.3f, 0.1f}; float X[] = { 0.194f, -0.959f }; int incX = -1; float Y[] = { 0.096f, 0.032f }; int incY = 1; float expected[] = { 0.1337f, 0.3391f }; cblas_caxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected[2*i], flteps, "caxpy(case 70) real"); gsl_test_rel(Y[2*i+1], expected[2*i+1], flteps, "caxpy(case 70) imag"); }; }; }; { int N = 1; double alpha[2] = {0, 1}; double X[] = { 0.776, -0.671 }; int incX = -1; double Y[] = { 0.39, 0.404 }; int incY = 1; double expected[] = { 1.061, 1.18 }; cblas_zaxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected[2*i], dbleps, "zaxpy(case 71) real"); gsl_test_rel(Y[2*i+1], expected[2*i+1], dbleps, "zaxpy(case 71) imag"); }; }; }; { int N = 1; float alpha = 1.0f; float X[] = { 0.647f }; int incX = -1; float Y[] = { 0.016f }; int incY = -1; float expected[] = { 0.663f }; cblas_saxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected[i], flteps, "saxpy(case 72)"); } }; }; { int N = 1; double alpha = -1; double X[] = { -0.558 }; int incX = -1; double Y[] = { 0.308 }; int incY = -1; double expected[] = { 0.866 }; cblas_daxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected[i], dbleps, "daxpy(case 73)"); } }; }; { int N = 1; float alpha[2] = {-0.3f, 0.1f}; float X[] = { 0.899f, -0.624f }; int incX = -1; float Y[] = { 0.155f, -0.33f }; int incY = -1; float expected[] = { -0.0523f, -0.0529f }; cblas_caxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected[2*i], flteps, "caxpy(case 74) real"); gsl_test_rel(Y[2*i+1], expected[2*i+1], flteps, "caxpy(case 74) imag"); }; }; }; { int N = 1; double alpha[2] = {0, 1}; double X[] = { -0.451, 0.768 }; int incX = -1; double Y[] = { 0.007, 0.732 }; int incY = -1; double expected[] = { -0.761, 0.281 }; cblas_zaxpy(N, alpha, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected[2*i], dbleps, "zaxpy(case 75) real"); gsl_test_rel(Y[2*i+1], expected[2*i+1], dbleps, "zaxpy(case 75) imag"); }; }; }; }
{ "alphanum_fraction": 0.4741737582, "avg_line_length": 21.594017094, "ext": "c", "hexsha": "b15cde70d0735aec2673364fde55e88e49527203", "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_axpy.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_axpy.c", "max_line_length": 78, "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_axpy.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": 2110, "size": 5053 }
/** * @file batchg_zdotu.c * * Part of API test for Batched BLAS routines. * * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date * * @precisions normal z -> c d s * **/ #include <cblas.h> #include "bblas.h" #define COMPLEX void batchg_zdotu_sub( const int *n, BBLAS_Complex64_t const * const * x, const int *incx, BBLAS_Complex64_t const * const * y, const int *incy, BBLAS_Complex64_t *dotu, const int group_count, const int *group_size, int* info) { /* Local variables */ char func_name[15] = "batchg_zdotu"; int group_iter = 0; int offset = 0; // How many subproblems solved so far int end_of_group = 0; // End of the current group /* Check group_count */ if (group_count < 0) { xerbla_batch(func_name, BBLAS_ERR_GROUP_COUNT, -1); return; } /* Check group_size and call fixed batch computation */ for (group_iter = 0; group_iter < group_count; group_iter++) { if (group_size[group_iter] < 0) { end_of_group = end_of_group + group_size[group_iter]; xerbla_batch(func_name, BBLAS_ERR_GROUP_SIZE, group_iter); info[group_iter] = BBLAS_ERR_GROUP_SIZE; continue; } /* Call fixed batch computation on the group */ batchf_zdotu_sub( n[group_iter], x+offset, incx[group_iter], y+offset, incy[group_iter], dotu+offset, group_size[group_iter], info+group_iter); /* Update offset */ offset += group_size[group_iter]; } // End of group loop } #undef COMPLEX
{ "alphanum_fraction": 0.6610058785, "avg_line_length": 22.1884057971, "ext": "c", "hexsha": "64c8024438b5ae60769f889fe35b8f74bd229445", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_path": "src/batchg_zdotu.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_path": "src/batchg_zdotu.c", "max_line_length": 61, "max_stars_count": 3, "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_path": "src/batchg_zdotu.c", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "num_tokens": 457, "size": 1531 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <cblas.h> #include <time.h> #include <sys/time.h> // http://stackoverflow.com/questions/5167269 #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif // http://stackoverflow.com/questions/7034930 double drand() { return (rand()+1.0)/(RAND_MAX+1.0); } double random_normal() { return sqrt(-2*log(drand())) * cos(2*M_PI*drand()); } double* random_array(int size) { double *a = malloc(sizeof(double) * size); int i; for (i = 0 ; i < size; i++) { a[i] = random_normal(); } return a; } long currentTimeNanos() { struct timespec ts; #ifdef __MACH__ clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts.tv_sec = mts.tv_sec; ts.tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, &ts); #endif return (ts.tv_sec * 1000000000) + ts.tv_nsec; }
{ "alphanum_fraction": 0.6991869919, "avg_line_length": 17.8909090909, "ext": "c", "hexsha": "ed1fb713338adb91118fe5e165a3dae3064bce59", "lang": "C", "max_forks_count": 154, "max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z", "max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "debasish83/netlib-java", "max_forks_repo_path": "perf/src/main/c/common.c", "max_issues_count": 59, "max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "debasish83/netlib-java", "max_issues_repo_path": "perf/src/main/c/common.c", "max_line_length": 66, "max_stars_count": 624, "max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "debasish83/netlib-java", "max_stars_repo_path": "perf/src/main/c/common.c", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z", "num_tokens": 290, "size": 984 }
/* $Id$ */ /* * Copyright (c) 2015 Kristaps Dzonsons <kristaps@kcons.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <math.h> #include <stdint.h> #include <stdlib.h> #include <gtk/gtk.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_histogram.h> #include <kplot.h> #include "extern.h" struct simbuf * simbuf_alloc_warm(struct kdata *hot, size_t bufsz) { struct simbuf *buf; g_assert(NULL != hot); buf = g_malloc0(sizeof(struct simbuf)); buf->cold = kdata_buffer_alloc(bufsz); g_assert(NULL != buf->cold); return(buf); } struct simbuf * simbuf_alloc(struct kdata *hot, size_t bufsz) { struct simbuf *buf; g_assert(NULL != hot); buf = g_malloc0(sizeof(struct simbuf)); buf->hot = hot; buf->hotlsb = kdata_buffer_alloc(bufsz); g_assert(NULL != buf->hotlsb); buf->warm = kdata_buffer_alloc(bufsz); g_assert(NULL != buf->warm); buf->cold = kdata_buffer_alloc(bufsz); g_assert(NULL != buf->cold); return(buf); } void simbuf_free(struct simbuf *buf) { kdata_destroy(buf->hot); kdata_destroy(buf->hotlsb); kdata_destroy(buf->warm); kdata_destroy(buf->cold); free(buf); } void simbuf_copy_hotlsb(struct simbuf *buf) { int rc; rc = kdata_buffer_copy(buf->hotlsb, buf->hot); g_assert(0 != rc); } void simbuf_copy_warm(struct simbuf *buf) { int rc; rc = kdata_buffer_copy(buf->warm, buf->hotlsb); g_assert(0 != rc); } void simbuf_copy_cold(struct simbuf *buf) { int rc; rc = kdata_buffer_copy(buf->cold, buf->warm); g_assert(0 != rc); }
{ "alphanum_fraction": 0.7211191336, "avg_line_length": 23.0833333333, "ext": "c", "hexsha": "932818158c8ca7dd01bbcaafbc2c8707a884b0b1", "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": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_path": "buf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_path": "buf.c", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_path": "buf.c", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "num_tokens": 596, "size": 2216 }
#pragma once #include <type_traits> #include <cuda/runtime_api.hpp> #include <gsl-lite/gsl-lite.hpp> namespace thrustshift { namespace kernel { template <typename SrcT, typename MapT, typename DstT> __global__ void scatter(gsl_lite::span<const SrcT> src, gsl_lite::span<const MapT> map, gsl_lite::span<DstT> dst) { const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; if (gtid < src.size()) { dst[map[gtid]] = src[gtid]; } } } // namespace kernel namespace async { template <class SrcRange, class MapRange, class DstRange> void scatter(cuda::stream_t& stream, SrcRange&& src, MapRange&& map, DstRange&& dst) { gsl_Expects(src.size() == dst.size()); gsl_Expects(src.size() == map.size()); gsl_Expects(src.data() != dst.data()); if (src.empty()) { return; } using src_value_type = typename std::remove_reference<SrcRange>::type::value_type; using map_index_type = typename std::remove_reference<MapRange>::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::scatter<src_value_type, map_index_type, dst_value_type>; cuda::enqueue_launch(k, stream, c, src, map, dst); } } // namespace async } // namespace thrustshift
{ "alphanum_fraction": 0.673455979, "avg_line_length": 25.7966101695, "ext": "h", "hexsha": "fa6f283949096b338be8aef36ae96218a0210fb7", "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/scatter.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/scatter.h", "max_line_length": 74, "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/scatter.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": 381, "size": 1522 }
#pragma once #include "CesiumGltf/IExtensionJsonHandler.h" #include "CesiumGltf/Model.h" #include "CesiumGltf/ReaderLibrary.h" #include <functional> #include <gsl/span> #include <map> #include <memory> #include <optional> #include <string> #include <unordered_map> #include <vector> namespace CesiumGltf { struct ReaderContext; /** * @brief The result of reading a glTF model with * {@link GltfReader::readModel}. */ struct CESIUMGLTFREADER_API ModelReaderResult { /** * @brief The read model, or std::nullopt if the model could not be read. */ std::optional<Model> model; /** * @brief Errors, if any, that occurred during the load process. */ std::vector<std::string> errors; /** * @brief Warnings, if any, that occurred during the load process. */ std::vector<std::string> warnings; }; /** * @brief The result of reading an image with * {@link GltfReader::readImage}. */ struct CESIUMGLTFREADER_API ImageReaderResult { /** * @brief The {@link ImageCesium} that was read. * * This will be `std::nullopt` if the image could not be read. */ std::optional<ImageCesium> image; /** * @brief Error messages that occurred while trying to read the image. */ std::vector<std::string> errors; /** * @brief Warning messages that occurred while reading the image. */ std::vector<std::string> warnings; }; /** * @brief The state of a glTF extension. */ enum class ExtensionState { /** * @brief The extension is enabled. * * If a statically-typed class is available for the extension, it will be * used. Otherwise the extension will be represented as a * {@link CesiumUtility::JsonValue}. */ Enabled, /** * @brief The extension is enabled but will always be deserialized as a * {@link CesiumUtility::JsonValue}. * * Even if a statically-typed class is available for the extension, it will * not be used. */ JsonOnly, /** * @brief The extension is disabled. * * It will not be represented in the loaded model at all. */ Disabled }; /** * @brief Options for how to read a glTF. */ struct CESIUMGLTFREADER_API ReadModelOptions { /** * @brief Whether data URLs in buffers and images should be automatically * decoded as part of the load process. */ bool decodeDataUrls = true; /** * @brief Whether data URLs should be cleared after they are successfully * decoded. * * This reduces the memory usage of the model. */ bool clearDecodedDataUrls = true; /** * @brief Whether embedded images in {@link Model::buffers} should be * automatically decoded as part of the load process. * * The {@link ImageSpec::mimeType} property is ignored, and instead the * [stb_image](https://github.com/nothings/stb) library is used to decode * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format. */ bool decodeEmbeddedImages = true; /** * @brief Whether geometry compressed using the `KHR_draco_mesh_compression` * extension should be automatically decoded as part of the load process. */ bool decodeDraco = true; }; /** * @brief Reads glTF models and images. */ class CESIUMGLTFREADER_API GltfReader { public: /** * @brief Constructs a new instance. */ GltfReader(); /** * @brief Registers an extension for a glTF object. * * @tparam TExtended The glTF object to extend. * @tparam TExtensionHandler The extension's * {@link CesiumJsonReader::JsonHandler}. * @param extensionName The name of the extension. */ template <typename TExtended, typename TExtensionHandler> void registerExtension(const std::string& extensionName) { auto it = this->_extensions.emplace(extensionName, ObjectTypeToHandler()).first; it->second.insert_or_assign( TExtended::TypeName, ExtensionReaderFactory([](const ReaderContext& context) { return std::make_unique<TExtensionHandler>(context); })); } /** * @brief Registers an extension for a glTF object. * * The extension name is obtained from `TExtensionHandler::ExtensionName`. * * @tparam TExtended The glTF object to extend. * @tparam TExtensionHandler The extension's * {@link CesiumJsonReader::JsonHandler}. */ template <typename TExtended, typename TExtensionHandler> void registerExtension() { auto it = this->_extensions .emplace(TExtensionHandler::ExtensionName, ObjectTypeToHandler()) .first; it->second.insert_or_assign( TExtended::TypeName, ExtensionHandlerFactory([](const ReaderContext& context) { return std::make_unique<TExtensionHandler>(context); })); } /** * @brief Enables or disables a glTF extension. * * By default, all extensions are enabled. When an enabled extension is * encountered in the source glTF, it is read into a statically-typed * extension class, if one is registered, or into a * {@link CesiumUtility::JsonValue} if not. * * When a disabled extension is encountered in the source glTF, it is ignored * completely. * * An extension may also be set to `ExtensionState::JsonOnly`, in which case * it will be read into a {@link CesiumUtility::JsonValue} even if a * statically-typed extension class is registered. * * @param extensionName The name of the extension to be enabled or disabled. * @param newState The new state for the extension. */ void setExtensionState(const std::string& extensionName, ExtensionState newState); /** * @brief Reads a glTF or binary glTF (GLB) from a buffer. * * @param data The buffer from which to read the glTF. * @param options Options for how to read the glTF. * @return The result of reading the glTF. */ ModelReaderResult readModel( const gsl::span<const std::byte>& data, const ReadModelOptions& options = ReadModelOptions()) const; /** * @brief Reads an image from a buffer. * * The [stb_image](https://github.com/nothings/stb) library is used to decode * images in `JPG`, `PNG`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, or `PIC` format. * * @param data The buffer from which to read the image. * @return The result of reading the image. */ ImageReaderResult readImage(const gsl::span<const std::byte>& data) const; std::unique_ptr<IExtensionJsonHandler> createExtensionHandler( const ReaderContext& context, const std::string_view& extensionName, const std::string& extendedObjectType) const; private: using ExtensionHandlerFactory = std::function<std::unique_ptr<IExtensionJsonHandler>( const ReaderContext&)>; using ObjectTypeToHandler = std::map<std::string, ExtensionHandlerFactory>; using ExtensionNameMap = std::map<std::string, ObjectTypeToHandler>; ExtensionNameMap _extensions; std::unordered_map<std::string, ExtensionState> _extensionStates; }; } // namespace CesiumGltf
{ "alphanum_fraction": 0.6847170353, "avg_line_length": 29.0083333333, "ext": "h", "hexsha": "fa2a2bfd812ca0814069c97be685f8b6096d2582", "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": "CesiumGltfReader/include/CesiumGltf/GltfReader.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": "CesiumGltfReader/include/CesiumGltf/GltfReader.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": "CesiumGltfReader/include/CesiumGltf/GltfReader.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1733, "size": 6962 }
/* * * ML fitting of dots using a 2D Gaussian model provided by gaussianInt2. * I.e., only x and y are fitted. * * Compilation: * For debugging: * gcc 3.c -Wall -std=c99 -I/usr/local/include -L/usr/local/lib -lgsl -lgslcblas -lm -g -o 3 * valgrind ./3 * For speed: * gcc -Wall -std=c99 3.c -I/usr/local/include -L/usr/local/lib -lgsl -lgslcblas -lm -O3 -o 3 * ./3 * Memory accesses can also be checked with Valgrind or the gcc -fmudflap memory protection option. * * MATLAB interface in df_mlfit1.c * 2017.04.12. Valgrind ok. * * TODO: * - What are good step sizes? * - Set the initial positions with higher than integer precision if possible. * */ /* From the GSL documentation: If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector_get(v,i) by v->data[i*v->stride] and calls to gsl_vector_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off. */ #include <assert.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_statistics.h> #include "gaussianInt2.h" #include "mlfit.h" #include "blit3.h" #include "mlfit1.h" // use the compile flag -D verbose=0 etc // 0 = no information // 1 = per dot information // 2 = per iteration information #ifndef verbose #define verbose 1 #endif // Globals const size_t maxIterations = 10000; // for z-fitting const double convCriteria = 1e-7; // for z-fitting // Possibly, add the window size, denoted Ws in most places // Headers double lxy (const gsl_vector *, void *); double lz (const gsl_vector *, void *); int localizeDotXY(double *, size_t, double *, double *, double); // sigma int localizeDotZ(double *, size_t, double *, double *, double); // sigma int localize(double *, size_t, size_t, size_t, double *, size_t, double *, double, double); // sigma_xy, sigma_z -- size of dot int unit_tests(void); void lxy_df (const gsl_vector *v, void *params, gsl_vector * df); void lxy_fdf (const gsl_vector *v, void *params, double * f, gsl_vector *df); // Optimization constants typedef struct { double * R; // local region double * G; // A already allocated temporary space for the Gaussian kernel size_t Rw; // R and G has size Rw*Rw double sigma; // For constant sigma fitting double bg; } optParams; double lz (const gsl_vector *v, void *params) { double x; optParams *p = (optParams *) params; size_t Rw = p->Rw; double * R = p->R; double * GI = p->G; double sigma = p->sigma; double bg = p->bg; #if verbose > 2 printf("Rw: %lu\n", Rw); printf("Nphot: %lu\n", Nphot); printf("sigma: %f\n", sigma); printf("bg : %f\n", bg); #endif // Get the other parameters ... x = gsl_vector_get(v, 0); double Nphot = gsl_vector_get(v,1); // printf("bg: %f, Nphot: %f, sigma: %f z: %f\n", bg, Nphot, sigma, x); // Create Gaussian ... double mu[] = {x}; gaussianInt1(GI, mu, &sigma, Rw); for(size_t kk = 0; kk<Rw; kk++) GI[kk] = bg+Nphot*GI[kk]; #if verbose>2 printf("GI:\n"); showRegion(GI, Rw); #endif /* * from LL2PG.m * model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2); * mask = disk2d((size(patch,1)-1)/2); * %L = -sum(sum(-(patch-model).^2./model - .5*log(model))); * L = -sum(sum(mask.*(-(patch-model).^2./model - .5*log(model)))); */ double E = 0; for (size_t kk=0; kk<Rw; kk++) { E+= (GI[kk]-R[kk])*(GI[kk]-R[kk])/GI[kk] - .5*log(GI[kk]); } // E = -E; if(0){ printf("R=["); for (size_t kk=0; kk<Rw; kk++) { printf("%f ", R[kk]); } printf("]\n"); printf("G = ["); for (size_t kk=0; kk<Rw; kk++) { printf("%f ", GI[kk]); } printf("]\n"); printf("E: %f, mu: %f\n", E, mu[0]); } /* Quadratic * for (size_t kk=0; kk<Rw*Rw; kk++) * E+= (GI[kk]-R[kk])*(GI[kk]-R[kk]); */ if(!isfinite(E)) E = 10e99; return E; } double lxy (const gsl_vector *v, void *params) // likelihood in xy, function to optimize { double x, y; optParams *p = (optParams *) params; size_t Rw = p->Rw; double * R = p->R; double * GI = p->G; double sigma = p->sigma; double bg = p->bg; #if verbose > 2 printf("Rw: %lu\n", Rw); printf("Nphot: %lu\n", Nphot); printf("sigma: %f\n", sigma); printf("bg : %f\n", bg); #endif // Get the other parameters ... x = gsl_vector_get(v, 0); y = gsl_vector_get(v, 1); double Nphot = gsl_vector_get(v,2); // Create Gaussian ... double mu[] = {x,y}; gaussianInt2(GI, mu, &sigma, Rw); for(size_t kk = 0; kk<Rw*Rw; kk++) GI[kk] = bg+Nphot*GI[kk]; #if verbose>2 printf("GI:\n"); showRegion(GI, Rw); #endif /* * from LL2PG.m * model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2); * mask = disk2d((size(patch,1)-1)/2); * %L = -sum(sum(-(patch-model).^2./model - .5*log(model))); * L = -sum(sum(mask.*(-(patch-model).^2./model - .5*log(model)))); */ double E = 0; for (size_t kk=0; kk<Rw*Rw; kk++) E+= (GI[kk]-R[kk])*(GI[kk]-R[kk])/GI[kk] - .5*log(GI[kk]); // E = -E; /* Quadratic * for (size_t kk=0; kk<Rw*Rw; kk++) * E+= (GI[kk]-R[kk])*(GI[kk]-R[kk]); */ // printf("E = %f\n", E); return E; } void lxy_df (const gsl_vector *v, void *params, gsl_vector * df) { double h = 1.49e-8; // step size gsl_vector * dv = gsl_vector_alloc(3); gsl_vector_memcpy(dv, v); for(int kk = 0; kk<3; kk++) { gsl_vector_set(dv, kk, gsl_vector_get(v, kk) + h); // Set gsl_vector_set(df, kk, (lxy(dv, params)-lxy(v, params))/h); // printf("%f ", gsl_vector_get(df, kk)); gsl_vector_set(dv, kk, gsl_vector_get(v, kk)); // Reset } // printf("\n"); gsl_vector_free(dv); } void lxy_fdf (const gsl_vector *v, void *params, double * f, gsl_vector *df) { *f = lxy(v, params); lxy_df(v, params, df); } int localizeDotXY(double * V, size_t Vm, double * D, double * F, double sigma) // Localization for a dot roughly centered in V of size Vm x Vm // D[0], D[1], D[3] are the global coordinates of the dot // F are the fitted coordinates { /* Parameters that will not be optimized */ optParams par; par.R = V; par.Rw = Vm; par.sigma = sigma; par.bg = estimateBG(V, Vm); par.G = (double *) malloc(Vm*Vm*sizeof(double)); const gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_vector_bfgs; //const gsl_multimin_fminimizer_type *T = // gsl_multimin_fminimizer_nmsimplex2; gsl_multimin_fdfminimizer *s = NULL; gsl_vector *ss, *x; gsl_multimin_function_fdf minex_func; size_t iter = 0; int status; double size; /* Starting point for parameters to be optimized */ x = gsl_vector_alloc (3); gsl_vector_set(x, 0, 0); // x position gsl_vector_set(x, 1, 0); // y position gsl_vector_set(x, 2, estimateNphot(V, Vm)); // Nphot /* Grid search to find a reasonable starting point * for (x,y) to avoid local minima */ if(1) { double xmin = 0; double ymin = 0; double emin = 10e99; int ng = 5; // ng*ng grid points for(double dx = -.4; dx<.4; dx=dx+0.8/ng) for(double dy = -.4; dy<.4; dy=dy+0.8/ng) { gsl_vector_set(x, 0, dx); // x position gsl_vector_set(x, 1, dy); // y position double err = lxy(x, (void *) &par); // printf("%f %f : %f\n", dx, dy, err); if( err < emin) { emin = err; xmin = dx; ymin = dy; } } gsl_vector_set(x, 0, xmin); // x position gsl_vector_set(x, 1, ymin); // y position // printf("Initial position: %f %f\n", xmin, ymin); } /* Set initial step sizes */ ss = gsl_vector_alloc(3); gsl_vector_set_all(ss, 0.1); /* Initialize method and iterate */ minex_func.n = 3; minex_func.f = lxy; // Error minex_func.df = lxy_df; // Derivative minex_func.fdf = lxy_fdf; // Error and Derivative minex_func.params = &par; s = gsl_multimin_fdfminimizer_alloc (T, 3); gsl_multimin_fdfminimizer_set (s, // Optimizer &minex_func, // Function to optimize x, // Start point 0.1, // Default step size of the line search 0.1); // tol. 0 = exact line search 0.1 = recommended from GSL manual /* tol=0.1 was about twice as fast as tol=0 for this problem with no noticeable * regression in accuracy */ size_t maxIterationsQN = 500; // abort if more iterations do { iter++; status = gsl_multimin_fdfminimizer_iterate(s); if (status) break; size = 0; //gsl_multimin_fdfminimizer_size(s); status = gsl_multimin_test_gradient (s->gradient, 1e-4); if (status == GSL_SUCCESS) { #if verbose > 0 printf ("converged to minimum at\n"); printf ("%5lu x:%10.3e y:%10.3e NP:%6.1f f() = %7.3f size = %10.3e\n", iter, gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1), gsl_vector_get (s->x, 2), 0.0, size); #endif } } while (status == GSL_CONTINUE && iter < maxIterationsQN); // F is always written even if the convergence failed F[0] = gsl_vector_get (s->x, 0)+nearbyint(D[0]); F[1] = gsl_vector_get (s->x, 1)+nearbyint(D[1]); F[2] = D[2]; // Not optimized gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fdfminimizer_free (s); free(par.G); return status; } int localizeDotZ(double * V, size_t Vm, double * D, double * F, double sigma) // Localization for a dot roughly centered in V of size Vm x Vm // D[0], D[1], D[3] are the global coordinates of the dot // F are the fitted coordinates { // Non-optimized parameters optParams par; par.R = V; par.Rw = Vm; par.sigma = sigma; par.bg = estimateBG(V, Vm); par.G = (double *) malloc(Vm*sizeof(double)); const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2; gsl_multimin_fminimizer *s = NULL; gsl_vector *ss, *x; gsl_multimin_function minex_func; size_t iter = 0; int status; double size; /* Starting point */ x = gsl_vector_alloc (2); gsl_vector_set(x, 0, 0); // z position gsl_vector_set(x, 1, estimateNphot(V, Vm)); // Nphot /* Set initial step sizes */ ss = gsl_vector_alloc(2); gsl_vector_set_all(ss, 0.1); gsl_vector_set(ss, 1, 10); // Number of photons /* Initialize method and iterate */ minex_func.n = 2; minex_func.f = lz; minex_func.params = &par; //printf(".\n"); fflush(stdout); s = gsl_multimin_fminimizer_alloc (T, 2); // printf("..\n"); fflush(stdout); int error = gsl_multimin_fminimizer_set(s, &minex_func, x, // starting point ss); // Step sizes if(error>0) printf("error: %d\n", error); // printf("...\n"); fflush(stdout); do { iter++; status = gsl_multimin_fminimizer_iterate(s); // printf("....\n"); fflush(stdout); if (status) break; size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, convCriteria); // printf(".....\n"); fflush(stdout); if (status == GSL_SUCCESS) { #if verbose > 0 printf ("converged to minimum at\n"); printf ("%5lu z:%10.3e NP:%6.1f f() = %7.3f size = %10.3e\n", iter, gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1), s->fval, size); #endif } } while (status == GSL_CONTINUE && iter < maxIterations); // Always Update Z position -- even if convergence failed F[2] = gsl_vector_get (s->x, 0)+nearbyint(D[2]); gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free (s); free(par.G); return status; } int localize(double * V, size_t Vm, size_t Vn, size_t Vp, double * D, size_t Dm, double * F, double sigma_xy, double sigma_z) // run the localization routine for a list of dots { /* The window size is a very important parameter. Small windows can not capture the full signals and that results in * bad fittings. * Ws = 7 is good until sigma = 1.1 * Ws = 9 is good at least until sigma = 1.6 */ int Ws = 9; // Window size double * W = malloc(Ws*Ws*sizeof(double)); for(size_t kk =0; kk<Dm; kk++) { // Copy the neighbourhood around each D into W if(getRegion(W, Ws, V, Vm, Vn, Vp, D+kk*3) == 0) { #if verbose > 1 printf("W:\n"); showRegion(W, Ws); #endif // Local fitting in W #if verbose > 0 int status = localizeDotXY(W, Ws, D+kk*3, F+kk*3, sigma_xy); printf("Status: %d\n", status); #else localizeDotXY(W, Ws, D+kk*3, F+kk*3, sigma_xy); #endif if(getZLine(W,Ws, V, Vm, Vn, Vp, D+kk*3) == 0) { localizeDotZ(W, Ws, D+kk*3, F+kk*3, sigma_z); } } else { // TODO: add also Nphot and status to the output F[kk*3] = -1; F[kk*3+1] = -1; F[kk*3+2] = -1; } } free(W); return 0; } int unit_tests(){ double * V; // image int Vm = 1024; int Vn = 1024; int Vp = 60; double * D; // list of dots size_t Dm = 5; // number of dots double * F; // fitted dots printf("Image size: %dx%dx%d\n", Vm, Vn, Vp); printf("Localizing %lu dots\n", Dm); V = (double *) malloc(Vm*Vn*Vp*sizeof(double)); D = (double *) malloc(3*Dm*sizeof(double)); F = (double *) malloc(3*Dm*sizeof(double)); // Initialize the data for(int kk=0; kk<Vm*Vn*Vp; kk++) V[kk] = 1000+rand_range(0,0); for(uint32_t kk=0; kk<Dm; kk++) { size_t pos = kk*3; D[pos] = rand_range(6, Vm-7); D[pos+1] = rand_range(6, Vn-7); D[pos+2] = rand_range(6, Vp-7); if(D[pos] < 6) D[pos] = 6; if(D[pos+1] < 6) D[pos+1] = 6; if(D[pos+2] < 6) D[pos+2] = 6; #if verbose > 0 printf("D %03d %f %f %f\n", kk, D[pos], D[pos+1], D[pos+2]); #endif } for(uint32_t kk=0; kk<Dm; kk++) { size_t pos = D[kk*3] + D[kk*3+1]*Vm + D[kk*3+2]*Vm*Vn; V[pos] = V[pos]+5; } D[0] = 100; D[1] = 100; D[2] = 30; V[(int) D[0]+(int) D[1]*Vm+(int) D[2]*Vm*Vn] = 7; V[(int) D[0]+1+(int) D[1]*Vm+(int) D[2]*Vm*Vn] = 6; // Run the optimization localize(V, Vm, Vn, Vp, D, Dm, F, 1.1, 1.1); if(1) { for(double sigma = 0.1; sigma<2; sigma=sigma+0.1) localize(V, Vm, Vn, Vp, D, Dm, F, sigma, sigma); } // In next version, also supply clustering information #if verbose >0 for(size_t kk = 0; kk<Dm; kk++) { size_t pos = kk*3; printf("%6lu (%f, %f, %f) -> (%f, %f, %f)\n", kk, D[pos], D[pos+1], D[pos+2], F[pos], F[pos+1], F[pos+2]); } #endif free(F); free(D); free(V); return 0; } int main(int argc, char ** argv) // For testing, not used any more, see the MATLAB interface in // df_mlfit.c { printf("%s\n", argv[0]); if(argc == 1) return unit_tests(); return 0; }
{ "alphanum_fraction": 0.5938896671, "avg_line_length": 24.8606965174, "ext": "c", "hexsha": "cb1e2122204af8ffbb53f0c553db83d477cdb63f", "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": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elgw/dotter", "max_forks_repo_path": "common/mex/mlfit1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "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": "elgw/dotter", "max_issues_repo_path": "common/mex/mlfit1.c", "max_line_length": 119, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elgw/dotter", "max_stars_repo_path": "common/mex/mlfit1.c", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "num_tokens": 5141, "size": 14991 }
#pragma once #include <algorithm> #include <array> #include <cstdint> #include <initializer_list> #include <iterator> #include <sstream> #include <string> #include <absl/types/span.h> #include <gsl/gsl> #include "chainerx/axes.h" #include "chainerx/constant.h" #include "chainerx/dims.h" #include "chainerx/error.h" namespace chainerx { class Strides; class Shape : public Dims { using BaseVector = Dims; public: using const_iterator = BaseVector::const_iterator; using const_reverse_iterator = BaseVector::const_reverse_iterator; // TODO(niboshi): Declare other types required for this class to be a container. Shape() = default; ~Shape() = default; // by iterators template <typename InputIt> Shape(InputIt first, InputIt last) { if (std::distance(first, last) > kMaxNdim) { throw DimensionError{"too many dimensions: ", std::distance(first, last)}; } insert(begin(), first, last); } // by span explicit Shape(absl::Span<const int64_t> dims) : Shape{dims.begin(), dims.end()} {} // by initializer list Shape(std::initializer_list<int64_t> dims) : Shape{dims.begin(), dims.end()} {} // copy Shape(const Shape&) = default; Shape& operator=(const Shape&) = default; // move Shape(Shape&&) = default; Shape& operator=(Shape&&) = default; int64_t GetTotalSize() const; std::string ToString() const; int8_t ndim() const noexcept { return gsl::narrow_cast<int8_t>(size()); } const int64_t& operator[](int8_t index) const { if (!(0 <= index && static_cast<size_t>(index) < size())) { throw IndexError{"Shape index ", index, " out of bounds for shape with ", size(), " size."}; } return this->Dims::operator[](index); } int64_t& operator[](int8_t index) { if (!(0 <= index && static_cast<size_t>(index) < size())) { throw IndexError{"Shape index ", index, " out of bounds for shape with ", size(), " size."}; } return this->Dims::operator[](index); } // span absl::Span<const int64_t> span() const { return {*this}; } }; namespace internal { bool IsContiguous(const Shape& shape, const Strides& strides, int64_t item_size); // Returns true if a reduction can take place under the given conditions, only considering the number of dimensions. // Otherwise, returns false. // // TODO(hvy): Check the dimension lengths too and reconsider the interface. E.g. return void and assert inside the function if only used for // assertions. bool IsValidReductionShape(const Shape& in_shape, const Axes& axes, const Shape& out_shape, bool allow_keepdims); int64_t CountItemsAlongAxes(const Shape& shape, const Axes& axes); Shape BroadcastShapes(const Shape& shape0, const Shape& shape1); // Returns a shape where axes are reduced. Shape ReduceShape(const Shape& shape, const Axes& axes, bool keepdims); // Returns a shape with additional axes, with length 1. Shape ExpandShape(const Shape& shape, const Axes& axes); Shape TransposeShape(const Shape& shape, const Axes& axes); } // namespace internal std::ostream& operator<<(std::ostream& os, const Shape& shape); void CheckEqual(const Shape& lhs, const Shape& rhs); } // namespace chainerx
{ "alphanum_fraction": 0.6739859713, "avg_line_length": 29.2767857143, "ext": "h", "hexsha": "683b25cf52af9a9bd8d100ebed6d34357a5390ac", "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": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zaltoprofen/chainer", "max_forks_repo_path": "chainerx_cc/chainerx/shape.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "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": "zaltoprofen/chainer", "max_issues_repo_path": "chainerx_cc/chainerx/shape.h", "max_line_length": 140, "max_stars_count": 2, "max_stars_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zaltoprofen/chainer", "max_stars_repo_path": "chainerx_cc/chainerx/shape.h", "max_stars_repo_stars_event_max_datetime": "2020-08-27T18:04:20.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-12T21:48:04.000Z", "num_tokens": 793, "size": 3279 }
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2013. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Steffen Sass, Holger Plattfaut, Bastian Blank $ // -------------------------------------------------------------------------- #ifndef OPENMS_FILTERING_DATAREDUCTION_SILACFILTER_H #define OPENMS_FILTERING_DATAREDUCTION_SILACFILTER_H #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h> #include <OpenMS/FILTERING/DATAREDUCTION/SILACPattern.h> #include <OpenMS/FILTERING/DATAREDUCTION/IsotopeDistributionCache.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <queue> #include <list> namespace OpenMS { /** * @brief Filter to use for SILACFiltering * * A SILACFilter searches for SILAC patterns, which correspond to the defined mass shifts and charge. * Only peaks are taken into account, which were not blacklisted by other filters before e.g. are not part of * a SILAC pair yet. * * @see SILACFiltering */ class OPENMS_DLLAPI SILACFilter { private: friend class SILACFiltering; typedef IsotopeDistributionCache::TheoreticalIsotopePattern TheoreticalIsotopePattern; /** * @brief mass shift(s) in [Da] to search for */ std::vector<DoubleReal> mass_separations_; /** * @brief charge of the ions to search for */ Int charge_; /** * @brief maximal value of which a predicted SILAC feature may deviate from the averagine model */ DoubleReal model_deviation_; /** * @brief number of peaks per peptide to search for */ Size isotopes_per_peptide_; /** * @brief minimal intensity of SILAC features */ DoubleReal intensity_cutoff_; /** * @brief minimal intensity correlation between regions of different peaks */ DoubleReal intensity_correlation_; /** * @brief flag for missing peaks */ bool allow_missing_peaks_; /** * Isotope distributions */ static IsotopeDistributionCache * isotope_distribution_; /** * @brief number of peptides [i.e. number of labelled peptides +1, e.g. for SILAC triplet =3] */ Size number_of_peptides_; /** * @brief peak positions of SILAC pattern */ std::vector<DoubleReal> peak_positions_; /** * @brief m/z separation between individual peptides [e.g. {0 Th, 4 Th, 5 Th}] */ std::vector<DoubleReal> mz_peptide_separations_; /** * @brief m/z shifts relative to mono-isotopic peak of unlabelled peptide */ std::vector<DoubleReal> expected_mz_shifts_; /** * @brief distance between isotopic peaks of a peptide in [Th] */ DoubleReal isotope_distance_; /** * @brief holds the recognized features */ std::vector<SILACPattern> elements_; /** * @brief m/z at which the filter is currently applied to */ DoubleReal current_mz_; /** * @brief exact m/z shift of isotopic peaks in a SILAC pattern relative to the mono-isotopic peak of the light peptide, peptides (row) x isotope (column) */ std::vector<std::vector<DoubleReal> > exact_shifts_; /** * @brief m/z positions mz + exact_shifts in a SILAC pattern, where mz is the m/z of the mono-isotopic peak of light peptide */ std::vector<std::vector<DoubleReal> > exact_mz_positions_; /** * @brief intensities at mz + exact_shifts in a SILAC pattern, where mz is the m/z of the mono-isotopic peak of light peptide */ std::vector<std::vector<DoubleReal> > exact_intensities_; /** * @brief expected m/z shift of isotopic peaks in a SILAC pattern relative to the mono-isotopic peak of the light peptide, peptides (row) x isotope (column) */ std::vector<std::vector<DoubleReal> > expected_shifts_; /** * @brief Checks if there exists a SILAC feature at the given position in the raw (interpolated) data, which corresponds to the filter's properties * @param rt RT value of the position * @param mz m/z value of the position */ bool isSILACPattern_(const MSSpectrum<Peak1D> &, const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, DoubleReal picked_mz, const SILACFiltering &, MSSpectrum<Peak1D> & debug, SILACPattern & pattern); /** * @brief Checks if there exists a SILAC feature at the given position in the picked data */ bool isSILACPatternPicked_(const MSSpectrum<Peak1D> &, DoubleReal mz, const SILACFiltering &, MSSpectrum<Peak1D> & debug); /** * @brief Extracts mass shifts and intensities from the raw (interpolated) data */ bool extractMzShiftsAndIntensities_(const MSSpectrum<Peak1D> &, const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, DoubleReal picked_mz, const SILACFiltering &); /** * @brief Extracts mass shifts and intensities from the picked data */ bool extractMzShiftsAndIntensitiesPicked_(const MSSpectrum<Peak1D> &, DoubleReal mz, const SILACFiltering &); /** * @brief Extracts mass shifts and intensities from the picked data and returns pattern information */ bool extractMzShiftsAndIntensitiesPickedToPattern_(const MSSpectrum<Peak1D> &, DoubleReal mz, const SILACFiltering &, SILACPattern & pattern); /** * @brief Checks all peaks against intensity cutoff */ bool intensityFilter_(); /** * @brief Checks peak form correlation between peaks of one isotope */ bool correlationFilter1_(const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, const SILACFiltering &); /** * @brief Checks peak form correlation between peaks of different isotopes */ bool correlationFilter2_(const SILACFiltering::SpectrumInterpolation &, DoubleReal mz, const SILACFiltering &); /** * @brief Checks peak intensities against the averagine model */ bool averageneFilter_(DoubleReal mz); public: /** * @brief detailed constructor for SILAC pair filtering * @param mass_separations all mass shifts of the filter * @param charge charge of the ions to search for * @param model_deviation maximum deviation from the averagine model * @param isotopes_per_peptide number of peaks per peptide to search for * @param intensity_cutoff ... * @param intensity_correlation minimal intensity correlation between regions of different peaks * @param allow_missing_peaks flag for missing peaks */ SILACFilter(std::vector<DoubleReal> mass_separations, Int charge, DoubleReal model_deviation, Int isotopes_per_peptide, DoubleReal intensity_cutoff, DoubleReal intensity_correlation, bool allow_missing_peaks); /** * @brief gets the m/z values of all peaks , which belong the last identified feature */ std::vector<DoubleReal> getPeakPositions(); /** * @brief gets the m/z shifts relative to mono-isotopic peak of unlabelled peptide */ const std::vector<DoubleReal> & getExpectedMzShifts(); /** * @brief returns all identified elements */ std::vector<SILACPattern> & getElements(); /** * @brief returns the charge of the filter */ Int getCharge(); /** * @brief returns the mass shifts of the filter in [Da] */ std::vector<DoubleReal> & getMassSeparations(); }; } #endif /* SILACFILTER_H_ */
{ "alphanum_fraction": 0.6764990849, "avg_line_length": 37.3052208835, "ext": "h", "hexsha": "99c1708041a8ba021aba2483bba0ca9964f1540f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": [ "Zlib", "Apache-2.0" ], "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFilter.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib", "Apache-2.0" ], "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFilter.h", "max_line_length": 213, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": [ "Zlib", "Apache-2.0" ], "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_path": "include/OpenMS/FILTERING/DATAREDUCTION/SILACFilter.h", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "num_tokens": 2131, "size": 9289 }
/* * hubble.c * * written by christian wagner * */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_odeiv.h> #include <gsl/gsl_errno.h> #define VC 299792.458 #define TWOPI 6.283185307179586 #define PI 3.141592653589793 #define Tcmb 2.725 #define pow2(x) ((x)*(x)) #define pow3(x) ((x)*(x)*(x)) #define pow4(x) ((x)*(x)*(x)*(x)) #include "hubble.h" double hubble(struct cosmo mycosmo, double a){ double H0=mycosmo.hub*100.; double Omega_m = mycosmo.wm/pow2(mycosmo.hub); double Omega_r = 4.15e-5/pow2(mycosmo.hub); double Omega_X = 1.-Omega_m; double Omega_k = 0.; return H0*sqrt(Omega_r/pow4(a)+Omega_m/pow3(a)+Omega_k/pow2(a)+Omega_X*pow(a,-3*(1+mycosmo.w0+mycosmo.wa))*exp(-3.*mycosmo.wa*(1.-a))); } double co_distance_int(double a,void * params){ double t; struct cosmo mycosmo = *(struct cosmo *) params; return 1./(a*a*hubble(mycosmo,a)); } double co_distance(struct cosmo mycosmo, double a){ gsl_function F; double result; double epsabs=0.001; double epsrel=0.001; double abserr; size_t neval; F.function = &co_distance_int; F.params = &mycosmo; gsl_integration_qng (&F, a, 1., epsabs, epsrel, &result, &abserr, &neval); return result*VC*mycosmo.hub; } double ang_dist(struct cosmo mycosmo, double a){ return co_distance(mycosmo,a); // assuming flatness } int ode_growth (double a, const double y[], double f[], void *params) { struct cosmo mycosmo = * (struct cosmo *) params; double w_a=mycosmo.w0+(1-a)*mycosmo.wa; double Omega_m=mycosmo.wm/pow2(mycosmo.hub); double Omega_X=1-Omega_m; double Xvar=(1-Omega_m)*pow(a,-3.*(1+mycosmo.w0+mycosmo.wa))*exp(-3.*mycosmo.wa*(1.-a))/(Omega_m/(a*a*a)+(1-Omega_m)*pow(a,-3.*(1+mycosmo.w0+mycosmo.wa))*exp(-3.*mycosmo.wa*(1.-a))); f[0] = y[1]; f[1] = -1.5*(1.-w_a)*Xvar*y[0]/(a*a) - (3.5-1.5*w_a*Xvar)*y[1]/a ; return GSL_SUCCESS; } int jac_growth (double a, const double y[], double *dfdy, double dfdt[], void *params) { return GSL_SUCCESS; } double growth(struct cosmo mycosmo, double a){ const gsl_odeiv_step_type * T = gsl_odeiv_step_rkf45; gsl_odeiv_step * s = gsl_odeiv_step_alloc (T, 2); gsl_odeiv_control * c = gsl_odeiv_control_y_new (1e-12, 0.0); gsl_odeiv_evolve * e = gsl_odeiv_evolve_alloc (2); double mu = 10; gsl_odeiv_system sys = {ode_growth, jac_growth, 2, &mycosmo}; double t1=a; double t = 1.E-12; double d1; double h = 1e-12; double y[2] = { 1.0, 0.0 }; int status; while (t < t1){ status = gsl_odeiv_evolve_apply (e, c, s, &sys, &t, t1, &h, y); if (h>0.001) h=0.001; if (status != GSL_SUCCESS) break; } d1=y[0]*(t); gsl_odeiv_evolve_free (e); gsl_odeiv_control_free (c); gsl_odeiv_step_free (s); return d1; } double z_lastscattering(struct cosmo mycosmo){ /* z_lastscattering(cosmo): Returns z_LS from Hu & White, DampingTail paper. */ double wm = mycosmo.wm; double wb = mycosmo.wb; double b1 = 0.0783*pow(wb,(-0.238))/(1+39.5*pow(wb,0.763)); double b2 = 0.560/(1+21.1*pow(wb,1.81)); double zls= 1048.*(1+0.00124*pow(wb,(-0.738)))*(1+b1*pow(wm,b2)); return zls; } double soundhorizon(struct cosmo mycosmo){ /* soundhorizon(cosmo): A fit to the sound horizon, in Mpc, from Hu & Sugiyama (1995), Eq. B6 */ double wm = mycosmo.wm; double wb = mycosmo.wb; double wg = 2.4888e-5*pow4(Tcmb/2.73); double r0 = 0.75*wb/wg; double zeq= 5464.0*(wm/0.135)/pow4(Tcmb/2.725)/(1+0.6851)-1.0; double req= r0/(1.+zeq); double zLS= z_lastscattering(mycosmo); double rls= r0/(1+zLS); double tmp= (sqrt(1.+rls)+sqrt(rls+req))/(1.+sqrt(req)); tmp= 3997.0*sqrt(wg/wm/wb)*log(tmp); return(tmp); } double distls(struct cosmo mycosmo){ /* distls(cosmo): Returns the distance to LS, in Mpc. */ double zLS = z_lastscattering(mycosmo); double dLS = ang_dist(mycosmo,1./(1.+zLS))/mycosmo.hub; return(dLS); } double solvehh(double dLS,struct cosmo mycosmo){ /* solvehh(dLS,cosmo): Solves for h given the other cosmological parameters and the distance to last scattering (in Mpc). */ struct cosmo hmin = mycosmo; hmin.hub = 0.3; // printf("min_cosmo: %g %g %g %g %g\n",hmin.hub,hmin.w0,hmin.wa,hmin.wm,hmin.wb); double ymin = distls(hmin)-dLS; // printf("ymin: %g\n",ymin); struct cosmo hmax = mycosmo; hmax.hub = 1.0; double ymax = distls(hmax)-dLS; // printf("ymax: %g\n",ymax); double ymid; struct cosmo hmid = mycosmo; while (fabs(hmax.hub-hmin.hub)>1e-3){ hmid.hub = (hmax.hub+hmin.hub)/2.0; ymid = distls(hmid)-dLS; if (ymin*ymid<0){ hmax = hmid; ymax = ymid; } else { hmin = hmid; ymin = ymid; } } // printf("hubble from CMB: %g\n",hmid.hub); return hmid.hub; } //void getH0fromCMB(double *xstar, double myh, double *rs, double *z_lss, double *d_lss, double *h_CMB, int *writeout, char *fname){ void getH0fromCMB(double *xstar, double *stuff){ FILE *fp; struct cosmo mycosmo={ 0.72, xstar[3], 0, xstar[1], xstar[0]}; double rs=soundhorizon(mycosmo); stuff[0] = rs; double z_lss=z_lastscattering(mycosmo); stuff[1] = z_lss; double d_lss=302.4*rs/PI; stuff[2] = d_lss; double hubble_cmb= solvehh(d_lss,mycosmo); stuff[3] = hubble_cmb; } // Linker function for use with Fortran void geth0fromcmb_(double *xstar, double *stuff){ void getH0fromCMB(); getH0fromCMB(xstar,stuff); }
{ "alphanum_fraction": 0.6334048641, "avg_line_length": 22.1904761905, "ext": "c", "hexsha": "894c34d77c9320f73d5255a7491a3184d7bf5d86", "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/FrankenEmu/hubble.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/FrankenEmu/hubble.c", "max_line_length": 184, "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/FrankenEmu/hubble.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": 2106, "size": 5592 }
#ifndef __PAR_EQUILIBRIUM_IC_H__ #define __PAR_EQUILIBRIUM_IC_H__ #include "GAMER.h" #include "TestProb.h" #include "vector" #include <iostream> #include <fstream> #include <sstream> using namespace std; //gsl library #ifdef SUPPORT_GSL #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #endif typedef struct Filename_Parameter{ int Cloud_Num; vector<string> Params_Filenames; }FP; typedef struct Physical_Parameter{ int Cloud_Num; string Params_Filenames; char Cloud_Type[MAX_STRING]; char Density_Table_Name[MAX_STRING]; int AddExtPot; char ExtPot_Table_Name[MAX_STRING]; int Cloud_RSeed; double Cloud_Rho0; double Cloud_R0; double Cloud_MaxR; double* Cloud_Center; double* Cloud_BulkVel; double Cloud_Einasto_Power_Factor; double Cloud_Par_Num; int Cloud_MassProfNBin; }PhysP; class Par_EquilibriumIC { public: Par_EquilibriumIC(); virtual ~Par_EquilibriumIC(); void Read_Filenames( const char *filename_para); void Load_Physical_Params(const FP filenames,const int cloud_idx, const long NPar_AllRank); void Init(); void Par_SetEquilibriumIC(real *Mass_AllRank, real *Pos_AllRank[3], real *Vel_AllRank[3],const long Par_Idx); PhysP params; FP filenames; protected: private: // Derive physical attributes for particles double Set_Mass( double x ); double Set_Density( double x ); double Set_Velocity(const double x); // Initialize physical parameter tables void Init_Mass(); void Init_Pot(); void Init_Prob_Dens(); // Initialization through Table void Init_Mass_Table(); void Init_Pot_Table(); // Add External Potential void Add_Ext_Pot(); // Auxiliary functions int Aux_CountRow( const char *filename ); int Aux_Countcolumn( const char *filename ); int GetParams( const char *filename,const char *keyword,const int para_num,const char *para_type,vector <string> &container); void Check_InputFileName(); void RanVec_FixRadius( const double r, double RanVec[] ); // Solve Eddington's equation double potential(const double x); double inverse_psi_to_index (double psi); double integration_eng_base(double eng); double delta; double eng_min; double *prob_dens; double *int_prob_dens; double *psi; // statistics double slope(double* a,double* b,int start,int fin); void smooth_all(double* x,int start,int fin); double ave(double* a,int start,int fin); double var_n(double* a,int start,int fin); double cor(double* x,double* y,int start,int fin); void mask(double* x,int start,int fin); void add_num(double* x,int start,int fin); // Tables of particles' attributes double *Table_r; double *Table_Enclosed_Mass; double *Table_Density; double *Table_dRho_dr; double *Table_dRho_dx; double *Table_Gravity_Field; double *Table_Gravity_Potential; // Random number generator RandomNumber_t *Random_Num_Gen ; }; #endif //__PAR_EQUILIBRIUM_IC_H__
{ "alphanum_fraction": 0.6852932146, "avg_line_length": 26.056, "ext": "h", "hexsha": "c67bccd5c71f7f2b4c66f25cb8ab0e5097767904", "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": "4feb2c8efe3b4dc92391b0b2a03b2c1c39aaa384", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "CrazyAncestor/gamer", "max_forks_repo_path": "include/Par_EquilibriumIC.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4feb2c8efe3b4dc92391b0b2a03b2c1c39aaa384", "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": "CrazyAncestor/gamer", "max_issues_repo_path": "include/Par_EquilibriumIC.h", "max_line_length": 131, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4feb2c8efe3b4dc92391b0b2a03b2c1c39aaa384", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "CrazyAncestor/gamer", "max_stars_repo_path": "include/Par_EquilibriumIC.h", "max_stars_repo_stars_event_max_datetime": "2019-08-29T13:43:35.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:43:35.000Z", "num_tokens": 804, "size": 3257 }
#pragma once #include "typetraits.h" #if defined(__has_include) && __has_include(<version>) #include <version> #if defined(__cpp_lib_span) && __cpp_lib_span >= 202002L #include <span> #else #include <gsl/span> #endif // __cpp_lib_span >= 202002L #else #include <gsl/span> #endif //__has_include(<version>) #include "uuid.h" #include <array> #include <chrono> #include <compare> template <typename T> struct UuidObjectT; template <typename T> struct UuidBasedId { static UuidBasedId<T> Create() { UuidBasedId<T> uuid; std::random_device rd; auto seed_data = std::array<unsigned, std::mt19937::state_size>{}; std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::mt19937 generator(seq); uuids::uuid_random_generator gen{generator}; uuid.uuid = gen(); return uuid; } template <typename TStr> static constexpr UuidBasedId<T> FromString(TStr const& str) { UuidBasedId<T> uuid; uuid.guid = uuids::uuid(str); } public: UuidBasedId() = default; uuids::uuid uuid; constexpr bool Empty() const { return uuid == Invalid().uuid; } static constexpr UuidBasedId<T> Invalid() { return UuidBasedId<T>(); } friend UuidObjectT<T>; friend std::hash<UuidBasedId<T>>; }; template <typename T> struct UuidObjectT { using Id = UuidBasedId<T>; UuidObjectT() {} Id id = Id::Create(); }; template <> struct Stencil::TypeTraits<uuids::uuid> { using Categories = std::tuple<Stencil::Category::Primitive>; }; template <typename T> struct Stencil::TypeTraits<UuidBasedId<T>> { using Categories = std::tuple<Stencil::Category::Primitive>; };
{ "alphanum_fraction": 0.6364622897, "avg_line_length": 25.5972222222, "ext": "h", "hexsha": "0a1a4b5668a79ae3ca12ce730a1c10cfc41c2400", "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": "b6429f8b92947273a5e66d5f10210b960616a89d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ankurvdev/stencil", "max_forks_repo_path": "include/stencil/uuidobject.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b6429f8b92947273a5e66d5f10210b960616a89d", "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": "ankurvdev/stencil", "max_issues_repo_path": "include/stencil/uuidobject.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "b6429f8b92947273a5e66d5f10210b960616a89d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ankurvdev/stencil", "max_stars_repo_path": "include/stencil/uuidobject.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 473, "size": 1843 }
/** * * @file qwrapper_dlacpy.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 Julien Langou * @author Henricus Bouwmeester * @author Mathieu Faverge * @date 2010-11-15 * @generated d Tue Jan 7 11:44:56 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_dlacpy(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum uplo, int m, int n, int nb, const double *A, int lda, double *B, int ldb) { DAG_CORE_LACPY; QUARK_Insert_Task(quark, CORE_dlacpy_quark, task_flags, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(double)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(double)*nb*nb, B, OUTPUT, sizeof(int), &ldb, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlacpy_quark = PCORE_dlacpy_quark #define CORE_dlacpy_quark PCORE_dlacpy_quark #endif void CORE_dlacpy_quark(Quark *quark) { PLASMA_enum uplo; int M; int N; const double *A; int LDA; double *B; int LDB; quark_unpack_args_7(quark, uplo, M, N, A, LDA, B, LDB); LAPACKE_dlacpy_work( LAPACK_COL_MAJOR, lapack_const(uplo), M, N, A, LDA, B, LDB); } /***************************************************************************//** * **/ void QUARK_CORE_dlacpy_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum uplo, int m, int n, int nb, const double *A, int lda, double *B, int ldb, double *fake1, int szefake1, int flag1) { DAG_CORE_LACPY; if ( fake1 == B ) { QUARK_Insert_Task(quark, CORE_dlacpy_quark, task_flags, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(double)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(double)*nb*nb, B, OUTPUT | flag1, sizeof(int), &ldb, VALUE, 0); } else { QUARK_Insert_Task(quark, CORE_dlacpy_f1_quark, task_flags, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(double)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(double)*nb*nb, B, OUTPUT, sizeof(int), &ldb, VALUE, sizeof(double)*szefake1, fake1, flag1, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlacpy_f1_quark = PCORE_dlacpy_f1_quark #define CORE_dlacpy_f1_quark PCORE_dlacpy_f1_quark #endif void CORE_dlacpy_f1_quark(Quark *quark) { PLASMA_enum uplo; int M; int N; const double *A; int LDA; double *B; int LDB; void *fake1; quark_unpack_args_8(quark, uplo, M, N, A, LDA, B, LDB, fake1); LAPACKE_dlacpy_work( LAPACK_COL_MAJOR, lapack_const(uplo), M, N, A, LDA, B, LDB); }
{ "alphanum_fraction": 0.4630529276, "avg_line_length": 31.5403225806, "ext": "c", "hexsha": "5bcbbef2e38a62b00643d16958e1ed6a1f6e4a41", "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_dlacpy.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_dlacpy.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlacpy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1015, "size": 3911 }
#pragma once #include <type_traits> #include <cuda/runtime_api.hpp> #include <gsl-lite/gsl-lite.hpp> namespace thrustshift { namespace kernel { template <typename MapT, typename SrcT, typename DstT> __global__ void gather(gsl_lite::span<const MapT> map, gsl_lite::span<const SrcT> src, gsl_lite::span<DstT> dst) { const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; if (gtid < src.size()) { dst[gtid] = src[map[gtid]]; } } } // namespace kernel namespace async { template <class MapRange, class SrcRange, class DstRange> void gather(cuda::stream_t& stream, MapRange&& map, SrcRange&& src, DstRange&& dst) { gsl_Expects(src.size() == dst.size()); gsl_Expects(src.size() == map.size()); gsl_Expects(src.data() != dst.data()); if (src.empty()) { return; } using map_index_type = typename std::remove_reference<MapRange>::type::value_type; 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::gather<map_index_type, src_value_type, dst_value_type>; cuda::enqueue_launch(k, stream, c, map, src, dst); } } // namespace async } // namespace thrustshift
{ "alphanum_fraction": 0.714185884, "avg_line_length": 27, "ext": "h", "hexsha": "1e5c92adb570d9980897e72e066e384a4b7199fa", "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/gather.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/gather.h", "max_line_length": 114, "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/gather.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": 377, "size": 1431 }
#include <stdio.h> #include <gsl/gsl_matrix.h> int main (void) { int i, j; gsl_matrix * m = gsl_matrix_alloc (10, 3); for (i = 0; i < 10; i++) for (j = 0; j < 3; j++) gsl_matrix_set (m, i, j, 0.23 + 100*i + j); for (i = 0; i < 100; i++) /* OUT OF RANGE ERROR */ for (j = 0; j < 3; j++) printf ("m(%d,%d) = %g\n", i, j, gsl_matrix_get (m, i, j)); gsl_matrix_free (m); return 0; }
{ "alphanum_fraction": 0.47597254, "avg_line_length": 19, "ext": "c", "hexsha": "7704687621c1be616b3a45f0fe64f7363af04ae1", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/matrix.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/matrix.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/matrix.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": 177, "size": 437 }
#include <bindings.cmacros.h> #include <gsl/gsl_multifit_nlin.h> BC_INLINE3VOID(GSL_MULTIFIT_FN_EVAL,gsl_multifit_function*,gsl_vector*,gsl_vector*) BC_INLINE3(GSL_MULTIFIT_FN_EVAL_F,gsl_multifit_function_fdf*,gsl_vector*,gsl_vector*,int) BC_INLINE3(GSL_MULTIFIT_FN_EVAL_DF,gsl_multifit_function_fdf*,gsl_vector*,gsl_matrix*,int) BC_INLINE4(GSL_MULTIFIT_FN_EVAL_F_DF,gsl_multifit_function_fdf*,gsl_vector*,gsl_vector*,gsl_matrix*,int)
{ "alphanum_fraction": 0.871559633, "avg_line_length": 54.5, "ext": "c", "hexsha": "0dc44adb98ec172c7b297a15b165012aed58ad3c", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/NonlinearLeastSquaresFitting.c", "max_issues_count": 23, "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/NonlinearLeastSquaresFitting.c", "max_line_length": 104, "max_stars_count": 25, "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/NonlinearLeastSquaresFitting.c", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "num_tokens": 141, "size": 436 }
#ifndef QDM_LOGL_H #define QDM_LOGL_H 1 #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <qdm/tau.h> int qdm_find_tau( double *result, double v, size_t spline_df, const gsl_vector *knots, const gsl_vector *mmm ); int qdm_logl( double *log_likelihood, double *tau, double v, size_t spline_df, const gsl_vector *knots, const gsl_vector *mmm, double tau_low, double tau_high, double xi_low, double xi_high ); int qdm_logl_2( double *log_likelihood, double *tau, double x, double y, double tau_low, double tau_high, double xi_low, double xi_high, size_t spline_df, const gsl_matrix *theta, const gsl_vector *knots ); void qdm_logl_3( double *log_likelihood, double *tau, double x, double y, const qdm_tau *t, const gsl_vector *xi, const gsl_matrix *theta ); #endif /* QDM_LOGL_H */
{ "alphanum_fraction": 0.6493644068, "avg_line_length": 13.4857142857, "ext": "h", "hexsha": "05b6dbaf00761bc35fdf3125abe3f6977991112e", "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": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "include/qdm/logl.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "include/qdm/logl.h", "max_line_length": 28, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "include/qdm/logl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 276, "size": 944 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <sys/time.h> #ifdef _WIN32 #else #include <sys/resource.h> #endif #include <unistd.h> #include <signal.h> #include <gsl/gsl_rng.h> #ifndef NOMPI #include <mpi.h> #endif #include "allvars.h" #include "proto.h" /*! \file system.c * \brief contains miscellaneous routines, e.g. elapsed time measurements */ /*! This routine returns a random number taken from a table of random numbers, * which is refilled every timestep. This method is used to allow random * number application to particles independent of the number of processors * used, and independent of the particular order the particles have. In order * to work properly, the particle IDs should be set properly to unique * integer values. */ double get_random_number(int id) { return RndTable[(id % RNDTABLE)]; } /*! This routine fills the random number table. */ void set_random_numbers(void) { int i; for(i = 0; i < RNDTABLE; i++) RndTable[i] = gsl_rng_uniform(random_generator); } /*! returns the number of cpu-ticks in seconds that have elapsed, or the * wall-clock time obtained with MPI_Wtime(). */ double second(void) { #ifdef WALLCLOCK #ifndef NOMPI return MPI_Wtime(); #else return ((double) clock()) / CLOCKS_PER_SEC; #endif #else return ((double) clock()) / CLOCKS_PER_SEC; #endif /* note: on AIX and presumably many other 32bit systems, * clock() has only a resolution of 10ms=0.01sec */ } /*! returns the time difference between two measurements obtained with * second(). The routine takes care of the possible overflow of the tick * counter on 32bit systems, but depending on the system, this may not always * work properly. Similarly, in some MPI implementations, the MPI_Wtime() * function may also overflow, in which case a negative time difference would * be returned. The routine returns instead a time difference equal to 0. */ double timediff(double t0, double t1) { double dt; dt = t1 - t0; if(dt < 0) /* overflow has occured (for systems with 32bit tick counter) */ { #ifdef WALLCLOCK dt = 0; #else dt = t1 + pow(2, 32) / CLOCKS_PER_SEC - t0; #endif } return dt; } /*! returns the maximum of two double */ double dmax(double x, double y) { if(x > y) return x; else return y; } /*! returns the minimum of two double */ double dmin(double x, double y) { if(x < y) return x; else return y; } /*! returns the maximum of two integers */ int imax(int x, int y) { if(x > y) return x; else return y; } /*! returns the minimum of two integers */ int imin(int x, int y) { if(x < y) return x; else return y; }
{ "alphanum_fraction": 0.6804236669, "avg_line_length": 19.9854014599, "ext": "c", "hexsha": "f7c3d584f10d1dfaf42f634668b716076bc35e0e", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rieder/amuse", "max_forks_repo_path": "src/amuse/community/gadget2/src/system.c", "max_issues_count": 690, "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rknop/amuse", "max_issues_repo_path": "src/amuse/community/gadget2/src/system.c", "max_line_length": 78, "max_stars_count": 131, "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rknop/amuse", "max_stars_repo_path": "src/amuse/community/gadget2/src/system.c", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "num_tokens": 725, "size": 2738 }
#include <stdio.h> #include <cblas.h> #define M 2 #define N 2 #define K 3 #define X 4 #define Y 5 void print_mat(const char *name, int r, int c, float *m) { printf("%s =\n", name); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { printf("%.2lf ", m[i * c + j]); } printf("\n"); } } int main() { float A[M * K] = { 1, 2, 3, 4, 5, 6, }; float B[K * N] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, }; float C[X * Y] = { 0 }; // M x K, K x N -> M x N (single precision, 's'gemm) // Save A x B in C starting from (1, 1) cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1, A, K, B, N, 0, C + Y + 1, Y ); print_mat("A", M, K, A); print_mat("B", K, N, B); print_mat("C", X, Y, C); return 0; }
{ "alphanum_fraction": 0.4097452935, "avg_line_length": 17.3653846154, "ext": "c", "hexsha": "a79e231e37f2630e5e77952a010dedeea6408ebe", "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": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hsyis/object-detection-yolo2-tiny", "max_forks_repo_path": "proj3/examples/openBLAS/openblas_example.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "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": "hsyis/object-detection-yolo2-tiny", "max_issues_repo_path": "proj3/examples/openBLAS/openblas_example.c", "max_line_length": 56, "max_stars_count": null, "max_stars_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hsyis/object-detection-yolo2-tiny", "max_stars_repo_path": "proj3/examples/openBLAS/openblas_example.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 352, "size": 903 }
#ifndef OPENMC_TALLIES_FILTER_MATERIAL_H #define OPENMC_TALLIES_FILTER_MATERIAL_H #include <cstdint> #include <unordered_map> #include <gsl/gsl> #include "openmc/tallies/filter.h" #include "openmc/vector.h" namespace openmc { //============================================================================== //! Specifies which material tally events reside in. //============================================================================== class MaterialFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~MaterialFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override {return "material";} void from_xml(pugi::xml_node node) override; void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; std::string text_label(int bin) const override; //---------------------------------------------------------------------------- // Accessors vector<int32_t>& materials() { return materials_; } const vector<int32_t>& materials() const { return materials_; } void set_materials(gsl::span<const int32_t> materials); private: //---------------------------------------------------------------------------- // Data members //! The indices of the materials binned by this filter. vector<int32_t> materials_; //! A map from material indices to filter bin indices. std::unordered_map<int32_t, int> map_; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_MATERIAL_H
{ "alphanum_fraction": 0.5324292453, "avg_line_length": 27.3548387097, "ext": "h", "hexsha": "65bfce04eb455a97454475ad957db5ec11551a04", "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": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_path": "include/openmc/tallies/filter_material.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_path": "include/openmc/tallies/filter_material.h", "max_line_length": 84, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_path": "include/openmc/tallies/filter_material.h", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "num_tokens": 314, "size": 1696 }
/* linalg/gsl_linalg.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006, 2007, 2019 Gerard Jungman, Brian Gough, Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_LINALG_H__ #define __GSL_LINALG_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_mode.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_blas.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus #define __BEGIN_DECLS extern "C" { #define __END_DECLS } #else #define __BEGIN_DECLS /* empty */ #define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef enum { GSL_LINALG_MOD_NONE = 0, GSL_LINALG_MOD_TRANSPOSE = 1, GSL_LINALG_MOD_CONJUGATE = 2 } gsl_linalg_matrix_mod_t; /* Note: You can now use the gsl_blas_dgemm function instead of matmult */ /* Simple implementation of matrix multiply. * Calculates C = A.B * * exceptions: GSL_EBADLEN */ GSL_FUN int gsl_linalg_matmult (const gsl_matrix * A, const gsl_matrix * B, gsl_matrix * C); /* Simple implementation of matrix multiply. * Allows transposition of either matrix, so it * can compute A.B or Trans(A).B or A.Trans(B) or Trans(A).Trans(B) * * exceptions: GSL_EBADLEN */ GSL_FUN int gsl_linalg_matmult_mod (const gsl_matrix * A, gsl_linalg_matrix_mod_t modA, const gsl_matrix * B, gsl_linalg_matrix_mod_t modB, gsl_matrix * C); /* Calculate the matrix exponential by the scaling and * squaring method described in Moler + Van Loan, * SIAM Rev 20, 801 (1978). The mode argument allows * choosing an optimal strategy, from the table * given in the paper, for a given precision. * * exceptions: GSL_ENOTSQR, GSL_EBADLEN */ GSL_FUN int gsl_linalg_exponential_ss( const gsl_matrix * A, gsl_matrix * eA, gsl_mode_t mode ); /* Householder Transformations */ GSL_FUN double gsl_linalg_householder_transform (gsl_vector * v); GSL_FUN double gsl_linalg_householder_transform2 (double * alpha, gsl_vector * v); GSL_FUN gsl_complex gsl_linalg_complex_householder_transform (gsl_vector_complex * v); GSL_FUN int gsl_linalg_householder_hm (double tau, const gsl_vector * v, gsl_matrix * A); GSL_FUN int gsl_linalg_householder_mh (double tau, const gsl_vector * v, gsl_matrix * A); GSL_FUN int gsl_linalg_householder_hv (double tau, const gsl_vector * v, gsl_vector * w); GSL_FUN int gsl_linalg_householder_left(const double tau, const gsl_vector * v, gsl_matrix * A, gsl_vector * work); GSL_FUN int gsl_linalg_householder_right(const double tau, const gsl_vector * v, gsl_matrix * A, gsl_vector * work); GSL_FUN int gsl_linalg_householder_hm1 (double tau, gsl_matrix * A); GSL_FUN int gsl_linalg_complex_householder_hm (gsl_complex tau, const gsl_vector_complex * v, gsl_matrix_complex * A); GSL_FUN int gsl_linalg_complex_householder_mh (gsl_complex tau, const gsl_vector_complex * v, gsl_matrix_complex * A); GSL_FUN int gsl_linalg_complex_householder_hv (gsl_complex tau, const gsl_vector_complex * v, gsl_vector_complex * w); GSL_FUN int gsl_linalg_complex_householder_left (const gsl_complex tau, const gsl_vector_complex * v, gsl_matrix_complex * A, gsl_vector_complex * work); /* Hessenberg reduction */ GSL_FUN int gsl_linalg_hessenberg_decomp(gsl_matrix *A, gsl_vector *tau); GSL_FUN int gsl_linalg_hessenberg_unpack(gsl_matrix * H, gsl_vector * tau, gsl_matrix * U); GSL_FUN int gsl_linalg_hessenberg_unpack_accum(gsl_matrix * H, gsl_vector * tau, gsl_matrix * U); GSL_FUN int gsl_linalg_hessenberg_set_zero(gsl_matrix * H); GSL_FUN int gsl_linalg_hessenberg_submatrix(gsl_matrix *M, gsl_matrix *A, size_t top, gsl_vector *tau); /* Hessenberg-Triangular reduction */ GSL_FUN int gsl_linalg_hesstri_decomp(gsl_matrix * A, gsl_matrix * B, gsl_matrix * U, gsl_matrix * V, gsl_vector * work); /* Singular Value Decomposition * exceptions: */ GSL_FUN int gsl_linalg_SV_decomp (gsl_matrix * A, gsl_matrix * V, gsl_vector * S, gsl_vector * work); GSL_FUN int gsl_linalg_SV_decomp_mod (gsl_matrix * A, gsl_matrix * X, gsl_matrix * V, gsl_vector * S, gsl_vector * work); GSL_FUN int gsl_linalg_SV_decomp_jacobi (gsl_matrix * A, gsl_matrix * Q, gsl_vector * S); GSL_FUN int gsl_linalg_SV_solve (const gsl_matrix * U, const gsl_matrix * Q, const gsl_vector * S, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_SV_leverage(const gsl_matrix *U, gsl_vector *h); /* LU Decomposition, Gaussian elimination with partial pivoting */ GSL_FUN int gsl_linalg_LU_decomp (gsl_matrix * A, gsl_permutation * p, int *signum); GSL_FUN int gsl_linalg_LU_solve (const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_LU_svx (const gsl_matrix * LU, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_LU_refine (const gsl_matrix * A, const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x, gsl_vector * work); GSL_FUN int gsl_linalg_LU_invert (const gsl_matrix * LU, const gsl_permutation * p, gsl_matrix * inverse); GSL_FUN int gsl_linalg_LU_invx (gsl_matrix * LU, const gsl_permutation * p); GSL_FUN double gsl_linalg_LU_det (gsl_matrix * LU, int signum); GSL_FUN double gsl_linalg_LU_lndet (gsl_matrix * LU); GSL_FUN int gsl_linalg_LU_sgndet (gsl_matrix * lu, int signum); /* Complex LU Decomposition */ GSL_FUN int gsl_linalg_complex_LU_decomp (gsl_matrix_complex * A, gsl_permutation * p, int *signum); GSL_FUN int gsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x); GSL_FUN int gsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_vector_complex * x); GSL_FUN int gsl_linalg_complex_LU_refine (const gsl_matrix_complex * A, const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x, gsl_vector_complex * work); GSL_FUN int gsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_matrix_complex * inverse); GSL_FUN int gsl_linalg_complex_LU_invx (gsl_matrix_complex * LU, const gsl_permutation * p); GSL_FUN gsl_complex gsl_linalg_complex_LU_det (gsl_matrix_complex * LU, int signum); GSL_FUN double gsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU); GSL_FUN gsl_complex gsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU, int signum); /* QR decomposition */ GSL_FUN int gsl_linalg_QR_decomp (gsl_matrix * A, gsl_vector * tau); GSL_FUN int gsl_linalg_QR_decomp_r (gsl_matrix * A, gsl_matrix * T); GSL_FUN int gsl_linalg_QR_solve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QR_solve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QR_svx (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * x); GSL_FUN int gsl_linalg_QR_lssolve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x, gsl_vector * residual); GSL_FUN int gsl_linalg_QR_lssolve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x, gsl_vector * work); GSL_FUN int gsl_linalg_QR_QRsolve (gsl_matrix * Q, gsl_matrix * R, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QR_Rsolve (const gsl_matrix * QR, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QR_Rsvx (const gsl_matrix * QR, gsl_vector * x); GSL_FUN int gsl_linalg_QR_update (gsl_matrix * Q, gsl_matrix * R, gsl_vector * w, const gsl_vector * v); GSL_FUN int gsl_linalg_QR_QTvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v); GSL_FUN int gsl_linalg_QR_QTvec_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_vector * b, gsl_vector * work); GSL_FUN int gsl_linalg_QR_Qvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v); GSL_FUN int gsl_linalg_QR_QTmat (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * A); GSL_FUN int gsl_linalg_QR_QTmat_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * B, gsl_matrix * work); GSL_FUN int gsl_linalg_QR_matQ (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * A); GSL_FUN int gsl_linalg_QR_unpack (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * R); GSL_FUN int gsl_linalg_QR_unpack_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q, gsl_matrix * R); GSL_FUN int gsl_linalg_R_solve (const gsl_matrix * R, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_R_svx (const gsl_matrix * R, gsl_vector * x); GSL_FUN int gsl_linalg_QR_rcond(const gsl_matrix * QR, double * rcond, gsl_vector * work); /* Q R P^T decomposition */ GSL_FUN int gsl_linalg_QRPT_decomp (gsl_matrix * A, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm); GSL_FUN int gsl_linalg_QRPT_decomp2 (const gsl_matrix * A, gsl_matrix * q, gsl_matrix * r, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm); GSL_FUN int gsl_linalg_QRPT_solve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QRPT_lssolve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x, gsl_vector * residual); GSL_FUN int gsl_linalg_QRPT_lssolve2 (const gsl_matrix * QR, const gsl_vector * tau, const gsl_permutation * p, const gsl_vector * b, const size_t rank, gsl_vector * x, gsl_vector * residual); GSL_FUN int gsl_linalg_QRPT_svx (const gsl_matrix * QR, const gsl_vector * tau, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_QRPT_QRsolve (const gsl_matrix * Q, const gsl_matrix * R, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QRPT_Rsolve (const gsl_matrix * QR, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_QRPT_Rsvx (const gsl_matrix * QR, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_QRPT_update (gsl_matrix * Q, gsl_matrix * R, const gsl_permutation * p, gsl_vector * u, const gsl_vector * v); GSL_FUN size_t gsl_linalg_QRPT_rank (const gsl_matrix * QR, const double tol); GSL_FUN int gsl_linalg_QRPT_rcond(const gsl_matrix * QR, double * rcond, gsl_vector * work); /* triangle on top of rectangle QR decomposition */ GSL_FUN int gsl_linalg_QR_TR_decomp (gsl_matrix * S, gsl_matrix * A, gsl_matrix * T); /* QL decomposition */ GSL_FUN int gsl_linalg_QL_decomp (gsl_matrix * A, gsl_vector * tau); GSL_FUN int gsl_linalg_QL_unpack (const gsl_matrix * QL, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * L); /* COD decomposition */ GSL_FUN int gsl_linalg_COD_decomp(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z, gsl_permutation * p, size_t * rank, gsl_vector * work); GSL_FUN int gsl_linalg_COD_decomp_e(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z, gsl_permutation * p, double tol, size_t * rank, gsl_vector * work); GSL_FUN int gsl_linalg_COD_lssolve (const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z, const gsl_permutation * perm, const size_t rank, const gsl_vector * b, gsl_vector * x, gsl_vector * residual); GSL_FUN int gsl_linalg_COD_lssolve2 (const double lambda, const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z, const gsl_permutation * perm, const size_t rank, const gsl_vector * b, gsl_vector * x, gsl_vector * residual, gsl_matrix * S, gsl_vector * work); GSL_FUN int gsl_linalg_COD_unpack(const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z, const size_t rank, gsl_matrix * Q, gsl_matrix * R, gsl_matrix * Z); GSL_FUN int gsl_linalg_COD_matZ(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank, gsl_matrix * A, gsl_vector * work); /* LQ decomposition */ GSL_FUN int gsl_linalg_LQ_decomp (gsl_matrix * A, gsl_vector * tau); GSL_FUN int gsl_linalg_LQ_lssolve(const gsl_matrix * LQ, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x, gsl_vector * residual); GSL_FUN int gsl_linalg_LQ_QTvec(const gsl_matrix * LQ, const gsl_vector * tau, gsl_vector * v); GSL_FUN int gsl_linalg_LQ_solve_T (const gsl_matrix * LQ, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_LQ_svx_T (const gsl_matrix * LQ, const gsl_vector * tau, gsl_vector * x); GSL_FUN int gsl_linalg_LQ_lssolve_T (const gsl_matrix * LQ, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x, gsl_vector * residual); GSL_FUN int gsl_linalg_LQ_Lsolve_T (const gsl_matrix * LQ, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_LQ_Lsvx_T (const gsl_matrix * LQ, gsl_vector * x); GSL_FUN int gsl_linalg_L_solve_T (const gsl_matrix * L, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_LQ_vecQ (const gsl_matrix * LQ, const gsl_vector * tau, gsl_vector * v); GSL_FUN int gsl_linalg_LQ_vecQT (const gsl_matrix * LQ, const gsl_vector * tau, gsl_vector * v); GSL_FUN int gsl_linalg_LQ_unpack (const gsl_matrix * LQ, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * L); GSL_FUN int gsl_linalg_LQ_update (gsl_matrix * Q, gsl_matrix * R, const gsl_vector * v, gsl_vector * w); GSL_FUN int gsl_linalg_LQ_LQsolve (gsl_matrix * Q, gsl_matrix * L, const gsl_vector * b, gsl_vector * x); /* P^T L Q decomposition */ GSL_FUN int gsl_linalg_PTLQ_decomp (gsl_matrix * A, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm); GSL_FUN int gsl_linalg_PTLQ_decomp2 (const gsl_matrix * A, gsl_matrix * q, gsl_matrix * r, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm); GSL_FUN int gsl_linalg_PTLQ_solve_T (const gsl_matrix * QR, const gsl_vector * tau, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_PTLQ_svx_T (const gsl_matrix * LQ, const gsl_vector * tau, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_PTLQ_LQsolve_T (const gsl_matrix * Q, const gsl_matrix * L, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_PTLQ_Lsolve_T (const gsl_matrix * LQ, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_PTLQ_Lsvx_T (const gsl_matrix * LQ, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_PTLQ_update (gsl_matrix * Q, gsl_matrix * L, const gsl_permutation * p, const gsl_vector * v, gsl_vector * w); /* Cholesky Decomposition */ GSL_FUN int gsl_linalg_cholesky_decomp (gsl_matrix * A); GSL_FUN int gsl_linalg_cholesky_decomp1 (gsl_matrix * A); GSL_FUN int gsl_linalg_cholesky_solve (const gsl_matrix * cholesky, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_cholesky_solve_mat (const gsl_matrix * cholesky, const gsl_matrix * B, gsl_matrix * X); GSL_FUN int gsl_linalg_cholesky_svx (const gsl_matrix * cholesky, gsl_vector * x); GSL_FUN int gsl_linalg_cholesky_svx_mat (const gsl_matrix * cholesky, gsl_matrix * X); GSL_FUN int gsl_linalg_cholesky_invert(gsl_matrix * cholesky); /* Cholesky decomposition with unit-diagonal triangular parts. * A = L D L^T, where diag(L) = (1,1,...,1). * Upon exit, A contains L and L^T as for Cholesky, and * the diagonal of A is (1,1,...,1). The vector Dis set * to the diagonal elements of the diagonal matrix D. */ GSL_FUN int gsl_linalg_cholesky_decomp_unit(gsl_matrix * A, gsl_vector * D); GSL_FUN int gsl_linalg_cholesky_scale(const gsl_matrix * A, gsl_vector * S); GSL_FUN int gsl_linalg_cholesky_scale_apply(gsl_matrix * A, const gsl_vector * S); GSL_FUN int gsl_linalg_cholesky_decomp2(gsl_matrix * A, gsl_vector * S); GSL_FUN int gsl_linalg_cholesky_svx2 (const gsl_matrix * LLT, const gsl_vector * S, gsl_vector * x); GSL_FUN int gsl_linalg_cholesky_solve2 (const gsl_matrix * LLT, const gsl_vector * S, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_cholesky_rcond (const gsl_matrix * LLT, double * rcond, gsl_vector * work); /* Complex Cholesky Decomposition */ GSL_FUN int gsl_linalg_complex_cholesky_decomp (gsl_matrix_complex * A); GSL_FUN int gsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky, const gsl_vector_complex * b, gsl_vector_complex * x); GSL_FUN int gsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky, gsl_vector_complex * x); GSL_FUN int gsl_linalg_complex_cholesky_invert(gsl_matrix_complex * cholesky); /* Pivoted Cholesky LDLT decomposition */ GSL_FUN int gsl_linalg_pcholesky_decomp (gsl_matrix * A, gsl_permutation * p); GSL_FUN int gsl_linalg_pcholesky_solve(const gsl_matrix * LDLT, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_pcholesky_svx(const gsl_matrix * LDLT, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_pcholesky_decomp2(gsl_matrix * A, gsl_permutation * p, gsl_vector * S); GSL_FUN int gsl_linalg_pcholesky_solve2(const gsl_matrix * LDLT, const gsl_permutation * p, const gsl_vector * S, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_pcholesky_svx2(const gsl_matrix * LDLT, const gsl_permutation * p, const gsl_vector * S, gsl_vector * x); GSL_FUN int gsl_linalg_pcholesky_invert(const gsl_matrix * LDLT, const gsl_permutation * p, gsl_matrix * Ainv); GSL_FUN int gsl_linalg_pcholesky_rcond (const gsl_matrix * LDLT, const gsl_permutation * p, double * rcond, gsl_vector * work); /* Modified Cholesky decomposition */ GSL_FUN int gsl_linalg_mcholesky_decomp (gsl_matrix * A, gsl_permutation * p, gsl_vector * E); GSL_FUN int gsl_linalg_mcholesky_solve(const gsl_matrix * LDLT, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_mcholesky_svx(const gsl_matrix * LDLT, const gsl_permutation * p, gsl_vector * x); GSL_FUN int gsl_linalg_mcholesky_rcond (const gsl_matrix * LDLT, const gsl_permutation * p, double * rcond, gsl_vector * work); GSL_FUN int gsl_linalg_mcholesky_invert(const gsl_matrix * LDLT, const gsl_permutation * p, gsl_matrix * Ainv); /* Banded Cholesky decomposition */ GSL_FUN int gsl_linalg_cholesky_band_decomp(gsl_matrix * A); GSL_FUN int gsl_linalg_cholesky_band_solve (const gsl_matrix * LLT, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_cholesky_band_svx (const gsl_matrix * LLT, gsl_vector * x); GSL_FUN int gsl_linalg_cholesky_band_invert (const gsl_matrix * LLT, gsl_matrix * Ainv); GSL_FUN int gsl_linalg_cholesky_band_unpack (const gsl_matrix * LLT, gsl_matrix * L); GSL_FUN int gsl_linalg_cholesky_band_rcond (const gsl_matrix * LLT, double * rcond, gsl_vector * work); /* L D L^T decomposition */ GSL_FUN int gsl_linalg_ldlt_decomp (gsl_matrix * A); GSL_FUN int gsl_linalg_ldlt_solve (const gsl_matrix * LDLT, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_ldlt_svx (const gsl_matrix * LDLT, gsl_vector * x); GSL_FUN int gsl_linalg_ldlt_rcond (const gsl_matrix * LDLT, double * rcond, gsl_vector * work); /* Banded L D L^T decomposition */ GSL_FUN int gsl_linalg_ldlt_band_decomp (gsl_matrix * A); GSL_FUN int gsl_linalg_ldlt_band_solve (const gsl_matrix * LDLT, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_ldlt_band_svx (const gsl_matrix * LDLT, gsl_vector * x); GSL_FUN int gsl_linalg_ldlt_band_unpack (const gsl_matrix * LDLT, gsl_matrix * L, gsl_vector * D); GSL_FUN int gsl_linalg_ldlt_band_rcond (const gsl_matrix * LDLT, double * rcond, gsl_vector * work); /* Symmetric to symmetric tridiagonal decomposition */ GSL_FUN int gsl_linalg_symmtd_decomp (gsl_matrix * A, gsl_vector * tau); GSL_FUN int gsl_linalg_symmtd_unpack (const gsl_matrix * A, const gsl_vector * tau, gsl_matrix * Q, gsl_vector * diag, gsl_vector * subdiag); GSL_FUN int gsl_linalg_symmtd_unpack_T (const gsl_matrix * A, gsl_vector * diag, gsl_vector * subdiag); /* Hermitian to symmetric tridiagonal decomposition */ GSL_FUN int gsl_linalg_hermtd_decomp (gsl_matrix_complex * A, gsl_vector_complex * tau); GSL_FUN int gsl_linalg_hermtd_unpack (const gsl_matrix_complex * A, const gsl_vector_complex * tau, gsl_matrix_complex * U, gsl_vector * diag, gsl_vector * sudiag); GSL_FUN int gsl_linalg_hermtd_unpack_T (const gsl_matrix_complex * A, gsl_vector * diag, gsl_vector * subdiag); /* Linear Solve Using Householder Transformations * exceptions: */ GSL_FUN int gsl_linalg_HH_solve (gsl_matrix * A, const gsl_vector * b, gsl_vector * x); GSL_FUN int gsl_linalg_HH_svx (gsl_matrix * A, gsl_vector * x); /* Linear solve for a symmetric tridiagonal system. * The input vectors represent the NxN matrix as follows: * * diag[0] offdiag[0] 0 ... * offdiag[0] diag[1] offdiag[1] ... * 0 offdiag[1] diag[2] ... * 0 0 offdiag[2] ... * ... ... ... ... */ GSL_FUN int gsl_linalg_solve_symm_tridiag (const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * b, gsl_vector * x); /* Linear solve for a nonsymmetric tridiagonal system. * The input vectors represent the NxN matrix as follows: * * diag[0] abovediag[0] 0 ... * belowdiag[0] diag[1] abovediag[1] ... * 0 belowdiag[1] diag[2] ... * 0 0 belowdiag[2] ... * ... ... ... ... */ GSL_FUN int gsl_linalg_solve_tridiag (const gsl_vector * diag, const gsl_vector * abovediag, const gsl_vector * belowdiag, const gsl_vector * b, gsl_vector * x); /* Linear solve for a symmetric cyclic tridiagonal system. * The input vectors represent the NxN matrix as follows: * * diag[0] offdiag[0] 0 ..... offdiag[N-1] * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] ..... * 0 0 offdiag[2] ..... * ... ... * offdiag[N-1] ... */ GSL_FUN int gsl_linalg_solve_symm_cyc_tridiag (const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * b, gsl_vector * x); /* Linear solve for a nonsymmetric cyclic tridiagonal system. * The input vectors represent the NxN matrix as follows: * * diag[0] abovediag[0] 0 ..... belowdiag[N-1] * belowdiag[0] diag[1] abovediag[1] ..... * 0 belowdiag[1] diag[2] * 0 0 belowdiag[2] ..... * ... ... * abovediag[N-1] ... */ GSL_FUN int gsl_linalg_solve_cyc_tridiag (const gsl_vector * diag, const gsl_vector * abovediag, const gsl_vector * belowdiag, const gsl_vector * b, gsl_vector * x); /* Bidiagonal decomposition */ GSL_FUN int gsl_linalg_bidiag_decomp (gsl_matrix * A, gsl_vector * tau_U, gsl_vector * tau_V); GSL_FUN int gsl_linalg_bidiag_unpack (const gsl_matrix * A, const gsl_vector * tau_U, gsl_matrix * U, const gsl_vector * tau_V, gsl_matrix * V, gsl_vector * diag, gsl_vector * superdiag); GSL_FUN int gsl_linalg_bidiag_unpack2 (gsl_matrix * A, gsl_vector * tau_U, gsl_vector * tau_V, gsl_matrix * V); GSL_FUN int gsl_linalg_bidiag_unpack_B (const gsl_matrix * A, gsl_vector * diag, gsl_vector * superdiag); /* Balancing */ GSL_FUN int gsl_linalg_balance_matrix (gsl_matrix * A, gsl_vector * D); GSL_FUN int gsl_linalg_balance_accum (gsl_matrix * A, gsl_vector * D); GSL_FUN int gsl_linalg_balance_columns (gsl_matrix * A, gsl_vector * D); /* condition estimation */ GSL_FUN int gsl_linalg_tri_rcond(CBLAS_UPLO_t Uplo, const gsl_matrix * A, double * rcond, gsl_vector * work); GSL_FUN int gsl_linalg_tri_upper_rcond(const gsl_matrix * A, double * rcond, gsl_vector * work); GSL_FUN int gsl_linalg_tri_lower_rcond(const gsl_matrix * A, double * rcond, gsl_vector * work); GSL_FUN int gsl_linalg_invnorm1(const size_t N, int (* Ainvx)(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params), void * params, double * Ainvnorm, gsl_vector * work); /* triangular matrices */ GSL_FUN int gsl_linalg_tri_upper_invert(gsl_matrix * T); GSL_FUN int gsl_linalg_tri_lower_invert(gsl_matrix * T); GSL_FUN int gsl_linalg_tri_upper_unit_invert(gsl_matrix * T); GSL_FUN int gsl_linalg_tri_lower_unit_invert(gsl_matrix * T); GSL_FUN int gsl_linalg_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T); GSL_FUN int gsl_linalg_complex_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T); GSL_FUN int gsl_linalg_tri_LTL(gsl_matrix * L); GSL_FUN int gsl_linalg_tri_UL(gsl_matrix * LU); GSL_FUN int gsl_linalg_complex_tri_LHL(gsl_matrix_complex * L); GSL_FUN int gsl_linalg_complex_tri_UL(gsl_matrix_complex * LU); GSL_FUN INLINE_DECL void gsl_linalg_givens (const double a, const double b, double *c, double *s); GSL_FUN INLINE_DECL void gsl_linalg_givens_gv (gsl_vector * v, const size_t i, const size_t j, const double c, const double s); #ifdef HAVE_INLINE /* Generate a Givens rotation (cos,sin) which takes v=(x,y) to (|v|,0) From Golub and Van Loan, "Matrix Computations", Section 5.1.8 */ INLINE_FUN void gsl_linalg_givens (const double a, const double b, double *c, double *s) { if (b == 0) { *c = 1; *s = 0; } else if (fabs (b) > fabs (a)) { double t = -a / b; double s1 = 1.0 / sqrt (1 + t * t); *s = s1; *c = s1 * t; } else { double t = -b / a; double c1 = 1.0 / sqrt (1 + t * t); *c = c1; *s = c1 * t; } } /* gsl_linalg_givens() */ INLINE_FUN void gsl_linalg_givens_gv (gsl_vector * v, const size_t i, const size_t j, const double c, const double s) { /* Apply rotation to vector v' = G^T v */ double vi = gsl_vector_get (v, i); double vj = gsl_vector_get (v, j); gsl_vector_set (v, i, c * vi - s * vj); gsl_vector_set (v, j, s * vi + c * vj); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_LINALG_H__ */
{ "alphanum_fraction": 0.5938533997, "avg_line_length": 39.4670588235, "ext": "h", "hexsha": "ebe3f607ee7049111caa5f7a5935c016e46d83bb", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "zhanghe9704/jspec2", "max_forks_repo_path": "include/gsl/gsl_linalg.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "zhanghe9704/jspec2", "max_issues_repo_path": "include/gsl/gsl_linalg.h", "max_line_length": 122, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "zhanghe9704/jspec2", "max_stars_repo_path": "include/gsl/gsl_linalg.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": 8136, "size": 33547 }
/* * Copyright 2017 RIS. * Authored by Ron Dahlgren <ron@red83.net> */ #include "entities.h" #include "utility/lists.h" #include <stdlib.h> #include <string.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> vector* entity_vec; entity_info entity_template; entity_info** working_copy; static void no_op_renderer(double deltaT, entity_info *e) { } static sd_result initialize() { gsl_matrix_view frame_view; const int starting_size = 10; working_copy = malloc(sizeof(void*) * starting_size); entity_vec = vector_ops.vector_alloc(starting_size); /* Set the desired template values */ entity_template.shader = shaders.load_material(MAT_ID_BASIC_ALPHA); entity_template.renderer = no_op_renderer; bzero(&entity_template.animation_state, sizeof(animation_state)); bzero(&entity_template.math_context, sizeof(math_context)); /* First the reference frame */ frame_view = gsl_matrix_view_array(entity_template.reference_frame, 4, 4); gsl_matrix_set_identity(&frame_view.matrix); /* Now the transform */ frame_view = gsl_matrix_view_array(entity_template.transform, 4, 4); gsl_matrix_set_identity(&frame_view.matrix); entity_template.initialize = NULL; entity_template.terminate = NULL; entity_template.pre_update = NULL; entity_template.post_update = NULL; entity_template.data = NULL; return SD_OK; } static sd_result release_resources() { entity_info *cursor = NULL; while ((cursor = vector_ops.pop(entity_vec)) != NULL) { if (cursor->terminate != NULL) { cursor->terminate(cursor); } entities.entity_free(cursor); } return SD_OK; } static sd_result terminate() { release_resources(); vector_ops.vector_free(&entity_vec); free(working_copy); return SD_OK; } void add_entity(entity_info* info) { vector_ops.append(entity_vec, info); // Resize buffer int size = entity_vec->size; free(working_copy); working_copy = malloc(sizeof(void*) * size); // initialize the entity if (info->initialize != NULL) { info->initialize(info); } } void remove_entity(entity_info* info) { int located_index = -1; unsigned int i; for (i = 0; i < entity_vec->size; ++i) { if (entity_vec->storage[i] == info) { located_index = i; break; } } if (located_index >= 0) { vector_ops.remove(entity_vec, located_index); // terminate the entity if (info->terminate != NULL) { info->terminate(info); } } } void update(double deltaT) { int size = entity_vec->size; /* TODO Safety lock here */ memcpy(working_copy, entity_vec->storage, sizeof(void*) * size); /* TODO End safety lock here */ /* Update the entities */ entity_info *cursor = NULL; for (int i = 0; i < size; i++) { cursor = working_copy[i]; if (cursor->pre_update) { cursor->pre_update(deltaT, cursor); } // UPDATE! // animation transform_animation.animate_entity(deltaT, working_copy[i]); gsl_matrix_view transform_view = gsl_matrix_view_array( cursor->transform, 4, 4); gsl_matrix_view frame_view = gsl_matrix_view_array( cursor->reference_frame, 4, 4); // Apply the animation if necessary if (cursor->animation_state.current_cycle != NULL) { animation_state *state = &cursor->animation_state; int reverse = state->playback_speed < 0; state->current_cycle->get_transform( state->current_cycle_time, state->playback_mode, reverse, state->current_cycle->data, state->animation_solution); gsl_matrix_view animation_view = gsl_matrix_view_array( state->animation_solution, 4, 4); // T = Frame * Anim gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &frame_view.matrix, &animation_view.matrix, 0.0, &transform_view.matrix); } else { gsl_matrix_memcpy(&transform_view.matrix, &frame_view.matrix); } // physics? if (cursor->post_update) { cursor->post_update(deltaT, cursor); } } } entity_info* entity_alloc() { entity_info* result = (entity_info*)malloc(sizeof(entity_info)); memcpy(result, &entity_template, sizeof(entity_info)); return result; } void entity_free(entity_info* info) { free(info); } entities_struct const entities = { .initialize=initialize, .release_resources=release_resources, .terminate=terminate, .entity_alloc=entity_alloc, .entity_free=entity_free, .add_entity=add_entity, .remove_entity=remove_entity, .update=update };
{ "alphanum_fraction": 0.7039711191, "avg_line_length": 28.2292993631, "ext": "c", "hexsha": "b9b92e1c3c3d09a350b6477756cc34e55e28e91c", "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": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "influenza/c8", "max_forks_repo_path": "src/entities/entities.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "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": "influenza/c8", "max_issues_repo_path": "src/entities/entities.c", "max_line_length": 127, "max_stars_count": null, "max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "influenza/c8", "max_stars_repo_path": "src/entities/entities.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1080, "size": 4432 }
static char help[] = "Solves the p-Helmholtz equation in 2D using Q_1 FEM. Option prefix -ph_.\n" "Problem is posed as minimizing this objective functional over W^{1,p}\n" "for p>1:\n" " I[u] = int_Omega (1/p) |grad u|^p + (1/2) u^2 - f u.\n" "The strong form equation, namely setting the gradient to zero, is a PDE\n" " - div( |grad u|^{p-2} grad u ) + u = f\n" "subject to homogeneous Neumann boundary conditions. Implements objective\n" "and gradient (residual) but no Hessian (Jacobian). Defaults to linear\n" "problem (p=2) and quadrature degree 2. Can be run with only an objective\n" "function; use -ph_no_gradient -snes_fd_function.\n\n"; #include <petsc.h> #include "../interlude/quadrature.h" typedef struct { PetscReal p, eps; PetscInt quadpts; PetscReal (*f)(PetscReal x, PetscReal y, PetscReal p, PetscReal eps); } PHelmCtx; static PetscReal f_constant(PetscReal x, PetscReal y, PetscReal p, PetscReal eps) { return 1.0; } static PetscReal u_exact_cosines(PetscReal x, PetscReal y, PetscReal p, PetscReal eps) { return PetscCosReal(PETSC_PI * x) * PetscCosReal(PETSC_PI * y); } static PetscReal f_cosines(PetscReal x, PetscReal y, PetscReal p, PetscReal eps) { const PetscReal uu = u_exact_cosines(x,y,p,eps), pi2 = PETSC_PI * PETSC_PI, lapu = - 2 * pi2 * uu; if (p == 2.0) { return - lapu + uu; } else { const PetscReal ux = - PETSC_PI * PetscSinReal(PETSC_PI * x) * PetscCosReal(PETSC_PI * y), uy = - PETSC_PI * PetscCosReal(PETSC_PI * x) * PetscSinReal(PETSC_PI * y), // note regularization changes f(x,y) but not u(x,y): w = ux * ux + uy * uy + eps * eps, pi3 = pi2 * PETSC_PI, wx = pi3 * PetscSinReal(2 * PETSC_PI * x) * PetscCosReal(2 * PETSC_PI * y), wy = pi3 * PetscCosReal(2 * PETSC_PI * x) * PetscSinReal(2 * PETSC_PI * y); const PetscReal s = (p - 2) / 2; // -1/2 <= s <= 0 return - s * PetscPowScalar(w,s-1) * (wx * ux + wy * uy) - PetscPowScalar(w,s) * lapu + uu; } } typedef enum {CONSTANT, COSINES} ProblemType; static const char* ProblemTypes[] = {"constant","cosines", "ProblemType", "", NULL}; extern PetscErrorCode GetVecFromFunction(DMDALocalInfo*, Vec, PetscReal (*)(PetscReal, PetscReal, PetscReal, PetscReal), PHelmCtx*); extern PetscErrorCode FormObjectiveLocal(DMDALocalInfo*, PetscReal**, PetscReal*, PHelmCtx*); extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal**, PetscReal**, PHelmCtx*); int main(int argc,char **argv) { PetscErrorCode ierr; DM da; SNES snes; Vec u_initial, u, u_exact; PHelmCtx user; DMDALocalInfo info; ProblemType problem = COSINES; PetscBool no_objective = PETSC_FALSE, no_gradient = PETSC_FALSE, exact_init = PETSC_FALSE, view_f = PETSC_FALSE; PetscReal err; ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr; user.p = 2.0; user.eps = 0.0; user.quadpts = 2; ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"ph_", "p-Helmholtz solver options",""); CHKERRQ(ierr); ierr = PetscOptionsReal("-eps", "regularization parameter eps", "phelm.c",user.eps,&(user.eps),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-exact_init", "use exact solution to initialize", "phelm.c",exact_init,&(exact_init),NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-no_objective", "do not set the objective evaluation function", "phelm.c",no_objective,&(no_objective),NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-no_gradient", "do not set the residual evaluation function", "phelm.c",no_gradient,&(no_gradient),NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-p", "exponent p > 1", "phelm.c",user.p,&(user.p),NULL); CHKERRQ(ierr); if (user.p < 1.0) { SETERRQ(PETSC_COMM_SELF,1,"p >= 1 required"); } if (user.p == 1.0) { ierr = PetscPrintf(PETSC_COMM_WORLD, "WARNING: well-posedness only known for p > 1\n"); CHKERRQ(ierr); } ierr = PetscOptionsEnum("-problem", "problem type determines right side f(x,y)", "phelm.c",ProblemTypes,(PetscEnum)problem,(PetscEnum*)&problem, NULL); CHKERRQ(ierr); ierr = PetscOptionsInt("-quadpts", "number n of quadrature points in each direction (= 1,2,3 only)", "phelm.c",user.quadpts,&(user.quadpts),NULL); CHKERRQ(ierr); if ((user.quadpts < 1) || (user.quadpts > 3)) { SETERRQ(PETSC_COMM_SELF,3,"quadrature points n=1,2,3 only"); } ierr = PetscOptionsBool("-view_f", "view right-hand side to STDOUT", "phelm.c",view_f,&(view_f),NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX, 2,2,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,-1.0,-1.0); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetDM(snes,da); CHKERRQ(ierr); if (!no_objective) { ierr = DMDASNESSetObjectiveLocal(da, (DMDASNESObjective)FormObjectiveLocal,&user); CHKERRQ(ierr); } if (no_gradient) { // why isn't this the default? why no programmatic way to set? ierr = PetscOptionsSetValue(NULL,"-snes_fd_function_eps","0.0"); CHKERRQ(ierr); } else { ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr); } ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); // set initial iterate and right-hand side ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr); ierr = VecSet(u_initial,0.5); CHKERRQ(ierr); switch (problem) { case CONSTANT: if (exact_init) { ierr = VecSet(u_initial,1.0); CHKERRQ(ierr); } user.f = &f_constant; break; case COSINES: if (exact_init) { ierr = GetVecFromFunction(&info,u_initial,&u_exact_cosines,&user); CHKERRQ(ierr); } user.f = &f_cosines; break; default: SETERRQ(PETSC_COMM_SELF,4,"unknown problem type\n"); } // optionally view right-hand-side on initial grid if (view_f) { Vec vf; ierr = VecDuplicate(u_initial,&vf); CHKERRQ(ierr); switch (problem) { case CONSTANT: ierr = VecSet(vf,1.0); CHKERRQ(ierr); break; case COSINES: ierr = GetVecFromFunction(&info,vf,&f_cosines,&user); CHKERRQ(ierr); break; } ierr = VecView(vf,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); VecDestroy(&vf); } // solve and clean up ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr); ierr = VecDestroy(&u_initial); CHKERRQ(ierr); ierr = DMDestroy(&da); CHKERRQ(ierr); ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); ierr = SNESGetDM(snes,&da); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); // evaluate numerical error ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr); switch (problem) { case CONSTANT: ierr = VecSet(u_exact,1.0); CHKERRQ(ierr); break; case COSINES: ierr = GetVecFromFunction(&info,u_exact,&u_exact_cosines,&user); CHKERRQ(ierr); break; } ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact ierr = VecNorm(u,NORM_INFINITY,&err); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "done on %d x %d grid with p=%.3f ...\n" " numerical error: |u-u_exact|_inf = %.3e\n", info.mx,info.my,user.p,err); CHKERRQ(ierr); VecDestroy(&u_exact); SNESDestroy(&snes); return PetscFinalize(); } PetscErrorCode GetVecFromFunction(DMDALocalInfo *info, Vec w, PetscReal (*fcn)(PetscReal, PetscReal, PetscReal, PetscReal), PHelmCtx *user) { PetscErrorCode ierr; const PetscReal hx = 1.0 / (info->mx - 1), hy = 1.0 / (info->my - 1); PetscReal x, y, **aw; PetscInt i, j; ierr = DMDAVecGetArray(info->da,w,&aw); CHKERRQ(ierr); for (j = info->ys; j < info->ys + info->ym; j++) { y = j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { x = i * hx; aw[j][i] = (*fcn)(x,y,user->p,user->eps); } } ierr = DMDAVecRestoreArray(info->da,w,&aw); CHKERRQ(ierr); return 0; } //STARTFEM static PetscReal xiL[4] = { 1.0, -1.0, -1.0, 1.0}, etaL[4] = { 1.0, 1.0, -1.0, -1.0}; static PetscReal chi(PetscInt L, PetscReal xi, PetscReal eta) { return 0.25 * (1.0 + xiL[L] * xi) * (1.0 + etaL[L] * eta); } // evaluate v(xi,eta) on reference element using local node numbering static PetscReal eval(const PetscReal v[4], PetscReal xi, PetscReal eta) { return v[0] * chi(0,xi,eta) + v[1] * chi(1,xi,eta) + v[2] * chi(2,xi,eta) + v[3] * chi(3,xi,eta); } typedef struct { PetscReal xi, eta; } gradRef; static gradRef dchi(PetscInt L, PetscReal xi, PetscReal eta) { const gradRef result = {0.25 * xiL[L] * (1.0 + etaL[L] * eta), 0.25 * etaL[L] * (1.0 + xiL[L] * xi)}; return result; } // evaluate partial derivs of v(xi,eta) on reference element static gradRef deval(const PetscReal v[4], PetscReal xi, PetscReal eta) { gradRef sum = {0.0,0.0}, tmp; PetscInt L; for (L=0; L<4; L++) { tmp = dchi(L,xi,eta); sum.xi += v[L] * tmp.xi; sum.eta += v[L] * tmp.eta; } return sum; } static PetscReal GradInnerProd(PetscReal hx, PetscReal hy, gradRef du, gradRef dv) { const PetscReal cx = 4.0 / (hx * hx), cy = 4.0 / (hy * hy); return cx * du.xi * dv.xi + cy * du.eta * dv.eta; } static PetscReal GradPow(PetscReal hx, PetscReal hy, gradRef du, PetscReal P, PetscReal eps) { return PetscPowScalar(GradInnerProd(hx,hy,du,du) + eps*eps, P/2.0); } //ENDFEM /* FLOPS: (counting PetscPowScalar as 1) chi = 6 eval = 4*6+7 = 31 dchi = 8 deval = 4*8+4 = 36 GradInnerProd = 9 GradPow = 9+4 = 13 ObjIntegrandRef = deval + 2*eval + GradPow + 10 = 121 FunIntegrandRef = chi + dchi + 2*eval + deval + GradPo + GradInnerProd + 9 = 143 */ //STARTOBJECTIVE static PetscReal ObjIntegrandRef(DMDALocalInfo *info, const PetscReal ff[4], const PetscReal uu[4], PetscReal xi, PetscReal eta, PHelmCtx *user) { const gradRef du = deval(uu,xi,eta); const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1), u = eval(uu,xi,eta); return GradPow(hx,hy,du,user->p,0.0) / user->p + 0.5 * u * u - eval(ff,xi,eta) * u; } PetscErrorCode FormObjectiveLocal(DMDALocalInfo *info, PetscReal **au, PetscReal *obj, PHelmCtx *user) { PetscErrorCode ierr; const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1); const Quad1D q = gausslegendre[user->quadpts-1]; PetscReal x, y, lobj = 0.0; PetscInt i,j,r,s; MPI_Comm com; // loop over all elements for (j = info->ys; j < info->ys + info->ym; j++) { if (j == 0) continue; y = j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { if (i == 0) continue; x = i * hx; const PetscReal ff[4] = {user->f(x,y,user->p,user->eps), user->f(x-hx,y,user->p,user->eps), user->f(x-hx,y-hy,user->p,user->eps), user->f(x,y-hy,user->p,user->eps)}; const PetscReal uu[4] = {au[j][i],au[j][i-1], au[j-1][i-1],au[j-1][i]}; // loop over quadrature points on this element for (r = 0; r < q.n; r++) { for (s = 0; s < q.n; s++) { lobj += q.w[r] * q.w[s] * ObjIntegrandRef(info,ff,uu, q.xi[r],q.xi[s],user); } } } } lobj *= hx * hy / 4.0; // from change of variables formula ierr = PetscObjectGetComm((PetscObject)(info->da),&com); CHKERRQ(ierr); ierr = MPI_Allreduce(&lobj,obj,1,MPIU_REAL,MPIU_SUM,com); CHKERRQ(ierr); ierr = PetscLogFlops(129*info->xm*info->ym); CHKERRQ(ierr); return 0; } //ENDOBJECTIVE //STARTFUNCTION static PetscReal IntegrandRef(DMDALocalInfo *info, PetscInt L, const PetscReal ff[4], const PetscReal uu[4], PetscReal xi, PetscReal eta, PHelmCtx *user) { const gradRef du = deval(uu,xi,eta), dchiL = dchi(L,xi,eta); const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1); return GradPow(hx,hy,du,user->p - 2.0,user->eps) * GradInnerProd(hx,hy,du,dchiL) + (eval(uu,xi,eta) - eval(ff,xi,eta)) * chi(L,xi,eta); } PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal **au, PetscReal **FF, PHelmCtx *user) { PetscErrorCode ierr; const PetscReal hx = 1.0 / (info->mx-1), hy = 1.0 / (info->my-1); const Quad1D q = gausslegendre[user->quadpts-1]; const PetscInt li[4] = {0,-1,-1,0}, lj[4] = {0,0,-1,-1}; PetscReal x, y; PetscInt i,j,l,r,s,PP,QQ; // clear residuals for (j = info->ys; j < info->ys + info->ym; j++) for (i = info->xs; i < info->xs + info->xm; i++) FF[j][i] = 0.0; // loop over all elements for (j = info->ys; j <= info->ys + info->ym; j++) { if ((j == 0) || (j > info->my-1)) continue; y = j * hy; for (i = info->xs; i <= info->xs + info->xm; i++) { if ((i == 0) || (i > info->mx-1)) continue; x = i * hx; const PetscReal ff[4] = {user->f(x,y,user->p,user->eps), user->f(x-hx,y,user->p,user->eps), user->f(x-hx,y-hy,user->p,user->eps), user->f(x,y-hy,user->p,user->eps)}; const PetscReal uu[4] = {au[j][i],au[j][i-1], au[j-1][i-1],au[j-1][i]}; // loop over corners of element i,j for (l = 0; l < 4; l++) { PP = i + li[l]; QQ = j + lj[l]; // only update residual if we own node if (PP >= info->xs && PP < info->xs + info->xm && QQ >= info->ys && QQ < info->ys + info->ym) { // loop over quadrature points for (r = 0; r < q.n; r++) { for (s = 0; s < q.n; s++) { FF[QQ][PP] += 0.25 * hx * hy * q.w[r] * q.w[s] * IntegrandRef(info,l,ff,uu, q.xi[r],q.xi[s],user); } } } } } } ierr = PetscLogFlops((5+q.n*q.n*149)*(info->xm+1)*(info->ym+1)); CHKERRQ(ierr); return 0; } //ENDFUNCTION
{ "alphanum_fraction": 0.5394302101, "avg_line_length": 39.4127764128, "ext": "c", "hexsha": "02251bd1617d52ff3b21433a630b59f449f4d055", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch9/phelm.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch9/phelm.c", "max_line_length": 133, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch9/phelm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 4803, "size": 16041 }
/* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_errno.h> /* Compile all the inline functions */ #define COMPILE_INLINE_STATIC #include "build.h" #include <gsl/gsl_qrng.h>
{ "alphanum_fraction": 0.7086956522, "avg_line_length": 16.4285714286, "ext": "c", "hexsha": "5b9c8b560b964cd4588d28763bc962d37f92c35f", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/qrng/inline.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/qrng/inline.c", "max_line_length": 38, "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/qrng/inline.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": 61, "size": 230 }
#include <ceed.h> #include <petsc.h> #include "../include/bcfunctions.h" // ----------------------------------------------------------------------------- // Boundary Conditions // ----------------------------------------------------------------------------- // Diff boundary condition function PetscErrorCode BCsDiff(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt num_comp_u, PetscScalar *u, void *ctx) { // *INDENT-OFF* #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // *INDENT-ON* const CeedScalar c[3] = { 0, 1., 2. }; const CeedScalar k[3] = { 1., 2., 3. }; PetscFunctionBeginUser; for (PetscInt i = 0; i < num_comp_u; i++) u[i] = sin(M_PI*(c[0] + k[0]*x[0])) * sin(M_PI*(c[1] + k[1]*x[1])) * sin(M_PI*(c[2] + k[2]*x[2])); PetscFunctionReturn(0); } // Mass boundary condition function PetscErrorCode BCsMass(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt num_comp_u, PetscScalar *u, void *ctx) { PetscFunctionBeginUser; for (PetscInt i = 0; i < num_comp_u; i++) u[i] = PetscSqrtScalar(PetscSqr(x[0]) + PetscSqr(x[1]) + PetscSqr(x[2])); PetscFunctionReturn(0); } // -----------------------------------------------------------------------------
{ "alphanum_fraction": 0.4882842026, "avg_line_length": 30.7674418605, "ext": "c", "hexsha": "4d5f60b1d996a39b8307e39e549cb3edb30d7bf3", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/petsc/src/bcfunctions.c", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/petsc/src/bcfunctions.c", "max_line_length": 80, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/petsc/src/bcfunctions.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 364, "size": 1323 }
/* matrix/gsl_matrix_complex_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_COMPLEX_FLOAT_H__ #define __GSL_MATRIX_COMPLEX_FLOAT_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_complex_float.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; float * data; gsl_block_complex_float * block; int owner; } gsl_matrix_complex_float ; typedef struct { gsl_matrix_complex_float matrix; } _gsl_matrix_complex_float_view; typedef _gsl_matrix_complex_float_view gsl_matrix_complex_float_view; typedef struct { gsl_matrix_complex_float matrix; } _gsl_matrix_complex_float_const_view; typedef const _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view; /* Allocation */ GSL_EXPORT gsl_matrix_complex_float * gsl_matrix_complex_float_alloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_complex_float * gsl_matrix_complex_float_calloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_complex_float * gsl_matrix_complex_float_alloc_from_block (gsl_block_complex_float * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_EXPORT gsl_matrix_complex_float * gsl_matrix_complex_float_alloc_from_matrix (gsl_matrix_complex_float * b, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_EXPORT gsl_vector_complex_float * gsl_vector_complex_float_alloc_row_from_matrix (gsl_matrix_complex_float * m, const size_t i); GSL_EXPORT gsl_vector_complex_float * gsl_vector_complex_float_alloc_col_from_matrix (gsl_matrix_complex_float * m, const size_t j); GSL_EXPORT void gsl_matrix_complex_float_free (gsl_matrix_complex_float * m); /* Views */ GSL_EXPORT _gsl_matrix_complex_float_view gsl_matrix_complex_float_submatrix (gsl_matrix_complex_float * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_complex_float_view gsl_matrix_complex_float_row (gsl_matrix_complex_float * m, const size_t i); GSL_EXPORT _gsl_vector_complex_float_view gsl_matrix_complex_float_column (gsl_matrix_complex_float * m, const size_t j); GSL_EXPORT _gsl_vector_complex_float_view gsl_matrix_complex_float_diagonal (gsl_matrix_complex_float * m); GSL_EXPORT _gsl_vector_complex_float_view gsl_matrix_complex_float_subdiagonal (gsl_matrix_complex_float * m, const size_t k); GSL_EXPORT _gsl_vector_complex_float_view gsl_matrix_complex_float_superdiagonal (gsl_matrix_complex_float * m, const size_t k); GSL_EXPORT _gsl_matrix_complex_float_view gsl_matrix_complex_float_view_array (float * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_float_view gsl_matrix_complex_float_view_array_with_tda (float * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_complex_float_view gsl_matrix_complex_float_view_vector (gsl_vector_complex_float * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_float_view gsl_matrix_complex_float_view_vector_with_tda (gsl_vector_complex_float * v, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_submatrix (const gsl_matrix_complex_float * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_complex_float_const_view gsl_matrix_complex_float_const_row (const gsl_matrix_complex_float * m, const size_t i); GSL_EXPORT _gsl_vector_complex_float_const_view gsl_matrix_complex_float_const_column (const gsl_matrix_complex_float * m, const size_t j); GSL_EXPORT _gsl_vector_complex_float_const_view gsl_matrix_complex_float_const_diagonal (const gsl_matrix_complex_float * m); GSL_EXPORT _gsl_vector_complex_float_const_view gsl_matrix_complex_float_const_subdiagonal (const gsl_matrix_complex_float * m, const size_t k); GSL_EXPORT _gsl_vector_complex_float_const_view gsl_matrix_complex_float_const_superdiagonal (const gsl_matrix_complex_float * m, const size_t k); GSL_EXPORT _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view_array (const float * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view_array_with_tda (const float * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view_vector (const gsl_vector_complex_float * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view_vector_with_tda (const gsl_vector_complex_float * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_EXPORT gsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x); GSL_EXPORT gsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j); GSL_EXPORT const gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_complex_float_set_zero (gsl_matrix_complex_float * m); GSL_EXPORT void gsl_matrix_complex_float_set_identity (gsl_matrix_complex_float * m); GSL_EXPORT void gsl_matrix_complex_float_set_all (gsl_matrix_complex_float * m, gsl_complex_float x); GSL_EXPORT int gsl_matrix_complex_float_fread (FILE * stream, gsl_matrix_complex_float * m) ; GSL_EXPORT int gsl_matrix_complex_float_fwrite (FILE * stream, const gsl_matrix_complex_float * m) ; GSL_EXPORT int gsl_matrix_complex_float_fscanf (FILE * stream, gsl_matrix_complex_float * m); GSL_EXPORT int gsl_matrix_complex_float_fprintf (FILE * stream, const gsl_matrix_complex_float * m, const char * format); GSL_EXPORT int gsl_matrix_complex_float_memcpy(gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src); GSL_EXPORT int gsl_matrix_complex_float_swap(gsl_matrix_complex_float * m1, gsl_matrix_complex_float * m2); GSL_EXPORT int gsl_matrix_complex_float_swap_rows(gsl_matrix_complex_float * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_complex_float_swap_columns(gsl_matrix_complex_float * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_complex_float_swap_rowcol(gsl_matrix_complex_float * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_complex_float_transpose (gsl_matrix_complex_float * m); GSL_EXPORT int gsl_matrix_complex_float_transpose_memcpy (gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src); GSL_EXPORT int gsl_matrix_complex_float_isnull (const gsl_matrix_complex_float * m); GSL_EXPORT int gsl_matrix_complex_float_add (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b); GSL_EXPORT int gsl_matrix_complex_float_sub (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b); GSL_EXPORT int gsl_matrix_complex_float_mul_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b); GSL_EXPORT int gsl_matrix_complex_float_div_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b); GSL_EXPORT int gsl_matrix_complex_float_scale (gsl_matrix_complex_float * a, const gsl_complex_float x); GSL_EXPORT int gsl_matrix_complex_float_add_constant (gsl_matrix_complex_float * a, const gsl_complex_float x); GSL_EXPORT int gsl_matrix_complex_float_add_diagonal (gsl_matrix_complex_float * a, const gsl_complex_float x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_EXPORT int gsl_matrix_complex_float_get_row(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t i); GSL_EXPORT int gsl_matrix_complex_float_get_col(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t j); GSL_EXPORT int gsl_matrix_complex_float_set_row(gsl_matrix_complex_float * m, const size_t i, const gsl_vector_complex_float * v); GSL_EXPORT int gsl_matrix_complex_float_set_col(gsl_matrix_complex_float * m, const size_t j, const gsl_vector_complex_float * v); #ifdef HAVE_INLINE extern inline gsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK gsl_complex_float zero = {{0,0}}; if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ; } #endif return *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ; } extern inline void gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) = x ; } extern inline gsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ; } extern inline const gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_MATRIX_COMPLEX_FLOAT_H__ */
{ "alphanum_fraction": 0.7110196978, "avg_line_length": 37.399408284, "ext": "h", "hexsha": "3f4a66e658bd75b6b435e641039b8d52e4a3ff7b", "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_matrix_complex_float.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_matrix_complex_float.h", "max_line_length": 140, "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_matrix_complex_float.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2867, "size": 12641 }
#pragma once #include "iarg.h" #include "optioninfo.h" #include "configaccess.h" #include "format.h" #include "streamreader.h" #include <gsl/gsl> #include <cmdlime/errors.h> #include <cmdlime/customnames.h> #include <sstream> #include <functional> #include <memory> namespace cmdlime::detail{ template <typename T> class Arg : public IArg{ public: Arg(std::string name, std::string type, std::function<T&()> argGetter) : info_(std::move(name), {}, std::move(type)) , argGetter_(std::move(argGetter)) { } OptionInfo& info() override { return info_; } const OptionInfo& info() const override { return info_; } private: bool read(const std::string& data) override { auto stream = std::stringstream{data}; return readFromStream(stream, argGetter_()); } private: OptionInfo info_; std::function<T&()> argGetter_; }; template <> inline bool Arg<std::string>::read(const std::string& data) { argGetter_() = data; return true; } template<typename T, typename TConfig> class ArgCreator{ using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider; public: ArgCreator(TConfig& cfg, const std::string& varName, const std::string& type, std::function<T&()> argGetter) : cfg_(cfg) { Expects(!varName.empty()); Expects(!type.empty()); arg_ = std::make_unique<Arg<T>>(NameProvider::fullName(varName), NameProvider::valueName(type), std::move(argGetter)); } ArgCreator<T, TConfig>& operator<<(const std::string& info) { arg_->info().addDescription(info); return *this; } ArgCreator<T, TConfig>& operator<<(const Name& customName) { arg_->info().resetName(customName.value()); return *this; } ArgCreator<T, TConfig>& operator<<(const ValueName& valueName) { arg_->info().resetValueName(valueName.value()); return *this; } operator T() { ConfigAccess<TConfig>{cfg_}.addArg(std::move(arg_)); return T{}; } private: std::unique_ptr<Arg<T>> arg_; TConfig& cfg_; }; template <typename T, typename TConfig> ArgCreator<T, TConfig> makeArgCreator(TConfig& cfg, const std::string& varName, const std::string& type, std::function<T&()> argGetter) { return ArgCreator<T, TConfig>{cfg, varName, type, std::move(argGetter)}; } }
{ "alphanum_fraction": 0.5741911491, "avg_line_length": 23.796460177, "ext": "h", "hexsha": "2919c483ba83fb5c0d0142986ceda1fd39e23d6d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arg.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arg.h", "max_line_length": 88, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/arg.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 622, "size": 2689 }
#ifndef OPENMC_TALLIES_FILTER_MU_H #define OPENMC_TALLIES_FILTER_MU_H #include <vector> #include <gsl/gsl> #include "openmc/tallies/filter.h" namespace openmc { //============================================================================== //! Bins the incoming-outgoing direction cosine. This is only used for scatter //! reactions. //============================================================================== class MuFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~MuFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override {return "mu";} void from_xml(pugi::xml_node node) override; void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; std::string text_label(int bin) const override; //---------------------------------------------------------------------------- // Accessors void set_bins(gsl::span<double> bins); private: //---------------------------------------------------------------------------- // Data members std::vector<double> bins_; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_MU_H
{ "alphanum_fraction": 0.4718934911, "avg_line_length": 25.5094339623, "ext": "h", "hexsha": "7f6f29e5f7e581ae6ef5d59c2feb92ccd694ec5b", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mehmeturkmen/openmc", "max_forks_repo_path": "include/openmc/tallies/filter_mu.h", "max_issues_count": 9, "max_issues_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mehmeturkmen/openmc", "max_issues_repo_path": "include/openmc/tallies/filter_mu.h", "max_line_length": 84, "max_stars_count": 2, "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_path": "include/openmc/tallies/filter_mu.h", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "num_tokens": 247, "size": 1352 }
/* gsl_histogram2d_oper.c * Copyright (C) 2000 Simone Piccardi * * This library 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 library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /*************************************************************** * * File gsl_histogram2d_oper.c: * Routine to make operation on 2D histograms. * Need GSL library and header. * Contains the routines: * gsl_histogram2d_same_binning check if two histograms have the same binning * gsl_histogram2d_add add two histogram * gsl_histogram2d_sub subctract two histogram * gsl_histogram2d_mult multiply two histogram * gsl_histogram2d_div divide two histogram * gsl_histogram2d_scale scale histogram contents * * Author: S. Piccardi * Jan. 2000 * ***************************************************************/ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram2d.h> /* * gsl_histogram2d_same_binning: * control if two histogram have the * same binning */ int gsl_histogram2d_equal_bins_p (const gsl_histogram2d * h1, const gsl_histogram2d * h2) { if ((h1->nx != h2->nx) || (h1->ny != h2->ny)) { return 0; } { size_t i; /* init ranges */ for (i = 0; i <= (h1->nx); i++) { if (h1->xrange[i] != h2->xrange[i]) { return 0; } } for (i = 0; i <= (h1->ny); i++) { if (h1->yrange[i] != h2->yrange[i]) { return 0; } } } return 1; } /* * gsl_histogram2d_add: * add two histogram */ int gsl_histogram2d_add (gsl_histogram2d * h1, const gsl_histogram2d * h2) { size_t i; if (!gsl_histogram2d_equal_bins_p (h1, h2)) { GSL_ERROR ("histograms have different binning", GSL_EINVAL); } for (i = 0; i < (h1->nx) * (h1->ny); i++) { h1->bin[i] += h2->bin[i]; } return GSL_SUCCESS; } /* * gsl_histogram2d_sub: * subtract two histogram */ int gsl_histogram2d_sub (gsl_histogram2d * h1, const gsl_histogram2d * h2) { size_t i; if (!gsl_histogram2d_equal_bins_p (h1, h2)) { GSL_ERROR ("histograms have different binning", GSL_EINVAL); } for (i = 0; i < (h1->nx) * (h1->ny); i++) { h1->bin[i] -= h2->bin[i]; } return GSL_SUCCESS; } /* * gsl_histogram2d_mult: * multiply two histogram */ int gsl_histogram2d_mul (gsl_histogram2d * h1, const gsl_histogram2d * h2) { size_t i; if (!gsl_histogram2d_equal_bins_p (h1, h2)) { GSL_ERROR ("histograms have different binning", GSL_EINVAL); } for (i = 0; i < (h1->nx) * (h1->ny); i++) { h1->bin[i] *= h2->bin[i]; } return GSL_SUCCESS; } /* * gsl_histogram2d_div: * divide two histogram */ int gsl_histogram2d_div (gsl_histogram2d * h1, const gsl_histogram2d * h2) { size_t i; if (!gsl_histogram2d_equal_bins_p (h1, h2)) { GSL_ERROR ("histograms have different binning", GSL_EINVAL); } for (i = 0; i < (h1->nx) * (h1->ny); i++) { h1->bin[i] /= h2->bin[i]; } return GSL_SUCCESS; } /* * gsl_histogram2d_scale: * scale a histogram by a numeric factor */ int gsl_histogram2d_scale (gsl_histogram2d * h, double scale) { size_t i; for (i = 0; i < (h->nx) * (h->ny); i++) { h->bin[i] *= scale; } return GSL_SUCCESS; } /* * gsl_histogram2d_shift: * shift a histogram by a numeric offset */ int gsl_histogram2d_shift (gsl_histogram2d * h, double shift) { size_t i; for (i = 0; i < (h->nx) * (h->ny); i++) { h->bin[i] += shift; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5956898571, "avg_line_length": 20.9264705882, "ext": "c", "hexsha": "bd6b72e8cf8338d3730ec402f82209de9bd9dcd3", "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/histogram/oper2d.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/histogram/oper2d.c", "max_line_length": 78, "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/histogram/oper2d.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": 1269, "size": 4269 }
/* (c) 2016 Greg Lee */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_sf_bessel.h> // union cast macro from Matt Gallagher #define UNION_CAST(x, destType) \ (((union {__typeof__(x) a; destType b;})x).b) long int gsl_sf_bessel_J0_c( long int i) { double result = gsl_sf_bessel_J0( UNION_CAST( i, double ) ); return UNION_CAST( result, long int ); } /* End of file */
{ "alphanum_fraction": 0.6674757282, "avg_line_length": 17.9130434783, "ext": "c", "hexsha": "9684492f0978f5ad30ce6bd759397f4da53417d6", "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": "b65c846e193d31f309a267f35e12b1f72cd0c904", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gleetbone/picolisp-fp", "max_forks_repo_path": "examples/bessel_separate/bessel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b65c846e193d31f309a267f35e12b1f72cd0c904", "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": "gleetbone/picolisp-fp", "max_issues_repo_path": "examples/bessel_separate/bessel.c", "max_line_length": 63, "max_stars_count": 8, "max_stars_repo_head_hexsha": "b65c846e193d31f309a267f35e12b1f72cd0c904", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gleetbone/picolisp-fp", "max_stars_repo_path": "examples/bessel_separate/bessel.c", "max_stars_repo_stars_event_max_datetime": "2019-12-11T13:49:23.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-25T03:44:07.000Z", "num_tokens": 125, "size": 412 }
#ifndef SOURCE_UTILS_H_ #define SOURCE_UTILS_H_ // *** source/utils.h *** // Author: Kevin Wolz, date: 08/2018 // // Various utilities used in the code. #include <fstream> #include <iostream> #include <iomanip> #include <sstream> #include <vector> #include <string> #include <unistd.h> #include <algorithm> #include <stdlib.h> #include <sys/stat.h> #include <time.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 <gsl/gsl_sort_vector.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_cdf.h> std::string Timestamp(); double get_signum(double x); void PrintGslVector(gsl_vector* vector); void PrintGslVector(gsl_vector* vector, std::string label); void PrintGslMatrix(gsl_matrix* matrix); void PrintGslMatrix(gsl_matrix* matrix, std::string label); bool file_exists(const std::string& filename); void AppendTwoGslVectors(gsl_vector* vector1, gsl_vector* vector2, gsl_vector* new_vector); void ConcatenateTwoGslMatrices(gsl_matrix* mmatrix1, gsl_matrix* matrix2, gsl_matrix* new_matrix, bool vertical_axis); void BlockDiagFromTwoGslMatrices(gsl_matrix* matrix1, gsl_matrix* matrix2, gsl_matrix* new_matrix, unsigned int dimnew1, unsigned int dimnew2); void SubtractTwoDoubleVectors(const std::vector<double> &vector1, const std::vector<double> &vector2, std::vector<double> &difference); double GslVec1MatVec2(gsl_vector* vector1, gsl_matrix* matrix, gsl_vector* vector2, int dim); void InvertGslMatrix(gsl_matrix* tobeinverted, unsigned int dim, gsl_matrix* inverted); double DeterminantGslMatrix(gsl_matrix* square_matrix, unsigned int dim); double Vec1MatVec2(std::vector<double> vector1, gsl_matrix* matrix, std::vector<double> vector2, int dim); double TraceGslMatrix(gsl_matrix* square_matrix, int dim); void MultiplyFourGslMatrices(gsl_matrix* matrix1, gsl_matrix* matrix2, gsl_matrix* matrix3, gsl_matrix* matrix4, int dim, gsl_matrix* resulting_matrix); void MultiplyThreeGslMatrices(gsl_matrix* matrix1, gsl_matrix* matrix2, gsl_matrix* matrix3, int dim, gsl_matrix* resulting_matrix); #endif // SOURCE_UTILS_H_
{ "alphanum_fraction": 0.6759880686, "avg_line_length": 30.8275862069, "ext": "h", "hexsha": "fbdd3642a4708ea56c46ca728debcbeef8727ca1", "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/utils.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/utils.h", "max_line_length": 78, "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/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 643, "size": 2682 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "mersenne.h" //#include <lapacke/lapacke.h> #include <stdbool.h> #include <lapacke.h> #include <time.h> #include <sys/time.h> #ifndef M_PI #define M_PI 3.14159265358979323846264338327 #endif /* Lattice size and dimensions */ #define ND 4 /* Size of the lattice dimensions */ static int Ldim[ND] = { 4, 4, 4, 4 }; #define NDIRS (2*ND) int VOLUME; // Choose update method #define WORM_UPDATE //#define LOCAL_UPDATE //Choose spatial boundary conditions (temporal alway antiperiodic) //#define PERIODIC #define ANTIPERIODIC //Uncomment to include site mass in the determinant //(does not work with fluctuation determinant) //#define MASS_IN_MATRIX /* Flavors */ #define N_FLAVOR 2 /* Choose here the method for calculating the derivative */ //#define FULL_DETERMINANT #define FLUCTUATION_DETERMINANT /* Toggle direct measurement for site and link vev */ //#define MEASUREVEV /* Save memory to fit large lattices * Reduces memory use significantly and * slightly increases compute times */ #define SAVE_MEMORY /* field values */ #define UNOCCUPIED 0 #define OCCUPIED 1 #define NONE -100 //A meta value for sites that don't exist /* In Staggered.c */ int site_vector_to_index( int vector[] ); void site_index_to_vector(int index, int vector[] ); void print_config(); /* In fermion_matrix.c */ void Dv( double * y, double * x ); void calc_Dinv( ); double determinant(); void * wrapmalloc( int size, size_t bitsize ); double det_add_monomers(int x1, int x2, int do_flavor[N_FLAVOR]); double det_move_monomers(int x1, int x2, int do_flavor[N_FLAVOR]); double det_remove_monomers(int x1, int x2, int do_flavor[N_FLAVOR]); #ifdef MASS_IN_MATRIX double det_add_monomers1(int x1, int do_flavor[N_FLAVOR]); double det_remove_monomers1(int x1, int do_flavor[N_FLAVOR]); #endif void update_current_determinant( int do_flavor[N_FLAVOR] ); void update_background( int monomer ); void measure_vev( double * linkvev, double * sitevev ); /* update functions */ double worm_update( int *additions, int *removals, int *m_additions, int *m_removals, int *switches ); void local_update( int *additions, int *removals, int *moves,int *m_additions, int *m_removals, int *m_moves, int *switches ); /* Inversions */ void init_Dinv_cg(); void init_Dinv_deprecated(); void cg( double *source );
{ "alphanum_fraction": 0.7474533107, "avg_line_length": 26.1777777778, "ext": "h", "hexsha": "ce1a920d4c7954545fa7df2deb8d38c430541cd8", "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": "9f16f3917890a6853aac40ca10fd0f7e03f8cbfb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rantahar/Staggered-fourfermion", "max_forks_repo_path": "Staggered.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9f16f3917890a6853aac40ca10fd0f7e03f8cbfb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rantahar/Staggered-fourfermion", "max_issues_repo_path": "Staggered.h", "max_line_length": 126, "max_stars_count": 1, "max_stars_repo_head_hexsha": "9f16f3917890a6853aac40ca10fd0f7e03f8cbfb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rantahar/Staggered-fourfermion", "max_stars_repo_path": "Staggered.h", "max_stars_repo_stars_event_max_datetime": "2018-02-15T13:05:32.000Z", "max_stars_repo_stars_event_min_datetime": "2018-02-15T13:05:32.000Z", "num_tokens": 651, "size": 2356 }
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.openairinterface.org/?page_id=698 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /*! \file PHY/LTE_TRANSPORT/dlsch_demodulation.c * \brief Top-level routines for demodulating the PDSCH physical channel from 36-211, V8.6 2009-03 * \author R. Knopp, F. Kaltenberger,A. Bhamri, S. Aubert, X. Xiang * \date 2011 * \version 0.1 * \company Eurecom * \email: knopp@eurecom.fr,florian.kaltenberger@eurecom.fr,ankit.bhamri@eurecom.fr,sebastien.aubert@eurecom.fr * \note * \warning */ #include "PHY/defs_UE.h" #include "PHY/phy_extern_ue.h" #include "SCHED_UE/sched_UE.h" #include "transport_ue.h" #include "transport_proto_ue.h" #include "PHY/sse_intrin.h" #include "T.h" #include<stdio.h> #include<math.h> #include <stdlib.h> #include <string.h> #include <linux/version.h> #if RHEL_RELEASE_CODE >= 1796 #include <lapacke/lapacke_utils.h> #include <lapacke/lapacke.h> #else #include <lapacke_utils.h> #include <lapacke.h> #endif #include <cblas.h> #include "linear_preprocessing_rec.h" #define NOCYGWIN_STATIC //#define DEBUG_MMSE /* dynamic shift for LLR computation for TM3/4 * set as command line argument, see lte-softmodem.c * default value: 0 */ int16_t dlsch_demod_shift = 0; int16_t interf_unaw_shift = 13; //#define DEBUG_HARQ //#define DEBUG_PHY 1 //#define DEBUG_DLSCH_DEMOD 1 //#define DISABLE_LOG_X // [MCS][i_mod (0,1,2) = (2,4,6)] unsigned char offset_mumimo_llr_drange_fix=0; //inferference-free case unsigned char interf_unaw_shift_tm4_mcs[29]= {5, 3, 4, 3, 3, 2, 1, 1, 2, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 2, 1, 0, 1, 0, 1, 0, 0 } ; unsigned char interf_unaw_shift_tm1_mcs[29]= {5, 5, 4, 3, 3, 3, 2, 2, 4, 4, 2, 3, 3, 3, 1, 1, 0, 1, 1, 2, 5, 4, 4, 6, 5, 1, 0, 5, 6 } ; // mcs 21, 26, 28 seem to be errorneous /* //original values from sebastion + same hand tuning unsigned char offset_mumimo_llr_drange[29][3]={{8,8,8},{7,7,7},{7,7,7},{7,7,7},{6,6,6},{6,6,6},{6,6,6},{5,5,5},{4,4,4},{1,2,4}, // QPSK {5,5,4},{5,5,5},{5,5,5},{3,3,3},{2,2,2},{2,2,2},{2,2,2}, // 16-QAM {2,2,1},{3,3,3},{3,3,3},{3,3,1},{2,2,2},{2,2,2},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}; //64-QAM */ /* //first optimization try unsigned char offset_mumimo_llr_drange[29][3]={{7, 8, 7},{6, 6, 7},{6, 6, 7},{6, 6, 6},{5, 6, 6},{5, 5, 6},{5, 5, 6},{4, 5, 4},{4, 3, 4},{3, 2, 2},{6, 5, 5},{5, 4, 4},{5, 5, 4},{3, 3, 2},{2, 2, 1},{2, 1, 1},{2, 2, 2},{3, 3, 3},{3, 3, 2},{3, 3, 2},{3, 2, 1},{2, 2, 2},{2, 2, 2},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}}; */ //second optimization try /* unsigned char offset_mumimo_llr_drange[29][3]={{5, 8, 7},{4, 6, 8},{3, 6, 7},{7, 7, 6},{4, 7, 8},{4, 7, 4},{6, 6, 6},{3, 6, 6},{3, 6, 6},{1, 3, 4},{1, 1, 0},{3, 3, 2},{3, 4, 1},{4, 0, 1},{4, 2, 2},{3, 1, 2},{2, 1, 0},{2, 1, 1},{1, 0, 1},{1, 0, 1},{0, 0, 0},{1, 0, 0},{0, 0, 0},{0, 1, 0},{1, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}}; w */ unsigned char offset_mumimo_llr_drange[29][3]= {{0, 6, 5},{0, 4, 5},{0, 4, 5},{0, 5, 4},{0, 5, 6},{0, 5, 3},{0, 4, 4},{0, 4, 4},{0, 3, 3},{0, 1, 2},{1, 1, 0},{1, 3, 2},{3, 4, 1},{2, 0, 0},{2, 2, 2},{1, 1, 1},{2, 1, 0},{2, 1, 1},{1, 0, 1},{1, 0, 1},{0, 0, 0},{1, 0, 0},{0, 0, 0},{0, 1, 0},{1, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0},{0, 0, 0}}; extern void print_shorts(char *s,int16_t *x); int rx_pdsch(PHY_VARS_UE *ue, PDSCH_t type, unsigned char eNB_id, unsigned char eNB_id_i, //if this == ue->n_connected_eNB, we assume MU interference uint32_t frame, uint8_t subframe, unsigned char symbol, unsigned char first_symbol_flag, RX_type_t rx_type, unsigned char i_mod, unsigned char harq_pid) { LTE_UE_COMMON *common_vars = &ue->common_vars; LTE_UE_PDSCH **pdsch_vars; LTE_DL_FRAME_PARMS *frame_parms = &ue->frame_parms; PHY_MEASUREMENTS *measurements = &ue->measurements; LTE_UE_DLSCH_t **dlsch; int avg[4]; int avg_0[2]; int avg_1[2]; unsigned short mmse_flag=0; #if UE_TIMING_TRACE uint8_t slot = 0; #endif unsigned char aatx,aarx; unsigned short nb_rb = 0, round; int avgs = 0, rb; LTE_DL_UE_HARQ_t *dlsch0_harq,*dlsch1_harq = 0; uint8_t beamforming_mode; uint32_t *rballoc; int32_t **rxdataF_comp_ptr; int32_t **dl_ch_mag_ptr; int32_t codeword_TB0 = -1; int32_t codeword_TB1 = -1; switch (type) { case SI_PDSCH: pdsch_vars = &ue->pdsch_vars_SI[eNB_id]; dlsch = &ue->dlsch_SI[eNB_id]; dlsch0_harq = dlsch[0]->harq_processes[harq_pid]; beamforming_mode = 0; break; case RA_PDSCH: pdsch_vars = &ue->pdsch_vars_ra[eNB_id]; dlsch = &ue->dlsch_ra[eNB_id]; dlsch0_harq = dlsch[0]->harq_processes[harq_pid]; beamforming_mode = 0; break; case PDSCH: pdsch_vars = ue->pdsch_vars[ue->current_thread_id[subframe]]; dlsch = ue->dlsch[ue->current_thread_id[subframe]][eNB_id]; //printf("status TB0 = %d, status TB1 = %d \n", dlsch[0]->harq_processes[harq_pid]->status, dlsch[1]->harq_processes[harq_pid]->status); LOG_D(PHY,"AbsSubframe %d.%d / Sym %d harq_pid %d, harq status %d.%d \n", frame,subframe,symbol,harq_pid, dlsch[0]->harq_processes[harq_pid]->status, dlsch[1]->harq_processes[harq_pid]->status); if ((dlsch[0]->harq_processes[harq_pid]->status == ACTIVE) && (dlsch[1]->harq_processes[harq_pid]->status == ACTIVE)) { codeword_TB0 = dlsch[0]->harq_processes[harq_pid]->codeword; codeword_TB1 = dlsch[1]->harq_processes[harq_pid]->codeword; dlsch0_harq = dlsch[codeword_TB0]->harq_processes[harq_pid]; dlsch1_harq = dlsch[codeword_TB1]->harq_processes[harq_pid]; #ifdef DEBUG_HARQ printf("[DEMOD] I am assuming both TBs are active\n"); #endif } else if ((dlsch[0]->harq_processes[harq_pid]->status == ACTIVE) && (dlsch[1]->harq_processes[harq_pid]->status != ACTIVE) ) { codeword_TB0 = dlsch[0]->harq_processes[harq_pid]->codeword; dlsch0_harq = dlsch[0]->harq_processes[harq_pid]; dlsch1_harq = NULL; codeword_TB1 = -1; #ifdef DEBUG_HARQ printf("[DEMOD] I am assuming only TB0 is active\n"); #endif } else if ((dlsch[0]->harq_processes[harq_pid]->status != ACTIVE) && (dlsch[1]->harq_processes[harq_pid]->status == ACTIVE) ) { codeword_TB1 = dlsch[1]->harq_processes[harq_pid]->codeword; dlsch0_harq = dlsch[1]->harq_processes[harq_pid]; dlsch1_harq = NULL; codeword_TB0 = -1; #ifdef DEBUG_HARQ printf("[DEMOD] I am assuming only TB1 is active, it is in cw %d\n", dlsch0_harq->codeword); #endif } else { LOG_E(PHY,"[UE][FATAL] Frame %d subframe %d: no active DLSCH\n",ue->proc.proc_rxtx[0].frame_rx,subframe); return(-1); } beamforming_mode = ue->transmission_mode[eNB_id]<7?0:ue->transmission_mode[eNB_id]; break; default: LOG_E(PHY,"[UE][FATAL] Frame %d subframe %d: Unknown PDSCH format %d\n",ue->proc.proc_rxtx[0].frame_rx,subframe,type); return(-1); break; } #ifdef DEBUG_HARQ printf("[DEMOD] MIMO mode = %d\n", dlsch0_harq->mimo_mode); printf("[DEMOD] cw for TB0 = %d, cw for TB1 = %d\n", codeword_TB0, codeword_TB1); #endif DevAssert(dlsch0_harq); round = dlsch0_harq->round; //printf("round = %d\n", round); if (eNB_id > 2) { LOG_W(PHY,"dlsch_demodulation.c: Illegal eNB_id %d\n",eNB_id); return(-1); } if (!common_vars) { LOG_W(PHY,"dlsch_demodulation.c: Null common_vars\n"); return(-1); } if (!dlsch[0]) { LOG_W(PHY,"dlsch_demodulation.c: Null dlsch_ue pointer\n"); return(-1); } if (!pdsch_vars) { LOG_W(PHY,"dlsch_demodulation.c: Null pdsch_vars pointer\n"); return(-1); } if (!frame_parms) { LOG_W(PHY,"dlsch_demodulation.c: Null frame_parms\n"); return(-1); } if (((frame_parms->Ncp == NORMAL) && (symbol>=7)) || ((frame_parms->Ncp == EXTENDED) && (symbol>=6))) rballoc = dlsch0_harq->rb_alloc_odd; else rballoc = dlsch0_harq->rb_alloc_even; if (dlsch0_harq->mimo_mode>DUALSTREAM_PUSCH_PRECODING) { LOG_E(PHY,"This transmission mode is not yet supported!\n"); return(-1); } if ((dlsch0_harq->mimo_mode==LARGE_CDD) || ((dlsch0_harq->mimo_mode>=DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode<=DUALSTREAM_PUSCH_PRECODING))) { DevAssert(dlsch1_harq); if (eNB_id!=eNB_id_i) { LOG_E(PHY,"TM3/TM4 requires to set eNB_id==eNB_id_i!\n"); return(-1); } } #if UE_TIMING_TRACE if(symbol > ue->frame_parms.symbols_per_tti>>1) { slot = 1; } #endif #ifdef DEBUG_HARQ printf("Demod dlsch0_harq->pmi_alloc %d\n", dlsch0_harq->pmi_alloc); #endif if (frame_parms->nb_antenna_ports_eNB>1 && beamforming_mode==0) { #ifdef DEBUG_DLSCH_MOD LOG_I(PHY,"dlsch: using pmi %x (%p), rb_alloc %x\n",pmi2hex_2Ar1(dlsch0_harq->pmi_alloc),dlsch[0],dlsch0_harq->rb_alloc_even[0]); #endif #if UE_TIMING_TRACE start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #endif nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id], pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_ch_estimates_ext, dlsch0_harq->pmi_alloc, pdsch_vars[eNB_id]->pmi_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms, dlsch0_harq->mimo_mode); #ifdef DEBUG_DLSCH_MOD printf("dlsch: using pmi %lx, rb_alloc %x, pmi_ext ",pmi2hex_2Ar1(dlsch0_harq->pmi_alloc),*rballoc); for (rb=0; rb<nb_rb; rb++) printf("%d",pdsch_vars[eNB_id]->pmi_ext[rb]); printf("\n"); #endif if (rx_type >= rx_IC_single_stream) { if (eNB_id_i<ue->n_connected_eNB) // we are in TM5 nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id_i], pdsch_vars[eNB_id_i]->rxdataF_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, dlsch0_harq->pmi_alloc, pdsch_vars[eNB_id_i]->pmi_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms, dlsch0_harq->mimo_mode); else nb_rb = dlsch_extract_rbs_dual(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id], pdsch_vars[eNB_id_i]->rxdataF_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, dlsch0_harq->pmi_alloc, pdsch_vars[eNB_id_i]->pmi_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms, dlsch0_harq->mimo_mode); } } else if (beamforming_mode==0) { //else if nb_antennas_ports_eNB==1 && beamforming_mode == 0 nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id], pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_ch_estimates_ext, dlsch0_harq->pmi_alloc, pdsch_vars[eNB_id]->pmi_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms); if (rx_type==rx_IC_single_stream) { if (eNB_id_i<ue->n_connected_eNB) nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id_i], pdsch_vars[eNB_id_i]->rxdataF_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, dlsch0_harq->pmi_alloc, pdsch_vars[eNB_id_i]->pmi_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms); else nb_rb = dlsch_extract_rbs_single(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id], pdsch_vars[eNB_id_i]->rxdataF_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, dlsch0_harq->pmi_alloc, pdsch_vars[eNB_id_i]->pmi_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms); } } else if (beamforming_mode==7) { //else if beamforming_mode == 7 nb_rb = dlsch_extract_rbs_TM7(common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF, pdsch_vars[eNB_id]->dl_bf_ch_estimates, pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext, rballoc, symbol, subframe, ue->high_speed_flag, frame_parms); } else if(beamforming_mode>7) { LOG_W(PHY,"dlsch_demodulation: beamforming mode not supported yet.\n"); } //printf("nb_rb = %d, eNB_id %d\n",nb_rb,eNB_id); if (nb_rb==0) { // LOG_D(PHY,"dlsch_demodulation.c: nb_rb=0\n"); return(-1); } #if UE_TIMING_TRACE stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #if DISABLE_LOG_X printf("[AbsSFN %d.%d] Slot%d Symbol %d Flag %d type %d: Pilot/Data extraction %5.2f \n",frame,subframe,slot, symbol,ue->high_speed_flag,type,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #else LOG_I(PHY, "[AbsSFN %d.%d] Slot%d Symbol %d Flag %d type %d: Pilot/Data extraction %5.2f \n",frame,subframe,slot,symbol, ue->high_speed_flag,type,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #endif #endif #if UE_TIMING_TRACE start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #endif aatx = frame_parms->nb_antenna_ports_eNB; aarx = frame_parms->nb_antennas_rx; dlsch_scale_channel(pdsch_vars[eNB_id]->dl_ch_estimates_ext, frame_parms, dlsch, symbol, nb_rb); if ((dlsch0_harq->mimo_mode<DUALSTREAM_UNIFORM_PRECODING1) && (rx_type==rx_IC_single_stream) && (eNB_id_i==ue->n_connected_eNB) && (dlsch0_harq->dl_power_off==0) ) { // TM5 two-user dlsch_scale_channel(pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, frame_parms, dlsch, symbol, nb_rb); } #if UE_TIMING_TRACE stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #if DISABLE_LOG_X printf("[AbsSFN %d.%d] Slot%d Symbol %d: Channel Scale %5.2f \n",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #else LOG_I(PHY, "[AbsSFN %d.%d] Slot%d Symbol %d: Channel Scale %5.2f \n",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #endif #endif #if UE_TIMING_TRACE start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #endif if (first_symbol_flag==1) { if (beamforming_mode==0) { if (dlsch0_harq->mimo_mode<LARGE_CDD) { dlsch_channel_level(pdsch_vars[eNB_id]->dl_ch_estimates_ext, frame_parms, avg, symbol, nb_rb); avgs = 0; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) avgs = cmax(avgs,avg[(aatx<<1)+aarx]); pdsch_vars[eNB_id]->log2_maxh = (log2_approx(avgs)/2)+1; } else if ((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) { dlsch_channel_level_TM34(pdsch_vars[eNB_id]->dl_ch_estimates_ext, frame_parms, pdsch_vars[eNB_id]->pmi_ext, avg_0, avg_1, symbol, nb_rb, mmse_flag, dlsch0_harq->mimo_mode); LOG_D(PHY,"Channel Level TM34 avg_0 %d, avg_1 %d, rx_type %d, rx_standard %d, dlsch_demod_shift %d \n", avg_0[0], avg_1[0], rx_type, rx_standard, dlsch_demod_shift); if (rx_type>rx_standard) { avg_0[0] = (log2_approx(avg_0[0])/2) + dlsch_demod_shift;// + 2 ;//+ 4; avg_1[0] = (log2_approx(avg_1[0])/2) + dlsch_demod_shift;// + 2 ;//+ 4; pdsch_vars[eNB_id]->log2_maxh0 = cmax(avg_0[0],0); pdsch_vars[eNB_id]->log2_maxh1 = cmax(avg_1[0],0); // printf("dlsch_demod_shift %d\n", dlsch_demod_shift); } else { avg_0[0] = (log2_approx(avg_0[0])/2) - 13 + interf_unaw_shift; avg_1[0] = (log2_approx(avg_1[0])/2) - 13 + interf_unaw_shift; pdsch_vars[eNB_id]->log2_maxh0 = cmax(avg_0[0],0); pdsch_vars[eNB_id]->log2_maxh1 = cmax(avg_1[0],0); } } else if (dlsch0_harq->mimo_mode<DUALSTREAM_UNIFORM_PRECODING1) { // single-layer precoding (TM5, TM6) if ((rx_type==rx_IC_single_stream) && (eNB_id_i==ue->n_connected_eNB) && (dlsch0_harq->dl_power_off==0)) { dlsch_channel_level_TM56(pdsch_vars[eNB_id]->dl_ch_estimates_ext, frame_parms, pdsch_vars[eNB_id]->pmi_ext, avg, symbol, nb_rb); avg[0] = log2_approx(avg[0]) - 13 + offset_mumimo_llr_drange[dlsch0_harq->mcs][(i_mod>>1)-1]; pdsch_vars[eNB_id]->log2_maxh = cmax(avg[0],0); } else if (dlsch0_harq->dl_power_off==1) { //TM6 dlsch_channel_level(pdsch_vars[eNB_id]->dl_ch_estimates_ext, frame_parms, avg, symbol, nb_rb); avgs = 0; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) avgs = cmax(avgs,avg[(aatx<<1)+aarx]); pdsch_vars[eNB_id]->log2_maxh = (log2_approx(avgs)/2) + 1; pdsch_vars[eNB_id]->log2_maxh++; } } } else if (beamforming_mode==7) dlsch_channel_level_TM7(pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext, frame_parms, avg, symbol, nb_rb); #ifdef UE_DEBUG_TRACE LOG_D(PHY,"[DLSCH] AbsSubframe %d.%d log2_maxh = %d [log2_maxh0 %d log2_maxh1 %d] (%d,%d)\n", frame%1024,subframe, pdsch_vars[eNB_id]->log2_maxh, pdsch_vars[eNB_id]->log2_maxh0, pdsch_vars[eNB_id]->log2_maxh1, avg[0],avgs); //LOG_D(PHY,"[DLSCH] mimo_mode = %d\n", dlsch0_harq->mimo_mode); #endif //wait until pdcch is decoded //proc->channel_level = 1; } /* uint32_t wait = 0; while(proc->channel_level == 0) { usleep(1); wait++; } */ #if T_TRACER if (type == PDSCH) { T(T_UE_PHY_PDSCH_ENERGY, T_INT(eNB_id), T_INT(frame%1024), T_INT(subframe), T_INT(avg[0]), T_INT(avg[1]), T_INT(avg[2]), T_INT(avg[3])); } #endif #if UE_TIMING_TRACE stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #if DISABLE_LOG_X printf("[AbsSFN %d.%d] Slot%d Symbol %d first_symbol_flag %d: Channel Level %5.2f \n",frame,subframe,slot,symbol,first_symbol_flag, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #else LOG_I(PHY, "[AbsSFN %d.%d] Slot%d Symbol %d first_symbol_flag %d: Channel Level %5.2f \n",frame,subframe,slot,symbol,first_symbol_flag, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #endif #endif #if UE_TIMING_TRACE start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #endif if (rx_type==rx_IC_dual_stream && mmse_flag==1) { precode_channel_est(pdsch_vars[eNB_id]->dl_ch_estimates_ext, frame_parms, pdsch_vars[eNB_id], symbol, nb_rb, dlsch0_harq->mimo_mode); mmse_processing_oai(pdsch_vars[eNB_id], frame_parms, measurements, first_symbol_flag, dlsch0_harq->mimo_mode, mmse_flag, 0.0, symbol, nb_rb); } // Now channel compensation if (dlsch0_harq->mimo_mode<LARGE_CDD) { dlsch_channel_compensation(pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, pdsch_vars[eNB_id]->rxdataF_comp0, (aatx>1) ? pdsch_vars[eNB_id]->rho : NULL, frame_parms, symbol, first_symbol_flag, dlsch0_harq->Qm, nb_rb, pdsch_vars[eNB_id]->log2_maxh, measurements); // log2_maxh+I0_shift if (symbol == 5) { LOG_M("rxF_comp_d.m","rxF_c_d",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1); } if ((rx_type==rx_IC_single_stream) && (eNB_id_i<ue->n_connected_eNB)) { dlsch_channel_compensation(pdsch_vars[eNB_id_i]->rxdataF_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, pdsch_vars[eNB_id_i]->dl_ch_mag0, pdsch_vars[eNB_id_i]->dl_ch_magb0, pdsch_vars[eNB_id_i]->rxdataF_comp0, (aatx>1) ? pdsch_vars[eNB_id_i]->rho : NULL, frame_parms, symbol, first_symbol_flag, i_mod, nb_rb, pdsch_vars[eNB_id]->log2_maxh, measurements); // log2_maxh+I0_shift if (symbol == 5) { LOG_M("rxF_comp_d.m","rxF_c_d",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1); LOG_M("rxF_comp_i.m","rxF_c_i",&pdsch_vars[eNB_id_i]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1); } dlsch_dual_stream_correlation(frame_parms, symbol, nb_rb, pdsch_vars[eNB_id]->dl_ch_estimates_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->log2_maxh); } } else if ((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) { dlsch_channel_compensation_TM34(frame_parms, pdsch_vars[eNB_id], measurements, eNB_id, symbol, dlsch0_harq->Qm, dlsch1_harq->Qm, harq_pid, dlsch0_harq->round, dlsch0_harq->mimo_mode, nb_rb, mmse_flag, pdsch_vars[eNB_id]->log2_maxh0, pdsch_vars[eNB_id]->log2_maxh1); if (symbol == 5) { LOG_M("rxF_comp_d00.m","rxF_c_d00",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);// should be QAM LOG_M("rxF_comp_d01.m","rxF_c_d01",&pdsch_vars[eNB_id]->rxdataF_comp0[1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0 LOG_M("rxF_comp_d10.m","rxF_c_d10",&pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0 LOG_M("rxF_comp_d11.m","rxF_c_d11",&pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be QAM } // compute correlation between signal and interference channels (rho12 and rho21) dlsch_dual_stream_correlation(frame_parms, // this is doing h11'*h12 and h21'*h22 symbol, nb_rb, pdsch_vars[eNB_id]->dl_ch_estimates_ext, &(pdsch_vars[eNB_id]->dl_ch_estimates_ext[2]), pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->log2_maxh0); //printf("rho stream1 =%d\n", &pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round] ); //to be optimized (just take complex conjugate) dlsch_dual_stream_correlation(frame_parms, // this is doing h12'*h11 and h22'*h21 symbol, nb_rb, &(pdsch_vars[eNB_id]->dl_ch_estimates_ext[2]), pdsch_vars[eNB_id]->dl_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->log2_maxh1); // printf("rho stream2 =%d\n",&pdsch_vars[eNB_id]->dl_ch_rho2_ext ); //printf("TM3 log2_maxh : %d\n",pdsch_vars[eNB_id]->log2_maxh); if (symbol == 5) { LOG_M("rho0_0.m","rho0_0",&pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);// should be QAM LOG_M("rho2_0.m","rho2_0",&pdsch_vars[eNB_id]->dl_ch_rho2_ext[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0 LOG_M("rho0_1.m.m","rho0_1",&pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0 LOG_M("rho2_1.m","rho2_1",&pdsch_vars[eNB_id]->dl_ch_rho2_ext[1][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be QAM } } else if (dlsch0_harq->mimo_mode<DUALSTREAM_UNIFORM_PRECODING1) {// single-layer precoding (TM5, TM6) if ((rx_type==rx_IC_single_stream) && (eNB_id_i==ue->n_connected_eNB) && (dlsch0_harq->dl_power_off==0)) { dlsch_channel_compensation_TM56(pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->pmi_ext, frame_parms, measurements, eNB_id, symbol, dlsch0_harq->Qm, nb_rb, pdsch_vars[eNB_id]->log2_maxh, dlsch0_harq->dl_power_off); for (rb=0; rb<nb_rb; rb++) { switch(pdsch_vars[eNB_id]->pmi_ext[rb]) { case 0: pdsch_vars[eNB_id_i]->pmi_ext[rb]=1; break; case 1: pdsch_vars[eNB_id_i]->pmi_ext[rb]=0; break; case 2: pdsch_vars[eNB_id_i]->pmi_ext[rb]=3; break; case 3: pdsch_vars[eNB_id_i]->pmi_ext[rb]=2; break; } // if (rb==0) // printf("pmi %d, pmi_i %d\n",pdsch_vars[eNB_id]->pmi_ext[rb],pdsch_vars[eNB_id_i]->pmi_ext[rb]); } dlsch_channel_compensation_TM56(pdsch_vars[eNB_id_i]->rxdataF_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, pdsch_vars[eNB_id_i]->dl_ch_mag0, pdsch_vars[eNB_id_i]->dl_ch_magb0, pdsch_vars[eNB_id_i]->rxdataF_comp0, pdsch_vars[eNB_id_i]->pmi_ext, frame_parms, measurements, eNB_id_i, symbol, i_mod, nb_rb, pdsch_vars[eNB_id]->log2_maxh, dlsch0_harq->dl_power_off); if (symbol==5) { LOG_M("rxF_comp_d.m","rxF_c_d",&pdsch_vars[eNB_id]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1); LOG_M("rxF_comp_i.m","rxF_c_i",&pdsch_vars[eNB_id_i]->rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1); } dlsch_dual_stream_correlation(frame_parms, symbol, nb_rb, pdsch_vars[eNB_id]->dl_ch_estimates_ext, pdsch_vars[eNB_id_i]->dl_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->log2_maxh); } else if (dlsch0_harq->dl_power_off==1) { dlsch_channel_compensation_TM56(pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->pmi_ext, frame_parms, measurements, eNB_id, symbol, dlsch0_harq->Qm, nb_rb, pdsch_vars[eNB_id]->log2_maxh, 1); } } else if (dlsch0_harq->mimo_mode==TM7) { //TM7 dlsch_channel_compensation(pdsch_vars[eNB_id]->rxdataF_ext, pdsch_vars[eNB_id]->dl_bf_ch_estimates_ext, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, pdsch_vars[eNB_id]->rxdataF_comp0, (aatx>1) ? pdsch_vars[eNB_id]->rho : NULL, frame_parms, symbol, first_symbol_flag, get_Qm(dlsch0_harq->mcs), nb_rb, //9, pdsch_vars[eNB_id]->log2_maxh, measurements); // log2_maxh+I0_shift } #if UE_TIMING_TRACE stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #if DISABLE_LOG_X printf("[AbsSFN %d.%d] Slot%d Symbol %d log2_maxh %d channel_level %d: Channel Comp %5.2f \n",frame,subframe,slot,symbol,pdsch_vars[eNB_id]->log2_maxh,proc->channel_level, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #else LOG_I(PHY, "[AbsSFN %d.%d] Slot%d Symbol %d log2_maxh %d Channel Comp %5.2f \n",frame,subframe,slot,symbol,pdsch_vars[eNB_id]->log2_maxh, ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #endif #endif // MRC #if UE_TIMING_TRACE start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #endif if (frame_parms->nb_antennas_rx > 1) { if ((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) { // TM3 or TM4 if (frame_parms->nb_antenna_ports_eNB == 2) { dlsch_detection_mrc_TM34(frame_parms, pdsch_vars[eNB_id], harq_pid, dlsch0_harq->round, symbol, nb_rb, 1); if (symbol == 5) { LOG_M("rho0_mrc.m","rho0_0",&pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round][0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);// should be QAM LOG_M("rho2_mrc.m","rho2_0",&pdsch_vars[eNB_id]->dl_ch_rho2_ext[0][symbol*frame_parms->N_RB_DL*12],frame_parms->N_RB_DL*12,1,1);//should be almost 0 } } } else { dlsch_detection_mrc(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id_i]->rxdataF_comp0, pdsch_vars[eNB_id]->rho, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, pdsch_vars[eNB_id_i]->dl_ch_mag0, pdsch_vars[eNB_id_i]->dl_ch_magb0, symbol, nb_rb, rx_type==rx_IC_single_stream); } } // printf("Combining"); if ((dlsch0_harq->mimo_mode == SISO) || ((dlsch0_harq->mimo_mode >= UNIFORM_PRECODING11) && (dlsch0_harq->mimo_mode <= PUSCH_PRECODING0)) || (dlsch0_harq->mimo_mode == TM7)) { /* dlsch_siso(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp, pdsch_vars[eNB_id_i]->rxdataF_comp, symbol, nb_rb); */ } else if (dlsch0_harq->mimo_mode == ALAMOUTI) { dlsch_alamouti(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, symbol, nb_rb); } // printf("LLR"); if ((dlsch0_harq->mimo_mode == LARGE_CDD) || ((dlsch0_harq->mimo_mode >=DUALSTREAM_UNIFORM_PRECODING1) && (dlsch0_harq->mimo_mode <=DUALSTREAM_PUSCH_PRECODING))) { rxdataF_comp_ptr = pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round]; dl_ch_mag_ptr = pdsch_vars[eNB_id]->dl_ch_mag1[harq_pid][round]; } else { rxdataF_comp_ptr = pdsch_vars[eNB_id_i]->rxdataF_comp0; dl_ch_mag_ptr = pdsch_vars[eNB_id_i]->dl_ch_mag0; //i_mod should have been passed as a parameter } #if UE_TIMING_TRACE stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #if DISABLE_LOG_X printf("[AbsSFN %d.%d] Slot%d Symbol %d: Channel Combine %5.2f \n",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #else LOG_I(PHY, "[AbsSFN %d.%d] Slot%d Symbol %d: Channel Combine %5.2f \n",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #endif #endif #if UE_TIMING_TRACE start_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #endif //printf("LLR dlsch0_harq->Qm %d rx_type %d cw0 %d cw1 %d symbol %d \n",dlsch0_harq->Qm,rx_type,codeword_TB0,codeword_TB1,symbol); // compute LLRs // -> // compute @pointer where llrs should filled for this ofdm-symbol int8_t *pllr_symbol_cw0; int8_t *pllr_symbol_cw1; uint32_t llr_offset_symbol; llr_offset_symbol = pdsch_vars[eNB_id]->llr_offset[symbol]; pllr_symbol_cw0 = (int8_t *)pdsch_vars[eNB_id]->llr[0]; pllr_symbol_cw1 = (int8_t *)pdsch_vars[eNB_id]->llr[1]; pllr_symbol_cw0 += llr_offset_symbol; pllr_symbol_cw1 += llr_offset_symbol; /* LOG_I(PHY,"compute LLRs [AbsSubframe %d.%d-%d] NbRB %d Qm %d LLRs-Length %d LLR-Offset %d @LLR Buff %p @LLR Buff(symb) %p\n", frame, subframe,symbol, nb_rb,dlsch0_harq->Qm, pdsch_vars[eNB_id]->llr_length[symbol], pdsch_vars[eNB_id]->llr_offset[symbol], (int16_t*)pdsch_vars[eNB_id]->llr[0], pllr_symbol_cw0); */ switch (dlsch0_harq->Qm) { case 2 : if ((rx_type==rx_standard) || (codeword_TB1 == -1)) { dlsch_qpsk_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, (int16_t *)pllr_symbol_cw0, symbol, first_symbol_flag, nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol), beamforming_mode); } else if (codeword_TB0 == -1) { dlsch_qpsk_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, (int16_t *)pllr_symbol_cw1, symbol, first_symbol_flag, nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol), beamforming_mode); } else if (rx_type >= rx_IC_single_stream) { if (dlsch1_harq->Qm == 2) { dlsch_qpsk_qpsk_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr, pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_qpsk_qpsk_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,2,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } else if (dlsch1_harq->Qm == 4) { dlsch_qpsk_16qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i dl_ch_mag_ptr,//i pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_16qam_qpsk_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i dl_ch_mag_ptr, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } else { dlsch_qpsk_64qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i dl_ch_mag_ptr,//i pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_64qam_qpsk_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i dl_ch_mag_ptr, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } } break; case 4 : if ((rx_type==rx_standard ) || (codeword_TB1 == -1)) { dlsch_16qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->llr[0], pdsch_vars[eNB_id]->dl_ch_mag0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128, beamforming_mode); } else if (codeword_TB0 == -1) { dlsch_16qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->llr[1], pdsch_vars[eNB_id]->dl_ch_mag0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream, beamforming_mode); } else if (rx_type >= rx_IC_single_stream) { if (dlsch1_harq->Qm == 2) { dlsch_16qam_qpsk_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_qpsk_16qam_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i pdsch_vars[eNB_id]->dl_ch_mag0,//i pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,2,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } else if (dlsch1_harq->Qm == 4) { dlsch_16qam_16qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i pdsch_vars[eNB_id]->dl_ch_mag0, dl_ch_mag_ptr,//i pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_16qam_16qam_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i dl_ch_mag_ptr, pdsch_vars[eNB_id]->dl_ch_mag0,//i pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } else { dlsch_16qam_64qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i pdsch_vars[eNB_id]->dl_ch_mag0, dl_ch_mag_ptr,//i pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_64qam_16qam_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0, dl_ch_mag_ptr, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } } break; case 6 : if ((rx_type==rx_standard) || (codeword_TB1 == -1)) { dlsch_64qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, (int16_t *)pllr_symbol_cw0, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr_offset[symbol], beamforming_mode); } else if (codeword_TB0 == -1) { dlsch_64qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, (int16_t *)pllr_symbol_cw1, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr_offset[symbol], beamforming_mode); } else if (rx_type >= rx_IC_single_stream) { if (dlsch1_harq->Qm == 2) { dlsch_64qam_qpsk_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_qpsk_64qam_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,2,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } else if (dlsch1_harq->Qm == 4) { dlsch_64qam_16qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i pdsch_vars[eNB_id]->dl_ch_mag0, dl_ch_mag_ptr,//i pdsch_vars[eNB_id]->dl_ch_rho2_ext, pdsch_vars[eNB_id]->llr[0], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr128); if (rx_type==rx_IC_dual_stream) { dlsch_16qam_64qam_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i dl_ch_mag_ptr, pdsch_vars[eNB_id]->dl_ch_mag0,//i pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], pdsch_vars[eNB_id]->llr[1], symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128_2ndstream); } } else { dlsch_64qam_64qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, rxdataF_comp_ptr,//i pdsch_vars[eNB_id]->dl_ch_mag0, dl_ch_mag_ptr,//i pdsch_vars[eNB_id]->dl_ch_rho2_ext, (int16_t *)pllr_symbol_cw0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr_offset[symbol]); if (rx_type==rx_IC_dual_stream) { dlsch_64qam_64qam_llr(frame_parms, rxdataF_comp_ptr, pdsch_vars[eNB_id]->rxdataF_comp0,//i dl_ch_mag_ptr, pdsch_vars[eNB_id]->dl_ch_mag0,//i pdsch_vars[eNB_id]->dl_ch_rho_ext[harq_pid][round], (int16_t *)pllr_symbol_cw1, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch1_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr_offset[symbol]); } } } break; default: LOG_W(PHY,"rx_dlsch.c : Unknown mod_order!!!!\n"); return(-1); break; } if (dlsch1_harq) { switch (get_Qm(dlsch1_harq->mcs)) { case 2 : if (rx_type==rx_standard) { dlsch_qpsk_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, (int16_t *)pllr_symbol_cw0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,2,subframe,symbol), beamforming_mode); } break; case 4: if (rx_type==rx_standard) { dlsch_16qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, pdsch_vars[eNB_id]->llr[0], pdsch_vars[eNB_id]->dl_ch_mag0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,4,subframe,symbol), pdsch_vars[eNB_id]->llr128, beamforming_mode); } break; case 6 : if (rx_type==rx_standard) { dlsch_64qam_llr(frame_parms, pdsch_vars[eNB_id]->rxdataF_comp0, (int16_t *)pllr_symbol_cw0, pdsch_vars[eNB_id]->dl_ch_mag0, pdsch_vars[eNB_id]->dl_ch_magb0, symbol,first_symbol_flag,nb_rb, adjust_G2(frame_parms,dlsch0_harq->rb_alloc_even,6,subframe,symbol), pdsch_vars[eNB_id]->llr_offset[symbol], beamforming_mode); } break; default: LOG_W(PHY,"rx_dlsch.c : Unknown mod_order!!!!\n"); return(-1); break; } } #if UE_TIMING_TRACE stop_meas(&ue->generic_stat_bis[ue->current_thread_id[subframe]][slot]); #if DISABLE_LOG_X printf("[AbsSFN %d.%d] Slot%d Symbol %d: LLR Computation %5.2f \n",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #else LOG_D(PHY, "[AbsSFN %d.%d] Slot%d Symbol %d: LLR Computation %5.2f \n",frame,subframe,slot,symbol,ue->generic_stat_bis[ue->current_thread_id[subframe]][slot].p_time/(cpuf*1000.0)); #endif #endif // Please keep it: useful for debugging #if 0 if( (symbol == 13) && (subframe==0) && (dlsch0_harq->Qm == 6) /*&& (nb_rb==25)*/) { LOG_E(PHY,"Dump Phy Chan Est \n"); if(1) { #if 1 LOG_M("rxdataF0.m" , "rxdataF0", &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF[0][0],14*frame_parms->ofdm_symbol_size,1,1); //LOG_M("rxdataF1.m" , "rxdataF1", &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].rxdataF[0][0],14*frame_parms->ofdm_symbol_size,1,1); LOG_M("dl_ch_estimates00.m", "dl_ch_estimates00", &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][0][0],14*frame_parms->ofdm_symbol_size,1,1); //LOG_M("dl_ch_estimates01.m", "dl_ch_estimates01", &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][1][0],14*frame_parms->ofdm_symbol_size,1,1); //LOG_M("dl_ch_estimates10.m", "dl_ch_estimates10", &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][2][0],14*frame_parms->ofdm_symbol_size,1,1); //LOG_M("dl_ch_estimates11.m", "dl_ch_estimates11", &common_vars->common_vars_rx_data_per_thread[ue->current_thread_id[subframe]].dl_ch_estimates[eNB_id][3][0],14*frame_parms->ofdm_symbol_size,1,1); //LOG_M("rxdataF_ext00.m" , "rxdataF_ext00", &pdsch_vars[eNB_id]->rxdataF_ext[0][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("rxdataF_ext01.m" , "rxdataF_ext01", &pdsch_vars[eNB_id]->rxdataF_ext[1][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("rxdataF_ext10.m" , "rxdataF_ext10", &pdsch_vars[eNB_id]->rxdataF_ext[2][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("rxdataF_ext11.m" , "rxdataF_ext11", &pdsch_vars[eNB_id]->rxdataF_ext[3][0],14*frame_parms->N_RB_DL*12,1,1); LOG_M("dl_ch_estimates_ext00.m", "dl_ch_estimates_ext00", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[0][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("dl_ch_estimates_ext01.m", "dl_ch_estimates_ext01", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[1][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("dl_ch_estimates_ext10.m", "dl_ch_estimates_ext10", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[2][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("dl_ch_estimates_ext11.m", "dl_ch_estimates_ext11", &pdsch_vars[eNB_id]->dl_ch_estimates_ext[3][0],14*frame_parms->N_RB_DL*12,1,1); LOG_M("rxdataF_comp00.m","rxdataF_comp00", &pdsch_vars[eNB_id]->rxdataF_comp0[0][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("rxdataF_comp01.m","rxdataF_comp01", &pdsch_vars[eNB_id]->rxdataF_comp0[1][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("rxdataF_comp10.m","rxdataF_comp10", &pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][0][0],14*frame_parms->N_RB_DL*12,1,1); //LOG_M("rxdataF_comp11.m","rxdataF_comp11", &pdsch_vars[eNB_id]->rxdataF_comp1[harq_pid][round][1][0],14*frame_parms->N_RB_DL*12,1,1); #endif LOG_M("llr0.m","llr0", &pdsch_vars[eNB_id]->llr[0][0],(14*nb_rb*12*dlsch1_harq->Qm) - 4*(nb_rb*4*dlsch1_harq->Qm),1,0); //LOG_M("llr1.m","llr1", &pdsch_vars[eNB_id]->llr[1][0],(14*nb_rb*12*dlsch1_harq->Qm) - 4*(nb_rb*4*dlsch1_harq->Qm),1,0); AssertFatal(0," "); } } #endif T(T_UE_PHY_PDSCH_IQ, T_INT(eNB_id), T_INT(frame%1024), T_INT(subframe), T_INT(nb_rb), T_INT(frame_parms->N_RB_UL), T_INT(frame_parms->symbols_per_tti), T_BUFFER(&pdsch_vars[eNB_id]->rxdataF_comp0[eNB_id][0], 2 * /* ulsch[UE_id]->harq_processes[harq_pid]->nb_rb */ frame_parms->N_RB_UL *12*frame_parms->symbols_per_tti*2)); return 0; } //============================================================================================== // Pre-processing for LLR computation //============================================================================================== void dlsch_channel_compensation(int **rxdataF_ext, int **dl_ch_estimates_ext, int **dl_ch_mag, int **dl_ch_magb, int **rxdataF_comp, int **rho, LTE_DL_FRAME_PARMS *frame_parms, unsigned char symbol, uint8_t first_symbol_flag, unsigned char mod_order, unsigned short nb_rb, unsigned char output_shift, PHY_MEASUREMENTS *measurements) { #if defined(__i386) || defined(__x86_64) unsigned short rb; unsigned char aatx,aarx,symbol_mod,pilots=0; __m128i *dl_ch128,*dl_ch128_2,*dl_ch_mag128,*dl_ch_mag128b,*rxdataF128,*rxdataF_comp128,*rho128; __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp128; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) { if (frame_parms->nb_antenna_ports_eNB==1) // 10 out of 12 so don't reduce size nb_rb=1+(5*nb_rb/6); else pilots=1; } for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { __m128i QAM_amp128b = _mm_setzero_si128(); if (mod_order == 4) { QAM_amp128 = _mm_set1_epi16(QAM16_n1); // 2/sqrt(10) } else if (mod_order == 6) { QAM_amp128 = _mm_set1_epi16(QAM64_n1); // QAM_amp128b = _mm_set1_epi16(QAM64_n2); } for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { /* TODO: hack to be removed. There is crash for 1 antenna case, so * for 1 antenna case, I put back the value 2 as it was before * Elena's commit. */ int x = frame_parms->nb_antennas_rx > 1 ? frame_parms->nb_antennas_rx : 2; dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12]; //print_shorts("dl_ch128[0]=",&dl_ch128[0]);*/ dl_ch_mag128 = (__m128i *)&dl_ch_mag[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128b = (__m128i *)&dl_ch_magb[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF128 = (__m128i *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128 = (__m128i *)&rxdataF_comp[aatx*x + aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { if (mod_order>2) { // get channel amplitude if not QPSK mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128[0]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_madd_epi16(dl_ch128[1],dl_ch128[1]); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1); // store channel magnitude here in a new field of dlsch dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0); dl_ch_mag128b[0] = dl_ch_mag128[0]; dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0],QAM_amp128); dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0],1); //print_ints("Re(ch):",(int16_t*)&mmtmpD0); //print_shorts("QAM_amp:",(int16_t*)&QAM_amp128); //print_shorts("mag:",(int16_t*)&dl_ch_mag128[0]); dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0); dl_ch_mag128b[1] = dl_ch_mag128[1]; dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1],QAM_amp128); dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1],1); if (pilots==0) { mmtmpD0 = _mm_madd_epi16(dl_ch128[2],dl_ch128[2]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0); dl_ch_mag128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1); dl_ch_mag128b[2] = dl_ch_mag128[2]; dl_ch_mag128[2] = _mm_mulhi_epi16(dl_ch_mag128[2],QAM_amp128); dl_ch_mag128[2] = _mm_slli_epi16(dl_ch_mag128[2],1); } dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0],QAM_amp128b); dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0],1); dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1],QAM_amp128b); dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1],1); if (pilots==0) { dl_ch_mag128b[2] = _mm_mulhi_epi16(dl_ch_mag128b[2],QAM_amp128b); dl_ch_mag128b[2] = _mm_slli_epi16(dl_ch_mag128b[2],1); } } // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[0],rxdataF128[0]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); // print_ints("im",&mmtmpD1); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128); // print_shorts("ch:",dl_ch128); // print_shorts("pack:",rxdataF_comp128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[1],rxdataF128[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+1); // print_shorts("ch:",dl_ch128+1); // print_shorts("pack:",rxdataF_comp128+1); if (pilots==0) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[2],rxdataF128[2]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+2); // print_shorts("ch:",dl_ch128+2); // print_shorts("pack:",rxdataF_comp128+2); dl_ch128+=3; dl_ch_mag128+=3; dl_ch_mag128b+=3; rxdataF128+=3; rxdataF_comp128+=3; } else { // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less dl_ch128+=2; dl_ch_mag128+=2; dl_ch_mag128b+=2; rxdataF128+=2; rxdataF_comp128+=2; } } } } if (rho) { for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { rho128 = (__m128i *)&rho[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch128_2 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128_2[0]); // print_ints("re",&mmtmpD0); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); // print_ints("im",&mmtmpD1); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[0]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rho128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); //print_shorts("rx:",dl_ch128_2); //print_shorts("ch:",dl_ch128); //print_shorts("pack:",rho128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[1],dl_ch128_2[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rho128[1] =_mm_packs_epi32(mmtmpD2,mmtmpD3); //print_shorts("rx:",dl_ch128_2+1); //print_shorts("ch:",dl_ch128+1); //print_shorts("pack:",rho128+1); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[2],dl_ch128_2[2]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[2]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rho128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3); //print_shorts("rx:",dl_ch128_2+2); //print_shorts("ch:",dl_ch128+2); //print_shorts("pack:",rho128+2); dl_ch128+=3; dl_ch128_2+=3; rho128+=3; } if (first_symbol_flag==1) { measurements->rx_correlation[0][aarx] = signal_energy(&rho[aarx][symbol*frame_parms->N_RB_DL*12],rb*12); } } } _mm_empty(); _m_empty(); #elif defined(__arm__) unsigned short rb; unsigned char aatx,aarx,symbol_mod,pilots=0; int16x4_t *dl_ch128,*dl_ch128_2,*rxdataF128; int32x4_t mmtmpD0,mmtmpD1,mmtmpD0b,mmtmpD1b; int16x8_t *dl_ch_mag128,*dl_ch_mag128b,mmtmpD2,mmtmpD3,mmtmpD4; int16x8_t QAM_amp128,QAM_amp128b; int16x4x2_t *rxdataF_comp128,*rho128; int16_t conj[4]__attribute__((aligned(16))) = {1,-1,1,-1}; int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift); symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) { if (frame_parms->nb_antenna_ports_eNB==1) { // 10 out of 12 so don't reduce size nb_rb=1+(5*nb_rb/6); } else { pilots=1; } } for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { if (mod_order == 4) { QAM_amp128 = vmovq_n_s16(QAM16_n1); // 2/sqrt(10) QAM_amp128b = vmovq_n_s16(0); } else if (mod_order == 6) { QAM_amp128 = vmovq_n_s16(QAM64_n1); // QAM_amp128b = vmovq_n_s16(QAM64_n2); } // printf("comp: rxdataF_comp %p, symbol %d\n",rxdataF_comp[0],symbol); for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch128 = (int16x4_t *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128 = (int16x8_t *)&dl_ch_mag[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128b = (int16x8_t *)&dl_ch_magb[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF128 = (int16x4_t *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128 = (int16x4x2_t *)&rxdataF_comp[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { if (mod_order>2) { // get channel amplitude if not QPSK mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128[0]); // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3]; mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128[1]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits mmtmpD0 = vmull_s16(dl_ch128[2], dl_ch128[2]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch128[3], dl_ch128[3]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch128[4], dl_ch128[4]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch128[5], dl_ch128[5]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); } dl_ch_mag128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128b); dl_ch_mag128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128b); dl_ch_mag128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128); dl_ch_mag128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128); if (pilots==0) { dl_ch_mag128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp128b); dl_ch_mag128[2] = vqdmulhq_s16(mmtmpD4,QAM_amp128); } } mmtmpD0 = vmull_s16(dl_ch128[0], rxdataF128[0]); //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])] mmtmpD1 = vmull_s16(dl_ch128[1], rxdataF128[1]); //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])] mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])] mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[0],*(int16x4_t *)conj)), rxdataF128[0]); //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])] mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[1],*(int16x4_t *)conj)), rxdataF128[1]); //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])] mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])] mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp128[0] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch128[2], rxdataF128[2]); mmtmpD1 = vmull_s16(dl_ch128[3], rxdataF128[3]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[2],*(int16x4_t *)conj)), rxdataF128[2]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[3],*(int16x4_t *)conj)), rxdataF128[3]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp128[1] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch128[4], rxdataF128[4]); mmtmpD1 = vmull_s16(dl_ch128[5], rxdataF128[5]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[4],*(int16x4_t *)conj)), rxdataF128[4]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[5],*(int16x4_t *)conj)), rxdataF128[5]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp128[2] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); dl_ch128+=6; dl_ch_mag128+=3; dl_ch_mag128b+=3; rxdataF128+=6; rxdataF_comp128+=3; } else { // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less dl_ch128+=4; dl_ch_mag128+=2; dl_ch_mag128b+=2; rxdataF128+=4; rxdataF_comp128+=2; } } } } if (rho) { for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { rho128 = (int16x4x2_t *)&rho[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch128 = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch128_2 = (int16x4_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128_2[0]); mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128_2[1]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[0],*(int16x4_t *)conj)), dl_ch128_2[0]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[1],*(int16x4_t *)conj)), dl_ch128_2[1]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rho128[0] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch128[2], dl_ch128_2[2]); mmtmpD1 = vmull_s16(dl_ch128[3], dl_ch128_2[3]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[2],*(int16x4_t *)conj)), dl_ch128_2[2]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[3],*(int16x4_t *)conj)), dl_ch128_2[3]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rho128[1] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch128[0], dl_ch128_2[0]); mmtmpD1 = vmull_s16(dl_ch128[1], dl_ch128_2[1]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[4],*(int16x4_t *)conj)), dl_ch128_2[4]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch128[5],*(int16x4_t *)conj)), dl_ch128_2[5]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rho128[2] = vzip_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); dl_ch128+=6; dl_ch128_2+=6; rho128+=3; } if (first_symbol_flag==1) { measurements->rx_correlation[0][aarx] = signal_energy(&rho[aarx][symbol*frame_parms->N_RB_DL*12],rb*12); } } } #endif } void dlsch_channel_compensation_core(int **rxdataF_ext, int **dl_ch_estimates_ext, int **dl_ch_mag, int **dl_ch_magb, int **rxdataF_comp, int **rho, unsigned char n_tx, unsigned char n_rx, unsigned char mod_order, unsigned char output_shift, int length, int start_point) { unsigned short ii; int length_mod8 = 0; int length2; __m128i *dl_ch128,*dl_ch_mag128,*dl_ch_mag128b, *dl_ch128_2, *rxdataF128,*rxdataF_comp128,*rho128; __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp128; int aatx = 0, aarx = 0; for (aatx=0; aatx<n_tx; aatx++) { __m128i QAM_amp128b; if (mod_order == 4) { QAM_amp128 = _mm_set1_epi16(QAM16_n1); // 2/sqrt(10) QAM_amp128b = _mm_setzero_si128(); } else if (mod_order == 6) { QAM_amp128 = _mm_set1_epi16(QAM64_n1); // QAM_amp128b = _mm_set1_epi16(QAM64_n2); } for (aarx=0; aarx<n_rx; aarx++) { /* TODO: hack to be removed. There is crash for 1 antenna case, so * for 1 antenna case, I put back the value 2 as it was before * Elena's commit. */ int x = n_rx > 1 ? n_rx : 2; dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aatx*x + aarx][start_point]; dl_ch_mag128 = (__m128i *)&dl_ch_mag[aatx*x + aarx][start_point]; dl_ch_mag128b = (__m128i *)&dl_ch_magb[aatx*x + aarx][start_point]; rxdataF128 = (__m128i *)&rxdataF_ext[aarx][start_point]; rxdataF_comp128 = (__m128i *)&rxdataF_comp[aatx*x + aarx][start_point]; length_mod8 = length&7; if (length_mod8 == 0) { length2 = length>>3; for (ii=0; ii<length2; ++ii) { if (mod_order>2) { // get channel amplitude if not QPSK mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128[0]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_madd_epi16(dl_ch128[1],dl_ch128[1]); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1); // store channel magnitude here in a new field of dlsch dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0); dl_ch_mag128b[0] = dl_ch_mag128[0]; dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0],QAM_amp128); dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0],1); //print_ints("Re(ch):",(int16_t*)&mmtmpD0); //print_shorts("QAM_amp:",(int16_t*)&QAM_amp128); //print_shorts("mag:",(int16_t*)&dl_ch_mag128[0]); dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0); dl_ch_mag128b[1] = dl_ch_mag128[1]; dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1],QAM_amp128); dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1],1); dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0],QAM_amp128b); dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0],1); dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1],QAM_amp128b); dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1],1); } // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[0],rxdataF128[0]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); // print_ints("im",&mmtmpD1); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128); // print_shorts("ch:",dl_ch128); // print_shorts("pack:",rxdataF_comp128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[1],rxdataF128[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+1); // print_shorts("ch:",dl_ch128+1); //print_shorts("pack:",rxdataF_comp128+1); dl_ch128+=2; dl_ch_mag128+=2; dl_ch_mag128b+=2; rxdataF128+=2; rxdataF_comp128+=2; } } else { printf ("Channel Compensation: Received number of subcarriers is not multiple of 8, \n" "need to adapt the code!\n"); } } } /*This part of code makes sense only for processing in 2x2 blocks*/ if (rho) { for (aarx=0; aarx<n_rx; aarx++) { rho128 = (__m128i *)&rho[aarx][start_point]; dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aarx][start_point]; dl_ch128_2 = (__m128i *)&dl_ch_estimates_ext[2+aarx][start_point]; if (length_mod8 == 0) { length2 = length>>3; for (ii=0; ii<length2; ++ii) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128_2[0]); // print_ints("re",&mmtmpD0); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); // print_ints("im",&mmtmpD1); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[0]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rho128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); //print_shorts("rx:",dl_ch128_2); //print_shorts("ch:",dl_ch128); //print_shorts("pack:",rho128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[1],dl_ch128_2[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128_2[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rho128[1] =_mm_packs_epi32(mmtmpD2,mmtmpD3); dl_ch128+=2; dl_ch128_2+=2; rho128+=2; } } else { printf ("Channel Compensation: Received number of subcarriers is not multiple of 8, \n" "need to adapt the code!\n"); } } } _mm_empty(); _m_empty(); } #if defined(__x86_64__) || defined(__i386__) void prec2A_TM56_128(unsigned char pmi,__m128i *ch0,__m128i *ch1) { __m128i amp; amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15); switch (pmi) { case 0 : // +1 +1 // print_shorts("phase 0 :ch0",ch0); // print_shorts("phase 0 :ch1",ch1); ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]); break; case 1 : // +1 -1 // print_shorts("phase 1 :ch0",ch0); // print_shorts("phase 1 :ch1",ch1); ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]); // print_shorts("phase 1 :ch0-ch1",ch0); break; case 2 : // +1 +j ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]); ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]); break; // +1 -j case 3 : ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]); ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]); break; } ch0[0] = _mm_mulhi_epi16(ch0[0],amp); ch0[0] = _mm_slli_epi16(ch0[0],1); _mm_empty(); _m_empty(); } #elif defined(__arm__) void prec2A_TM56_128(unsigned char pmi,__m128i *ch0,__m128i *ch1) { // sqrt(2) is already taken into account in computation sqrt_rho_a, sqrt_rho_b, //so removed it //__m128i amp; //amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15); switch (pmi) { case 0 : // +1 +1 // print_shorts("phase 0 :ch0",ch0); // print_shorts("phase 0 :ch1",ch1); ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]); break; case 1 : // +1 -1 // print_shorts("phase 1 :ch0",ch0); // print_shorts("phase 1 :ch1",ch1); ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]); // print_shorts("phase 1 :ch0-ch1",ch0); break; case 2 : // +1 +j ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]); ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch0[0] = _mm_subs_epi16(ch0[0],ch1[0]); break; // +1 -j case 3 : ch1[0] = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]); ch1[0] = _mm_shufflelo_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch1[0] = _mm_shufflehi_epi16(ch1[0],_MM_SHUFFLE(2,3,0,1)); ch0[0] = _mm_adds_epi16(ch0[0],ch1[0]); break; } //ch0[0] = _mm_mulhi_epi16(ch0[0],amp); //ch0[0] = _mm_slli_epi16(ch0[0],1); _mm_empty(); _m_empty(); } #endif // precoding is stream 0 .5(1,1) .5(1,-1) .5(1,1) .5(1,-1) // stream 1 .5(1,-1) .5(1,1) .5(1,-1) .5(1,1) // store "precoded" channel for stream 0 in ch0, stream 1 in ch1 short TM3_prec[8]__attribute__((aligned(16))) = {1,1,-1,-1,1,1,-1,-1} ; void prec2A_TM3_128(__m128i *ch0,__m128i *ch1) { __m128i amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15); __m128i tmp0,tmp1; //_mm_mulhi_epi16 // print_shorts("prec2A_TM3 ch0 (before):",ch0); // print_shorts("prec2A_TM3 ch1 (before):",ch1); tmp0 = ch0[0]; tmp1 = _mm_sign_epi16(ch1[0],((__m128i *)&TM3_prec)[0]); // print_shorts("prec2A_TM3 ch1*s (mid):",(__m128i*)TM3_prec); ch0[0] = _mm_adds_epi16(ch0[0],tmp1); ch1[0] = _mm_subs_epi16(tmp0,tmp1); ch0[0] = _mm_mulhi_epi16(ch0[0],amp); ch0[0] = _mm_slli_epi16(ch0[0],1); ch1[0] = _mm_mulhi_epi16(ch1[0],amp); ch1[0] = _mm_slli_epi16(ch1[0],1); // print_shorts("prec2A_TM3 ch0 (mid):",&tmp0); // print_shorts("prec2A_TM3 ch1 (mid):",ch1); //ch0[0] = _mm_mulhi_epi16(ch0[0],amp); //ch0[0] = _mm_slli_epi16(ch0[0],1); //ch1[0] = _mm_mulhi_epi16(ch1[0],amp); //ch1[0] = _mm_slli_epi16(ch1[0],1); //ch0[0] = _mm_srai_epi16(ch0[0],1); //ch1[0] = _mm_srai_epi16(ch1[0],1); // print_shorts("prec2A_TM3 ch0 (after):",ch0); // print_shorts("prec2A_TM3 ch1 (after):",ch1); _mm_empty(); _m_empty(); } // pmi = 0 => stream 0 (1,1), stream 1 (1,-1) // pmi = 1 => stream 0 (1,j), stream 2 (1,-j) void prec2A_TM4_128(int pmi,__m128i *ch0,__m128i *ch1) { // sqrt(2) is already taken into account in computation sqrt_rho_a, sqrt_rho_b, //so divide by 2 is replaced by divide by sqrt(2). // printf ("demod pmi=%d\n", pmi); __m128i amp; amp = _mm_set1_epi16(ONE_OVER_SQRT2_Q15); __m128i tmp0,tmp1; // print_shorts("prec2A_TM4 ch0 (before):",ch0); // print_shorts("prec2A_TM4 ch1 (before):",ch1); if (pmi == 0) { //[1 1;1 -1] tmp0 = ch0[0]; tmp1 = ch1[0]; ch0[0] = _mm_adds_epi16(tmp0,tmp1); ch1[0] = _mm_subs_epi16(tmp0,tmp1); } else { //ch0+j*ch1 ch0-j*ch1 tmp0 = ch0[0]; tmp1 = _mm_sign_epi16(ch1[0],*(__m128i *)&conjugate[0]); tmp1 = _mm_shufflelo_epi16(tmp1,_MM_SHUFFLE(2,3,0,1)); tmp1 = _mm_shufflehi_epi16(tmp1,_MM_SHUFFLE(2,3,0,1)); ch0[0] = _mm_subs_epi16(tmp0,tmp1); ch1[0] = _mm_add_epi16(tmp0,tmp1); } //print_shorts("prec2A_TM4 ch0 (middle):",ch0); //print_shorts("prec2A_TM4 ch1 (middle):",ch1); ch0[0] = _mm_mulhi_epi16(ch0[0],amp); ch0[0] = _mm_slli_epi16(ch0[0],1); ch1[0] = _mm_mulhi_epi16(ch1[0],amp); ch1[0] = _mm_slli_epi16(ch1[0],1); // ch0[0] = _mm_srai_epi16(ch0[0],1); //divide by 2 // ch1[0] = _mm_srai_epi16(ch1[0],1); //divide by 2 //print_shorts("prec2A_TM4 ch0 (end):",ch0); //print_shorts("prec2A_TM4 ch1 (end):",ch1); _mm_empty(); _m_empty(); // print_shorts("prec2A_TM4 ch0 (end):",ch0); //print_shorts("prec2A_TM4 ch1 (end):",ch1); } void dlsch_channel_compensation_TM56(int **rxdataF_ext, int **dl_ch_estimates_ext, int **dl_ch_mag, int **dl_ch_magb, int **rxdataF_comp, unsigned char *pmi_ext, LTE_DL_FRAME_PARMS *frame_parms, PHY_MEASUREMENTS *measurements, int eNB_id, unsigned char symbol, unsigned char mod_order, unsigned short nb_rb, unsigned char output_shift, unsigned char dl_power_off) { #if defined(__x86_64__) || defined(__i386__) unsigned short rb,Nre; __m128i *dl_ch0_128,*dl_ch1_128,*dl_ch_mag128,*dl_ch_mag128b,*rxdataF128,*rxdataF_comp128; unsigned char aarx=0,symbol_mod,pilots=0; int precoded_signal_strength=0; __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp128; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) pilots=1; //printf("comp prec: symbol %d, pilots %d\n",symbol, pilots); __m128i QAM_amp128b = _mm_setzero_si128(); if (mod_order == 4) { QAM_amp128 = _mm_set1_epi16(QAM16_n1); } else if (mod_order == 6) { QAM_amp128 = _mm_set1_epi16(QAM64_n1); QAM_amp128b = _mm_set1_epi16(QAM64_n2); } for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128 = (__m128i *)&dl_ch_mag[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128b = (__m128i *)&dl_ch_magb[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF128 = (__m128i *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128 = (__m128i *)&rxdataF_comp[aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { // combine TX channels using precoder from pmi #ifdef DEBUG_DLSCH_DEMOD printf("mode 6 prec: rb %d, pmi->%d\n",rb,pmi_ext[rb]); #endif prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128[2],&dl_ch1_128[2]); } if (mod_order>2) { // get channel amplitude if not QPSK mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],dl_ch0_128[0]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_madd_epi16(dl_ch0_128[1],dl_ch0_128[1]); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1); dl_ch_mag128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0); dl_ch_mag128b[0] = dl_ch_mag128[0]; dl_ch_mag128[0] = _mm_mulhi_epi16(dl_ch_mag128[0],QAM_amp128); dl_ch_mag128[0] = _mm_slli_epi16(dl_ch_mag128[0],1); //print_shorts("dl_ch_mag128[0]=",&dl_ch_mag128[0]); //print_shorts("dl_ch_mag128[0]=",&dl_ch_mag128[0]); dl_ch_mag128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0); dl_ch_mag128b[1] = dl_ch_mag128[1]; dl_ch_mag128[1] = _mm_mulhi_epi16(dl_ch_mag128[1],QAM_amp128); dl_ch_mag128[1] = _mm_slli_epi16(dl_ch_mag128[1],1); if (pilots==0) { mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],dl_ch0_128[2]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0); dl_ch_mag128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1); dl_ch_mag128b[2] = dl_ch_mag128[2]; dl_ch_mag128[2] = _mm_mulhi_epi16(dl_ch_mag128[2],QAM_amp128); dl_ch_mag128[2] = _mm_slli_epi16(dl_ch_mag128[2],1); } dl_ch_mag128b[0] = _mm_mulhi_epi16(dl_ch_mag128b[0],QAM_amp128b); dl_ch_mag128b[0] = _mm_slli_epi16(dl_ch_mag128b[0],1); //print_shorts("dl_ch_mag128b[0]=",&dl_ch_mag128b[0]); dl_ch_mag128b[1] = _mm_mulhi_epi16(dl_ch_mag128b[1],QAM_amp128b); dl_ch_mag128b[1] = _mm_slli_epi16(dl_ch_mag128b[1],1); if (pilots==0) { dl_ch_mag128b[2] = _mm_mulhi_epi16(dl_ch_mag128b[2],QAM_amp128b); dl_ch_mag128b[2] = _mm_slli_epi16(dl_ch_mag128b[2],1); } } // MF multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],rxdataF128[0]); // print_ints("re",&mmtmpD0); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); // print_ints("im",&mmtmpD1); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rxdataF_comp128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128); // print_shorts("ch:",dl_ch128); // print_shorts("pack:",rxdataF_comp128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch0_128[1],rxdataF128[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+1); // print_shorts("ch:",dl_ch128+1); // print_shorts("pack:",rxdataF_comp128+1); if (pilots==0) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],rxdataF128[2]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[2],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+2); // print_shorts("ch:",dl_ch128+2); // print_shorts("pack:",rxdataF_comp128+2); dl_ch0_128+=3; dl_ch1_128+=3; dl_ch_mag128+=3; dl_ch_mag128b+=3; rxdataF128+=3; rxdataF_comp128+=3; } else { dl_ch0_128+=2; dl_ch1_128+=2; dl_ch_mag128+=2; dl_ch_mag128b+=2; rxdataF128+=2; rxdataF_comp128+=2; } } Nre = (pilots==0) ? 12 : 8; precoded_signal_strength += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre], (nb_rb*Nre))) - (measurements->n0_power[aarx])); } // rx_antennas measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength,measurements->n0_power_tot); //printf("eNB_id %d, symbol %d: precoded CQI %d dB\n",eNB_id,symbol, // measurements->precoded_cqi_dB[eNB_id][0]); #elif defined(__arm__) uint32_t rb,Nre; uint32_t aarx,symbol_mod,pilots=0; int16x4_t *dl_ch0_128,*dl_ch1_128,*rxdataF128; int16x8_t *dl_ch0_128b,*dl_ch1_128b; int32x4_t mmtmpD0,mmtmpD1,mmtmpD0b,mmtmpD1b; int16x8_t *dl_ch_mag128,*dl_ch_mag128b,mmtmpD2,mmtmpD3,mmtmpD4,*rxdataF_comp128; int16x8_t QAM_amp128,QAM_amp128b; int16_t conj[4]__attribute__((aligned(16))) = {1,-1,1,-1}; int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift); int32_t precoded_signal_strength=0; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) { if (frame_parms->nb_antenna_ports_eNB==1) { // 10 out of 12 so don't reduce size nb_rb=1+(5*nb_rb/6); } else { pilots=1; } } if (mod_order == 4) { QAM_amp128 = vmovq_n_s16(QAM16_n1); // 2/sqrt(10) QAM_amp128b = vmovq_n_s16(0); } else if (mod_order == 6) { QAM_amp128 = vmovq_n_s16(QAM64_n1); // QAM_amp128b = vmovq_n_s16(QAM64_n2); } // printf("comp: rxdataF_comp %p, symbol %d\n",rxdataF_comp[0],symbol); for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128 = (int16x4_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch0_128b = (int16x8_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128b = (int16x8_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128 = (int16x8_t *)&dl_ch_mag[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128b = (int16x8_t *)&dl_ch_magb[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF128 = (int16x4_t *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128 = (int16x8_t *)&rxdataF_comp[aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { #ifdef DEBUG_DLSCH_DEMOD printf("mode 6 prec: rb %d, pmi->%u\n",rb,pmi_ext[rb]); #endif prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128b[0],&dl_ch1_128b[0]); prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128b[1],&dl_ch1_128b[1]); if (pilots==0) { prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128b[2],&dl_ch1_128b[2]); } if (mod_order>2) { // get channel amplitude if not QPSK mmtmpD0 = vmull_s16(dl_ch0_128[0], dl_ch0_128[0]); // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3]; mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits mmtmpD1 = vmull_s16(dl_ch0_128[1], dl_ch0_128[1]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits mmtmpD0 = vmull_s16(dl_ch0_128[2], dl_ch0_128[2]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch0_128[3], dl_ch0_128[3]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch0_128[4], dl_ch0_128[4]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch0_128[5], dl_ch0_128[5]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); } dl_ch_mag128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128b); dl_ch_mag128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128b); dl_ch_mag128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp128); dl_ch_mag128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp128); if (pilots==0) { dl_ch_mag128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp128b); dl_ch_mag128[2] = vqdmulhq_s16(mmtmpD4,QAM_amp128); } } mmtmpD0 = vmull_s16(dl_ch0_128[0], rxdataF128[0]); //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])] mmtmpD1 = vmull_s16(dl_ch0_128[1], rxdataF128[1]); //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])] mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])] mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0],*(int16x4_t *)conj)), rxdataF128[0]); //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])] mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1],*(int16x4_t *)conj)), rxdataF128[1]); //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])] mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])] mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp128[0] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch0_128[2], rxdataF128[2]); mmtmpD1 = vmull_s16(dl_ch0_128[3], rxdataF128[3]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2],*(int16x4_t *)conj)), rxdataF128[2]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3],*(int16x4_t *)conj)), rxdataF128[3]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp128[1] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch0_128[4], rxdataF128[4]); mmtmpD1 = vmull_s16(dl_ch0_128[5], rxdataF128[5]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[4],*(int16x4_t *)conj)), rxdataF128[4]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[5],*(int16x4_t *)conj)), rxdataF128[5]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp128[2] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); dl_ch0_128+=6; dl_ch1_128+=6; dl_ch_mag128+=3; dl_ch_mag128b+=3; rxdataF128+=6; rxdataF_comp128+=3; } else { // we have a smaller PDSCH in symbols with pilots so skip last group of 4 REs and increment less dl_ch0_128+=4; dl_ch1_128+=4; dl_ch_mag128+=2; dl_ch_mag128b+=2; rxdataF128+=4; rxdataF_comp128+=2; } } Nre = (pilots==0) ? 12 : 8; precoded_signal_strength += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre], (nb_rb*Nre))) - (measurements->n0_power[aarx])); // rx_antennas } measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength,measurements->n0_power_tot); //printf("eNB_id %d, symbol %d: precoded CQI %d dB\n",eNB_id,symbol, // measurements->precoded_cqi_dB[eNB_id][0]); #endif _mm_empty(); _m_empty(); } void precode_channel_est(int32_t **dl_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, LTE_UE_PDSCH *pdsch_vars, unsigned char symbol, unsigned short nb_rb, MIMO_mode_t mimo_mode) { unsigned short rb; __m128i *dl_ch0_128,*dl_ch1_128; unsigned char aarx=0,symbol_mod,pilots=0; unsigned char *pmi_ext = pdsch_vars->pmi_ext; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) pilots=1; for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; // this is h11 dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; // this is h12 for (rb=0; rb<nb_rb; rb++) { if (mimo_mode==LARGE_CDD) { prec2A_TM3_128(&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM3_128(&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM3_128(&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) { prec2A_TM4_128(0,&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(0,&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(0,&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) { prec2A_TM4_128(1,&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(1,&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(1,&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) { prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[2],&dl_ch1_128[2]); } } else { LOG_E(PHY,"Unknown MIMO mode\n"); return; } if (pilots==0) { dl_ch0_128+=3; dl_ch1_128+=3; } else { dl_ch0_128+=2; dl_ch1_128+=2; } } } } void dlsch_channel_compensation_TM34(LTE_DL_FRAME_PARMS *frame_parms, LTE_UE_PDSCH *pdsch_vars, PHY_MEASUREMENTS *measurements, int eNB_id, unsigned char symbol, unsigned char mod_order0, unsigned char mod_order1, int harq_pid, int round, MIMO_mode_t mimo_mode, unsigned short nb_rb, unsigned short mmse_flag, unsigned char output_shift0, unsigned char output_shift1) { #if defined(__x86_64__) || defined(__i386__) unsigned short rb,Nre; __m128i *dl_ch0_128,*dl_ch1_128,*dl_ch_mag0_128,*dl_ch_mag1_128,*dl_ch_mag0_128b,*dl_ch_mag1_128b,*rxdataF128,*rxdataF_comp0_128,*rxdataF_comp1_128; unsigned char aarx=0,symbol_mod,pilots=0; int precoded_signal_strength0=0,precoded_signal_strength1=0; int rx_power_correction; int **rxdataF_ext = pdsch_vars->rxdataF_ext; int **dl_ch_estimates_ext = pdsch_vars->dl_ch_estimates_ext; int **dl_ch_mag0 = pdsch_vars->dl_ch_mag0; int **dl_ch_mag1 = pdsch_vars->dl_ch_mag1[harq_pid][round]; int **dl_ch_magb0 = pdsch_vars->dl_ch_magb0; int **dl_ch_magb1 = pdsch_vars->dl_ch_magb1[harq_pid][round]; int **rxdataF_comp0 = pdsch_vars->rxdataF_comp0; int **rxdataF_comp1 = pdsch_vars->rxdataF_comp1[harq_pid][round]; unsigned char *pmi_ext = pdsch_vars->pmi_ext; __m128i mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3,QAM_amp0_128,QAM_amp1_128; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) pilots=1; rx_power_correction = 1; // printf("comp prec: symbol %d, pilots %d\n",symbol, pilots); __m128i QAM_amp0_128b = _mm_setzero_si128(); if (mod_order0 == 4) { QAM_amp0_128 = _mm_set1_epi16(QAM16_n1); } else if (mod_order0 == 6) { QAM_amp0_128 = _mm_set1_epi16(QAM64_n1); QAM_amp0_128b = _mm_set1_epi16(QAM64_n2); } __m128i QAM_amp1_128b = _mm_setzero_si128(); if (mod_order1 == 4) { QAM_amp1_128 = _mm_set1_epi16(QAM16_n1); } else if (mod_order1 == 6) { QAM_amp1_128 = _mm_set1_epi16(QAM64_n1); QAM_amp1_128b = _mm_set1_epi16(QAM64_n2); } for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; // this is h11 dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; // this is h12 dl_ch_mag0_128 = (__m128i *)&dl_ch_mag0[aarx][symbol*frame_parms->N_RB_DL*12]; //responsible for x1 dl_ch_mag0_128b = (__m128i *)&dl_ch_magb0[aarx][symbol*frame_parms->N_RB_DL*12];//responsible for x1 dl_ch_mag1_128 = (__m128i *)&dl_ch_mag1[aarx][symbol*frame_parms->N_RB_DL*12]; //responsible for x2. always coming from tx2 dl_ch_mag1_128b = (__m128i *)&dl_ch_magb1[aarx][symbol*frame_parms->N_RB_DL*12]; //responsible for x2. always coming from tx2 rxdataF128 = (__m128i *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; //received signal on antenna of interest h11*x1+h12*x2 rxdataF_comp0_128 = (__m128i *)&rxdataF_comp0[aarx][symbol*frame_parms->N_RB_DL*12]; //result of multipl with MF x1 on antenna of interest rxdataF_comp1_128 = (__m128i *)&rxdataF_comp1[aarx][symbol*frame_parms->N_RB_DL*12]; //result of multipl with MF x2 on antenna of interest for (rb=0; rb<nb_rb; rb++) { if (mmse_flag == 0) { // combine TX channels using precoder from pmi if (mimo_mode==LARGE_CDD) { prec2A_TM3_128(&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM3_128(&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM3_128(&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) { prec2A_TM4_128(0,&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(0,&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(0,&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) { prec2A_TM4_128(1,&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(1,&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(1,&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) { prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128[2],&dl_ch1_128[2]); } } else { LOG_E(PHY,"Unknown MIMO mode\n"); return; } } if (mod_order0>2) { // get channel amplitude if not QPSK mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],dl_ch0_128[0]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0); mmtmpD1 = _mm_madd_epi16(dl_ch0_128[1],dl_ch0_128[1]); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0); mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1); dl_ch_mag0_128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0); dl_ch_mag0_128b[0] = dl_ch_mag0_128[0]; dl_ch_mag0_128[0] = _mm_mulhi_epi16(dl_ch_mag0_128[0],QAM_amp0_128); dl_ch_mag0_128[0] = _mm_slli_epi16(dl_ch_mag0_128[0],1); // print_shorts("dl_ch_mag0_128[0]=",&dl_ch_mag0_128[0]); dl_ch_mag0_128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0); dl_ch_mag0_128b[1] = dl_ch_mag0_128[1]; dl_ch_mag0_128[1] = _mm_mulhi_epi16(dl_ch_mag0_128[1],QAM_amp0_128); dl_ch_mag0_128[1] = _mm_slli_epi16(dl_ch_mag0_128[1],1); if (pilots==0) { mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],dl_ch0_128[2]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0); mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0); dl_ch_mag0_128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1); dl_ch_mag0_128b[2] = dl_ch_mag0_128[2]; dl_ch_mag0_128[2] = _mm_mulhi_epi16(dl_ch_mag0_128[2],QAM_amp0_128); dl_ch_mag0_128[2] = _mm_slli_epi16(dl_ch_mag0_128[2],1); } dl_ch_mag0_128b[0] = _mm_mulhi_epi16(dl_ch_mag0_128b[0],QAM_amp0_128b); dl_ch_mag0_128b[0] = _mm_slli_epi16(dl_ch_mag0_128b[0],1); // print_shorts("dl_ch_mag0_128b[0]=",&dl_ch_mag0_128b[0]); dl_ch_mag0_128b[1] = _mm_mulhi_epi16(dl_ch_mag0_128b[1],QAM_amp0_128b); dl_ch_mag0_128b[1] = _mm_slli_epi16(dl_ch_mag0_128b[1],1); if (pilots==0) { dl_ch_mag0_128b[2] = _mm_mulhi_epi16(dl_ch_mag0_128b[2],QAM_amp0_128b); dl_ch_mag0_128b[2] = _mm_slli_epi16(dl_ch_mag0_128b[2],1); } } if (mod_order1>2) { // get channel amplitude if not QPSK mmtmpD0 = _mm_madd_epi16(dl_ch1_128[0],dl_ch1_128[0]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1); mmtmpD1 = _mm_madd_epi16(dl_ch1_128[1],dl_ch1_128[1]); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1); mmtmpD0 = _mm_packs_epi32(mmtmpD0,mmtmpD1); dl_ch_mag1_128[0] = _mm_unpacklo_epi16(mmtmpD0,mmtmpD0); dl_ch_mag1_128b[0] = dl_ch_mag1_128[0]; dl_ch_mag1_128[0] = _mm_mulhi_epi16(dl_ch_mag1_128[0],QAM_amp1_128); dl_ch_mag1_128[0] = _mm_slli_epi16(dl_ch_mag1_128[0],1); // print_shorts("dl_ch_mag1_128[0]=",&dl_ch_mag1_128[0]); dl_ch_mag1_128[1] = _mm_unpackhi_epi16(mmtmpD0,mmtmpD0); dl_ch_mag1_128b[1] = dl_ch_mag1_128[1]; dl_ch_mag1_128[1] = _mm_mulhi_epi16(dl_ch_mag1_128[1],QAM_amp1_128); dl_ch_mag1_128[1] = _mm_slli_epi16(dl_ch_mag1_128[1],1); if (pilots==0) { mmtmpD0 = _mm_madd_epi16(dl_ch1_128[2],dl_ch1_128[2]); mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1); mmtmpD1 = _mm_packs_epi32(mmtmpD0,mmtmpD0); dl_ch_mag1_128[2] = _mm_unpacklo_epi16(mmtmpD1,mmtmpD1); dl_ch_mag1_128b[2] = dl_ch_mag1_128[2]; dl_ch_mag1_128[2] = _mm_mulhi_epi16(dl_ch_mag1_128[2],QAM_amp1_128); dl_ch_mag1_128[2] = _mm_slli_epi16(dl_ch_mag1_128[2],1); } dl_ch_mag1_128b[0] = _mm_mulhi_epi16(dl_ch_mag1_128b[0],QAM_amp1_128b); dl_ch_mag1_128b[0] = _mm_slli_epi16(dl_ch_mag1_128b[0],1); // print_shorts("dl_ch_mag1_128b[0]=",&dl_ch_mag1_128b[0]); dl_ch_mag1_128b[1] = _mm_mulhi_epi16(dl_ch_mag1_128b[1],QAM_amp1_128b); dl_ch_mag1_128b[1] = _mm_slli_epi16(dl_ch_mag1_128b[1],1); if (pilots==0) { dl_ch_mag1_128b[2] = _mm_mulhi_epi16(dl_ch_mag1_128b[2],QAM_amp1_128b); dl_ch_mag1_128b[2] = _mm_slli_epi16(dl_ch_mag1_128b[2],1); } } // layer 0 // MF multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch0_128[0],rxdataF128[0]); // print_ints("re",&mmtmpD0); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]); // print_ints("im",&mmtmpD1); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0); // printf("Shift: %d\n",output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rxdataF_comp0_128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128); // print_shorts("ch:",dl_ch0_128); //print_shorts("pack:",rxdataF_comp0_128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch0_128[1],rxdataF128[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp0_128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+1); // print_shorts("ch:",dl_ch0_128+1); // print_shorts("pack:",rxdataF_comp0_128+1); if (pilots==0) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch0_128[2],rxdataF128[2]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch0_128[2],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift0); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp0_128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+2); // print_shorts("ch:",dl_ch0_128+2); // print_shorts("pack:",rxdataF_comp0_128+2); } // layer 1 // MF multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch1_128[0],rxdataF128[0]); // print_ints("re",&mmtmpD0); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); // print_ints("im",&mmtmpD1); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[0]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); rxdataF_comp1_128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128); // print_shorts("ch:",dl_ch1_128); // print_shorts("pack:",rxdataF_comp1_128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch1_128[1],rxdataF128[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp1_128[1] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+1); // print_shorts("ch:",dl_ch1_128+1); // print_shorts("pack:",rxdataF_comp1_128+1); if (pilots==0) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch1_128[2],rxdataF128[2]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch1_128[2],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,rxdataF128[2]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift1); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); rxdataF_comp1_128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rx:",rxdataF128+2); // print_shorts("ch:",dl_ch1_128+2); // print_shorts("pack:",rxdataF_comp1_128+2); dl_ch0_128+=3; dl_ch1_128+=3; dl_ch_mag0_128+=3; dl_ch_mag1_128+=3; dl_ch_mag0_128b+=3; dl_ch_mag1_128b+=3; rxdataF128+=3; rxdataF_comp0_128+=3; rxdataF_comp1_128+=3; } else { dl_ch0_128+=2; dl_ch1_128+=2; dl_ch_mag0_128+=2; dl_ch_mag1_128+=2; dl_ch_mag0_128b+=2; dl_ch_mag1_128b+=2; rxdataF128+=2; rxdataF_comp0_128+=2; rxdataF_comp1_128+=2; } } // rb loop Nre = (pilots==0) ? 12 : 8; precoded_signal_strength0 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre], (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx])); precoded_signal_strength1 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx+2][symbol*frame_parms->N_RB_DL*Nre], (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx])); } // rx_antennas measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength0,measurements->n0_power_tot); measurements->precoded_cqi_dB[eNB_id][1] = dB_fixed2(precoded_signal_strength1,measurements->n0_power_tot); // printf("eNB_id %d, symbol %d: precoded CQI %d dB\n",eNB_id,symbol, // measurements->precoded_cqi_dB[eNB_id][0]); _mm_empty(); _m_empty(); #elif defined(__arm__) unsigned short rb,Nre; unsigned char aarx,symbol_mod,pilots=0; int precoded_signal_strength0=0,precoded_signal_strength1=0, rx_power_correction; int16x4_t *dl_ch0_128,*rxdataF128; int16x4_t *dl_ch1_128; int16x8_t *dl_ch0_128b,*dl_ch1_128b; int32x4_t mmtmpD0,mmtmpD1,mmtmpD0b,mmtmpD1b; int16x8_t *dl_ch_mag0_128,*dl_ch_mag0_128b,*dl_ch_mag1_128,*dl_ch_mag1_128b,mmtmpD2,mmtmpD3,mmtmpD4,*rxdataF_comp0_128,*rxdataF_comp1_128; int16x8_t QAM_amp0_128,QAM_amp0_128b,QAM_amp1_128,QAM_amp1_128b; int32x4_t output_shift128 = vmovq_n_s32(-(int32_t)output_shift); int **rxdataF_ext = pdsch_vars->rxdataF_ext; int **dl_ch_estimates_ext = pdsch_vars->dl_ch_estimates_ext; int **dl_ch_mag0 = pdsch_vars->dl_ch_mag0; int **dl_ch_mag1 = pdsch_vars->dl_ch_mag1[harq_pid][round]; int **dl_ch_magb0 = pdsch_vars->dl_ch_magb0; int **dl_ch_magb1 = pdsch_vars->dl_ch_magb1[harq_pid][round]; int **rxdataF_comp0 = pdsch_vars->rxdataF_comp0; int **rxdataF_comp1 = pdsch_vars->rxdataF_comp1[harq_pid][round]; int16_t conj[4]__attribute__((aligned(16))) = {1,-1,1,-1}; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) { if (frame_parms->nb_antenna_ports_eNB==1) { // 10 out of 12 so don't reduce size nb_rb=1+(5*nb_rb/6); } else { pilots=1; } } rx_power_correction=1; if (mod_order0 == 4) { QAM_amp0_128 = vmovq_n_s16(QAM16_n1); // 2/sqrt(10) QAM_amp0_128b = vmovq_n_s16(0); } else if (mod_order0 == 6) { QAM_amp0_128 = vmovq_n_s16(QAM64_n1); // QAM_amp0_128b = vmovq_n_s16(QAM64_n2); } if (mod_order1 == 4) { QAM_amp1_128 = vmovq_n_s16(QAM16_n1); // 2/sqrt(10) QAM_amp1_128b = vmovq_n_s16(0); } else if (mod_order1 == 6) { QAM_amp1_128 = vmovq_n_s16(QAM64_n1); // QAM_amp1_128b = vmovq_n_s16(QAM64_n2); } // printf("comp: rxdataF_comp %p, symbol %d\n",rxdataF_comp[0],symbol); for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (int16x4_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128 = (int16x4_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch0_128b = (int16x8_t *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128b = (int16x8_t *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag0_128 = (int16x8_t *)&dl_ch_mag0[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag0_128b = (int16x8_t *)&dl_ch_magb0[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag1_128 = (int16x8_t *)&dl_ch_mag1[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag1_128b = (int16x8_t *)&dl_ch_magb1[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF128 = (int16x4_t *)&rxdataF_ext[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp0_128 = (int16x8_t *)&rxdataF_comp0[aarx][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp1_128 = (int16x8_t *)&rxdataF_comp1[aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { if (mmse_flag == 0) { // combine TX channels using precoder from pmi if (mimo_mode==LARGE_CDD) { prec2A_TM3_128(&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM3_128(&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM3_128(&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) { prec2A_TM4_128(0,&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(0,&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(0,&dl_ch0_128[2],&dl_ch1_128[2]); } } else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) { prec2A_TM4_128(1,&dl_ch0_128[0],&dl_ch1_128[0]); prec2A_TM4_128(1,&dl_ch0_128[1],&dl_ch1_128[1]); if (pilots==0) { prec2A_TM4_128(1,&dl_ch0_128[2],&dl_ch1_128[2]); } } else { LOG_E(PHY,"Unknown MIMO mode\n"); return; } } if (mod_order0>2) { // get channel amplitude if not QPSK mmtmpD0 = vmull_s16(dl_ch0_128[0], dl_ch0_128[0]); // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3]; mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits mmtmpD1 = vmull_s16(dl_ch0_128[1], dl_ch0_128[1]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits mmtmpD0 = vmull_s16(dl_ch0_128[2], dl_ch0_128[2]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch0_128[3], dl_ch0_128[3]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch0_128[4], dl_ch0_128[4]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch0_128[5], dl_ch0_128[5]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); } dl_ch_mag0_128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp0_128b); dl_ch_mag0_128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp0_128b); dl_ch_mag0_128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp0_128); dl_ch_mag0_128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp0_128); if (pilots==0) { dl_ch_mag0_128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp0_128b); dl_ch_mag0_128[2] = vqdmulhq_s16(mmtmpD4,QAM_amp0_128); } } if (mod_order1>2) { // get channel amplitude if not QPSK mmtmpD0 = vmull_s16(dl_ch1_128[0], dl_ch1_128[0]); // mmtmpD0 = [ch0*ch0,ch1*ch1,ch2*ch2,ch3*ch3]; mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); // mmtmpD0 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3]>>output_shift128 on 32-bits mmtmpD1 = vmull_s16(dl_ch1_128[1], dl_ch1_128[1]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD2 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); // mmtmpD2 = [ch0*ch0 + ch1*ch1,ch0*ch0 + ch1*ch1,ch2*ch2 + ch3*ch3,ch2*ch2 + ch3*ch3,ch4*ch4 + ch5*ch5,ch4*ch4 + ch5*ch5,ch6*ch6 + ch7*ch7,ch6*ch6 + ch7*ch7]>>output_shift128 on 16-bits mmtmpD0 = vmull_s16(dl_ch1_128[2], dl_ch1_128[2]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch1_128[3], dl_ch1_128[3]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD3 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch1_128[4], dl_ch1_128[4]); mmtmpD0 = vqshlq_s32(vqaddq_s32(mmtmpD0,vrev64q_s32(mmtmpD0)),output_shift128); mmtmpD1 = vmull_s16(dl_ch1_128[5], dl_ch1_128[5]); mmtmpD1 = vqshlq_s32(vqaddq_s32(mmtmpD1,vrev64q_s32(mmtmpD1)),output_shift128); mmtmpD4 = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); } dl_ch_mag1_128b[0] = vqdmulhq_s16(mmtmpD2,QAM_amp1_128b); dl_ch_mag1_128b[1] = vqdmulhq_s16(mmtmpD3,QAM_amp1_128b); dl_ch_mag1_128[0] = vqdmulhq_s16(mmtmpD2,QAM_amp1_128); dl_ch_mag1_128[1] = vqdmulhq_s16(mmtmpD3,QAM_amp1_128); if (pilots==0) { dl_ch_mag1_128b[2] = vqdmulhq_s16(mmtmpD4,QAM_amp1_128b); dl_ch_mag1_128[2] = vqdmulhq_s16(mmtmpD4,QAM_amp1_128); } } mmtmpD0 = vmull_s16(dl_ch0_128[0], rxdataF128[0]); //mmtmpD0 = [Re(ch[0])Re(rx[0]) Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1]) Im(ch[1])Im(ch[1])] mmtmpD1 = vmull_s16(dl_ch0_128[1], rxdataF128[1]); //mmtmpD1 = [Re(ch[2])Re(rx[2]) Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3]) Im(ch[3])Im(ch[3])] mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); //mmtmpD0 = [Re(ch[0])Re(rx[0])+Im(ch[0])Im(ch[0]) Re(ch[1])Re(rx[1])+Im(ch[1])Im(ch[1]) Re(ch[2])Re(rx[2])+Im(ch[2])Im(ch[2]) Re(ch[3])Re(rx[3])+Im(ch[3])Im(ch[3])] mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0],*(int16x4_t *)conj)), rxdataF128[0]); //mmtmpD0 = [-Im(ch[0])Re(rx[0]) Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1]) Re(ch[1])Im(rx[1])] mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1],*(int16x4_t *)conj)), rxdataF128[1]); //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])] mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])] mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp0_128[0] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch0_128[2], rxdataF128[2]); mmtmpD1 = vmull_s16(dl_ch0_128[3], rxdataF128[3]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2],*(int16x4_t *)conj)), rxdataF128[2]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3],*(int16x4_t *)conj)), rxdataF128[3]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp0_128[1] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); // second stream mmtmpD0 = vmull_s16(dl_ch1_128[0], rxdataF128[0]); mmtmpD1 = vmull_s16(dl_ch1_128[1], rxdataF128[1]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[0],*(int16x4_t *)conj)), rxdataF128[0]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[1],*(int16x4_t *)conj)), rxdataF128[1]); //mmtmpD0 = [-Im(ch[2])Re(rx[2]) Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3]) Re(ch[3])Im(rx[3])] mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); //mmtmpD1 = [-Im(ch[0])Re(rx[0])+Re(ch[0])Im(rx[0]) -Im(ch[1])Re(rx[1])+Re(ch[1])Im(rx[1]) -Im(ch[2])Re(rx[2])+Re(ch[2])Im(rx[2]) -Im(ch[3])Re(rx[3])+Re(ch[3])Im(rx[3])] mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp1_128[0] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch1_128[2], rxdataF128[2]); mmtmpD1 = vmull_s16(dl_ch1_128[3], rxdataF128[3]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[2],*(int16x4_t *)conj)), rxdataF128[2]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[3],*(int16x4_t *)conj)), rxdataF128[3]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp1_128[1] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); if (pilots==0) { mmtmpD0 = vmull_s16(dl_ch0_128[4], rxdataF128[4]); mmtmpD1 = vmull_s16(dl_ch0_128[5], rxdataF128[5]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[4],*(int16x4_t *)conj)), rxdataF128[4]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch0_128[5],*(int16x4_t *)conj)), rxdataF128[5]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp0_128[2] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); mmtmpD0 = vmull_s16(dl_ch1_128[4], rxdataF128[4]); mmtmpD1 = vmull_s16(dl_ch1_128[5], rxdataF128[5]); mmtmpD0 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0),vget_high_s32(mmtmpD0)), vpadd_s32(vget_low_s32(mmtmpD1),vget_high_s32(mmtmpD1))); mmtmpD0b = vmull_s16(vrev32_s16(vmul_s16(dl_ch1_128[4],*(int16x4_t *)conj)), rxdataF128[4]); mmtmpD1b = vmull_s16(vrev32_s16(vmul_s16(dl_ch1_128[5],*(int16x4_t *)conj)), rxdataF128[5]); mmtmpD1 = vcombine_s32(vpadd_s32(vget_low_s32(mmtmpD0b),vget_high_s32(mmtmpD0b)), vpadd_s32(vget_low_s32(mmtmpD1b),vget_high_s32(mmtmpD1b))); mmtmpD0 = vqshlq_s32(mmtmpD0,output_shift128); mmtmpD1 = vqshlq_s32(mmtmpD1,output_shift128); rxdataF_comp1_128[2] = vcombine_s16(vmovn_s32(mmtmpD0),vmovn_s32(mmtmpD1)); } } Nre = (pilots==0) ? 12 : 8; // rx_antennas } Nre = (pilots==0) ? 12 : 8; precoded_signal_strength0 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*Nre], (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx])); precoded_signal_strength1 += ((signal_energy_nodc(&dl_ch_estimates_ext[aarx+2][symbol*frame_parms->N_RB_DL*Nre], (nb_rb*Nre))*rx_power_correction) - (measurements->n0_power[aarx])); measurements->precoded_cqi_dB[eNB_id][0] = dB_fixed2(precoded_signal_strength0,measurements->n0_power_tot); measurements->precoded_cqi_dB[eNB_id][1] = dB_fixed2(precoded_signal_strength1,measurements->n0_power_tot); #endif } void dlsch_dual_stream_correlation(LTE_DL_FRAME_PARMS *frame_parms, unsigned char symbol, unsigned short nb_rb, int **dl_ch_estimates_ext, int **dl_ch_estimates_ext_i, int **dl_ch_rho_ext, unsigned char output_shift) { #if defined(__x86_64__)||defined(__i386__) unsigned short rb; __m128i *dl_ch128,*dl_ch128i,*dl_ch_rho128,mmtmpD0,mmtmpD1,mmtmpD2,mmtmpD3; unsigned char aarx,symbol_mod,pilots=0; // printf("dlsch_dual_stream_correlation: symbol %d\n",symbol); symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) { pilots=1; } // printf("Dual stream correlation (%p)\n",dl_ch_estimates_ext_i); for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; if (dl_ch_estimates_ext_i == NULL) // TM3/4 dl_ch128i = (__m128i *)&dl_ch_estimates_ext[aarx + frame_parms->nb_antennas_rx][symbol*frame_parms->N_RB_DL*12]; else dl_ch128i = (__m128i *)&dl_ch_estimates_ext_i[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch_rho128 = (__m128i *)&dl_ch_rho_ext[aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[0],dl_ch128i[0]); // print_ints("re",&mmtmpD0); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[0],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)&conjugate[0]); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128i[0]); // print_ints("im",&mmtmpD1); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); // print_ints("re(shift)",&mmtmpD0); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); // print_ints("im(shift)",&mmtmpD1); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); // print_ints("c0",&mmtmpD2); // print_ints("c1",&mmtmpD3); dl_ch_rho128[0] = _mm_packs_epi32(mmtmpD2,mmtmpD3); // print_shorts("rho 0:",dl_ch_rho128); // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[1],dl_ch128i[1]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[1],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128i[1]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); dl_ch_rho128[1] =_mm_packs_epi32(mmtmpD2,mmtmpD3); if (pilots==0) { // multiply by conjugated channel mmtmpD0 = _mm_madd_epi16(dl_ch128[2],dl_ch128i[2]); // mmtmpD0 contains real part of 4 consecutive outputs (32-bit) mmtmpD1 = _mm_shufflelo_epi16(dl_ch128[2],_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_shufflehi_epi16(mmtmpD1,_MM_SHUFFLE(2,3,0,1)); mmtmpD1 = _mm_sign_epi16(mmtmpD1,*(__m128i *)conjugate); mmtmpD1 = _mm_madd_epi16(mmtmpD1,dl_ch128i[2]); // mmtmpD1 contains imag part of 4 consecutive outputs (32-bit) mmtmpD0 = _mm_srai_epi32(mmtmpD0,output_shift); mmtmpD1 = _mm_srai_epi32(mmtmpD1,output_shift); mmtmpD2 = _mm_unpacklo_epi32(mmtmpD0,mmtmpD1); mmtmpD3 = _mm_unpackhi_epi32(mmtmpD0,mmtmpD1); dl_ch_rho128[2] = _mm_packs_epi32(mmtmpD2,mmtmpD3); dl_ch128+=3; dl_ch128i+=3; dl_ch_rho128+=3; } else { dl_ch128+=2; dl_ch128i+=2; dl_ch_rho128+=2; } } } _mm_empty(); _m_empty(); #elif defined(__arm__) #endif } void dlsch_detection_mrc(LTE_DL_FRAME_PARMS *frame_parms, int **rxdataF_comp, int **rxdataF_comp_i, int **rho, int **rho_i, int **dl_ch_mag, int **dl_ch_magb, int **dl_ch_mag_i, int **dl_ch_magb_i, unsigned char symbol, unsigned short nb_rb, unsigned char dual_stream_UE) { #if defined(__x86_64__)||defined(__i386__) unsigned char aatx; int i; __m128i *rxdataF_comp128_0,*rxdataF_comp128_1,*rxdataF_comp128_i0,*rxdataF_comp128_i1,*dl_ch_mag128_0,*dl_ch_mag128_1,*dl_ch_mag128_0b,*dl_ch_mag128_1b,*rho128_0,*rho128_1,*rho128_i0,*rho128_i1, *dl_ch_mag128_i0,*dl_ch_mag128_i1,*dl_ch_mag128_i0b,*dl_ch_mag128_i1b; if (frame_parms->nb_antennas_rx>1) { for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { rxdataF_comp128_0 = (__m128i *)&rxdataF_comp[(aatx<<1)][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_1 = (__m128i *)&rxdataF_comp[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_0 = (__m128i *)&dl_ch_mag[(aatx<<1)][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_1 = (__m128i *)&dl_ch_mag[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_0b = (__m128i *)&dl_ch_magb[(aatx<<1)][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_1b = (__m128i *)&dl_ch_magb[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12]; // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation) for (i=0; i<nb_rb*3; i++) { rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i],1),_mm_srai_epi16(rxdataF_comp128_1[i],1)); dl_ch_mag128_0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i],1),_mm_srai_epi16(dl_ch_mag128_1[i],1)); dl_ch_mag128_0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i],1),_mm_srai_epi16(dl_ch_mag128_1b[i],1)); // print_shorts("mrc comp0:",&rxdataF_comp128_0[i]); // print_shorts("mrc mag0:",&dl_ch_mag128_0[i]); // print_shorts("mrc mag0b:",&dl_ch_mag128_0b[i]); // print_shorts("mrc rho1:",&rho128_1[i]); } } if (rho) { rho128_0 = (__m128i *) &rho[0][symbol*frame_parms->N_RB_DL*12]; rho128_1 = (__m128i *) &rho[1][symbol*frame_parms->N_RB_DL*12]; for (i=0; i<nb_rb*3; i++) { // print_shorts("mrc rho0:",&rho128_0[i]); // print_shorts("mrc rho1:",&rho128_1[i]); rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i],1),_mm_srai_epi16(rho128_1[i],1)); } } if (dual_stream_UE == 1) { rho128_i0 = (__m128i *) &rho_i[0][symbol*frame_parms->N_RB_DL*12]; rho128_i1 = (__m128i *) &rho_i[1][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_i0 = (__m128i *)&rxdataF_comp_i[0][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_i1 = (__m128i *)&rxdataF_comp_i[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i0 = (__m128i *)&dl_ch_mag_i[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i1 = (__m128i *)&dl_ch_mag_i[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i0b = (__m128i *)&dl_ch_magb_i[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i1b = (__m128i *)&dl_ch_magb_i[1][symbol*frame_parms->N_RB_DL*12]; for (i=0; i<nb_rb*3; i++) { rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i],1),_mm_srai_epi16(rxdataF_comp128_i1[i],1)); rho128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i],1),_mm_srai_epi16(rho128_i1[i],1)); dl_ch_mag128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i],1),_mm_srai_epi16(dl_ch_mag128_i1[i],1)); dl_ch_mag128_i0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i],1),_mm_srai_epi16(dl_ch_mag128_i1b[i],1)); } } } _mm_empty(); _m_empty(); #elif defined(__arm__) unsigned char aatx; int i; int16x8_t *rxdataF_comp128_0,*rxdataF_comp128_1,*rxdataF_comp128_i0,*rxdataF_comp128_i1,*dl_ch_mag128_0,*dl_ch_mag128_1,*dl_ch_mag128_0b,*dl_ch_mag128_1b,*rho128_0,*rho128_1,*rho128_i0,*rho128_i1, *dl_ch_mag128_i0,*dl_ch_mag128_i1,*dl_ch_mag128_i0b,*dl_ch_mag128_i1b; if (frame_parms->nb_antennas_rx>1) { for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { rxdataF_comp128_0 = (int16x8_t *)&rxdataF_comp[(aatx<<1)][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_1 = (int16x8_t *)&rxdataF_comp[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_0 = (int16x8_t *)&dl_ch_mag[(aatx<<1)][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_1 = (int16x8_t *)&dl_ch_mag[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_0b = (int16x8_t *)&dl_ch_magb[(aatx<<1)][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_1b = (int16x8_t *)&dl_ch_magb[(aatx<<1)+1][symbol*frame_parms->N_RB_DL*12]; // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation) for (i=0; i<nb_rb*3; i++) { rxdataF_comp128_0[i] = vhaddq_s16(rxdataF_comp128_0[i],rxdataF_comp128_1[i]); dl_ch_mag128_0[i] = vhaddq_s16(dl_ch_mag128_0[i],dl_ch_mag128_1[i]); dl_ch_mag128_0b[i] = vhaddq_s16(dl_ch_mag128_0b[i],dl_ch_mag128_1b[i]); } } if (rho) { rho128_0 = (int16x8_t *) &rho[0][symbol*frame_parms->N_RB_DL*12]; rho128_1 = (int16x8_t *) &rho[1][symbol*frame_parms->N_RB_DL*12]; for (i=0; i<nb_rb*3; i++) { // print_shorts("mrc rho0:",&rho128_0[i]); // print_shorts("mrc rho1:",&rho128_1[i]); rho128_0[i] = vhaddq_s16(rho128_0[i],rho128_1[i]); } } if (dual_stream_UE == 1) { rho128_i0 = (int16x8_t *) &rho_i[0][symbol*frame_parms->N_RB_DL*12]; rho128_i1 = (int16x8_t *) &rho_i[1][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_i0 = (int16x8_t *)&rxdataF_comp_i[0][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_i1 = (int16x8_t *)&rxdataF_comp_i[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i0 = (int16x8_t *)&dl_ch_mag_i[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i1 = (int16x8_t *)&dl_ch_mag_i[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i0b = (int16x8_t *)&dl_ch_magb_i[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i1b = (int16x8_t *)&dl_ch_magb_i[1][symbol*frame_parms->N_RB_DL*12]; for (i=0; i<nb_rb*3; i++) { rxdataF_comp128_i0[i] = vhaddq_s16(rxdataF_comp128_i0[i],rxdataF_comp128_i1[i]); rho128_i0[i] = vhaddq_s16(rho128_i0[i],rho128_i1[i]); dl_ch_mag128_i0[i] = vhaddq_s16(dl_ch_mag128_i0[i],dl_ch_mag128_i1[i]); dl_ch_mag128_i0b[i] = vhaddq_s16(dl_ch_mag128_i0b[i],dl_ch_mag128_i1b[i]); } } } #endif } void dlsch_detection_mrc_TM34(LTE_DL_FRAME_PARMS *frame_parms, LTE_UE_PDSCH *pdsch_vars, int harq_pid, int round, unsigned char symbol, unsigned short nb_rb, unsigned char dual_stream_UE) { int i; __m128i *rxdataF_comp128_0,*rxdataF_comp128_1; __m128i *dl_ch_mag128_0,*dl_ch_mag128_1; __m128i *dl_ch_mag128_0b,*dl_ch_mag128_1b; __m128i *rho128_0, *rho128_1; int **rxdataF_comp0 = pdsch_vars->rxdataF_comp0; int **rxdataF_comp1 = pdsch_vars->rxdataF_comp1[harq_pid][round]; int **dl_ch_rho_ext = pdsch_vars->dl_ch_rho_ext[harq_pid][round]; //for second stream int **dl_ch_rho2_ext = pdsch_vars->dl_ch_rho2_ext; int **dl_ch_mag0 = pdsch_vars->dl_ch_mag0; int **dl_ch_mag1 = pdsch_vars->dl_ch_mag1[harq_pid][round]; int **dl_ch_magb0 = pdsch_vars->dl_ch_magb0; int **dl_ch_magb1 = pdsch_vars->dl_ch_magb1[harq_pid][round]; rxdataF_comp128_0 = (__m128i *)&rxdataF_comp0[0][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_1 = (__m128i *)&rxdataF_comp0[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_0 = (__m128i *)&dl_ch_mag0[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_1 = (__m128i *)&dl_ch_mag0[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_0b = (__m128i *)&dl_ch_magb0[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_1b = (__m128i *)&dl_ch_magb0[1][symbol*frame_parms->N_RB_DL*12]; rho128_0 = (__m128i *) &dl_ch_rho2_ext[0][symbol*frame_parms->N_RB_DL*12]; rho128_1 = (__m128i *) &dl_ch_rho2_ext[1][symbol*frame_parms->N_RB_DL*12]; // MRC on each re of rb, both on MF output and magnitude (for 16QAM/64QAM llr computation) for (i=0; i<nb_rb*3; i++) { rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i],1),_mm_srai_epi16(rxdataF_comp128_1[i],1)); dl_ch_mag128_0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i],1),_mm_srai_epi16(dl_ch_mag128_1[i],1)); dl_ch_mag128_0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i],1),_mm_srai_epi16(dl_ch_mag128_1b[i],1)); rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i],1),_mm_srai_epi16(rho128_1[i],1)); if (frame_parms->nb_antennas_rx>2) { __m128i *rxdataF_comp128_2 = NULL; __m128i *rxdataF_comp128_3 = NULL; __m128i *dl_ch_mag128_2 = NULL; __m128i *dl_ch_mag128_3 = NULL; __m128i *dl_ch_mag128_2b = NULL; __m128i *dl_ch_mag128_3b = NULL; __m128i *rho128_2 = NULL; __m128i *rho128_3 = NULL; rxdataF_comp128_2 = (__m128i *)&rxdataF_comp0[2][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_3 = (__m128i *)&rxdataF_comp0[3][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_2 = (__m128i *)&dl_ch_mag0[2][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_3 = (__m128i *)&dl_ch_mag0[3][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_2b = (__m128i *)&dl_ch_magb0[2][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_3b = (__m128i *)&dl_ch_magb0[3][symbol*frame_parms->N_RB_DL*12]; rho128_2 = (__m128i *) &dl_ch_rho2_ext[2][symbol*frame_parms->N_RB_DL*12]; rho128_3 = (__m128i *) &dl_ch_rho2_ext[3][symbol*frame_parms->N_RB_DL*12]; /*rxdataF_comp*/ rxdataF_comp128_2[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_2[i],1),_mm_srai_epi16(rxdataF_comp128_3[i],1)); rxdataF_comp128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_0[i],1),_mm_srai_epi16(rxdataF_comp128_2[i],1)); /*dl_ch_mag*/ dl_ch_mag128_2[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_2[i],1),_mm_srai_epi16(dl_ch_mag128_3[i],1)); dl_ch_mag128_0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0[i],1),_mm_srai_epi16(dl_ch_mag128_2[i],1)); /*dl_ch_mag*/ dl_ch_mag128_2b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_2b[i],1),_mm_srai_epi16(dl_ch_mag128_3b[i],1)); dl_ch_mag128_0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_0b[i],1),_mm_srai_epi16(dl_ch_mag128_2b[i],1)); /*rho*/ rho128_2[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_2[i],1),_mm_srai_epi16(rho128_3[i],1)); rho128_0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_0[i],1),_mm_srai_epi16(rho128_2[i],1)); } } if (dual_stream_UE == 1) { __m128i *dl_ch_mag128_i0, *dl_ch_mag128_i1; __m128i *dl_ch_mag128_i0b, *dl_ch_mag128_i1b; __m128i *rho128_i0, *rho128_i1; __m128i *rxdataF_comp128_i0, *rxdataF_comp128_i1; rxdataF_comp128_i0 = (__m128i *)&rxdataF_comp1[0][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_i1 = (__m128i *)&rxdataF_comp1[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i0 = (__m128i *)&dl_ch_mag1[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i1 = (__m128i *)&dl_ch_mag1[1][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i0b = (__m128i *)&dl_ch_magb1[0][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i1b = (__m128i *)&dl_ch_magb1[1][symbol*frame_parms->N_RB_DL*12]; rho128_i0 = (__m128i *) &dl_ch_rho_ext[0][symbol*frame_parms->N_RB_DL*12]; rho128_i1 = (__m128i *) &dl_ch_rho_ext[1][symbol*frame_parms->N_RB_DL*12]; for (i=0; i<nb_rb*3; i++) { rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i],1),_mm_srai_epi16(rxdataF_comp128_i1[i],1)); dl_ch_mag128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i],1),_mm_srai_epi16(dl_ch_mag128_i1[i],1)); dl_ch_mag128_i0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i],1),_mm_srai_epi16(dl_ch_mag128_i1b[i],1)); rho128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i],1),_mm_srai_epi16(rho128_i1[i],1)); if (frame_parms->nb_antennas_rx>2) { __m128i *rxdataF_comp128_i2 = NULL; __m128i *rxdataF_comp128_i3 = NULL; __m128i *dl_ch_mag128_i2 = NULL; __m128i *dl_ch_mag128_i3 = NULL; __m128i *dl_ch_mag128_i2b = NULL; __m128i *dl_ch_mag128_i3b = NULL; __m128i *rho128_i2 = NULL; __m128i *rho128_i3 = NULL; rxdataF_comp128_i2 = (__m128i *)&rxdataF_comp1[2][symbol*frame_parms->N_RB_DL*12]; rxdataF_comp128_i3 = (__m128i *)&rxdataF_comp1[3][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i2 = (__m128i *)&dl_ch_mag1[2][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i3 = (__m128i *)&dl_ch_mag1[3][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i2b = (__m128i *)&dl_ch_magb1[2][symbol*frame_parms->N_RB_DL*12]; dl_ch_mag128_i3b = (__m128i *)&dl_ch_magb1[3][symbol*frame_parms->N_RB_DL*12]; rho128_i2 = (__m128i *) &dl_ch_rho_ext[2][symbol*frame_parms->N_RB_DL*12]; rho128_i3 = (__m128i *) &dl_ch_rho_ext[3][symbol*frame_parms->N_RB_DL*12]; /*rxdataF_comp*/ rxdataF_comp128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i2[i],1),_mm_srai_epi16(rxdataF_comp128_i3[i],1)); rxdataF_comp128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rxdataF_comp128_i0[i],1),_mm_srai_epi16(rxdataF_comp128_i2[i],1)); /*dl_ch_mag*/ dl_ch_mag128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i2[i],1),_mm_srai_epi16(dl_ch_mag128_i3[i],1)); dl_ch_mag128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0[i],1),_mm_srai_epi16(dl_ch_mag128_i2[i],1)); /*dl_ch_mag*/ dl_ch_mag128_i2b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i2b[i],1),_mm_srai_epi16(dl_ch_mag128_i3b[i],1)); dl_ch_mag128_i0b[i] = _mm_adds_epi16(_mm_srai_epi16(dl_ch_mag128_i0b[i],1),_mm_srai_epi16(dl_ch_mag128_i2b[i],1)); /*rho*/ rho128_i2[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i2[i],1),_mm_srai_epi16(rho128_i3[i],1)); rho128_i0[i] = _mm_adds_epi16(_mm_srai_epi16(rho128_i0[i],1),_mm_srai_epi16(rho128_i2[i],1)); } } } _mm_empty(); _m_empty(); } void dlsch_scale_channel(int **dl_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, LTE_UE_DLSCH_t **dlsch_ue, uint8_t symbol, unsigned short nb_rb) { #if defined(__x86_64__)||defined(__i386__) short rb, ch_amp; unsigned char aatx,aarx,pilots=0,symbol_mod; __m128i *dl_ch128, ch_amp128; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) { if (frame_parms->nb_antenna_ports_eNB==1) // 10 out of 12 so don't reduce size nb_rb=1+(5*nb_rb/6); else pilots=1; } // Determine scaling amplitude based the symbol ch_amp = ((pilots) ? (dlsch_ue[0]->sqrt_rho_b) : (dlsch_ue[0]->sqrt_rho_a)); LOG_D(PHY,"Scaling PDSCH Chest in OFDM symbol %d by %d, pilots %d nb_rb %d NCP %d symbol %d\n",symbol_mod,ch_amp,pilots,nb_rb,frame_parms->Ncp,symbol); // printf("Scaling PDSCH Chest in OFDM symbol %d by %d\n",symbol_mod,ch_amp); ch_amp128 = _mm_set1_epi16(ch_amp); // Q3.13 for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch128=(__m128i *)&dl_ch_estimates_ext[(aatx<<1)+aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { dl_ch128[0] = _mm_mulhi_epi16(dl_ch128[0],ch_amp128); dl_ch128[0] = _mm_slli_epi16(dl_ch128[0],3); dl_ch128[1] = _mm_mulhi_epi16(dl_ch128[1],ch_amp128); dl_ch128[1] = _mm_slli_epi16(dl_ch128[1],3); if (pilots) { dl_ch128+=2; } else { dl_ch128[2] = _mm_mulhi_epi16(dl_ch128[2],ch_amp128); dl_ch128[2] = _mm_slli_epi16(dl_ch128[2],3); dl_ch128+=3; } } } } #elif defined(__arm__) #endif } //compute average channel_level on each (TX,RX) antenna pair void dlsch_channel_level(int **dl_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, int32_t *avg, uint8_t symbol, unsigned short nb_rb) { #if defined(__x86_64__)||defined(__i386__) //printf("symbol = %d\n", symbol); short rb; unsigned char aatx,aarx,nre=12,symbol_mod; __m128i *dl_ch128, avg128D; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1)) nre=10; else nre=12; //nb_rb*nre = y * 2^x int16_t x = factor2(nb_rb*nre); int16_t y = (nb_rb*nre)>>x; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { //clear average level //printf("aatx = %d, aarx = %d, aatx*frame_parms->nb_antennas_rx + aarx] = %d \n", aatx, aarx, aatx*frame_parms->nb_antennas_rx + aarx); avg128D = _mm_setzero_si128(); // 5 is always a symbol with no pilots for both normal and extended prefix dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*2 + aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { //printf("rb %d : ",rb); avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[0],dl_ch128[0]),x)); avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[1],dl_ch128[1]),x)); //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[0],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[0], coeff128),15))); //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[1],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[1], coeff128),15))); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch128+=2; } else { avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[2],dl_ch128[2]),x)); //avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[2],_mm_srai_epi16(_mm_mulhi_epi16(dl_ch128[2], coeff128),15))); dl_ch128+=3; } /*if(rb==0){ print_shorts("dl_ch128",&dl_ch128[0]); print_shorts("dl_ch128",&dl_ch128[1]); print_shorts("dl_ch128",&dl_ch128[2]); }*/ } avg[aatx*frame_parms->nb_antennas_rx + aarx] =(((int32_t *)&avg128D)[0] + ((int32_t *)&avg128D)[1] + ((int32_t *)&avg128D)[2] + ((int32_t *)&avg128D)[3])/y; } _mm_empty(); _m_empty(); #elif defined(__arm__) short rb; unsigned char aatx,aarx,nre=12,symbol_mod; int32x4_t avg128D; int16x4_t *dl_ch128; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { //clear average level avg128D = vdupq_n_s32(0); // 5 is always a symbol with no pilots for both normal and extended prefix dl_ch128=(int16x4_t *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { // printf("rb %d : ",rb); // print_shorts("ch",&dl_ch128[0]); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[0],dl_ch128[0])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[1],dl_ch128[1])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[2],dl_ch128[2])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[3],dl_ch128[3])); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->mode1_flag==0)) { dl_ch128+=4; } else { avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[4],dl_ch128[4])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[5],dl_ch128[5])); dl_ch128+=6; } /* if (rb==0) { print_shorts("dl_ch128",&dl_ch128[0]); print_shorts("dl_ch128",&dl_ch128[1]); print_shorts("dl_ch128",&dl_ch128[2]); } */ } if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->mode1_flag==0)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->mode1_flag==1)) nre=10; else nre=12; avg[aatx*frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] + ((int32_t *)&avg128D)[1] + ((int32_t *)&avg128D)[2] + ((int32_t *)&avg128D)[3])/(nb_rb*nre); //printf("Channel level : %d\n",avg[aatx*(frame_parms->nb_antennas_rx-1) + aarx]); } #endif } void dlsch_channel_level_core(int **dl_ch_estimates_ext, int32_t *avg, int n_tx, int n_rx, int length, int start_point) { #if defined(__x86_64__)||defined(__i386__) short ii; int aatx,aarx; int length_mod8; int length2; __m128i *dl_ch128, avg128D; int16_t x = factor2(length); int16_t y = (length)>>x; for (aatx=0; aatx<n_tx; aatx++) for (aarx=0; aarx<n_rx; aarx++) { avg128D = _mm_setzero_si128(); dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*2 + aarx][start_point]; length_mod8=length&7; if (length_mod8 == 0) { length2 = length>>3; for (ii=0; ii<length2; ii++) { avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[0],dl_ch128[0]),x)); avg128D = _mm_add_epi32(avg128D,_mm_srai_epi32(_mm_madd_epi16(dl_ch128[1],dl_ch128[1]),x)); dl_ch128+=2; } } else { printf ("Channel level: Received number of subcarriers is not multiple of 4, \n" "need to adapt the code!\n"); } avg[aatx*n_rx + aarx] =(((int32_t *)&avg128D)[0] + ((int32_t *)&avg128D)[1] + ((int32_t *)&avg128D)[2] + ((int32_t *)&avg128D)[3])/y; //printf("Channel level [%d]: %d\n",aatx*n_rx + aarx, avg[aatx*n_rx + aarx]); } _mm_empty(); _m_empty(); /* FIXME This part needs to be adapted like the one above */ #elif defined(__arm__) short rb; unsigned char aatx,aarx,nre=12,symbol_mod; int32x4_t avg128D; int16x4_t *dl_ch128; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { //clear average level avg128D = vdupq_n_s32(0); // 5 is always a symbol with no pilots for both normal and extended prefix dl_ch128=(int16x4_t *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { // printf("rb %d : ",rb); // print_shorts("ch",&dl_ch128[0]); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[0],dl_ch128[0])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[1],dl_ch128[1])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[2],dl_ch128[2])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[3],dl_ch128[3])); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch128+=4; } else { avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[4],dl_ch128[4])); avg128D = vqaddq_s32(avg128D,vmull_s16(dl_ch128[5],dl_ch128[5])); dl_ch128+=6; } } if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1)) nre=10; else nre=12; avg[aatx*frame_parms->nb_antennas_rx + aarx] = (((int32_t *)&avg128D)[0] + ((int32_t *)&avg128D)[1] + ((int32_t *)&avg128D)[2] + ((int32_t *)&avg128D)[3])/(nb_rb*nre); //printf("Channel level : %d\n",avg[aatx*(frame_parms->nb_antennas_rx-1) + aarx]); } #endif } void dlsch_channel_level_median(int **dl_ch_estimates_ext, int32_t *median, int n_tx, int n_rx, int length, int start_point) { #if defined(__x86_64__)||defined(__i386__) short ii; int aatx,aarx; int length2; int max = 0, min=0; int norm_pack; __m128i *dl_ch128, norm128D; for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { max = 0; min = 0; norm128D = _mm_setzero_si128(); dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*2 + aarx][start_point]; length2 = length>>2; for (ii=0; ii<length2; ii++) { norm128D = _mm_srai_epi32( _mm_madd_epi16(dl_ch128[0],dl_ch128[0]), 1); //print_ints("norm128D",&norm128D[0]); norm_pack = ((int32_t *)&norm128D)[0] + ((int32_t *)&norm128D)[1] + ((int32_t *)&norm128D)[2] + ((int32_t *)&norm128D)[3]; if (norm_pack > max) max = norm_pack; if (norm_pack < min) min = norm_pack; dl_ch128+=1; } median[aatx*n_rx + aarx] = (max+min)>>1; // printf("Channel level median [%d]: %d\n",aatx*n_rx + aarx, median[aatx*n_rx + aarx]); } } _mm_empty(); _m_empty(); #elif defined(__arm__) short rb; unsigned char aatx,aarx,nre=12,symbol_mod; int32x4_t norm128D; int16x4_t *dl_ch128; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { max = 0; min = 0; norm128D = vdupq_n_s32(0); dl_ch128=(int16x4_t *)&dl_ch_estimates_ext[aatx*n_rx + aarx][start_point]; length_mod8=length&3; length2 = length>>2; for (ii=0; ii<length2; ii++) { norm128D = vshrq_n_u32(vmull_s16(dl_ch128[0],dl_ch128[0]), 1); norm_pack = ((int32_t *)&norm128D)[0] + ((int32_t *)&norm128D)[1] + ((int32_t *)&norm128D)[2] + ((int32_t *)&norm128D)[3]; if (norm_pack > max) max = norm_pack; if (norm_pack < min) min = norm_pack; dl_ch128+=1; } median[aatx*n_rx + aarx] = (max+min)>>1; //printf("Channel level median [%d]: %d\n",aatx*n_rx + aarx, median[aatx*n_rx + aarx]); } } #endif } void mmse_processing_oai(LTE_UE_PDSCH *pdsch_vars, LTE_DL_FRAME_PARMS *frame_parms, PHY_MEASUREMENTS *measurements, unsigned char first_symbol_flag, MIMO_mode_t mimo_mode, unsigned short mmse_flag, int noise_power, unsigned char symbol, unsigned short nb_rb) { int **rxdataF_ext = pdsch_vars->rxdataF_ext; int **dl_ch_estimates_ext = pdsch_vars->dl_ch_estimates_ext; unsigned char *pmi_ext = pdsch_vars->pmi_ext; int avg_00[frame_parms->nb_antenna_ports_eNB*frame_parms->nb_antennas_rx]; int avg_01[frame_parms->nb_antenna_ports_eNB*frame_parms->nb_antennas_rx]; int symbol_mod, length, start_point, nre; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1)) nre=10; else nre=12; length = nre*nb_rb; start_point = symbol*nb_rb*12; mmse_processing_core(rxdataF_ext, dl_ch_estimates_ext, noise_power, frame_parms->nb_antenna_ports_eNB, frame_parms->nb_antennas_rx, length, start_point); /*dlsch_channel_aver_band(dl_ch_estimates_ext, frame_parms, chan_avg, symbol, nb_rb); for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { H[aatx*frame_parms->nb_antennas_rx + aarx] = (float)(chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r/(32768.0)) + I*(float)(chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i/(32768.0)); // printf("H [%d] = (%f, %f) \n", aatx*frame_parms->nb_antennas_rx + aarx, creal(H[aatx*frame_parms->nb_antennas_rx + aarx]), cimag(H[aatx*frame_parms->nb_antennas_rx + aarx])); }*/ if (first_symbol_flag == 1) { dlsch_channel_level_TM34(dl_ch_estimates_ext, frame_parms, pmi_ext, avg_00, avg_01, symbol, nb_rb, mmse_flag, mimo_mode); avg_00[0] = (log2_approx(avg_00[0])/2) + dlsch_demod_shift+4;// + 2 ;//+ 4; avg_01[0] = (log2_approx(avg_01[0])/2) + dlsch_demod_shift+4;// + 2 ;//+ 4; pdsch_vars->log2_maxh0 = cmax(avg_00[0],0); pdsch_vars->log2_maxh1 = cmax(avg_01[0],0); } } void mmse_processing_core(int32_t **rxdataF_ext, int32_t **dl_ch_estimates_ext, int noise_power, int n_tx, int n_rx, int length, int start_point) { int aatx, aarx, re; float imag; float real; float complex **W_MMSE= malloc(n_tx*n_rx*sizeof(float complex *)); for (int j=0; j<n_tx*n_rx; j++) { W_MMSE[j] = malloc(sizeof(float complex)*length); } float complex *H= malloc(n_tx*n_rx*sizeof(float complex)); float complex *W_MMSE_re= malloc(n_tx*n_rx*sizeof(float complex)); float complex **dl_ch_estimates_ext_flcpx = malloc(n_tx*n_rx*sizeof(float complex *)); for (int j=0; j<n_tx*n_rx; j++) { dl_ch_estimates_ext_flcpx[j] = malloc(sizeof(float complex)*length); } float complex **rxdataF_ext_flcpx = malloc(n_rx*sizeof(float complex *)); for (int j=0; j<n_rx; j++) { rxdataF_ext_flcpx[j] = malloc(sizeof(float complex)*length); } chan_est_to_float(dl_ch_estimates_ext, dl_ch_estimates_ext_flcpx, n_tx, n_rx, length, start_point); for (re=0; re<length; re++) { for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { imag = cimag(dl_ch_estimates_ext_flcpx[aatx*n_rx + aarx][re]); real = creal(dl_ch_estimates_ext_flcpx[aatx*n_rx + aarx][re]); H[aatx*n_rx + aarx] = real+ I*imag; } } compute_MMSE(H, n_tx, noise_power, W_MMSE_re); for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { W_MMSE[aatx*n_rx + aarx][re] = W_MMSE_re[aatx*n_rx + aarx]; } } } rxdataF_to_float(rxdataF_ext, rxdataF_ext_flcpx, n_rx, length, start_point); mult_mmse_rxdataF(W_MMSE, rxdataF_ext_flcpx, n_tx, n_rx, length, start_point); mult_mmse_chan_est(W_MMSE, dl_ch_estimates_ext_flcpx, n_tx, n_rx, length, start_point); float_to_rxdataF(rxdataF_ext, rxdataF_ext_flcpx, n_tx, n_rx, length, start_point); float_to_chan_est(dl_ch_estimates_ext, dl_ch_estimates_ext_flcpx, n_tx, n_rx, length, start_point); free(W_MMSE); free(H); free(W_MMSE_re); free(dl_ch_estimates_ext_flcpx); free(rxdataF_ext_flcpx); } /*THIS FUNCTION TAKES FLOAT_POINT INPUT. SHOULD NOT BE USED WITH OAI*/ void mmse_processing_core_flp(float complex **rxdataF_ext_flcpx, float complex **H, int32_t **rxdataF_ext, int32_t **dl_ch_estimates_ext, float noise_power, int n_tx, int n_rx, int length, int start_point) { int aatx, aarx, re; float max = 0; float one_over_max = 0; float complex **W_MMSE= malloc(n_tx*n_rx*sizeof(float complex *)); for (int j=0; j<n_tx*n_rx; j++) { W_MMSE[j] = malloc(sizeof(float complex)*length); } float complex *H_re= malloc(n_tx*n_rx*sizeof(float complex)); float complex *W_MMSE_re= malloc(n_tx*n_rx*sizeof(float complex)); for (re=0; re<length; re++) { for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { H_re[aatx*n_rx + aarx] = H[aatx*n_rx + aarx][re]; #ifdef DEBUG_MMSE if (re == 0) printf(" H_re[%d]= (%f + i%f)\n", aatx*n_rx + aarx, creal(H_re[aatx*n_rx + aarx]), cimag(H_re[aatx*n_rx + aarx])); #endif } } compute_MMSE(H_re, n_tx, noise_power, W_MMSE_re); for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { W_MMSE[aatx*n_rx + aarx][re] = W_MMSE_re[aatx*n_rx + aarx]; if (fabs(creal(W_MMSE_re[aatx*n_rx + aarx])) > max) max = fabs(creal(W_MMSE_re[aatx*n_rx + aarx])); if (fabs(cimag(W_MMSE_re[aatx*n_rx + aarx])) > max) max = fabs(cimag(W_MMSE_re[aatx*n_rx + aarx])); } } } one_over_max = 1.0/max; for (re=0; re<length; re++) for (aatx=0; aatx<n_tx; aatx++) for (aarx=0; aarx<n_rx; aarx++) { #ifdef DEBUG_MMSE if (re == 0) printf(" W_MMSE[%d] = (%f + i%f)\n", aatx*n_rx + aarx, creal(W_MMSE[aatx*n_rx + aarx][re]), cimag(W_MMSE[aatx*n_rx + aarx][re])); #endif W_MMSE[aatx*n_rx + aarx][re] = one_over_max*W_MMSE[aatx*n_rx + aarx][re]; #ifdef DEBUG_MMSE if (re == 0) printf(" AFTER NORM W_MMSE[%d] = (%f + i%f), max = %f \n", aatx*n_rx + aarx, creal(W_MMSE[aatx*n_rx + aarx][re]), cimag(W_MMSE[aatx*n_rx + aarx][re]), max); #endif } mult_mmse_rxdataF(W_MMSE, rxdataF_ext_flcpx, n_tx, n_rx, length, start_point); mult_mmse_chan_est(W_MMSE, H, n_tx, n_rx, length, start_point); float_to_rxdataF(rxdataF_ext, rxdataF_ext_flcpx, n_tx, n_rx, length, start_point); float_to_chan_est(dl_ch_estimates_ext, H, n_tx, n_rx, length, start_point); free(H_re); free(W_MMSE); free(W_MMSE_re); } void dlsch_channel_aver_band(int **dl_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, struct complex32 *chan_avg, unsigned char symbol, unsigned short nb_rb) { #if defined(__x86_64__)||defined(__i386__) short rb; unsigned char aatx,aarx,nre=12,symbol_mod; __m128i *dl_ch128, avg128D; int32_t chan_est_avg[4]; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1)) nre=10; else nre=12; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) { for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; avg128D = _mm_setzero_si128(); // print_shorts("avg128D 1",&avg128D); for (rb=0; rb<nb_rb; rb++) { /* printf("symbol %d, ant %d, nre*nrb %d, rb %d \n", symbol, aatx*frame_parms->nb_antennas_rx + aarx, nb_rb*nre, rb); print_shorts("aver dl_ch128",&dl_ch128[0]); print_shorts("aver dl_ch128",&dl_ch128[1]); print_shorts("aver dl_ch128",&dl_ch128[2]); avg128D = _mm_add_epi16(avg128D, dl_ch128[0]);*/ //print_shorts("avg128D 2",&avg128D); avg128D = _mm_add_epi16(avg128D, dl_ch128[1]); // print_shorts("avg128D 3",&avg128D); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch128+=2; } else { avg128D = _mm_add_epi16(avg128D,dl_ch128[2]); // print_shorts("avg128D 4",&avg128D); dl_ch128+=3; } } chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r =(((int16_t *)&avg128D)[0] + ((int16_t *)&avg128D)[2] + ((int16_t *)&avg128D)[4] + ((int16_t *)&avg128D)[6])/(nb_rb*nre); // printf("symb %d chan_avg re [%d] = %d\n", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r); chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i =(((int16_t *)&avg128D)[1] + ((int16_t *)&avg128D)[3] + ((int16_t *)&avg128D)[5] + ((int16_t *)&avg128D)[7])/(nb_rb*nre); // printf("symb %d chan_avg im [%d] = %d\n", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i); //printf("symb %d chan_avg im [%d] = %d\n", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i); chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx] = (((int32_t)chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].i)<<16)|(((int32_t)chan_avg[aatx*frame_parms->nb_antennas_rx + aarx].r) & 0xffff); //printf("symb %d chan_est_avg [%d] = %d\n", symbol, aatx*frame_parms->nb_antennas_rx + aarx, chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]); dl_ch128=(__m128i *)&dl_ch_estimates_ext[aatx*frame_parms->nb_antennas_rx + aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { dl_ch128[0] = _mm_set1_epi32(chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]); dl_ch128[1] = _mm_set1_epi32(chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch128+=2; } else { dl_ch128[2] = _mm_set1_epi32(chan_est_avg[aatx*frame_parms->nb_antennas_rx + aarx]); dl_ch128+=3; } } } } _mm_empty(); _m_empty(); #elif defined(__arm__) #endif } void rxdataF_to_float(int32_t **rxdataF_ext, float complex **rxdataF_f, int n_rx, int length, int start_point) { short re; int aarx; int16_t imag; int16_t real; for (aarx=0; aarx<n_rx; aarx++) { for (re=0; re<length; re++) { imag = (int16_t) (rxdataF_ext[aarx][start_point + re] >> 16); real = (int16_t) (rxdataF_ext[aarx][start_point + re] & 0xffff); rxdataF_f[aarx][re] = (float)(real/(32768.0)) + I*(float)(imag/(32768.0)); #ifdef DEBUG_MMSE if (re==0) { printf("rxdataF_to_float: aarx = %d, real= %d, imag = %d\n", aarx, real, imag); //printf("rxdataF_to_float: rxdataF_ext[%d][%d] = %d\n", aarx, start_point + re, rxdataF_ext[aarx][start_point + re]); //printf("rxdataF_to_float: ant %d, re = %d, rxdataF_f real = %f, rxdataF_f imag = %f \n", aarx, re, creal(rxdataF_f[aarx][re]), cimag(rxdataF_f[aarx][re])); } #endif } } } void chan_est_to_float(int32_t **dl_ch_estimates_ext, float complex **dl_ch_estimates_ext_f, int n_tx, int n_rx, int length, int start_point) { short re; int aatx,aarx; int16_t imag; int16_t real; for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { for (re=0; re<length; re++) { imag = (int16_t) (dl_ch_estimates_ext[aatx*n_rx + aarx][start_point + re] >> 16); real = (int16_t) (dl_ch_estimates_ext[aatx*n_rx + aarx][start_point+ re] & 0xffff); dl_ch_estimates_ext_f[aatx*n_rx + aarx][re] = (float)(real/(32768.0)) + I*(float)(imag/(32768.0)); #ifdef DEBUG_MMSE if (re==0) { printf("ant %d, re = %d, real = %d, imag = %d \n", aatx*n_rx + aarx, re, real, imag); printf("ant %d, re = %d, real = %f, imag = %f \n", aatx*n_rx + aarx, re, creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])); } #endif } } } } void float_to_chan_est(int32_t **dl_ch_estimates_ext, float complex **dl_ch_estimates_ext_f, int n_tx, int n_rx, int length, int start_point) { short re; int aarx, aatx; int16_t imag; int16_t real; for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { for (re=0; re<length; re++) { if (cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])<-1) imag = 0x8000; else if (cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])>=1) imag = 0x7FFF; else imag = cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])*32768; if (creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])<-1) real = 0x8000; else if (creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])>=1) real = 0x7FFF; else real = creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])*32768; dl_ch_estimates_ext[aatx*n_rx + aarx][start_point + re] = (((int32_t)imag)<<16)|((int32_t)real & 0xffff); #ifdef DEBUG_MMSE if (re==0) { printf(" float_to_chan_est: chan est real = %f, chan est imag = %f\n",creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])); printf("float_to_chan_est: real fixed = %d, imag fixed = %d\n", real, imag); printf("float_to_chan_est: ant %d, re = %d, dl_ch_estimates_ext = %d \n", aatx*n_rx + aarx, re, dl_ch_estimates_ext[aatx*n_rx + aarx][start_point + re]); } #endif } } } } void float_to_rxdataF(int32_t **rxdataF_ext, float complex **rxdataF_f, int n_tx, int n_rx, int length, int start_point) { short re; int aarx; int16_t imag; int16_t real; for (aarx=0; aarx<n_rx; aarx++) { for (re=0; re<length; re++) { if (cimag(rxdataF_f[aarx][re])<-1) imag = 0x8000; else if (cimag(rxdataF_f[aarx][re])>=1) imag = 0x7FFF; else imag = cimag(rxdataF_f[aarx][re])*32768; if (creal(rxdataF_f[aarx][re])<-1) real = 0x8000; else if (creal(rxdataF_f[aarx][re])>=1) real = 0x7FFF; else real = creal(rxdataF_f[aarx][re])*32768; rxdataF_ext[aarx][start_point + re] = (((int32_t)imag)<<16)|(((int32_t)real) & 0xffff); #ifdef DEBUG_MMSE if (re==0) { printf(" float_to_rxdataF: real = %f, imag = %f\n",creal(rxdataF_f[aarx][re]), cimag(rxdataF_f[aarx][re])); printf("float_to_rxdataF: real fixed = %d, imag fixed = %d\n", real, imag); printf("float_to_rxdataF: ant %d, re = %d, rxdataF_ext = %d \n", aarx, re, rxdataF_ext[aarx][start_point + re]); } #endif } } } void mult_mmse_rxdataF(float complex **Wmmse, float complex **rxdataF_ext_f, int n_tx, int n_rx, int length, int start_point) { short re; int aarx, aatx; float complex *rxdata_re = malloc(n_rx*sizeof(float complex)); float complex *rxdata_mmse_re = malloc(n_rx*sizeof(float complex)); float complex *Wmmse_re = malloc(n_tx*n_rx*sizeof(float complex)); for (re=0; re<length; re++) { for (aarx=0; aarx<n_rx; aarx++) { rxdata_re[aarx] = rxdataF_ext_f[aarx][re]; #ifdef DEBUG_MMSE if (re==0) printf("mult_mmse_rxdataF before: rxdata_re[%d] = (%f, %f)\n", aarx, creal(rxdata_re[aarx]), cimag(rxdata_re[aarx])); #endif } for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { Wmmse_re[aatx*n_rx + aarx] = Wmmse[aatx*n_rx + aarx][re]; } } mutl_matrix_matrix_col_based(Wmmse_re, rxdata_re, n_rx, n_tx, n_rx, 1, rxdata_mmse_re); for (aarx=0; aarx<n_rx; aarx++) { rxdataF_ext_f[aarx][re] = rxdata_mmse_re[aarx]; #ifdef DEBUG_MMSE if (re==0) printf("mult_mmse_rxdataF after: rxdataF_ext_f[%d] = (%f, %f)\n", aarx, creal(rxdataF_ext_f[aarx][re]), cimag(rxdataF_ext_f[aarx][re])); #endif } } free(rxdata_re); free(rxdata_mmse_re); free(Wmmse_re); } void mult_mmse_chan_est(float complex **Wmmse, float complex **dl_ch_estimates_ext_f, int n_tx, int n_rx, int length, int start_point) { short re; int aarx, aatx; float complex *chan_est_re = malloc(n_tx*n_rx*sizeof(float complex)); float complex *chan_est_mmse_re = malloc(n_tx*n_rx*sizeof(float complex)); float complex *Wmmse_re = malloc(n_tx*n_rx*sizeof(float complex)); for (re=0; re<length; re++) { for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { chan_est_re[aatx*n_rx + aarx] = dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]; Wmmse_re[aatx*n_rx + aarx] = Wmmse[aatx*n_rx + aarx][re]; #ifdef DEBUG_MMSE if (re==0) printf("mult_mmse_chan_est: chan_est_re[%d] = (%f, %f)\n", aatx*n_rx + aarx, creal(chan_est_re[aatx*n_rx + aarx]), cimag(chan_est_re[aatx*n_rx + aarx])); #endif } } mutl_matrix_matrix_col_based(Wmmse_re, chan_est_re, n_rx, n_tx, n_rx, n_tx, chan_est_mmse_re); for (aatx=0; aatx<n_tx; aatx++) { for (aarx=0; aarx<n_rx; aarx++) { dl_ch_estimates_ext_f[aatx*n_rx + aarx][re] = chan_est_mmse_re[aatx*n_rx + aarx]; #ifdef DEBUG_MMSE if (re==0) printf("mult_mmse_chan_est: dl_ch_estimates_ext_f[%d][%d] = (%f, %f)\n", aatx*n_rx + aarx, re, creal(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re]), cimag(dl_ch_estimates_ext_f[aatx*n_rx + aarx][re])); #endif } } } free(Wmmse_re); free(chan_est_re); free(chan_est_mmse_re); } //compute average channel_level of effective (precoded) channel void dlsch_channel_level_TM34(int **dl_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, unsigned char *pmi_ext, int *avg_0, int *avg_1, uint8_t symbol, unsigned short nb_rb, unsigned int mmse_flag, MIMO_mode_t mimo_mode) { #if defined(__x86_64__)||defined(__i386__) short rb; unsigned char aarx,nre=12,symbol_mod; __m128i *dl_ch0_128,*dl_ch1_128, dl_ch0_128_tmp, dl_ch1_128_tmp, avg_0_128D, avg_1_128D; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; //clear average level // avg_0_128D = _mm_setzero_si128(); // avg_1_128D = _mm_setzero_si128(); avg_0[0] = 0; avg_0[1] = 0; avg_1[0] = 0; avg_1[1] = 0; // 5 is always a symbol with no pilots for both normal and extended prefix if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1)) nre=10; else nre=12; for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; avg_0_128D = _mm_setzero_si128(); avg_1_128D = _mm_setzero_si128(); for (rb=0; rb<nb_rb; rb++) { // printf("rb %d : \n",rb); //print_shorts("ch0\n",&dl_ch0_128[0]); //print_shorts("ch1\n",&dl_ch1_128[0]); dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[0]); dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[0]); if (mmse_flag == 0) { if (mimo_mode==LARGE_CDD) prec2A_TM3_128(&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) prec2A_TM4_128(0,&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) prec2A_TM4_128(1,&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp); } // mmtmpD0 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp); avg_0_128D = _mm_add_epi32(avg_0_128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp)); avg_1_128D = _mm_add_epi32(avg_1_128D,_mm_madd_epi16(dl_ch1_128_tmp,dl_ch1_128_tmp)); dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[1]); dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[1]); if (mmse_flag == 0) { if (mimo_mode==LARGE_CDD) prec2A_TM3_128(&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) prec2A_TM4_128(0,&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) prec2A_TM4_128(1,&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp); } // mmtmpD1 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp); avg_0_128D = _mm_add_epi32(avg_0_128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp)); avg_1_128D = _mm_add_epi32(avg_1_128D,_mm_madd_epi16(dl_ch1_128_tmp,dl_ch1_128_tmp)); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch0_128+=2; dl_ch1_128+=2; } else { dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[2]); dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[2]); if (mmse_flag == 0) { if (mimo_mode==LARGE_CDD) prec2A_TM3_128(&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODING1) prec2A_TM4_128(0,&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_UNIFORM_PRECODINGj) prec2A_TM4_128(1,&dl_ch0_128_tmp,&dl_ch1_128_tmp); else if (mimo_mode==DUALSTREAM_PUSCH_PRECODING) prec2A_TM4_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp); } // mmtmpD2 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp); avg_1_128D = _mm_add_epi32(avg_1_128D,_mm_madd_epi16(dl_ch1_128_tmp,dl_ch1_128_tmp)); avg_0_128D = _mm_add_epi32(avg_0_128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp)); dl_ch0_128+=3; dl_ch1_128+=3; } } avg_0[aarx] = (((int *)&avg_0_128D)[0])/(nb_rb*nre) + (((int *)&avg_0_128D)[1])/(nb_rb*nre) + (((int *)&avg_0_128D)[2])/(nb_rb*nre) + (((int *)&avg_0_128D)[3])/(nb_rb*nre); // printf("From Chan_level aver stream 0 %d =%d\n", aarx, avg_0[aarx]); avg_1[aarx] = (((int *)&avg_1_128D)[0])/(nb_rb*nre) + (((int *)&avg_1_128D)[1])/(nb_rb*nre) + (((int *)&avg_1_128D)[2])/(nb_rb*nre) + (((int *)&avg_1_128D)[3])/(nb_rb*nre); // printf("From Chan_level aver stream 1 %d =%d\n", aarx, avg_1[aarx]); } //avg_0[0] = max(avg_0[0],avg_0[1]); //avg_1[0] = max(avg_1[0],avg_1[1]); //avg_0[0]= max(avg_0[0], avg_1[0]); avg_0[0] = avg_0[0] + avg_0[1]; // printf("From Chan_level aver stream 0 final =%d\n", avg_0[0]); avg_1[0] = avg_1[0] + avg_1[1]; // printf("From Chan_level aver stream 1 final =%d\n", avg_1[0]); avg_0[0] = min (avg_0[0], avg_1[0]); avg_1[0] = avg_0[0]; _mm_empty(); _m_empty(); #elif defined(__arm__) #endif } //compute average channel_level of effective (precoded) channel void dlsch_channel_level_TM56(int **dl_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, unsigned char *pmi_ext, int *avg, uint8_t symbol, unsigned short nb_rb) { #if defined(__x86_64__)||defined(__i386__) short rb; unsigned char aarx,nre=12,symbol_mod; __m128i *dl_ch0_128,*dl_ch1_128, dl_ch0_128_tmp, dl_ch1_128_tmp,avg128D; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; //clear average level avg128D = _mm_setzero_si128(); avg[0] = 0; avg[1] = 0; // 5 is always a symbol with no pilots for both normal and extended prefix if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) nre=8; else if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB==1)) nre=10; else nre=12; for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { dl_ch0_128 = (__m128i *)&dl_ch_estimates_ext[aarx][symbol*frame_parms->N_RB_DL*12]; dl_ch1_128 = (__m128i *)&dl_ch_estimates_ext[2+aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[0]); dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[0]); prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp); // mmtmpD0 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp); avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp)); dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[1]); dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[1]); prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp); // mmtmpD1 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp); avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp)); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch0_128+=2; dl_ch1_128+=2; } else { dl_ch0_128_tmp = _mm_load_si128(&dl_ch0_128[2]); dl_ch1_128_tmp = _mm_load_si128(&dl_ch1_128[2]); prec2A_TM56_128(pmi_ext[rb],&dl_ch0_128_tmp,&dl_ch1_128_tmp); // mmtmpD2 = _mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp); avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch0_128_tmp,dl_ch0_128_tmp)); dl_ch0_128+=3; dl_ch1_128+=3; } } avg[aarx] = (((int *)&avg128D)[0])/(nb_rb*nre) + (((int *)&avg128D)[1])/(nb_rb*nre) + (((int *)&avg128D)[2])/(nb_rb*nre) + (((int *)&avg128D)[3])/(nb_rb*nre); } // choose maximum of the 2 effective channels avg[0] = cmax(avg[0],avg[1]); _mm_empty(); _m_empty(); #elif defined(__arm__) #endif } //compute average channel_level for TM7 void dlsch_channel_level_TM7(int **dl_bf_ch_estimates_ext, LTE_DL_FRAME_PARMS *frame_parms, int *avg, uint8_t symbol, unsigned short nb_rb) { #if defined(__x86_64__)||defined(__i386__) short rb; unsigned char aatx,aarx,nre=12,symbol_mod; __m128i *dl_ch128,avg128D; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; for (aatx=0; aatx<frame_parms->nb_antenna_ports_eNB; aatx++) for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { //clear average level avg128D = _mm_setzero_si128(); // 5 is always a symbol with no pilots for both normal and extended prefix dl_ch128=(__m128i *)&dl_bf_ch_estimates_ext[(aatx<<1)+aarx][symbol*frame_parms->N_RB_DL*12]; for (rb=0; rb<nb_rb; rb++) { // printf("rb %d : ",rb); // print_shorts("ch",&dl_ch128[0]); avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[0],dl_ch128[0])); avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[1],dl_ch128[1])); if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))&&(frame_parms->nb_antenna_ports_eNB!=1)) { dl_ch128+=2; } else { avg128D = _mm_add_epi32(avg128D,_mm_madd_epi16(dl_ch128[2],dl_ch128[2])); dl_ch128+=3; } /* if (rb==0) { print_shorts("dl_ch128",&dl_ch128[0]); print_shorts("dl_ch128",&dl_ch128[1]); print_shorts("dl_ch128",&dl_ch128[2]); } */ } if (((symbol_mod == 0) || (symbol_mod == (frame_parms->Ncp-1)))) nre=10; else if ((frame_parms->Ncp==0) && (symbol==3 || symbol==6 || symbol==9 || symbol==12)) nre=9; else if ((frame_parms->Ncp==1) && (symbol==4 || symbol==7 || symbol==9)) nre=8; else nre=12; avg[(aatx<<1)+aarx] = (((int *)&avg128D)[0] + ((int *)&avg128D)[1] + ((int *)&avg128D)[2] + ((int *)&avg128D)[3])/(nb_rb*nre); // printf("Channel level : %d\n",avg[(aatx<<1)+aarx]); } _mm_empty(); _m_empty(); #elif defined(__arm__) #endif } //#define ONE_OVER_2_Q15 16384 void dlsch_alamouti(LTE_DL_FRAME_PARMS *frame_parms, int **rxdataF_comp, int **dl_ch_mag, int **dl_ch_magb, unsigned char symbol, unsigned short nb_rb) { #if defined(__x86_64__)||defined(__i386__) short *rxF0,*rxF1; __m128i *ch_mag0,*ch_mag1,*ch_mag0b,*ch_mag1b, *rxF0_128; unsigned char rb,re; int jj = (symbol*frame_parms->N_RB_DL*12); uint8_t symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; uint8_t pilots = ((symbol_mod==0)||(symbol_mod==(4-frame_parms->Ncp))) ? 1 : 0; rxF0_128 = (__m128i *) &rxdataF_comp[0][jj]; //amp = _mm_set1_epi16(ONE_OVER_2_Q15); // printf("Doing alamouti!\n"); rxF0 = (short *)&rxdataF_comp[0][jj]; //tx antenna 0 h0*y rxF1 = (short *)&rxdataF_comp[2][jj]; //tx antenna 1 h1*y ch_mag0 = (__m128i *)&dl_ch_mag[0][jj]; ch_mag1 = (__m128i *)&dl_ch_mag[2][jj]; ch_mag0b = (__m128i *)&dl_ch_magb[0][jj]; ch_mag1b = (__m128i *)&dl_ch_magb[2][jj]; for (rb=0; rb<nb_rb; rb++) { for (re=0; re<((pilots==0)?12:8); re+=2) { // Alamouti RX combining // printf("Alamouti: symbol %d, rb %d, re %d: rxF0 (%d,%d,%d,%d), rxF1 (%d,%d,%d,%d)\n",symbol,rb,re,rxF0[0],rxF0[1],rxF0[2],rxF0[3],rxF1[0],rxF1[1],rxF1[2],rxF1[3]); rxF0[0] = rxF0[0] + rxF1[2]; rxF0[1] = rxF0[1] - rxF1[3]; rxF0[2] = rxF0[2] - rxF1[0]; rxF0[3] = rxF0[3] + rxF1[1]; // printf("Alamouti: rxF0 after (%d,%d,%d,%d)\n",rxF0[0],rxF0[1],rxF0[2],rxF0[3]); rxF0+=4; rxF1+=4; } // compute levels for 16QAM or 64 QAM llr unit ch_mag0[0] = _mm_adds_epi16(ch_mag0[0],ch_mag1[0]); ch_mag0[1] = _mm_adds_epi16(ch_mag0[1],ch_mag1[1]); ch_mag0b[0] = _mm_adds_epi16(ch_mag0b[0],ch_mag1b[0]); ch_mag0b[1] = _mm_adds_epi16(ch_mag0b[1],ch_mag1b[1]); // account for 1/sqrt(2) scaling at transmission //ch_mag0[0] = _mm_srai_epi16(ch_mag0[0],1); //ch_mag0[1] = _mm_srai_epi16(ch_mag0[1],1); //ch_mag0b[0] = _mm_srai_epi16(ch_mag0b[0],1); //ch_mag0b[1] = _mm_srai_epi16(ch_mag0b[1],1); //rxF0_128[0] = _mm_mulhi_epi16(rxF0_128[0],amp); //rxF0_128[0] = _mm_slli_epi16(rxF0_128[0],1); //rxF0_128[1] = _mm_mulhi_epi16(rxF0_128[1],amp); //rxF0_128[1] = _mm_slli_epi16(rxF0_128[1],1); //rxF0_128[0] = _mm_srai_epi16(rxF0_128[0],1); //rxF0_128[1] = _mm_srai_epi16(rxF0_128[1],1); if (pilots==0) { ch_mag0[2] = _mm_adds_epi16(ch_mag0[2],ch_mag1[2]); ch_mag0b[2] = _mm_adds_epi16(ch_mag0b[2],ch_mag1b[2]); //ch_mag0[2] = _mm_srai_epi16(ch_mag0[2],1); //ch_mag0b[2] = _mm_srai_epi16(ch_mag0b[2],1); //rxF0_128[2] = _mm_mulhi_epi16(rxF0_128[2],amp); //rxF0_128[2] = _mm_slli_epi16(rxF0_128[2],1); //rxF0_128[2] = _mm_srai_epi16(rxF0_128[2],1); ch_mag0+=3; ch_mag1+=3; ch_mag0b+=3; ch_mag1b+=3; rxF0_128+=3; } else { ch_mag0+=2; ch_mag1+=2; ch_mag0b+=2; ch_mag1b+=2; rxF0_128+=2; } } _mm_empty(); _m_empty(); #elif defined(__arm__) #endif } //============================================================================================== // Extraction functions //============================================================================================== unsigned short dlsch_extract_rbs_single(int **rxdataF, int **dl_ch_estimates, int **rxdataF_ext, int **dl_ch_estimates_ext, unsigned short pmi, unsigned char *pmi_ext, unsigned int *rb_alloc, unsigned char symbol, unsigned char subframe, uint32_t high_speed_flag, LTE_DL_FRAME_PARMS *frame_parms) { unsigned short rb,nb_rb=0; unsigned char rb_alloc_ind; unsigned char i,aarx,l,nsymb,skip_half=0,sss_symb,pss_symb=0; int *dl_ch0,*dl_ch0_ext,*rxF,*rxF_ext; unsigned char symbol_mod,pilots=0,j=0,poffset=0; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; pilots = ((symbol_mod==0)||(symbol_mod==(4-frame_parms->Ncp))) ? 1 : 0; l=symbol; nsymb = (frame_parms->Ncp==NORMAL) ? 14:12; if (frame_parms->frame_type == TDD) { // TDD sss_symb = nsymb-1; pss_symb = 2; } else { sss_symb = (nsymb>>1)-2; pss_symb = (nsymb>>1)-1; } if (symbol_mod==(4-frame_parms->Ncp)) poffset=3; for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { if (high_speed_flag == 1) dl_ch0 = &dl_ch_estimates[aarx][5+(symbol*(frame_parms->ofdm_symbol_size))]; else dl_ch0 = &dl_ch_estimates[aarx][5]; dl_ch0_ext = &dl_ch_estimates_ext[aarx][symbol*(frame_parms->N_RB_DL*12)]; rxF_ext = &rxdataF_ext[aarx][symbol*(frame_parms->N_RB_DL*12)]; rxF = &rxdataF[aarx][(frame_parms->first_carrier_offset + (symbol*(frame_parms->ofdm_symbol_size)))]; if ((frame_parms->N_RB_DL&1) == 0) // even number of RBs for (rb=0; rb<frame_parms->N_RB_DL; rb++) { if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // For second half of RBs skip DC carrier if (rb==(frame_parms->N_RB_DL>>1)) { rxF = &rxdataF[aarx][(1 + (symbol*(frame_parms->ofdm_symbol_size)))]; //dl_ch0++; } // PBCH if ((subframe==0) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } if (frame_parms->frame_type == FDD) { //PSS if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if ((frame_parms->frame_type == TDD) && (subframe==6)) { //TDD Subframe 6 if ((rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if (rb_alloc_ind==1) { *pmi_ext = (pmi>>((rb>>2)<<1))&3; memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int)); /* printf("rb %d\n",rb); for (i=0;i<12;i++) printf("(%d %d)",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]); printf("\n"); */ if (pilots==0) { for (i=0; i<12; i++) { rxF_ext[i]=rxF[i]; /* printf("%d : (%d,%d)\n",(rxF+i-&rxdataF[aarx][( (symbol*(frame_parms->ofdm_symbol_size)))]), ((short*)&rxF[i])[0],((short*)&rxF[i])[1]);*/ } dl_ch0_ext+=12; rxF_ext+=12; } else { j=0; for (i=0; i<12; i++) { if ((i!=(frame_parms->nushift+poffset)) && (i!=((frame_parms->nushift+poffset+6)%12))) { rxF_ext[j]=rxF[i]; // printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short*)&rxF_ext[j])); dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=10; rxF_ext+=10; } } dl_ch0+=12; rxF+=12; } else { // Odd number of RBs for (rb=0; rb<frame_parms->N_RB_DL>>1; rb++) { #ifdef DEBUG_DLSCH_DEMOD printf("dlch_ext %u\n",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]); #endif skip_half=0; if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // PBCH if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3 if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=1; else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=2; //SSS if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb)) skip_half=2; //PSS in subframe 0/5 if FDD if (frame_parms->frame_type == FDD) { //FDD if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if ((frame_parms->frame_type == TDD) && (subframe==6)) { //TDD Subframe 6 if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if (rb_alloc_ind==1) { #ifdef DEBUG_DLSCH_DEMOD printf("rb %d/symbol %d (skip_half %d)\n",rb,l,skip_half); #endif if (pilots==0) { // printf("Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); if (skip_half==1) { memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else if (skip_half==2) { memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[(i+6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else { memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int)); for (i=0; i<12; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=12; rxF_ext+=12; } } else { // printf("Extracting with pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); j=0; if (skip_half==1) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i]; } } rxF_ext+=5; dl_ch0_ext+=5; } else if (skip_half==2) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[(i+6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i+6]; } } dl_ch0_ext+=5; rxF_ext+=5; } else { for (i=0; i<12; i++) { if ((i!=(frame_parms->nushift+poffset)) && (i!=((frame_parms->nushift+poffset+6)%12))) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=10; rxF_ext+=10; } } } dl_ch0+=12; rxF+=12; } // first half loop // Do middle RB (around DC) if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // PBCH if ((subframe==0) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (l==sss_symb) ) { rb_alloc_ind = 0; } if (frame_parms->frame_type == FDD) { //PSS if (((subframe==0)||(subframe==5)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } //PSS if ((frame_parms->frame_type == TDD) && (subframe==6) && (l==pss_symb) ) { rb_alloc_ind = 0; } // printf("dlch_ext %d\n",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]); // printf("DC rb %d (%p)\n",rb,rxF); if (rb_alloc_ind==1) { #ifdef DEBUG_DLSCH_DEMOD printf("rb %d/symbol %d (skip_half %d)\n",rb,l,skip_half); #endif if (pilots==0) { for (i=0; i<6; i++) { dl_ch0_ext[i]=dl_ch0[i]; rxF_ext[i]=rxF[i]; } rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; for (; i<12; i++) { dl_ch0_ext[i]=dl_ch0[i]; rxF_ext[i]=rxF[(1+i-6)]; } dl_ch0_ext+=12; rxF_ext+=12; } else { // pilots==1 j=0; for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("**extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j-1],*(1+(short *)&rxF_ext[j-1])); #endif } } rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; for (; i<12; i++) { if (i!=((frame_parms->nushift+6+poffset)%12)) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++]=rxF[(1+i-6)]; #ifdef DEBUG_DLSCH_DEMOD printf("**extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j-1],*(1+(short *)&rxF_ext[j-1])); #endif } } dl_ch0_ext+=10; rxF_ext+=10; } // symbol_mod==0 } // rballoc==1 else { rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; } dl_ch0+=12; rxF+=7; rb++; for (; rb<frame_parms->N_RB_DL; rb++) { // printf("dlch_ext %d\n",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]); // printf("rb %d (%p)\n",rb,rxF); skip_half=0; if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // PBCH if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3 if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=1; else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=2; //SSS if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb)) skip_half=2; if (frame_parms->frame_type == FDD) { //PSS if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } //PSS if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if ((frame_parms->frame_type == TDD) && (subframe==6)) { //TDD Subframe 6 if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if (rb_alloc_ind==1) { #ifdef DEBUG_DLSCH_DEMOD printf("rb %d/symbol %d (skip_half %d)\n",rb,l,skip_half); #endif /* printf("rb %d\n",rb); for (i=0;i<12;i++) printf("(%d %d)",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]); printf("\n"); */ if (pilots==0) { // printf("Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); if (skip_half==1) { memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else if (skip_half==2) { memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[(i+6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else { memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int)); for (i=0; i<12; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=12; rxF_ext+=12; } } else { // printf("Extracting with pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); j=0; if (skip_half==1) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=5; rxF_ext+=5; } else if (skip_half==2) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[(i+6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i+6]; } } dl_ch0_ext+=5; rxF_ext+=5; } else { for (i=0; i<12; i++) { if ((i!=(frame_parms->nushift+poffset)) && (i!=((frame_parms->nushift+poffset+6)%12))) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=10; rxF_ext+=10; } } // pilots=0 } dl_ch0+=12; rxF+=12; } } } return(nb_rb/frame_parms->nb_antennas_rx); } unsigned short dlsch_extract_rbs_dual(int **rxdataF, int **dl_ch_estimates, int **rxdataF_ext, int **dl_ch_estimates_ext, unsigned short pmi, unsigned char *pmi_ext, unsigned int *rb_alloc, unsigned char symbol, unsigned char subframe, uint32_t high_speed_flag, LTE_DL_FRAME_PARMS *frame_parms, MIMO_mode_t mimo_mode) { int prb,nb_rb=0; int prb_off,prb_off2; int rb_alloc_ind,skip_half=0,sss_symb,pss_symb=0,nsymb,l; int i,aarx; int32_t *dl_ch0,*dl_ch0p,*dl_ch0_ext,*dl_ch1,*dl_ch1p,*dl_ch1_ext,*rxF,*rxF_ext; int symbol_mod,pilots=0,j=0; unsigned char *pmi_loc; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; // printf("extract_rbs: symbol_mod %d\n",symbol_mod); if ((symbol_mod == 0) || (symbol_mod == (4-frame_parms->Ncp))) pilots=1; nsymb = (frame_parms->Ncp==NORMAL) ? 14:12; l=symbol; if (frame_parms->frame_type == TDD) { // TDD sss_symb = nsymb-1; pss_symb = 2; } else { sss_symb = (nsymb>>1)-2; pss_symb = (nsymb>>1)-1; } for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { if (high_speed_flag==1) { dl_ch0 = &dl_ch_estimates[aarx][5+(symbol*(frame_parms->ofdm_symbol_size))]; dl_ch1 = &dl_ch_estimates[2+aarx][5+(symbol*(frame_parms->ofdm_symbol_size))]; } else { dl_ch0 = &dl_ch_estimates[aarx][5]; dl_ch1 = &dl_ch_estimates[2+aarx][5]; } pmi_loc = pmi_ext; // pointers to extracted RX signals and channel estimates rxF_ext = &rxdataF_ext[aarx][symbol*(frame_parms->N_RB_DL*12)]; dl_ch0_ext = &dl_ch_estimates_ext[aarx][symbol*(frame_parms->N_RB_DL*12)]; dl_ch1_ext = &dl_ch_estimates_ext[2+aarx][symbol*(frame_parms->N_RB_DL*12)]; for (prb=0; prb<frame_parms->N_RB_DL; prb++) { skip_half=0; if (prb < 32) rb_alloc_ind = (rb_alloc[0]>>prb) & 1; else if (prb < 64) rb_alloc_ind = (rb_alloc[1]>>(prb-32)) & 1; else if (prb < 96) rb_alloc_ind = (rb_alloc[2]>>(prb-64)) & 1; else if (prb < 100) rb_alloc_ind = (rb_alloc[3]>>(prb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; if ((frame_parms->N_RB_DL&1) == 0) { // even number of RBs // PBCH if ((subframe==0) && (prb>=((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; // printf("symbol %d / rb %d: skipping PBCH REs\n",symbol,prb); } //SSS if (((subframe==0)||(subframe==5)) && (prb>=((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; // printf("symbol %d / rb %d: skipping SSS REs\n",symbol,prb); } //PSS in subframe 0/5 if FDD if (frame_parms->frame_type == FDD) { //FDD if (((subframe==0)||(subframe==5)) && (prb>=((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; // printf("symbol %d / rb %d: skipping PSS REs\n",symbol,prb); } } if ((frame_parms->frame_type == TDD) && (subframe==6)) { //TDD Subframe 6 if ((prb>=((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if (rb_alloc_ind==1) { // PRB is allocated prb_off = 12*prb; prb_off2 = 1+(12*(prb-(frame_parms->N_RB_DL>>1))); dl_ch0p = dl_ch0+(12*prb); dl_ch1p = dl_ch1+(12*prb); if (prb<(frame_parms->N_RB_DL>>1)) { rxF = &rxdataF[aarx][prb_off+ frame_parms->first_carrier_offset + (symbol*(frame_parms->ofdm_symbol_size))]; } else { rxF = &rxdataF[aarx][prb_off2+ (symbol*(frame_parms->ofdm_symbol_size))]; } /* if (mimo_mode <= PUSCH_PRECODING1) *pmi_loc = (pmi>>((prb>>2)<<1))&3; else *pmi_loc=(pmi>>prb)&1;*/ *pmi_loc = get_pmi(frame_parms->N_RB_DL,mimo_mode,pmi,prb); pmi_loc++; if (pilots == 0) { memcpy(dl_ch0_ext,dl_ch0p,12*sizeof(int)); memcpy(dl_ch1_ext,dl_ch1p,12*sizeof(int)); memcpy(rxF_ext,rxF,12*sizeof(int)); dl_ch0_ext +=12; dl_ch1_ext +=12; rxF_ext +=12; } else { // pilots==1 j=0; for (i=0; i<12; i++) { if ((i!=frame_parms->nushift) && (i!=frame_parms->nushift+3) && (i!=frame_parms->nushift+6) && (i!=((frame_parms->nushift+9)%12))) { rxF_ext[j]=rxF[i]; // printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short*)&rxF_ext[j])); dl_ch0_ext[j]=dl_ch0p[i]; dl_ch1_ext[j++]=dl_ch1p[i]; } } dl_ch0_ext+=8; dl_ch1_ext+=8; rxF_ext+=8; } // pilots==1 } } else { // Odd number of RBs // PBCH if ((subframe==0) && (prb>((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; // printf("symbol %d / rb %d: skipping PBCH REs\n",symbol,prb); } //SSS if (((subframe==0)||(subframe==5)) && (prb>((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; // printf("symbol %d / rb %d: skipping SSS REs\n",symbol,prb); } //PSS in subframe 0/5 if FDD if (frame_parms->frame_type == FDD) { //FDD if (((subframe==0)||(subframe==5)) && (prb>((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; // printf("symbol %d / rb %d: skipping PSS REs\n",symbol,prb); } } if ((frame_parms->frame_type == TDD) && ((subframe==1) || (subframe==6))) { //TDD Subframe 1-6 if ((prb>((frame_parms->N_RB_DL>>1)-3)) && (prb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if (rb_alloc_ind == 1) { skip_half=0; //Check if we have to drop half a PRB due to PSS/SSS/PBCH // skip_half == 0 means full PRB // skip_half == 1 means first half is used (leftmost half-PRB from PSS/SSS/PBCH) // skip_half == 2 means second half is used (rightmost half-PRB from PSS/SSS/PBCH) //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3 if ((subframe==0) && (prb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=1; else if ((subframe==0) && (prb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=2; //SSS if (((subframe==0)||(subframe==5)) && (prb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (prb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb)) skip_half=2; //PSS Subframe 0,5 if (((frame_parms->frame_type == FDD) && (((subframe==0)||(subframe==5)))) || //FDD Subframes 0,5 ((frame_parms->frame_type == TDD) && (((subframe==1) || (subframe==6))))) { //TDD Subframes 1,6 if ((prb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if ((prb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } prb_off = 12*prb; prb_off2 = 7+(12*(prb-(frame_parms->N_RB_DL>>1)-1)); dl_ch0p = dl_ch0+(12*prb); dl_ch1p = dl_ch1+(12*prb); if (prb<=(frame_parms->N_RB_DL>>1)) { rxF = &rxdataF[aarx][prb_off+ frame_parms->first_carrier_offset + (symbol*(frame_parms->ofdm_symbol_size))]; } else { rxF = &rxdataF[aarx][prb_off2+ (symbol*(frame_parms->ofdm_symbol_size))]; } #ifdef DEBUG_DLSCH_DEMOD printf("symbol %d / rb %d: alloc %d skip_half %d (rxF %p, rxF_ext %p) prb_off (%d,%d)\n",symbol,prb,rb_alloc_ind,skip_half,rxF,rxF_ext,prb_off,prb_off2); #endif /* if (mimo_mode <= PUSCH_PRECODING1) *pmi_loc = (pmi>>((prb>>2)<<1))&3; else *pmi_loc=(pmi>>prb)&1; // printf("symbol_mod %d (pilots %d) rb %d, sb %d, pmi %d (pmi_loc %p,rxF %p, ch00 %p, ch01 %p, rxF_ext %p dl_ch0_ext %p dl_ch1_ext %p)\n",symbol_mod,pilots,prb,prb>>2,*pmi_loc,pmi_loc,rxF,dl_ch0, dl_ch1, rxF_ext,dl_ch0_ext,dl_ch1_ext); */ *pmi_loc = get_pmi(frame_parms->N_RB_DL,mimo_mode,pmi,prb); pmi_loc++; if (prb != (frame_parms->N_RB_DL>>1)) { // This PRB is not around DC if (pilots==0) { if (skip_half==1) { memcpy(dl_ch0_ext,dl_ch0p,6*sizeof(int32_t)); memcpy(dl_ch1_ext,dl_ch1p,6*sizeof(int32_t)); memcpy(rxF_ext,rxF,6*sizeof(int32_t)); #ifdef DEBUG_DLSCH_DEMOD for (i=0; i<6; i++) printf("extract rb %d, re %d => (%d,%d)\n",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif dl_ch0_ext+=6; dl_ch1_ext+=6; rxF_ext+=6; } else if (skip_half==2) { memcpy(dl_ch0_ext,dl_ch0p+6,6*sizeof(int32_t)); memcpy(dl_ch1_ext,dl_ch1p+6,6*sizeof(int32_t)); memcpy(rxF_ext,rxF+6,6*sizeof(int32_t)); #ifdef DEBUG_DLSCH_DEMOD for (i=0; i<6; i++) printf("extract rb %d, re %d => (%d,%d)\n",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif dl_ch0_ext+=6; dl_ch1_ext+=6; rxF_ext+=6; } else { // skip_half==0 memcpy(dl_ch0_ext,dl_ch0p,12*sizeof(int32_t)); memcpy(dl_ch1_ext,dl_ch1p,12*sizeof(int32_t)); memcpy(rxF_ext,rxF,12*sizeof(int32_t)); #ifdef DEBUG_DLSCH_DEMOD for (i=0; i<12; i++) printf("extract rb %d, re %d => (%d,%d)\n",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif dl_ch0_ext+=12; dl_ch1_ext+=12; rxF_ext+=12; } } else { // pilots=1 j=0; if (skip_half==1) { for (i=0; i<6; i++) { if ((i!=frame_parms->nushift) && (i!=((frame_parms->nushift+3)%6))) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("(pilots,skip1)extract rb %d, re %d (%d)=> (%d,%d)\n",prb,i,j,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j]=dl_ch0p[i]; dl_ch1_ext[j++]=dl_ch1p[i]; } } dl_ch0_ext+=4; dl_ch1_ext+=4; rxF_ext+=4; } else if (skip_half==2) { for (i=0; i<6; i++) { if ((i!=frame_parms->nushift) && (i!=((frame_parms->nushift+3)%6))) { rxF_ext[j]=rxF[(i+6)]; #ifdef DEBUG_DLSCH_DEMOD printf("(pilots,skip2)extract rb %d, re %d (%d) => (%d,%d)\n",prb,i,j,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j]=dl_ch0p[i+6]; dl_ch1_ext[j++]=dl_ch1p[i+6]; } } dl_ch0_ext+=4; dl_ch1_ext+=4; rxF_ext+=4; } else { //skip_half==0 for (i=0; i<12; i++) { if ((i!=frame_parms->nushift) && (i!=frame_parms->nushift+3) && (i!=frame_parms->nushift+6) && (i!=((frame_parms->nushift+9)%12))) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("(pilots)extract rb %d, re %d => (%d,%d)\n",prb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j] =dl_ch0p[i]; dl_ch1_ext[j++]=dl_ch1p[i]; } } dl_ch0_ext+=8; dl_ch1_ext+=8; rxF_ext+=8; } //skip_half==0 } //pilots==1 } else { // Do middle RB (around DC) if (pilots==0) { memcpy(dl_ch0_ext,dl_ch0p,6*sizeof(int32_t)); memcpy(dl_ch1_ext,dl_ch1p,6*sizeof(int32_t)); memcpy(rxF_ext,rxF,6*sizeof(int32_t)); #ifdef DEBUG_DLSCH_DEMOD for (i=0; i<6; i++) { printf("extract rb %d, re %d => (%d,%d)\n",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); } #endif rxF_ext+=6; dl_ch0_ext+=6; dl_ch1_ext+=6; dl_ch0p+=6; dl_ch1p+=6; rxF = &rxdataF[aarx][1+((symbol*(frame_parms->ofdm_symbol_size)))]; memcpy(dl_ch0_ext,dl_ch0p,6*sizeof(int32_t)); memcpy(dl_ch1_ext,dl_ch1p,6*sizeof(int32_t)); memcpy(rxF_ext,rxF,6*sizeof(int32_t)); #ifdef DEBUG_DLSCH_DEMOD for (i=0; i<6; i++) { printf("extract rb %d, re %d => (%d,%d)\n",prb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); } #endif rxF_ext+=6; dl_ch0_ext+=6; dl_ch1_ext+=6; } else { // pilots==1 j=0; for (i=0; i<6; i++) { if ((i!=frame_parms->nushift) && (i!=((frame_parms->nushift+3)%6))) { dl_ch0_ext[j]=dl_ch0p[i]; dl_ch1_ext[j]=dl_ch1p[i]; rxF_ext[j++]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("(pilots)extract rb %d, re %d (%d) => (%d,%d)\n",prb,i,j,*(short *)&rxF[i],*(1+(short *)&rxF[i])); #endif } } rxF = &rxdataF[aarx][1+symbol*(frame_parms->ofdm_symbol_size)]; for (; i<12; i++) { if ((i!=((frame_parms->nushift+6)%12)) && (i!=((frame_parms->nushift+9)%12))) { dl_ch0_ext[j]=dl_ch0p[i]; dl_ch1_ext[j]=dl_ch1p[i]; rxF_ext[j++]=rxF[i-6]; #ifdef DEBUG_DLSCH_DEMOD printf("(pilots)extract rb %d, re %d (%d) => (%d,%d)\n",prb,i,j,*(short *)&rxF[1+i-6],*(1+(short *)&rxF[1+i-6])); #endif } } dl_ch0_ext+=8; dl_ch1_ext+=8; rxF_ext+=8; } //pilots==1 } // if Middle PRB } // if odd PRB } // if rballoc==1 } // for prb } // for aarx return(nb_rb/frame_parms->nb_antennas_rx); } unsigned short dlsch_extract_rbs_TM7(int **rxdataF, int **dl_bf_ch_estimates, int **rxdataF_ext, int **dl_bf_ch_estimates_ext, unsigned int *rb_alloc, unsigned char symbol, unsigned char subframe, uint32_t high_speed_flag, LTE_DL_FRAME_PARMS *frame_parms) { unsigned short rb,nb_rb=0; unsigned char rb_alloc_ind; unsigned char i,aarx,l,nsymb,skip_half=0,sss_symb,pss_symb=0; int *dl_ch0,*dl_ch0_ext,*rxF,*rxF_ext; unsigned char symbol_mod,pilots=0,uespec_pilots=0,j=0,poffset=0,uespec_poffset=0; int8_t uespec_nushift = frame_parms->Nid_cell%3; symbol_mod = (symbol>=(7-frame_parms->Ncp)) ? symbol-(7-frame_parms->Ncp) : symbol; pilots = ((symbol_mod==0)||(symbol_mod==(4-frame_parms->Ncp))) ? 1 : 0; l=symbol; nsymb = (frame_parms->Ncp==NORMAL) ? 14:12; if (frame_parms->Ncp==0) { if (symbol==3 || symbol==6 || symbol==9 || symbol==12) uespec_pilots = 1; } else { if (symbol==4 || symbol==7 || symbol==10) uespec_pilots = 1; } if (frame_parms->frame_type == TDD) {// TDD sss_symb = nsymb-1; pss_symb = 2; } else { sss_symb = (nsymb>>1)-2; pss_symb = (nsymb>>1)-1; } if (symbol_mod==(4-frame_parms->Ncp)) poffset=3; if ((frame_parms->Ncp==0 && (symbol==6 ||symbol ==12)) || (frame_parms->Ncp==1 && symbol==7)) uespec_poffset=2; for (aarx=0; aarx<frame_parms->nb_antennas_rx; aarx++) { if (high_speed_flag == 1) dl_ch0 = &dl_bf_ch_estimates[aarx][symbol*(frame_parms->ofdm_symbol_size)]; else dl_ch0 = &dl_bf_ch_estimates[aarx][0]; dl_ch0_ext = &dl_bf_ch_estimates_ext[aarx][symbol*(frame_parms->N_RB_DL*12)]; rxF_ext = &rxdataF_ext[aarx][symbol*(frame_parms->N_RB_DL*12)]; rxF = &rxdataF[aarx][(frame_parms->first_carrier_offset + (symbol*(frame_parms->ofdm_symbol_size)))]; if ((frame_parms->N_RB_DL&1) == 0) // even number of RBs for (rb=0; rb<frame_parms->N_RB_DL; rb++) { if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // For second half of RBs skip DC carrier if (rb==(frame_parms->N_RB_DL>>1)) { rxF = &rxdataF[aarx][(1 + (symbol*(frame_parms->ofdm_symbol_size)))]; //dl_ch0++; } // PBCH if ((subframe==0) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } if (frame_parms->frame_type == FDD) { //PSS if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if ((frame_parms->frame_type == TDD) && (subframe==6)) { //TDD Subframe 6 if ((rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if (rb_alloc_ind==1) { /* printf("rb %d\n",rb); for (i=0;i<12;i++) printf("(%d %d)",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]); printf("\n"); */ if (pilots==0 && uespec_pilots==0) { memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int)); for (i=0; i<12; i++) { rxF_ext[i]=rxF[i]; } dl_ch0_ext+=12; rxF_ext+=12; } else if(pilots==1 && uespec_pilots==0) { j=0; for (i=0; i<12; i++) { if ((i!=(frame_parms->nushift+poffset)) && (i!=((frame_parms->nushift+poffset+6)%12))) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=10; rxF_ext+=10; } else if (pilots==0 && uespec_pilots==1) { j=0; for (i=0; i<12; i++) { if (frame_parms->Ncp==0) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j] = rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; } } else { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j] = rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; } } } dl_ch0_ext+=9-frame_parms->Ncp; rxF_ext+=9-frame_parms->Ncp; } else { LOG_E(PHY,"dlsch_extract_rbs_TM7(dl_demodulation.c):pilot or ue spec pilot detection error\n"); exit(-1); } } dl_ch0+=12; rxF+=12; } else { // Odd number of RBs for (rb=0; rb<frame_parms->N_RB_DL>>1; rb++) { skip_half=0; if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // PBCH if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3 if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=1; else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=2; //SSS if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb)) skip_half=2; //PSS in subframe 0/5 if FDD if (frame_parms->frame_type == FDD) { //FDD if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if ((frame_parms->frame_type == TDD) && ((subframe==1)||(subframe==6))) { //TDD Subframe 1 and 6 if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if (rb_alloc_ind==1) { #ifdef DEBUG_DLSCH_DEMOD printf("rb %d/symbol %d pilots %d, uespec_pilots %d, (skip_half %d)\n",rb,l,pilots,uespec_pilots,skip_half); #endif if (pilots==0 && uespec_pilots==0) { //printf("Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); if (skip_half==1) { memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else if (skip_half==2) { memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[(i+6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else { memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int)); for (i=0; i<12; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract symbol %d rb %d, re %d => (%d,%d)\n",symbol,rb,i,*(short *)&rxF[i],*(1+(short *)&rxF[i])); #endif } dl_ch0_ext+=12; rxF_ext+=12; } } else if (pilots==1 && uespec_pilots==0) { // printf("Extracting with pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); j=0; if (skip_half==1) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=5; rxF_ext+=5; } else if (skip_half==2) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[(i+6)]; dl_ch0_ext[j++]=dl_ch0[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=5; rxF_ext+=5; } else { for (i=0; i<12; i++) { if ((i!=(frame_parms->nushift+poffset)) && (i!=((frame_parms->nushift+poffset+6)%12))) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=10; rxF_ext+=10; } } else if(pilots==0 && uespec_pilots==1) { //printf("Extracting with uespec pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); j=0; if (skip_half==1) { if (frame_parms->Ncp==0) { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6); rxF_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6); } else { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=4; rxF_ext+=4; } } else if (skip_half==2) { if(frame_parms->Ncp==0) { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j]=rxF[(i+6)]; dl_ch0_ext[j++]=dl_ch0[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6); rxF_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6); } else { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j]=rxF[(i+6)]; dl_ch0_ext[j++]=dl_ch0[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=4; rxF_ext+=4; } } else { for (i=0; i<12; i++) { if (frame_parms->Ncp==0) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j] = rxF[i]; dl_ch0_ext[j++] = dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract symbol %d, rb %d, re %d, j %d => (%d,%d)\n", symbol,rb,i,j-1,*(short *)&dl_ch0[j],*(1+(short *)&dl_ch0[i])); #endif } } else { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j] = rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } } dl_ch0_ext+=9-frame_parms->Ncp; rxF_ext+=9-frame_parms->Ncp; } } else { LOG_E(PHY,"dlsch_extract_rbs_TM7(dl_demodulation.c):pilot or ue spec pilot detection error\n"); exit(-1); } } dl_ch0+=12; rxF+=12; } // first half loop // Do middle RB (around DC) if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind == 1) nb_rb++; // PBCH if ((subframe==0) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } if (frame_parms->frame_type == FDD) { //PSS if (((subframe==0)||(subframe==5)) && (rb>=((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } if ((frame_parms->frame_type == TDD) && ((subframe==1)||(subframe==6))) { //PSS if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } } //printf("dlch_ext %d\n",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]); //printf("DC rb %d (%p)\n",rb,rxF); if (rb_alloc_ind==1) { //printf("rb %d/symbol %d (skip_half %d)\n",rb,l,skip_half); if (pilots==0 && uespec_pilots==0) { for (i=0; i<6; i++) { dl_ch0_ext[i]=dl_ch0[i]; rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; for (; i<12; i++) { dl_ch0_ext[i]=dl_ch0[i]; rxF_ext[i]=rxF[(1+i-6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=12; rxF_ext+=12; } else if(pilots==1 && uespec_pilots==0) { // pilots==1 j=0; for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; for (; i<12; i++) { if (i!=((frame_parms->nushift+6+poffset)%12)) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++]=rxF[(1+i-6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=10; rxF_ext+=10; } else if(pilots==0 && uespec_pilots==1) { j=0; for (i=0; i<6; i++) { if (frame_parms->Ncp==0) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++] = rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } else { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++] = rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } } rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; for (; i<12; i++) { if (frame_parms->Ncp==0) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++]=rxF[(1+i-6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } else { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { dl_ch0_ext[j]=dl_ch0[i]; rxF_ext[j++] = rxF[(1+i-6)]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } } dl_ch0_ext+=9-frame_parms->Ncp; rxF_ext+=9-frame_parms->Ncp; }// symbol_mod==0 } // rballoc==1 else { rxF = &rxdataF[aarx][((symbol*(frame_parms->ofdm_symbol_size)))]; } dl_ch0+=12; rxF+=7; rb++; for (; rb<frame_parms->N_RB_DL; rb++) { // printf("dlch_ext %d\n",dl_ch0_ext-&dl_ch_estimates_ext[aarx][0]); // printf("rb %d (%p)\n",rb,rxF); skip_half=0; if (rb < 32) rb_alloc_ind = (rb_alloc[0]>>rb) & 1; else if (rb < 64) rb_alloc_ind = (rb_alloc[1]>>(rb-32)) & 1; else if (rb < 96) rb_alloc_ind = (rb_alloc[2]>>(rb-64)) & 1; else if (rb < 100) rb_alloc_ind = (rb_alloc[3]>>(rb-96)) & 1; else rb_alloc_ind = 0; if (rb_alloc_ind==1) nb_rb++; // PBCH if ((subframe==0) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l>=nsymb>>1) && (l<((nsymb>>1) + 4))) { rb_alloc_ind = 0; } //PBCH subframe 0, symbols nsymb>>1 ... nsymb>>1 + 3 if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=1; else if ((subframe==0) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l>=(nsymb>>1)) && (l<((nsymb>>1) + 4))) skip_half=2; //SSS if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb) ) { rb_alloc_ind = 0; } //SSS if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==sss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==sss_symb)) skip_half=2; //PSS if (frame_parms->frame_type == FDD) { if (((subframe==0)||(subframe==5)) && (rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if (((subframe==0)||(subframe==5)) && (rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if ((frame_parms->frame_type == TDD) && ((subframe==1)||(subframe==6))) { //TDD Subframe 1 and 6 if ((rb>((frame_parms->N_RB_DL>>1)-3)) && (rb<((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb) ) { rb_alloc_ind = 0; } if ((rb==((frame_parms->N_RB_DL>>1)-3)) && (l==pss_symb)) skip_half=1; else if ((rb==((frame_parms->N_RB_DL>>1)+3)) && (l==pss_symb)) skip_half=2; } if (rb_alloc_ind==1) { #ifdef DEBUG_DLSCH_DEMOD printf("rb %d/symbol %d (skip_half %d)\n",rb,l,skip_half); #endif /* printf("rb %d\n",rb); for (i=0;i<12;i++) printf("(%d %d)",((short *)dl_ch0)[i<<1],((short*)dl_ch0)[1+(i<<1)]); printf("\n"); */ if (pilots==0 && uespec_pilots==0) { //printf("Extracting w/o pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); if (skip_half==1) { memcpy(dl_ch0_ext,dl_ch0,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else if (skip_half==2) { memcpy(dl_ch0_ext,dl_ch0+6,6*sizeof(int)); for (i=0; i<6; i++) { rxF_ext[i]=rxF[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=6; rxF_ext+=6; } else { memcpy(dl_ch0_ext,dl_ch0,12*sizeof(int)); //printf("symbol %d, extract rb %d, => (%d,%d)\n",symbol,rb,*(short *)&dl_ch0[j],*(1+(short*)&dl_ch0[i])); for (i=0; i<12; i++) { rxF_ext[i]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } dl_ch0_ext+=12; rxF_ext+=12; } } else if (pilots==1 && uespec_pilots==0) { //printf("Extracting with pilots (symbol %d, rb %d, skip_half %d)\n",l,rb,skip_half); j=0; if (skip_half==1) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=5; rxF_ext+=5; } else if (skip_half==2) { for (i=0; i<6; i++) { if (i!=((frame_parms->nushift+poffset)%6)) { rxF_ext[j]=rxF[(i+6)]; dl_ch0_ext[j++]=dl_ch0[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=5; rxF_ext+=5; } else { for (i=0; i<12; i++) { if ((i!=(frame_parms->nushift+poffset)) && (i!=((frame_parms->nushift+poffset+6)%12))) { rxF_ext[j]=rxF[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[j],*(1+(short *)&rxF_ext[j])); #endif dl_ch0_ext[j++]=dl_ch0[i]; } } dl_ch0_ext+=10; rxF_ext+=10; } } else if(pilots==0 && uespec_pilots==1) { j=0; if (skip_half==1) { if (frame_parms->Ncp==0) { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6); rxF_ext+=6-(uespec_nushift+uespec_poffset<6)-(uespec_nushift+uespec_poffset+4<6)-((uespec_nushift+uespec_poffset+8)%12<6); } else { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j]=rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=4; rxF_ext+=4; } } else if (skip_half==2) { if(frame_parms->Ncp==0) { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j]=rxF[i+6]; dl_ch0_ext[j++]=dl_ch0[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6); rxF_ext+=6-(uespec_nushift+uespec_poffset>6)-(uespec_nushift+uespec_poffset+4>6)-((uespec_nushift+uespec_poffset+8)%12>6); } else { for (i=0; i<6; i++) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j]=rxF[(i+6)]; dl_ch0_ext[j++]=dl_ch0[i+6]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } dl_ch0_ext+=4; rxF_ext+=4; } } else { for (i=0; i<12; i++) { if (frame_parms->Ncp==0) { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+4 && i!=(uespec_nushift+uespec_poffset+8)%12) { rxF_ext[j] = rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } else { if (i!=uespec_nushift+uespec_poffset && i!=uespec_nushift+uespec_poffset+3 && i!=uespec_nushift+uespec_poffset+6 && i!=(uespec_nushift+uespec_poffset+9)%12) { rxF_ext[j] = rxF[i]; dl_ch0_ext[j++]=dl_ch0[i]; #ifdef DEBUG_DLSCH_DEMOD printf("extract rb %d, re %d => (%d,%d)\n",rb,i,*(short *)&rxF_ext[i],*(1+(short *)&rxF_ext[i])); #endif } } } dl_ch0_ext+=9-frame_parms->Ncp; rxF_ext+=9-frame_parms->Ncp; } }// pilots=0 } dl_ch0+=12; rxF+=12; } } } _mm_empty(); _m_empty(); return(nb_rb/frame_parms->nb_antennas_rx); } //============================================================================================== void dump_dlsch2(PHY_VARS_UE *ue,uint8_t eNB_id,uint8_t subframe,unsigned int *coded_bits_per_codeword,int round, unsigned char harq_pid) { #define NSYMB ((ue->frame_parms.Ncp == 0) ? 14 : 12) char fname[32],vname[32]; sprintf(fname,"dlsch%d_rxF_r%d_ext0.m",eNB_id,round); sprintf(vname,"dl%d_rxF_r%d_ext0",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_ext[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); if (ue->frame_parms.nb_antennas_rx >1) { sprintf(fname,"dlsch%d_rxF_r%d_ext1.m",eNB_id,round); sprintf(vname,"dl%d_rxF_r%d_ext1",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_ext[1], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); } sprintf(fname,"dlsch%d_ch_r%d_ext00.m",eNB_id,round); sprintf(vname,"dl%d_ch_r%d_ext00",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); if (ue->transmission_mode[eNB_id]==7) { sprintf(fname,"dlsch%d_bf_ch_r%d.m",eNB_id,round); sprintf(vname,"dl%d_bf_ch_r%d",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_bf_ch_estimates[0],512*NSYMB,1,1); //LOG_M(fname,vname,phy_vars_ue->lte_ue_pdsch_vars[eNB_id]->dl_bf_ch_estimates[0],512,1,1); sprintf(fname,"dlsch%d_bf_ch_r%d_ext00.m",eNB_id,round); sprintf(vname,"dl%d_bf_ch_r%d_ext00",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_bf_ch_estimates_ext[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); } if (ue->frame_parms.nb_antennas_rx == 2) { sprintf(fname,"dlsch%d_ch_r%d_ext01.m",eNB_id,round); sprintf(vname,"dl%d_ch_r%d_ext01",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[1], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); } if (ue->frame_parms.nb_antenna_ports_eNB == 2) { sprintf(fname,"dlsch%d_ch_r%d_ext10.m",eNB_id,round); sprintf(vname,"dl%d_ch_r%d_ext10",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[2], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); if (ue->frame_parms.nb_antennas_rx == 2) { sprintf(fname,"dlsch%d_ch_r%d_ext11.m",eNB_id,round); sprintf(vname,"dl%d_ch_r%d_ext11",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_estimates_ext[3], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); } } sprintf(fname,"dlsch%d_rxF_r%d_uespec0.m",eNB_id,round); sprintf(vname,"dl%d_rxF_r%d_uespec0",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_uespec_pilots[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); /* LOG_M("dlsch%d_ch_ext01.m","dl01_ch0_ext",pdsch_vars[eNB_id]->dl_ch_estimates_ext[1],12*N_RB_DL*NSYMB,1,1); LOG_M("dlsch%d_ch_ext10.m","dl10_ch0_ext",pdsch_vars[eNB_id]->dl_ch_estimates_ext[2],12*N_RB_DL*NSYMB,1,1); LOG_M("dlsch%d_ch_ext11.m","dl11_ch0_ext",pdsch_vars[eNB_id]->dl_ch_estimates_ext[3],12*N_RB_DL*NSYMB,1,1); */ sprintf(fname,"dlsch%d_r%d_rho.m",eNB_id,round); sprintf(vname,"dl_rho_r%d_%d",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_rho_ext[harq_pid][round][0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); sprintf(fname,"dlsch%d_r%d_rho2.m",eNB_id,round); sprintf(vname,"dl_rho2_r%d_%d",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_rho2_ext[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); sprintf(fname,"dlsch%d_rxF_r%d_comp0.m",eNB_id,round); sprintf(vname,"dl%d_rxF_r%d_comp0",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_comp0[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); if (ue->frame_parms.nb_antenna_ports_eNB == 2) { sprintf(fname,"dlsch%d_rxF_r%d_comp1.m",eNB_id,round); sprintf(vname,"dl%d_rxF_r%d_comp1",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->rxdataF_comp1[harq_pid][round][0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); } sprintf(fname,"dlsch%d_rxF_r%d_llr.m",eNB_id,round); sprintf(vname,"dl%d_r%d_llr",eNB_id,round); LOG_M(fname,vname, ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->llr[0],coded_bits_per_codeword[0],1,0); sprintf(fname,"dlsch%d_r%d_mag1.m",eNB_id,round); sprintf(vname,"dl%d_r%d_mag1",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_mag0[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); sprintf(fname,"dlsch%d_r%d_mag2.m",eNB_id,round); sprintf(vname,"dl%d_r%d_mag2",eNB_id,round); LOG_M(fname,vname,ue->pdsch_vars[ue->current_thread_id[subframe]][eNB_id]->dl_ch_magb0[0], 12*(ue->frame_parms.N_RB_DL)*NSYMB,1,1); }
{ "alphanum_fraction": 0.5656752979, "avg_line_length": 43.9786975046, "ext": "c", "hexsha": "aafd579899ad023de7cbc7e0c843b75bab09215d", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-05-30T08:01:04.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-06T16:35:41.000Z", "max_forks_repo_head_hexsha": "2195e8e4cf6c8c5e059b0e982620480225bfa17a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "LaughingBlue/openairinterface5g", "max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2195e8e4cf6c8c5e059b0e982620480225bfa17a", "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": "LaughingBlue/openairinterface5g", "max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_line_length": 343, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2195e8e4cf6c8c5e059b0e982620480225bfa17a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "LaughingBlue/openairinterface5g", "max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/dlsch_demodulation.c", "max_stars_repo_stars_event_max_datetime": "2021-03-08T07:58:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-08T07:58:23.000Z", "num_tokens": 98051, "size": 289028 }
#pragma once #include "commons.h" #include "Instancing.h" #include <renderer/VertexSpecification.h> #include <gsl/gsl> namespace ad { namespace vertex3D { struct Data { Vec<3, GLfloat> mPosition; Vec<3, GLfloat> mNormal{0.f, 0.f, 1.f}; }; constexpr AttributeDescriptionList gDescription = { { 0, 3, offsetof(Data, mPosition), MappedGL<GLfloat>::enumerator}, { 1, 3, offsetof(Data, mNormal), MappedGL<GLfloat>::enumerator}, }; inline Data operator*(const Data & aLhs, const Matrix<4> & aRhs) { Vec<4> position{aLhs.mPosition.x(), aLhs.mPosition.y(), aLhs.mPosition.z(), 1.0f}; Vec<4> normal{aLhs.mNormal.x(), aLhs.mNormal.y(), aLhs.mNormal.z(), 0.0f}; position *= aRhs; normal *= aRhs; return { {position.x(), position.y(), position.z()}, {normal.x(), normal.y(), normal.z()}, }; } inline const gsl::span<Data> & operator*=(const gsl::span<Data> & aLhs, const Matrix<4> & aRhs) { std::transform(aLhs.begin(), aLhs.end(), aLhs.begin(), [&aRhs](const Data & data){ return data * aRhs; }); return aLhs; } } // namespace vertex3D template <> class BufferData_trait<vertex3D::Data> { public: static constexpr AttributeDescriptionList description_value = vertex3D::gDescription; }; namespace ship3D { static const std::array<vertex3D::Data, 4> gVertices = { vertex3D::Data{ {-1.25f, -1.5f, 0.0f}, }, vertex3D::Data{ { 3.75f, 0.0f, 0.0f}, }, vertex3D::Data{ {-1.25f, 1.5f, 0.0f}, }, vertex3D::Data{ { 0.0f, 0.0f, 0.0f}, }, }; } // namespace ship3D namespace cube { static constexpr float cpi4 = 0.70710678f; static const std::array<vertex3D::Data, 8*3> gVertices = { // Frontface vertex3D::Data{ {-1.0f, -1.0f, 1.0f}, {-cpi4, 0.0f, cpi4}, }, vertex3D::Data{ {-1.0f, 1.0f, 1.0f}, {-cpi4, 0.0f, cpi4}, }, vertex3D::Data{ {-1.0f, 1.0f, 1.0f}, { 0.0f, cpi4, cpi4}, }, vertex3D::Data{ { 1.0f, 1.0f, 1.0f}, { 0.0f, cpi4, cpi4}, }, vertex3D::Data{ { 1.0f, 1.0f, 1.0f}, { cpi4, 0.0f, cpi4}, }, vertex3D::Data{ { 1.0f, -1.0f, 1.0f}, { cpi4, 0.0f, cpi4}, }, vertex3D::Data{ { 1.0f, -1.0f, 1.0f}, { 0.0f, -cpi4, cpi4}, }, vertex3D::Data{ {-1.0f, -1.0f, 1.0f}, { 0.0f, -cpi4, cpi4}, }, // Backface vertex3D::Data{ {-1.0f, -1.0f, -1.0f}, {-cpi4, 0.0f, -cpi4}, }, vertex3D::Data{ {-1.0f, 1.0f, -1.0f}, {-cpi4, 0.0f, -cpi4}, }, vertex3D::Data{ {-1.0f, 1.0f, -1.0f}, { 0.0f, cpi4, -cpi4}, }, vertex3D::Data{ { 1.0f, 1.0f, -1.0f}, { 0.0f, cpi4, -cpi4}, }, vertex3D::Data{ { 1.0f, 1.0f, -1.0f}, { cpi4, 0.0f, -cpi4}, }, vertex3D::Data{ { 1.0f, -1.0f, -1.0f}, { cpi4, 0.0f, -cpi4}, }, vertex3D::Data{ { 1.0f, -1.0f, -1.0f}, { 0.0f, -cpi4, -cpi4}, }, vertex3D::Data{ {-1.0f, -1.0f, -1.0f}, { 0.0f, -cpi4, -cpi4}, }, // Connect vertex3D::Data{ {-1.0f, -1.0f, -1.0f}, {-cpi4, -cpi4, 0.0f}, }, vertex3D::Data{ {-1.0f, -1.0f, +1.0f}, {-cpi4, -cpi4, 0.0f}, }, vertex3D::Data{ {-1.0f, 1.0f, -1.0f}, {-cpi4, cpi4, 0.0f}, }, vertex3D::Data{ {-1.0f, 1.0f, +1.0f}, {-cpi4, cpi4, 0.0f}, }, vertex3D::Data{ { 1.0f, 1.0f, -1.0f}, { cpi4, cpi4, 0.0f}, }, vertex3D::Data{ { 1.0f, 1.0f, +1.0f}, { cpi4, cpi4, 0.0f}, }, vertex3D::Data{ { 1.0f, -1.0f, -1.0f}, { cpi4, -cpi4, 0.0f}, }, vertex3D::Data{ { 1.0f, -1.0f, +1.0f}, { cpi4, -cpi4, 0.0f}, }, }; } // namespace cube namespace circle3D { enum Type { Circle, Disc, }; template <GLsizei N_vertices, Type N_type = Circle> std::vector<vertex3D::Data> makeVertices(GLfloat aRadius) { std::vector<vertex3D::Data> result; if (N_type == Disc) { result.push_back(vertex3D::Data{ {0.f, 0.f, 0.f}, }); } //result.reserve(N_vertices+2); for(int i=0; i<=N_vertices; ++i) { result.emplace_back(vertex3D::Data{{ cos(2*pi<float>*i/N_vertices) * aRadius, sin(2*pi<float>*i/N_vertices) * aRadius, 0.f, }, { 0.f, 0.f, N_type == Disc ? -1.f : 1.0f, }}); } return result; } } // namespace circle3D namespace rectangle3D { inline std::vector<vertex3D::Data> makeVertices(Size<2> aDimensions) { return { { {+aDimensions.width()/2.f, +aDimensions.height()/2.f, 0.f} }, { {-aDimensions.width()/2.f, +aDimensions.height()/2.f, 0.f} }, { {-aDimensions.width()/2.f, -aDimensions.height()/2.f, 0.f} }, { {+aDimensions.width()/2.f, -aDimensions.height()/2.f, 0.f} }, }; } } // namespace rectangle3D namespace instance3D { struct Data { Vec<2, GLfloat> mPosition; Matrix<4, GLfloat> mOrientationScale{Matrix<4, GLfloat>::Identity()}; }; constexpr AttributeDescriptionList gDescription = { {2, 2, offsetof(Data, mPosition), MappedGL<GLfloat>::enumerator}, {3, 4, offsetof(Data, mOrientationScale), MappedGL<GLfloat>::enumerator}, {4, 4, offsetof(Data, mOrientationScale) + 4*sizeof(GLfloat), MappedGL<GLfloat>::enumerator}, {5, 4, offsetof(Data, mOrientationScale) + 8*sizeof(GLfloat), MappedGL<GLfloat>::enumerator}, {6, 4, offsetof(Data, mOrientationScale) + 12*sizeof(GLfloat), MappedGL<GLfloat>::enumerator}, }; } // namespace instance3D template <> class BufferData_trait<instance3D::Data> { public: static constexpr AttributeDescriptionList description_value = instance3D::gDescription; }; } // namespace ad
{ "alphanum_fraction": 0.4968253968, "avg_line_length": 23.6842105263, "ext": "h", "hexsha": "8207777c743a3f66bd60df04d04401d5eabdbdc2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:17:54.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-31T13:17:54.000Z", "max_forks_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "FranzPoize/shmurp", "max_forks_repo_path": "src/app/shmurp/shapes3D.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "FranzPoize/shmurp", "max_issues_repo_path": "src/app/shmurp/shapes3D.h", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "FranzPoize/shmurp", "max_stars_repo_path": "src/app/shmurp/shapes3D.h", "max_stars_repo_stars_event_max_datetime": "2021-04-06T08:48:31.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-06T08:48:31.000Z", "num_tokens": 2292, "size": 6300 }
/* This file is auto-generated from countpairs_s_mu_mocks_impl.c.src */ #ifndef DOUBLE_PREC #define DOUBLE_PREC #endif // # -*- mode: c -*- /* File: countpairs_s_mu_mocks_impl.c.src */ /* This file is a part of the Corrfunc package Copyright (C) 2015-- Manodeep Sinha (manodeep@gmail.com) License: MIT LICENSE. See LICENSE file under the top-level directory at https://github.com/manodeep/Corrfunc/ */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <gsl/gsl_interp.h> #include "countpairs_s_mu_mocks_impl_double.h" #include "countpairs_s_mu_mocks_kernels_double.c" #include "cellarray_mocks_double.h" #include "gridlink_mocks_impl_double.h" #include "defs.h" #include "utils.h" #include "cosmology_params.h" #include "set_cosmo_dist.h" #include "cpu_features.h" #include "progressbar.h" #include "proj_functions_double.h" #if defined(_OPENMP) #include <omp.h> #endif int interrupt_status_DDsmu_mocks_double=EXIT_SUCCESS; void interrupt_handler_countpairs_s_mu_mocks_double(int signo) { fprintf(stderr,"Received signal = `%s' (signo = %d). Aborting \n",strsignal(signo), signo); interrupt_status_DDsmu_mocks_double = EXIT_FAILURE; } int check_ra_dec_cz_s_mu_double(const int64_t N, double *phi, double *theta, double *cz) { if(N==0) { return EXIT_SUCCESS; } if(phi == NULL || theta == NULL || cz == NULL) { fprintf(stderr,"Input arrays can not be NULL. Have RA = %p DEC = %p cz = %p\n", phi, theta, cz); return EXIT_FAILURE; } int fix_cz = 0; int fix_ra = 0; int fix_dec = 0; const double max_cz_threshold = 10.0;//if I find that max cz is smaller than this threshold, then I will assume z has been supplied rather than cz double max_cz = 0.0; //Check input cz -> ensure that cz contains cz and not z for(int64_t i=0;i<N;i++) { if(cz[i] > max_cz) max_cz = cz[i]; if(phi[i] < 0.0) { fix_ra = 1; } if(theta[i] > 90.0) { fix_dec = 1; } if(theta[i] > 180) { fprintf(stderr,"theta[%"PRId64"] = %"REAL_FORMAT"should be less than 180 deg\n", i, theta[i]); return EXIT_FAILURE; } } if(max_cz < max_cz_threshold) fix_cz = 1; //Only run the loop if something needs to be fixed if(fix_cz==1 || fix_ra == 1 || fix_dec == 1) { if(fix_ra == 1) { fprintf(stderr,"%s> Out of range values found for ra. Expected ra to be in the range [0.0,360.0]. Found ra values in [-180,180] -- fixing that\n", __FUNCTION__); } if(fix_dec == 1) { fprintf(stderr,"%s> Out of range values found for dec. Expected dec to be in the range [-90.0,90.0]. Found dec values in [0,180] -- fixing that\n", __FUNCTION__); } if(fix_cz == 1) { fprintf(stderr,"%s> Out of range values found for cz. Expected input to be `cz' but found `z' instead. max_cz (found in input) = %"REAL_FORMAT" threshold " "= %"REAL_FORMAT"\n",__FUNCTION__,max_cz,max_cz_threshold); } for(int64_t i=0;i<N;i++) { if(fix_ra==1) { phi[i] += (double) 180.0; } if(fix_dec==1) { theta[i] -= (double) 90.0; } if(fix_cz == 1) { cz[i] *= (double) SPEED_OF_LIGHT;//input was z -> convert to cz } } } return EXIT_SUCCESS; } countpairs_mocks_func_ptr_double countpairs_s_mu_mocks_driver_double(const struct config_options *options) { static countpairs_mocks_func_ptr_double function = NULL; static isa old_isa=-1; if(old_isa == options->instruction_set) { return function; } /* Array of function pointers */ countpairs_mocks_func_ptr_double allfunctions[] = { #ifdef __AVX__ countpairs_s_mu_mocks_avx_intrinsics_double, #endif #ifdef __SSE4_2__ countpairs_s_mu_mocks_sse_intrinsics_double, #endif countpairs_s_mu_mocks_fallback_double }; const int num_functions = sizeof(allfunctions)/sizeof(void *); const int fallback_offset = num_functions - 1; #if defined(__AVX__) || defined __SSE4_2__ const int highest_isa = instrset_detect(); #endif int curr_offset = 0; /* Now check if AVX is supported by the CPU */ int avx_offset = fallback_offset; #ifdef __AVX__ avx_offset = highest_isa >= 7 ? curr_offset:fallback_offset; curr_offset++; #endif /* Is the SSE function supported at runtime and enabled at compile-time?*/ int sse_offset = fallback_offset; #ifdef __SSE4_2__ sse_offset = highest_isa >= 6 ? curr_offset:fallback_offset; curr_offset++; #endif if( curr_offset != fallback_offset) { fprintf(stderr,"ERROR: Bug in code (current offset = %d *should equal* fallback function offset = %d)\n", curr_offset, fallback_offset); return NULL; } int function_dispatch=0; /* Check that cpu supports feature */ if(options->instruction_set >= 0) { switch(options->instruction_set) { case(AVX512F): case(AVX2): case(AVX):function_dispatch=avx_offset;break; case(SSE42): function_dispatch=sse_offset;break; default:function_dispatch=fallback_offset;break; } } if(function_dispatch >= num_functions) { fprintf(stderr,"In %s> ERROR: Could not resolve the correct function.\n Function index = %d must lie between [0, %d)\n", __FUNCTION__, function_dispatch, num_functions); return NULL; } function = allfunctions[function_dispatch]; old_isa = options->instruction_set; if(options->verbose){ // This must be first (AVX/SSE may be aliased to fallback) if(function_dispatch == fallback_offset){ fprintf(stderr,"Using fallback kernel\n"); } else if(function_dispatch == avx_offset){ fprintf(stderr,"Using AVX kernel\n"); } else if(function_dispatch == sse_offset){ fprintf(stderr,"Using SSE kernel\n"); } else { printf("Unknown kernel!\n"); } } return function; } int countpairs_mocks_s_mu_double(const int64_t ND1, double *ra1, double *dec1, double *czD1, const int64_t ND2, double *ra2, double *dec2, double *czD2, const int numthreads, const int autocorr, const char *sbinfile, const double max_mu, const int nmu_bins, const int cosmology, results_countpairs_mocks_s_mu *results, struct config_options *options, struct extra_options *extra) { if(options->float_type != sizeof(double)) { fprintf(stderr,"ERROR: In %s> Can only handle arrays of size=%zu. Got an array of size = %zu\n", __FUNCTION__, sizeof(double), options->float_type); return EXIT_FAILURE; } // If no extra options were passed, create dummy options // This allows us to pass arguments like "extra->weights0" below; // they'll just be NULLs, which is the correct behavior struct extra_options dummy_extra; if(extra == NULL){ weight_method_t dummy_method = NONE; dummy_extra = get_extra_options(dummy_method); extra = &dummy_extra; } int need_weightavg = extra->weight_method != NONE; options->sort_on_z = 1; struct timeval t0; if(options->c_api_timer) { gettimeofday(&t0, NULL); } if(options->fast_divide_and_NR_steps >= MAX_FAST_DIVIDE_NR_STEPS) { fprintf(stderr, ANSI_COLOR_MAGENTA"Warning: The number of requested Newton-Raphson steps = %u is larger than max. allowed steps = %u." " Switching to a standard divide"ANSI_COLOR_RESET"\n", options->fast_divide_and_NR_steps, MAX_FAST_DIVIDE_NR_STEPS); options->fast_divide_and_NR_steps = 0; } //Check inputs if(ND1 == 0 || (autocorr == 0 && ND2 == 0)) { return EXIT_SUCCESS; } //Check inputs int status1 = check_ra_dec_cz_s_mu_double(ND1, ra1, dec1, czD1); if(status1 != EXIT_SUCCESS) { return status1; } if(autocorr==0) { int status2 = check_ra_dec_cz_s_mu_double(ND2, ra2, dec2, czD2); if(status2 != EXIT_SUCCESS) { return status2; } } #if defined(_OPENMP) omp_set_num_threads(numthreads); #else (void) numthreads; #endif if(options->max_cells_per_dim == 0) { fprintf(stderr,"Warning: Max. cells per dimension is set to 0 - resetting to `NLATMAX' = %d\n", NLATMAX); options->max_cells_per_dim = NLATMAX; } for(int i=0;i<3;i++) { if(options->bin_refine_factors[i] < 1) { fprintf(stderr,"Warning: bin refine factor along axis = %d *must* be >=1. Instead found bin refine factor =%d\n", i, options->bin_refine_factors[i]); reset_bin_refine_factors(options); break;/* all factors have been reset -> no point continuing with the loop */ } } /* setup interrupt handler -> mostly useful during the python execution. Let's Ctrl-C abort the extension */ SETUP_INTERRUPT_HANDLERS(interrupt_handler_countpairs_s_mu_mocks_double); //Try to initialize cosmology - code will exit if comoslogy is not implemented. //Putting in a different scope so I can call the variable status { int status = init_cosmology(cosmology); if(status != EXIT_SUCCESS) { return status; } } /*********************** *initializing the bins ************************/ double *supp; int nsbin; double smin,smax; setup_bins(sbinfile,&smin,&smax,&nsbin,&supp); if( ! (smin > 0.0 && smax > 0.0 && smin < smax && nsbin > 0)) { fprintf(stderr,"Error: Could not setup with S bins correctly. (smin = %lf, smax = %lf, with nbins = %d). Expected non-zero smin/smax with smax > smin and nbins >=1 \n", smin, smax, nsbin); return EXIT_FAILURE; } if(max_mu <= 0.0 || max_mu > 1.0) { fprintf(stderr,"Error: max_mu (max. value for the cosine of the angle with line of sight) must be greater than 0 and at most 1).\n" "The passed value is max_mu = %lf. Please change it to be > 0 and <= 1.0\n", max_mu); return EXIT_FAILURE; } if(nmu_bins < 1 ) { fprintf(stderr,"Error: Number of mu bins = %d must be at least 1\n", nmu_bins); return EXIT_FAILURE; } //Change cz into co-moving distance double *D1 = NULL, *D2 = NULL; if(options->is_comoving_dist == 0) { D1 = my_malloc(sizeof(*D1),ND1); D2 = autocorr == 0 ? my_malloc(sizeof(*D2),ND2):D1; } else { D1 = czD1; D2 = autocorr == 0 ? czD2:czD1; } if(D1 == NULL || D2 == NULL) { free(D1);free(D2); return EXIT_FAILURE; } if(options->is_comoving_dist == 0) { //Setup variables to do the cz->comoving distance double czmax = 0.0; const double inv_speed_of_light = 1.0/SPEED_OF_LIGHT; get_max_double(ND1, czD1, &czmax); if(autocorr == 0) { get_max_double(ND2, czD2, &czmax); } const double zmax = czmax * inv_speed_of_light + 0.01; const int workspace_size = 10000; double *interp_redshift = my_calloc(sizeof(*interp_redshift), workspace_size);//the interpolation is done in 'z' and not in 'cz' double *interp_comoving_dist = my_calloc(sizeof(*interp_comoving_dist),workspace_size); int Nzdc = set_cosmo_dist(zmax, workspace_size, interp_redshift, interp_comoving_dist, cosmology); if(Nzdc < 0) { free(interp_redshift);free(interp_comoving_dist); return EXIT_FAILURE; } gsl_interp *interpolation; gsl_interp_accel *accelerator; accelerator = gsl_interp_accel_alloc(); interpolation = gsl_interp_alloc (gsl_interp_linear,Nzdc); gsl_interp_init(interpolation, interp_redshift, interp_comoving_dist, Nzdc); for(int64_t i=0;i<ND1;i++) { D1[i] = gsl_interp_eval(interpolation, interp_redshift, interp_comoving_dist, czD1[i]*inv_speed_of_light, accelerator); } if(autocorr==0) { for(int64_t i=0;i<ND2;i++) { D2[i] = gsl_interp_eval(interpolation, interp_redshift, interp_comoving_dist, czD2[i]*inv_speed_of_light, accelerator); } } free(interp_redshift);free(interp_comoving_dist); gsl_interp_free(interpolation); gsl_interp_accel_free(accelerator); } double *X1 = my_malloc(sizeof(*X1), ND1); double *Y1 = my_malloc(sizeof(*Y1), ND1); double *Z1 = my_malloc(sizeof(*Z1), ND1); if(X1 == NULL || Y1 == NULL || Z1 == NULL) { free(X1);free(Y1);free(Z1); return EXIT_FAILURE; } for(int64_t i=0;i<ND1;i++) { X1[i] = D1[i]*COSD(dec1[i])*COSD(ra1[i]); Y1[i] = D1[i]*COSD(dec1[i])*SIND(ra1[i]); Z1[i] = D1[i]*SIND(dec1[i]); } double *X2,*Y2,*Z2; if(autocorr==0) { X2 = my_malloc(sizeof(*X2), ND2); Y2 = my_malloc(sizeof(*Y2), ND2); Z2 = my_malloc(sizeof(*Z2), ND2); for(int64_t i=0;i<ND2;i++) { X2[i] = D2[i]*COSD(dec2[i])*COSD(ra2[i]); Y2[i] = D2[i]*COSD(dec2[i])*SIND(ra2[i]); Z2[i] = D2[i]*SIND(dec2[i]); } } else { X2 = X1; Y2 = Y1; Z2 = Z1; } double supp_sqr[nsbin]; for(int i=0; i < nsbin;i++) { supp_sqr[i] = supp[i]*supp[i]; } const double mu_max = (double) max_mu; double xmin=1e10,ymin=1e10,zmin=1e10; double xmax=-1e10,ymax=-1e10,zmax=-1e10; get_max_min_data_double(ND1, X1, Y1, Z1, &xmin, &ymin, &zmin, &xmax, &ymax, &zmax); if(autocorr==0) { get_max_min_data_double(ND2, X2, Y2, Z2, &xmin, &ymin, &zmin, &xmax, &ymax, &zmax); } const double xdiff = xmax-xmin; const double ydiff = ymax-ymin; const double zdiff = zmax-zmin; if(get_bin_refine_scheme(options) == BINNING_DFL) { if(smax < 0.05*xdiff) { options->bin_refine_factors[0] = 1; } if(smax < 0.05*ydiff) { options->bin_refine_factors[1] = 1; } if(smax < 0.05*zdiff) { options->bin_refine_factors[2] = 1; } } /*---Create 3-D lattice--------------------------------------*/ int nmesh_x=0,nmesh_y=0,nmesh_z=0; cellarray_mocks_index_particles_double *lattice1 = gridlink_mocks_index_particles_double(ND1, X1, Y1, Z1, D1, &(extra->weights0), xmin, xmax, ymin, ymax, zmin, zmax, smax, smax, smax, options->bin_refine_factors[0], options->bin_refine_factors[1], options->bin_refine_factors[2], &nmesh_x, &nmesh_y, &nmesh_z, options); if(lattice1 == NULL) { return EXIT_FAILURE; } /* If there too few cells (BOOST_CELL_THRESH is ~10), and the number of cells can be increased, then boost bin refine factor by ~1*/ const double avg_np = ((double)ND1)/(nmesh_x*nmesh_y*nmesh_z); const int8_t max_nmesh = fmax(nmesh_x, fmax(nmesh_y, nmesh_z)); if((max_nmesh <= BOOST_CELL_THRESH || avg_np >= BOOST_NUMPART_THRESH) && max_nmesh < options->max_cells_per_dim) { fprintf(stderr,"%s> gridlink seems inefficient. nmesh = (%d, %d, %d); avg_np = %.3g. ", __FUNCTION__, nmesh_x, nmesh_y, nmesh_z, avg_np); if(get_bin_refine_scheme(options) == BINNING_DFL) { fprintf(stderr,"Boosting bin refine factor - should lead to better performance\n"); // Only boost the first two dimensions. Prevents excessive refinement. for(int i=0;i<2;i++) { options->bin_refine_factors[i] += BOOST_BIN_REF; } free_cellarray_mocks_index_particles_double(lattice1, nmesh_x * (int64_t) nmesh_y * nmesh_z); lattice1 = gridlink_mocks_index_particles_double(ND1, X1, Y1, Z1, D1, &(extra->weights0), xmin, xmax, ymin, ymax, zmin, zmax, smax, smax, smax, options->bin_refine_factors[0], options->bin_refine_factors[1], options->bin_refine_factors[2], &nmesh_x, &nmesh_y, &nmesh_z, options); if(lattice1 == NULL) { return EXIT_FAILURE; } } else { fprintf(stderr,"Boosting bin refine factor could have helped. However, since custom bin refine factors " "= (%d, %d, %d) are being used - continuing with inefficient mesh\n", options->bin_refine_factors[0], options->bin_refine_factors[1], options->bin_refine_factors[2]); } } cellarray_mocks_index_particles_double *lattice2 = NULL; if(autocorr==0) { int ngrid2_x=0,ngrid2_y=0,ngrid2_z=0; lattice2 = gridlink_mocks_index_particles_double(ND2, X2, Y2, Z2, D2, &(extra->weights1), xmin, xmax, ymin, ymax, zmin, zmax, smax, smax, smax, options->bin_refine_factors[0], options->bin_refine_factors[1], options->bin_refine_factors[2], &ngrid2_x, &ngrid2_y, &ngrid2_z, options); if(lattice2 == NULL) { return EXIT_FAILURE; } if( ! (nmesh_x == ngrid2_x && nmesh_y == ngrid2_y && nmesh_z == ngrid2_z) ) { fprintf(stderr,"Error: The two sets of 3-D lattices do not have identical bins. First has dims (%d, %d, %d) while second has (%d, %d, %d)\n", nmesh_x, nmesh_y, nmesh_z, ngrid2_x, ngrid2_y, ngrid2_z); return EXIT_FAILURE; } } else { lattice2 = lattice1; } free(X1);free(Y1);free(Z1); if(autocorr == 0) { free(X2);free(Y2);free(Z2); } if(options->is_comoving_dist == 0) { free(D1); if(autocorr == 0) { free(D2); } } const int64_t totncells = (int64_t) nmesh_x * (int64_t) nmesh_y * (int64_t) nmesh_z; { int status = assign_ngb_cells_mocks_index_particles_double(lattice1, lattice2, totncells, options->bin_refine_factors[0], options->bin_refine_factors[1], options->bin_refine_factors[2], nmesh_x, nmesh_y, nmesh_z, autocorr); if(status != EXIT_SUCCESS) { free_cellarray_mocks_index_particles_double(lattice1, totncells); if(autocorr == 0) { free_cellarray_mocks_index_particles_double(lattice2, totncells); } free(supp); return EXIT_FAILURE; } } /*---Gridlink-variables----------------*/ const int totnbins = (nmu_bins+1)*(nsbin+1); const int nprojbins = nsbin-1; #if defined(_OPENMP) uint64_t **all_npairs = (uint64_t **) matrix_calloc(sizeof(uint64_t), numthreads, totnbins); double **all_savg = NULL; if(options->need_avg_sep){ all_savg = (double **) matrix_calloc(sizeof(double),numthreads,totnbins); } double **all_weightavg = NULL; if(need_weightavg) { all_weightavg = (double **) matrix_calloc(sizeof(double),numthreads,totnbins); } double **all_projpairs = (double **) matrix_calloc(sizeof(double),numthreads,nprojbins); double **all_projpairs_tensor = (double **) matrix_calloc(sizeof(double),numthreads,nprojbins*nprojbins); #else //USE_OMP uint64_t npairs[totnbins]; double savg[totnbins], weightavg[totnbins], projpairs[nprojbins]; double projpairs_tensor[nprojbins*nprojbins]; for(int i=0; i <totnbins;i++) { npairs[i] = 0; if(options->need_avg_sep) { savg[i] = ZERO; } if(need_weightavg) { weightavg[i] = ZERO; } } for(int i=0;i<nprojbins;i++) { projpairs[i] = ZERO; for(int j=0;j<nprojbins;j++) { projpairs_tensor[i*nprojbins+j] = ZERO; } } #endif //USE_OMP /* runtime dispatch - get the function pointer */ countpairs_mocks_func_ptr_double countpairs_s_mu_mocks_function_double = countpairs_s_mu_mocks_driver_double(options); if(countpairs_s_mu_mocks_function_double == NULL) { return EXIT_FAILURE; } int interrupted=0,numdone=0, abort_status=EXIT_SUCCESS; if(options->verbose) { init_my_progressbar(totncells,&interrupted); } #if defined(_OPENMP) #pragma omp parallel shared(numdone, abort_status, interrupt_status_DDsmu_mocks_double) { const int tid = omp_get_thread_num(); uint64_t npairs[totnbins]; double savg[totnbins], weightavg[totnbins], projpairs[nprojbins]; double projpairs_tensor[nprojbins*nprojbins]; for(int i=0;i<totnbins;i++) { npairs[i] = 0; if(options->need_avg_sep) { savg[i] = ZERO; } if(need_weightavg) { weightavg[i] = ZERO; } } for(int i=0;i<nprojbins;i++) { projpairs[i] = ZERO; for(int j=0;j<nprojbins;j++) { projpairs_tensor[i*nprojbins+j] = ZERO; } } #pragma omp for schedule(dynamic) #endif//USE_OMP /*---Loop-over-Data1-particles--------------------*/ for(int64_t index1=0;index1<totncells;index1++) { #if defined(_OPENMP) #pragma omp flush (abort_status, interrupt_status_DDsmu_mocks_double) #endif if(abort_status == EXIT_SUCCESS && interrupt_status_DDsmu_mocks_double == EXIT_SUCCESS) { //omp cancel was introduced in omp 4.0 - so this is my way of checking if loop needs to be cancelled /* If the verbose option is not enabled, avoid outputting anything unnecessary*/ if(options->verbose) { #if defined(_OPENMP) if (omp_get_thread_num() == 0) #endif my_progressbar(numdone,&interrupted); #if defined(_OPENMP) #pragma omp atomic #endif numdone++; } const cellarray_mocks_index_particles_double *first = &(lattice1[index1]); if(first->nelements == 0) { continue; } double *x1 = first->x; double *y1 = first->y; double *z1 = first->z; double *d1 = first->cz; const weight_struct_double *weights1 = &(first->weights); const int64_t N1 = first->nelements; if(autocorr == 1) { int same_cell = 1; double *this_savg = options->need_avg_sep ? &(savg[0]):NULL; double *this_weightavg = need_weightavg ? weightavg:NULL; const int status = countpairs_s_mu_mocks_function_double(N1, x1, y1, z1, d1, weights1, N1, x1, y1, z1, d1, weights1, same_cell, options->fast_divide_and_NR_steps, smax, smin, nsbin, nmu_bins, supp_sqr, mu_max, this_savg, npairs, projpairs, projpairs_tensor, this_weightavg, extra->weight_method); /* This actually causes a race condition under OpenMP - but mostly I care that an error occurred - rather than the exact value of the error status */ abort_status |= status; } for(int64_t ngb=0;ngb<first->num_ngb;ngb++){ const cellarray_mocks_index_particles_double *second = first->ngb_cells[ngb]; if(second->nelements == 0) { continue; } const int same_cell = 0; double *x2 = second->x; double *y2 = second->y; double *z2 = second->z; double *d2 = second->cz; const weight_struct_double *weights2 = &(second->weights); const int64_t N2 = second->nelements; double *this_savg = options->need_avg_sep ? &(savg[0]):NULL; double *this_weightavg = need_weightavg ? weightavg:NULL; const int status = countpairs_s_mu_mocks_function_double(N1, x1, y1, z1, d1, weights1, N2, x2, y2, z2, d2, weights2, same_cell, options->fast_divide_and_NR_steps, smax, smin, nsbin, nmu_bins, supp_sqr, mu_max, this_savg, npairs, projpairs, projpairs_tensor, this_weightavg, extra->weight_method); /* This actually causes a race condition under OpenMP - but mostly I care that an error occurred - rather than the exact value of the error status */ abort_status |= status; }//loop over ngb cells }//abort_status check }//i loop over ND1 particles #if defined(_OPENMP) for(int i=0;i<totnbins;i++) { all_npairs[tid][i] = npairs[i]; if(options->need_avg_sep) { all_savg[tid][i] = savg[i]; } if(need_weightavg) { all_weightavg[tid][i] = weightavg[i]; } } for (int i=0;i<nprojbins;i++) { all_projpairs[tid][i] = projpairs[i]; for(int j=0;j<nprojbins;j++) { all_projpairs_tensor[tid][i*nprojbins+j] = projpairs_tensor[i*nprojbins+j]; } } }//close the omp parallel region #endif//USE_OMP free_cellarray_mocks_index_particles_double(lattice1,totncells); if(autocorr == 0) { free_cellarray_mocks_index_particles_double(lattice2,totncells); } if(abort_status != EXIT_SUCCESS || interrupt_status_DDsmu_mocks_double != EXIT_SUCCESS) { /* Cleanup memory here if aborting */ free(supp); #if defined(_OPENMP) matrix_free((void **) all_npairs, numthreads); if(options->need_avg_sep) { matrix_free((void **) all_savg, numthreads); } if(need_weightavg) { matrix_free((void **) all_weightavg, numthreads); } matrix_free((void **) all_projpairs, numthreads); matrix_free((void **) all_projpairs_tensor, numthreads); #endif return EXIT_FAILURE; } if(options->verbose) { finish_myprogressbar(&interrupted); } #if defined(_OPENMP) uint64_t npairs[totnbins]; double savg[totnbins], weightavg[totnbins], projpairs[nprojbins]; double projpairs_tensor[nprojbins*nprojbins]; for(int i=0;i<totnbins;i++) { npairs[i] = 0; if(options->need_avg_sep) { savg[i] = ZERO; } if(need_weightavg) { weightavg[i] = ZERO; } } for(int i=0;i<nprojbins;i++) { projpairs[i] = ZERO; for(int j=0;j<nprojbins;j++) { projpairs_tensor[i*nprojbins+j] = ZERO; } } for(int i=0;i<numthreads;i++) { for(int j=0;j<totnbins;j++) { npairs[j] += all_npairs[i][j]; if(options->need_avg_sep) { savg[j] += all_savg[i][j]; } if(need_weightavg) { weightavg[j] += all_weightavg[i][j]; } } for(int j=0;j<nprojbins;j++) { projpairs[j] += all_projpairs[i][j]; for(int k=0;k<nprojbins;k++) { projpairs_tensor[j*nprojbins+k] += all_projpairs_tensor[i][j*nprojbins+k]; } } } matrix_free((void **) all_npairs, numthreads); if(options->need_avg_sep) { matrix_free((void **) all_savg, numthreads); } if(need_weightavg) { matrix_free((void **) all_weightavg, numthreads); } matrix_free((void **) all_projpairs, numthreads); matrix_free((void **) all_projpairs_tensor, numthreads); #endif //USE_OMP //The code does not double count for autocorrelations //which means the npairs and savg values need to be doubled; if(autocorr == 1) { const uint64_t int_fac = 2; const double dbl_fac = (double) 2.0; for(int i=0;i<totnbins;i++) { npairs[i] *= int_fac; if(options->need_avg_sep) { savg[i] *= dbl_fac; } if(need_weightavg) { weightavg[i] *= dbl_fac; } } //TODO: do i also want to double this? think so for(int i=0;i<nprojbins;i++) { projpairs[i] *= dbl_fac; for(int j=0;j<nprojbins;j++) { projpairs_tensor[i*nprojbins+j] *= dbl_fac; } } } for(int i=0;i<totnbins;i++) { if(npairs[i] > 0) { if(options->need_avg_sep) { savg[i] /= (double) npairs[i] ; } if(need_weightavg) { weightavg[i] /= (double) npairs[i]; } } } // don't need proj_pairs here, not averaging results->nsbin = nsbin; results->nmu_bins = nmu_bins; results->mu_max = max_mu;//NOTE max_mu which is double and not mu_max (which might be float) results->mu_min = ZERO; results->npairs = my_malloc(sizeof(*(results->npairs)), totnbins); results->projpairs = my_malloc(sizeof(*(results->npairs)), nprojbins); results->projpairs_tensor = my_malloc(sizeof(*(results->npairs)), nprojbins*nprojbins); results->supp = my_malloc(sizeof(*(results->supp)) , nsbin); results->savg = my_malloc(sizeof(*(results->savg)) , totnbins); results->weightavg = my_calloc(sizeof(double) , totnbins); if(results->npairs == NULL || results->supp == NULL || results->savg == NULL || results->weightavg == NULL || results->projpairs == NULL) { free_results_mocks_s_mu(results); free(supp); return EXIT_FAILURE; } for(int i=0;i<nsbin;i++) { results->supp[i] = supp[i]; for(int j=0;j<nmu_bins;j++) { const int index = i*(nmu_bins+1) + j; if( index >= totnbins ) { fprintf(stderr, "ERROR: In %s> index = %d must be in range [0, %d)\n", __FUNCTION__, index, totnbins); free_results_mocks_s_mu(results); free(supp); return EXIT_FAILURE; } results->npairs[index] = npairs[index]; results->savg[index] = ZERO; results->weightavg[index] = ZERO; if(options->need_avg_sep) { results->savg[index] = savg[index]; } if(need_weightavg) { results->weightavg[index] = weightavg[index]; } } } for(int i=0;i<nprojbins;i++) { results->projpairs[i] = projpairs[i]; for(int j=0;j<nprojbins;j++) { results->projpairs_tensor[i*nprojbins+j] = projpairs_tensor[i*nprojbins+j]; } } free(supp); /* reset interrupt handlers to default */ RESET_INTERRUPT_HANDLERS(); reset_bin_refine_factors(options); if(options->c_api_timer) { struct timeval t1; gettimeofday(&t1, NULL); options->c_api_time = ADD_DIFF_TIME(t0, t1); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5406177311, "avg_line_length": 38.9483944954, "ext": "c", "hexsha": "0cda749c5cdf450bb0175acf7b7aca87d156f069", "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": "ff72167804f55c46486c3b35143c6da62cf2779a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kstoreyf/foo", "max_forks_repo_path": "mocks/DDsmu_mocks/countpairs_s_mu_mocks_impl_double.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a", "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": "kstoreyf/foo", "max_issues_repo_path": "mocks/DDsmu_mocks/countpairs_s_mu_mocks_impl_double.c", "max_line_length": 176, "max_stars_count": null, "max_stars_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kstoreyf/foo", "max_stars_repo_path": "mocks/DDsmu_mocks/countpairs_s_mu_mocks_impl_double.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8333, "size": 33963 }
#ifndef __GSL_BLOCK_H__ #define __GSL_BLOCK_H__ #include <gsl/gsl_block_complex_long_double.h> #include <gsl/gsl_block_complex_double.h> #include <gsl/gsl_block_complex_float.h> #include <gsl/gsl_block_long_double.h> #include <gsl/gsl_block_double.h> #include <gsl/gsl_block_float.h> #include <gsl/gsl_block_ulong.h> #include <gsl/gsl_block_long.h> #include <gsl/gsl_block_uint.h> #include <gsl/gsl_block_int.h> #include <gsl/gsl_block_ushort.h> #include <gsl/gsl_block_short.h> #include <gsl/gsl_block_uchar.h> #include <gsl/gsl_block_char.h> #endif /* __GSL_BLOCK_H__ */
{ "alphanum_fraction": 0.7931034483, "avg_line_length": 23.2, "ext": "h", "hexsha": "c9cc863a3b6fa34082af3d03be8c1268c8b4d7ba", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "gsl-2.6/gsl/gsl_block.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/gsl/gsl_block.h", "max_line_length": 46, "max_stars_count": null, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/gsl/gsl_block.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 170, "size": 580 }
#include <string.h> #include <cblas.h> #include "util.h" #include "dense.h" denseLayer denseLayer_init(int M, int N) { denseLayer dl; DENSEL_INIT(dl); dl.M=M; dl.N=N; return dl; } void denseLayer_free(denseLayer *dl) { ftens_free(&dl->W); ftens_free(&dl->b); ftens_free(&dl->dW); ftens_free(&dl->db); ftens_free(&dl->out); ftens_free(&dl->in); } void denseLayer_print_shape(denseLayer *dl) { printf("dense: %d %d\n", dl->M, dl->N); } void denseLayer_set(ftens *W, denseLayer *dl) { const int M=W->M, N=W->N; ASSERT(W->D==1 && W->L==1, "err: dense shape\n"); ftens_free(&dl->W); dl->M = M; dl->N = N; dl->W = ftens_copy(W); } void denseLayer_forward(ftens *t, denseLayer *dl, int save) { const int D=t->D, M=dl->M, N=dl->N; ASSERT(t->MNL == dl->N, "err: dense shape\n"); if (save) { int M=t->M, N=t->N, L=t->L; if (!dl->in.data) dl->in = ftens_init(D,M,N,L); memcpy(dl->in.data, t->data, t->bytes); } if (!dl->out.data) dl->out = ftens_init(D, 1, M, 1); const float *a=dl->W.data; const float *b=t->data; float *c=dl->out.data; cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, D, M, N, 1, b, N, a, N, 0, c, M); } void denseLayer_backward(ftens *dout, denseLayer *dl) { fprintf(stderr, "not implemented yet\n"); exit(-2); }
{ "alphanum_fraction": 0.5595744681, "avg_line_length": 21.3636363636, "ext": "c", "hexsha": "756e6a6ee92cad93f48719a129c1b4da115dd782", "lang": "C", "max_forks_count": 21, "max_forks_repo_forks_event_max_datetime": "2021-09-16T17:50:19.000Z", "max_forks_repo_forks_event_min_datetime": "2017-06-10T17:50:57.000Z", "max_forks_repo_head_hexsha": "84e359418845ad80923c563716848216df94db12", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "pppoe/espresso", "max_forks_repo_path": "src/layers/densel.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "84e359418845ad80923c563716848216df94db12", "max_issues_repo_issues_event_max_datetime": "2019-04-18T08:06:59.000Z", "max_issues_repo_issues_event_min_datetime": "2017-06-20T06:06:58.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "pppoe/espresso", "max_issues_repo_path": "src/layers/densel.c", "max_line_length": 59, "max_stars_count": 55, "max_stars_repo_head_hexsha": "84e359418845ad80923c563716848216df94db12", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "pppoe/espresso", "max_stars_repo_path": "src/layers/densel.c", "max_stars_repo_stars_event_max_datetime": "2021-01-04T03:18:53.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-01T15:17:05.000Z", "num_tokens": 488, "size": 1410 }
#pragma once #include "Cesium3DTiles/BoundingVolume.h" #include "Cesium3DTiles/Library.h" #include "Cesium3DTiles/TileContentLoadInput.h" #include "Cesium3DTiles/TileContentLoadResult.h" #include "Cesium3DTiles/TileContentLoader.h" #include "Cesium3DTiles/TileID.h" #include "Cesium3DTiles/TileRefine.h" #include <gsl/span> #include <spdlog/fwd.h> #include <cstddef> #include <functional> #include <memory> #include <optional> #include <unordered_map> namespace Cesium3DTiles { class TileContent; class Tileset; /** * @brief Creates {@link TileContentLoadResult} objects from a {@link * TileContentLoadInput}. * * The class offers a lookup functionality for registering {@link * TileContentLoader} instances that can create {@link TileContentLoadResult} * instances from a {@link TileContentLoadInput}. * * The loaders are registered based on the magic header or the content type * of the input data. The raw data (i.e. the `data` of the {@link * TileContentLoadInput}) is usually received as a response to a network * request, and the first four bytes of the raw data form the magic header. * Based on this header or the content type of the network response, the loader * that will be used for processing the input can be looked up. */ class CESIUM3DTILES_API TileContentFactory final { public: TileContentFactory() = delete; /** * @brief Register the given function for the given magic header. * * The given magic header is a 4-character string. It will be compared * to the first 4 bytes of the raw input data, to decide whether the * given factory function should be used to create the * {@link TileContentLoadResult} from the input data. * * @param magic The string describing the magic header. * @param pLoader The loader that will be used to create the tile content. */ static void registerMagic( const std::string& magic, const std::shared_ptr<TileContentLoader>& pLoader); /** * @brief Register the given function for the given content type. * * The given string describes the content type of a network response. * It is used for deciding whether the given loader should be * used to create the {@link TileContentLoadResult} from a * {@link TileContentLoadInput} with the same `contentType`. * * @param contentType The string describing the content type. * @param pLoader The loader that will be used to create the tile content */ static void registerContentType( const std::string& contentType, const std::shared_ptr<TileContentLoader>& pLoader); /** * @brief Creates the {@link TileContentLoadResult} from the given {@link * TileContentLoadInput}. * * This will look up the {@link TileContentLoader} that can be used to * process the given input data, based on all loaders that * have been registered with {@link TileContentFactory::registerMagic} * or {@link TileContentFactory::registerContentType}. * * It will first try to find a loader based on the magic header * of the `data` in the given input. If no matching loader is found, then * it will look up a loader based on the `contentType` of the given input. * (This will ignore any parameters that may appear after a `;` in the * `contentType` string). * * If no such loader is found then `nullptr` is returned. * * If a matching loader is found, it will be applied to the given * input, and the result will be returned. * * @param input The {@link TileContentLoadInput}. * @return The {@link TileContentLoadResult}, or `nullptr` if there is * no loader registered for the magic header of the given * input, and no loader for the content type of the input. */ static std::unique_ptr<TileContentLoadResult> createContent(const TileContentLoadInput& input); private: static std::optional<std::string> getMagic(const gsl::span<const std::byte>& data); static std::unordered_map<std::string, std::shared_ptr<TileContentLoader>> _loadersByMagic; static std::unordered_map<std::string, std::shared_ptr<TileContentLoader>> _loadersByContentType; }; } // namespace Cesium3DTiles
{ "alphanum_fraction": 0.7317131858, "avg_line_length": 37.1071428571, "ext": "h", "hexsha": "b31547acd92529f04d3f0eced7efb0ca9eac9598", "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": "18a295f47b3118cc2edfc22354d93b938a68069c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "MAPSWorks/cesium-native", "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentFactory.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "18a295f47b3118cc2edfc22354d93b938a68069c", "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": "MAPSWorks/cesium-native", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentFactory.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b824699d3dd9503a5943007247f683b6adc132d4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "TJKoury/cesium-native", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentFactory.h", "max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z", "num_tokens": 1011, "size": 4156 }
/* Starting from version 7.8, MATLAB BLAS expects ptrdiff_t arguments for integers */ #if MATLAB_VERSION >= 0x0708 #include <stddef.h> #include <stdlib.h> #endif #include <string.h> /* Define MX_HAS_INTERLEAVED_COMPLEX for version <9.4 */ #ifndef MX_HAS_INTERLEAVED_COMPLEX #define MX_HAS_INTERLEAVED_COMPLEX 0 #endif /* Starting from version 7.6, MATLAB BLAS is seperated */ #if MATLAB_VERSION >= 0x0705 #include <blas.h> #endif #include <lapack.h> #include "f2c.h" // Conversion of optimal problems with coupling weighting terms to standard problems #define sb02mt FORTRAN_WRAPPER(sb02mt) extern void sb02mt( const char *jobg, const char *jobl, const char *fact, const char *uplo, const ptrdiff_t *n, const ptrdiff_t *m, double *a, const ptrdiff_t *lda, double *b, const ptrdiff_t *ldb, double *q, const ptrdiff_t *ldq, double *r, const ptrdiff_t *ldr, double *l, const ptrdiff_t *ldl, ptrdiff_t *ipiv, ptrdiff_t *oufact, double *g, const ptrdiff_t *ldg, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Conversion of optimal problems with coupling weighting terms to standard problems (more flexibility) #define sb02mx FORTRAN_WRAPPER(sb02mx) extern void sb02mx( const char *jobg, const char *jobl, const char *fact, const char *uplo, const char *trans, const char *flag, const char *def, const ptrdiff_t *n, const ptrdiff_t *m, double *a, const ptrdiff_t *lda, double *b, const ptrdiff_t *ldb, double *q, const ptrdiff_t *ldq, double *r, const ptrdiff_t *ldr, double *l, const ptrdiff_t *ldl, ptrdiff_t *ipiv, ptrdiff_t *oufact, double *g, const ptrdiff_t *ldg, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Constructing the 2n-by-2n Hamiltonian or symplectic matrix for linear-quadratic optimization problems #define sb02mu FORTRAN_WRAPPER(sb02mu) extern void sb02mu( const char *dico, const char *hinv, const char *uplo, const ptrdiff_t *n, double *a, const ptrdiff_t *lda, const double *g, const ptrdiff_t *ldg, const double *q, const ptrdiff_t *ldq, double *s, const ptrdiff_t *lds, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Constructing the 2n-by-2n Hamiltonian or symplectic matrix for linear-quadratic optimization problems (improved) #define sb02ru FORTRAN_WRAPPER(sb02ru) extern void sb02ru( const char *dico, const char *hinv, const char *trana, const char *uplo, const ptrdiff_t *n, const double *a, const ptrdiff_t *lda, double *g, const ptrdiff_t *ldg, double *q, const ptrdiff_t *ldq, double *s, const ptrdiff_t *lds, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Constructing the extended Hamiltonian or symplectic matrix pairs for linear-quadratic optimization problems, and compressing them to 2N-by-2N matrices #define sb02oy FORTRAN_WRAPPER(sb02oy) extern void sb02oy( const char *type, const char *dico, const char *jobb, const char *fact, const char *uplo, const char *jobl, const char *jobe, const ptrdiff_t *n, const ptrdiff_t *m, const ptrdiff_t *p, const double *a, const ptrdiff_t *lda, const double *b, const ptrdiff_t *ldb, const double *q, const ptrdiff_t *ldq, const double *r, const ptrdiff_t *ldr, const double *l, const ptrdiff_t *ldl, const double *e, const ptrdiff_t *lde, double *af, const ptrdiff_t *ldaf, double *bf, const ptrdiff_t *ldbf, double *tol, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Optimal state feedback matrix for an optimal control problem #define sb02nd FORTRAN_WRAPPER(sb02nd) extern void sb02nd( const char *dico, const char *fact, const char *uplo, const char *jobl, const ptrdiff_t *n, const ptrdiff_t *m, const ptrdiff_t *p, const double *a, const ptrdiff_t *lda, double *b, const ptrdiff_t *ldb, double *r, const ptrdiff_t *ldr, ptrdiff_t *ipiv, const double *l, const ptrdiff_t *ldl, double *x, const ptrdiff_t *ldx, const double *rnorm, double *f, const ptrdiff_t *ldf, ptrdiff_t *oufact, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Solution of continuous- or discrete-time algebraic Riccati equations for descriptor systems #define sg02nd FORTRAN_WRAPPER(sg02nd) extern void sg02nd( const char *dico, const char *jobe, const char *job, const char *jobx, const char *fact, const char *uplo, const char *jobl, const char *trans, const ptrdiff_t *n, const ptrdiff_t *m, const ptrdiff_t *p, const double *a, const ptrdiff_t *lda, const double *e, const ptrdiff_t *lde, double *b, const ptrdiff_t *ldb, double *r, const ptrdiff_t *ldr, ptrdiff_t *ipiv, const double *l, const ptrdiff_t *ldl, double *x, const ptrdiff_t *ldx, const double *rnorm, double *k, const ptrdiff_t *ldk, double *h, const ptrdiff_t *ldh, double *xe, const ptrdiff_t *ldxe, ptrdiff_t *oufact, ptrdiff_t *iwork, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Column interchanges in a complex matrix #define ma02gz FORTRAN_WRAPPER(ma02gz) extern void ma02gz( const ptrdiff_t *n, double *a, const ptrdiff_t *lda, const ptrdiff_t *k1, const ptrdiff_t *k2, const ptrdiff_t *ipiv, const ptrdiff_t *incx ); // Solution of linear equations X op(A) = B #define mb02vd FORTRAN_WRAPPER(mb02vd) extern void mb02vd( const char *trans, const ptrdiff_t *m, const ptrdiff_t *n, double *a, const ptrdiff_t *lda, ptrdiff_t *ipiv, double *b, const ptrdiff_t *ldb, ptrdiff_t *info ); // Periodic Hessenberg form of a product of p matrices using orthogonal similarity transformations #define mb03vd FORTRAN_WRAPPER(mb03vd) extern void mb03vd( const ptrdiff_t *n, const ptrdiff_t *p, const ptrdiff_t *ilo, const ptrdiff_t *ihi, double *a, const ptrdiff_t *lda1, const ptrdiff_t *lda2, double *tau, const ptrdiff_t *ldtau, double *dwork, ptrdiff_t *info ); // Orthogonal matrices for reduction to periodic Hessenberg form of a product of matrices #define mb03vy FORTRAN_WRAPPER(mb03vy) extern void mb03vy( const ptrdiff_t *n, const ptrdiff_t *p, const ptrdiff_t *ilo, const ptrdiff_t *ihi, double *a, const ptrdiff_t *lda1, const ptrdiff_t *lda2, double *tau, const ptrdiff_t *ldtau, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Schur decomposition and eigenvalues of a product of matrices in periodic Hessenberg form #define mb03wd FORTRAN_WRAPPER(mb03wd) extern void mb03wd( const char *job, const char *compz, const ptrdiff_t *n, const ptrdiff_t *p, const ptrdiff_t *ilo, const ptrdiff_t *ihi, const ptrdiff_t *iloz, const ptrdiff_t *ihiz, double *h, const ptrdiff_t *ldh1, const ptrdiff_t *ldh2, double *z, const ptrdiff_t *ldz1, const ptrdiff_t *ldz2, double *wr, double *wi, double *dwork, const ptrdiff_t *ldwork, ptrdiff_t *info ); // Computes the general product of K complex scalars trying to avoid over- and underflow. #define zlapr1 FORTRAN_WRAPPER(zlapr1) extern int zlapr1( doublereal *base, integer *k, integer *s, doublecomplex *a, integer *inca, doublecomplex *alpha, doublecomplex *beta, integer *scal ); // Finding the eigenvalues of the complex generalized matrix product. #define zpgeqz FORTRAN_WRAPPER(zpgeqz) extern int zpgeqz( char *job, char *compq, integer *k, integer *n, integer *ilo, integer *ihi, integer *s, doublecomplex *a, integer *lda1, integer *lda2, doublecomplex *alpha, doublecomplex *beta, integer *scal, doublecomplex *q, integer *ldq1, integer *ldq2, doublereal *dwork, integer *ldwork, doublecomplex *zwork, integer *lzwork, integer *info ); // Swaps adjacent diagonal 1-by-1 blocks in a complex generalized matrix product. #define zpgex2 FORTRAN_WRAPPER(zpgex2) extern int zpgex2( logical *wantq, integer *k, integer *n, integer *j, integer *s, doublecomplex *a, integer *lda1, integer *lda2, doublecomplex *q, integer *ldq1, integer *ldq2, doublecomplex *zwork, integer *info ); // Swaps adjacent diagonal 1-by-1 blocks in a complex generalized matrix product. #define zpghrd FORTRAN_WRAPPER(zpghrd) extern int zpghrd( char *compq, integer *k, integer *n, integer *ilo, integer *ihi, integer *s, doublecomplex *a, integer *lda1, integer *lda2, doublecomplex *q, integer *ldq1, integer *ldq2, doublereal *dwork, integer *ldwork, doublecomplex *zwork, integer *lzwork, integer *info ); // Reorders the periodic Schur decomposition of a complex generalized matrix product. #define zpgord FORTRAN_WRAPPER(zpgord) extern int zpgord( logical *wantq, integer *k, integer *n, integer *s, logical *select, doublecomplex *a, integer *lda1, integer *lda2, doublecomplex *alpha, doublecomplex *beta, integer *scal, doublecomplex *q, integer *ldq1, integer *ldq2, integer *m, doublecomplex *zwork, integer *lzwork, integer *info );
{ "alphanum_fraction": 0.5583026777, "avg_line_length": 27.830952381, "ext": "h", "hexsha": "ecf044e0dad5a907b905d22af3196620a6b91880", "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": "515076c0b6b7c6643378427553b4c302dc29ed3b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "iwoodsawyer/dpre", "max_forks_repo_path": "dprex.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "515076c0b6b7c6643378427553b4c302dc29ed3b", "max_issues_repo_issues_event_max_datetime": "2022-01-03T21:11:59.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-25T15:47:07.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "iwoodsawyer/dpre", "max_issues_repo_path": "dprex.h", "max_line_length": 154, "max_stars_count": 1, "max_stars_repo_head_hexsha": "515076c0b6b7c6643378427553b4c302dc29ed3b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "iwoodsawyer/dpre", "max_stars_repo_path": "dprex.h", "max_stars_repo_stars_event_max_datetime": "2021-11-17T13:13:08.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-17T13:13:08.000Z", "num_tokens": 2993, "size": 11689 }
/*This class introduces a method to work with experimental fitness landscapes given in a data file in the format sequence fitness 1 0 1 ... 1.987 and brings the adjacency matrix as well as other helpful properties (cc) Johannes Neidhart, 2012*/ #ifndef LANDSCAPE_H #define LANDSCAPE_H #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_multifit_nlin.h> #include <vector> #include <algorithm> #include <cmath> #include <map> #include <numeric> using namespace std; class Clandscape { private: vector < vector < int> > linekey; int n, L; string name; int delta(int, int); int hamming( vector < int >, vector < int > ); public: /*Clandscape gets a vector containing the fitness values, in the order of the linenumbers of the data file, a vector of vectors, containing the correspondance of the line number and the sequence. Sequence length and number of sequences are also given. */ double binomial (int, int); Clandscape (string, int , int); int distance (int, int); vector < double > fitness; void fitit( vector < double >, vector < double >, vector < double > &); void fit(vector <double>, vector < double > &, vector < double > &, double); vector < vector < int > > adjacency; vector < double > spectrum(); vector < vector < int > > hypercube; }; #endif
{ "alphanum_fraction": 0.6439490446, "avg_line_length": 28.5454545455, "ext": "h", "hexsha": "09c619fe9bb89fe84364b070910fcd750ef400cf", "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": "6424398778cf72d016154750acf17c1abcfe7c21", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "PidZero/Amplitudemaker", "max_forks_repo_path": "landscape.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6424398778cf72d016154750acf17c1abcfe7c21", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "PidZero/Amplitudemaker", "max_issues_repo_path": "landscape.h", "max_line_length": 88, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6424398778cf72d016154750acf17c1abcfe7c21", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "PidZero/Amplitudemaker", "max_stars_repo_path": "landscape.h", "max_stars_repo_stars_event_max_datetime": "2016-07-19T21:44:17.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-17T22:02:09.000Z", "num_tokens": 379, "size": 1570 }
#ifndef setup_h #define setup_h #include <ceed.h> #include <petsc.h> #include <petscdmplex.h> #include <petscfe.h> #include <petscksp.h> #include <stdbool.h> #include <string.h> #include "problems/problems.h" #include "include/cl-options.h" #include "include/matops.h" #include "include/misc.h" #include "include/structs.h" #include "include/setup-dm.h" #include "include/setup-libceed.h" #include "include/utils.h" #endif // setup_h
{ "alphanum_fraction": 0.7362385321, "avg_line_length": 20.7619047619, "ext": "h", "hexsha": "0a669982c9f8056bbc547874abd1d230d724cc7b", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/solids/elasticity.h", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/solids/elasticity.h", "max_line_length": 34, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/solids/elasticity.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 112, "size": 436 }
#include <cblas.h> const char* dgemm_desc = "Reference dgemm."; /* * This routine performs a dgemm operation * C := C + A * B * where A, B, and C are lda-by-lda matrices stored in column-major format. * On exit, A and B maintain their input values. * This function wraps a call to the BLAS-3 routine DGEMM, * via the standard FORTRAN interface - hence the reference semantics. */ void square_dgemm(int n, double* A, double* B, double* C) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1., A, n, B, n, 1., C, n); }
{ "alphanum_fraction": 0.6837294333, "avg_line_length": 34.1875, "ext": "c", "hexsha": "9b51a7ba6317aa9009c0d0ee80722fda14870c8f", "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": "808689cb24afcd9232b7ad189db0746d7820b8ec", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "AnthonyNg404/Parallel-Computing", "max_forks_repo_path": "hw1-knl/dgemm-blas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "808689cb24afcd9232b7ad189db0746d7820b8ec", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "AnthonyNg404/Parallel-Computing", "max_issues_repo_path": "hw1-knl/dgemm-blas.c", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "808689cb24afcd9232b7ad189db0746d7820b8ec", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "AnthonyNg404/Parallel-Computing", "max_stars_repo_path": "hw1-knl/dgemm-blas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 171, "size": 547 }
#ifndef UTILS_STRINGS_ONE_AWAY_H_INCLUDED #define UTILS_STRINGS_ONE_AWAY_H_INCLUDED #include <string> // std::string #include <gsl/gsl> bool isOneAway(const std::string &, const std::string &); #endif
{ "alphanum_fraction": 0.7832512315, "avg_line_length": 22.5555555556, "ext": "h", "hexsha": "66c45af4f7eca129391903c33945d2fa632f6aca", "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": "af08794fd21f67ee603c3538bb07a4cd9b5bc999", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tiagoinacio/algorithms_cpp", "max_forks_repo_path": "src/utils/strings/one-away.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999", "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": "tiagoinacio/algorithms_cpp", "max_issues_repo_path": "src/utils/strings/one-away.h", "max_line_length": 57, "max_stars_count": null, "max_stars_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tiagoinacio/algorithms_cpp", "max_stars_repo_path": "src/utils/strings/one-away.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 54, "size": 203 }
/*========================================================== * pca.c - Principal component analysis of diffraction data * * Calculates the two main components of the data * by Principal Component Analysis, as detailed in * Bernhardt et.al (2016), Biophys. J. * * The calling syntax is: * * pca(data, mask, qx, qy, w, phi, m, n) * * Copyright 2017 Institute for X-ray Physics (University of Göttingen) * * 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. * *========================================================*/ #include <math.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> #define PI 3.14159265 /* The computational routine */ void symmetry(double *x, double *bgr, double sigma, double noise_level, int m, int n) { int delta_theta = 20; /* hard coded theta window size */ int col; int row; /* calculate snr */ for (row=0; row<m; row++) { for (col=0; col<n; col++) { if (bgr[row*m + col] == 0){ x[row*m + col] = 0; } else { x[row*m + col] = (x[row*m + col] - bgr[row*m + col]) / sqrt(bgr[row*m + col]); } } /* next we implement % Gaussian filter (remove noise) h = fspecial('gaussian', [10 10], sigma); h = h./sum(h(:)); snr = conv2(snr,h,'same'); % binary image (snr threshold) binary_image = (snr >= noise_level); */ /* prepare fft */ work = gsl_fft_real_workspace_alloc (n); real = gsl_fft_real_wavetable_alloc (n); /* fourier transform the rows */ for (int row = 0; row < m; row++){ double* data = x[row*m]; gsl_fft_real_transform (data, 1, n, real, work); gsl_fft_real_wavetable_free (real); /* apply filter HERE */ hc = gsl_fft_halfcomplex_wavetable_alloc (n); gsl_fft_halfcomplex_inverse (data, 1, n, hc, work); gsl_fft_halfcomplex_wavetable_free (hc); gsl_fft_real_workspace_free (work); } /* fourier transform the rows */ /* apply gauss filter */ /* fourier-backtransform the rows */ /* fourier-backtransform the cols */ /* apply threshold */ for (row=0; row<m; row++) { for (col=0; col<n; col++) { if (x[row*m + col] > noise_level){ x[row*m + col] = 1; } else { x[row*m + col] = 0; } } }
{ "alphanum_fraction": 0.6004056795, "avg_line_length": 33.8333333333, "ext": "c", "hexsha": "b0c5b3b0766e0d030e5a1c89575743c94b97655f", "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/symmetry.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/symmetry.c", "max_line_length": 94, "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/symmetry.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 844, "size": 3451 }
#include "redisgears.h" #include "redisai.h" #include "minmax_heap.h" #include <math.h> #include "redisgears_memory.h" #include <cblas.h> #include <sys/time.h> #define STR1(a) #a #define STR(e) STR1(e) #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) static RedisModuleCtx* staticCtx; static RecordType* ScoreRecordType = NULL; static RecordType* HeapRecordType = NULL; #define VEC_SIZE 128 #define VEC_HOLDER_SIZE 1024 * 1024 typedef struct VecsHolder VecsHolder; typedef struct VecDT{ size_t index; VecsHolder* holder; RedisModuleString* keyName; }VecDT; typedef struct VecsHolder{ size_t size; VecDT* vecDT[VEC_HOLDER_SIZE]; float vecs[VEC_HOLDER_SIZE * VEC_SIZE]; }VecsHolder; #define HOLDER_VECDT(h, i) (h->vecDT[i]) #define HOLDER_VEC(h, i) (h->vecs[i * VEC_SIZE]) VecsHolder** vecList = NULL; RedisModuleType *vecRedisDT; typedef struct VecReaderCtx{ size_t index; Record** pendings; float vec[VEC_SIZE]; size_t topK; }VecReaderCtx; typedef struct TopKArg{ size_t topK; }TopKArg; typedef struct ScoreRecord{ Record baseRecord; RedisModuleString* key; float score; }ScoreRecord; typedef struct HeapRecord{ Record baseRecord; heap_t* heap; }HeapRecord; static VecReaderCtx* VecReaderCtx_Create(float* data, size_t topK){ VecReaderCtx* ctx = RG_ALLOC(sizeof(*ctx)); ctx->index = 0; ctx->pendings = array_new(Record*, 10); ctx->topK = topK; if(data){ memcpy(ctx->vec, data, VEC_SIZE * sizeof(*data)); float denom_vec = cblas_snrm2(VEC_SIZE, ctx->vec, 1); for(size_t i = 0 ; i < VEC_SIZE ; ++i){ ctx->vec[i] /= denom_vec; } } return ctx; } static void VecReaderCtx_Free(VecReaderCtx* ctx){ for(size_t i = 0 ; i < array_len(ctx->pendings) ; ++i){ Record* r = ctx->pendings[i]; RedisGears_FreeRecord(r); } array_free(ctx->pendings); RG_FREE(ctx); } static Record* to_score_records(ExecutionCtx* rctx, Record *data, void* arg){ HeapRecord* hr = (HeapRecord*)data; Record* lr = RedisGears_ListRecordCreate(hr->heap->count); size_t count = hr->heap->count; for(size_t i = 0 ; i < count ; ++i){ ScoreRecord* sr = mmh_pop_min(hr->heap); RedisGears_ListRecordAdd(lr, &sr->baseRecord); } RedisGears_FreeRecord(data); return lr; } static int heap_cmp(const void *a, const void *b, const void *udata){ ScoreRecord* s1 = (ScoreRecord*)a; ScoreRecord* s2 = (ScoreRecord*)b; if(s1->score < s2->score){ return -1; }else if(s1->score > s2->score){ return 1; }else { return 0; } } static Record* top_k(ExecutionCtx* rctx, Record *accumulate, Record *r, void* arg){ TopKArg* topKArg = arg; HeapRecord* heap = (HeapRecord*)accumulate; if(!heap){ heap = (HeapRecord*)RedisGears_RecordCreate(HeapRecordType); heap->heap = mmh_init_with_size(topKArg->topK, heap_cmp, NULL, (mmh_free_func)RedisGears_FreeRecord); } heap_t* h = heap->heap; ScoreRecord* currSr = (ScoreRecord*)r; // If the queue is not full - we just push the result into it // If the pool size is 0 we always do that, letting the heap grow dynamically if (h->count < topKArg->topK) { mmh_insert(h, r); } else { // find the min result ScoreRecord* sr = mmh_peek_min(h); if(sr->score < currSr->score){ void* temp = mmh_pop_min(h); RedisModule_Assert(temp == sr); RedisGears_FreeRecord(&(sr->baseRecord)); mmh_insert(h, r); }else{ RedisGears_FreeRecord(r); } } return &(heap->baseRecord); } static void on_done(ExecutionPlan* ctx, void* privateData){ RedisModuleBlockedClient *bc = privateData; RedisModuleCtx *rctx = RedisModule_GetThreadSafeContext(bc); RedisGears_ReturnResultsAndErrors(ctx, rctx); RedisModule_UnblockClient(bc, NULL); RedisGears_DropExecution(ctx); RedisModule_FreeThreadSafeContext(rctx); } VecDT* vec_insert(RedisModuleString *keyName, const float* data){ VecsHolder* holder = NULL; if(!vecList){ vecList = array_new(VecsHolder*, 1); } if(array_len(vecList) == 0){ holder = RG_CALLOC(1, sizeof(VecsHolder)); vecList = array_append(vecList, holder); }else{ holder = vecList[array_len(vecList) - 1]; } if(holder->size >= VEC_HOLDER_SIZE){ // we need to create a new holder holder = RG_CALLOC(1, sizeof(VecsHolder)); vecList = array_append(vecList, holder); } float* v = &HOLDER_VEC(holder, holder->size); memcpy(v, data, sizeof(float) * VEC_SIZE); float demon = cblas_snrm2(VEC_SIZE, v, 1); for(size_t i = 0 ; i < VEC_SIZE ; ++i){ v[i] /= demon; } VecDT* vDT = RG_CALLOC(1, sizeof(*vDT)); vDT->holder = holder; vDT->index = holder->size; vDT->keyName = keyName; RedisModule_RetainString(NULL, vDT->keyName); HOLDER_VECDT(holder, holder->size) = vDT; ++holder->size; return vDT; } /* * rg.vec_add <k> <blob> */ int vec_add_command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){ if(argc != 3){ return RedisModule_WrongArity(ctx); } size_t dataLen; float* data = (float*)RedisModule_StringPtrLen(argv[2], &dataLen); if(dataLen != (VEC_SIZE * sizeof(float))){ RedisModule_ReplyWithError(ctx, "Given blob is not float vector of size " STR(VEC_SIZE)); return REDISMODULE_OK; } RedisModuleKey *kp = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE); if(RedisModule_KeyType(kp) != REDISMODULE_KEYTYPE_EMPTY){ RedisModule_ReplyWithError(ctx, "Key is not empty"); RedisModule_CloseKey(kp); return REDISMODULE_OK; } VecDT* vDT = vec_insert(argv[1], data); RedisModule_ModuleTypeSetValue(kp, vecRedisDT, vDT); RedisModule_CloseKey(kp); RedisModule_ReplicateVerbatim(ctx); RedisModule_ReplyWithSimpleString(ctx, "OK"); return REDISMODULE_OK; } /* * rg.vec_sim <k> <blob> */ int vec_sim_command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){ if(argc != 3){ return RedisModule_WrongArity(ctx); } char* err = NULL; long long topK; if(RedisModule_StringToLongLong(argv[1], &topK) != REDISMODULE_OK){ RedisModule_ReplyWithError(ctx, "Failed extracting <k>"); return REDISMODULE_OK; } size_t dataSize; float* data = (float*)RedisModule_StringPtrLen(argv[2], &dataSize); if(dataSize != (VEC_SIZE * sizeof(float))){ RedisModule_ReplyWithError(ctx, "Given blob is not at the right size"); return REDISMODULE_OK; } TopKArg* topKArg2 = RG_ALLOC(sizeof(*topKArg2)); topKArg2->topK = topK; FlatExecutionPlan* fep = RGM_CreateCtx(VecReader, &err); VecReaderCtx* rCtx = VecReaderCtx_Create(data, topK); RGM_Collect(fep); RGM_Accumulate(fep, top_k, topKArg2); RGM_FlatMap(fep, to_score_records, NULL); ExecutionPlan* ep = RGM_Run(fep, ExecutionModeAsync, rCtx, NULL, NULL, &err); if(!ep){ RedisGears_FreeFlatExecution(fep); RedisModule_ReplyWithError(ctx, err); return REDISMODULE_OK; } RedisModuleBlockedClient *bc = RedisModule_BlockClient(ctx, NULL, NULL, NULL, 0); RedisGears_AddOnDoneCallback(ep, on_done, bc); RedisGears_FreeFlatExecution(fep); return REDISMODULE_OK; } static int ScoreRecord_SendReply(Record* base, RedisModuleCtx* rctx){ ScoreRecord* sr = (ScoreRecord*)base; RedisModule_ReplyWithArray(rctx, 2); RedisModule_ReplyWithString(rctx, sr->key); RedisModule_ReplyWithDouble(rctx, sr->score); return REDISMODULE_OK; } static int ScoreRecord_RecordSerialize(ExecutionCtx* ctx, Gears_BufferWriter* bw, Record* base){ ScoreRecord* sr = (ScoreRecord*)base; const char* keyStr = RedisModule_StringPtrLen(sr->key, NULL); RedisGears_BWWriteString(bw, keyStr); RedisGears_BWWriteBuffer(bw, (char*)(&(sr->score)), sizeof(sr->score)); return REDISMODULE_OK; } static Record* ScoreRecord_RecordDeserialize(ExecutionCtx* ctx, Gears_BufferReader* br){ ScoreRecord* sr = (ScoreRecord*)RedisGears_RecordCreate(ScoreRecordType); const char* keyStr = RedisGears_BRReadString(br); sr->key = RedisModule_CreateString(NULL, keyStr, strlen(keyStr)); size_t len; char* data = RedisGears_BRReadBuffer(br, &len); RedisModule_Assert(len == sizeof(float)); sr->score = *((float*)(data)); return &sr->baseRecord; } static void ScoreRecord_RecordFree(Record* base){ ScoreRecord* sr = (ScoreRecord*)base; if(sr->key){ RedisModule_FreeString(NULL, sr->key); } } static int HeapRecord_SendReply(Record* base, RedisModuleCtx* rctx){ RedisModule_Assert(false); return REDISMODULE_OK; } static int HeapRecord_Serialize(ExecutionCtx* ctx, Gears_BufferWriter* bw, Record* base){ RedisModule_Assert(false); return REDISMODULE_OK; } static Record* HeapRecord_Deserialize(ExecutionCtx* ctx, Gears_BufferReader* br){ RedisModule_Assert(false); return REDISMODULE_OK; } static void HeapRecord_Free(Record* base){ HeapRecord* hr = (HeapRecord*)base; mmh_free(hr->heap); } static void TopKArg_ObjectFree(void* arg){ RG_FREE(arg); } static void* TopKArg_ArgDuplicate(void* arg){ TopKArg* topK = arg; TopKArg* topKDup = RG_ALLOC(sizeof(*topKDup)); topKDup->topK = topK->topK; return topKDup; } static int TopKArg_ArgSerialize(FlatExecutionPlan* fep, void* arg, Gears_BufferWriter* bw, char** err){ TopKArg* topK = arg; RedisGears_BWWriteLong(bw, topK->topK); return REDISMODULE_OK; } static void* TopKArg_ArgDeserialize(FlatExecutionPlan* fep, Gears_BufferReader* br, int version, char** err){ TopKArg* topKDup = RG_ALLOC(sizeof(*topKDup)); topKDup->topK = RedisGears_BRReadLong(br); return topKDup; } static char* TopKArg_ArgToString(void* arg){ return RG_STRDUP("I am topk argument :)"); } #define TopKTypeVersion 1 #define VS_PLUGIN_NAME "VECTOR_SIM" #define REDISGEARSJVM_PLUGIN_VERSION 1 #define VEC_TYPE_VERSION 1 static void* VecDT_Load(RedisModuleIO *rdb, int encver){ RedisModuleString *keyName = RedisModule_LoadString(rdb); size_t dataLen; float* data = (float*)RedisModule_LoadStringBuffer(rdb, &dataLen); RedisModule_Assert(dataLen == sizeof(float) * VEC_SIZE); VecDT* vDT = vec_insert(keyName, data); RedisModule_FreeString(NULL, keyName); RedisModule_Free(data); return vDT; } static void VecDT_Save(RedisModuleIO *rdb, void *value){ VecDT* vDT = value; RedisModule_SaveString(rdb, vDT->keyName); RedisModule_SaveStringBuffer(rdb, (char*)&HOLDER_VEC(vDT->holder, vDT->index), sizeof(float) * VEC_SIZE); } static void VecDT_Free(void *value){ VecDT* vDT = value; VecsHolder* holder = vDT->holder; size_t index = vDT->index; RedisModule_FreeString(NULL, vDT->keyName); RG_FREE(vDT); if(!holder){ // we probably inside flush, the vector DT was detached and we can just return. return; } // get the last vector VecsHolder* lastVH = vecList[array_len(vecList) - 1]; --lastVH->size; VecDT* lastVDT = HOLDER_VECDT(lastVH, lastVH->size); if(lastVDT != vDT){ // swap last with current memmove(&HOLDER_VEC(holder, index), &HOLDER_VEC(lastVH, lastVH->size), VEC_SIZE * sizeof(float)); HOLDER_VECDT(holder, index) = lastVDT; lastVDT->holder = holder; lastVDT->index = index; } if(lastVH->size == 0){ // free the holder, it has no more data. RG_FREE(lastVH); if(array_len(vecList) > 1){ vecList = array_trimm_cap(vecList, array_len(vecList) - 1); }else{ array_free(vecList); vecList = NULL; } } } static float scores[VEC_HOLDER_SIZE]; static Record* VecReader_Next(ExecutionCtx* rctx, void* ctx){ // struct timeval stop, start; if(!vecList){ return NULL; } VecReaderCtx* readerCtx = ctx; RedisModuleCtx* redisCtx = RedisGears_GetRedisModuleCtx(rctx); if(array_len(readerCtx->pendings) > 0){ return array_pop(readerCtx->pendings); } RedisGears_LockHanlderAcquire(redisCtx); const float* b1 = readerCtx->vec; while(readerCtx->index < array_len(vecList)){ VecsHolder* holder = vecList[readerCtx->index++]; cblas_sgemv(CblasRowMajor, CblasNoTrans, holder->size, VEC_SIZE, 1, holder->vecs, VEC_SIZE, b1, 1, 0, scores, 1); for(size_t i = 0 ; i < MIN(holder->size, readerCtx->topK) ; ++i){ size_t index = cblas_isamax(holder->size, scores, 1); ScoreRecord* s = (ScoreRecord*)RedisGears_RecordCreate(ScoreRecordType); s->key = HOLDER_VECDT(holder, index)->keyName; RedisModule_RetainString(NULL, s->key); s->score = scores[index]; readerCtx->pendings = array_append(readerCtx->pendings, &s->baseRecord); scores[index] = 0; } if(array_len(readerCtx->pendings) > 0){ RedisGears_LockHanlderRelease(redisCtx); return array_pop(readerCtx->pendings); } } RedisGears_LockHanlderRelease(redisCtx); return NULL; } static void VecReader_Free(void* ctx){ VecReaderCtx_Free(ctx); } static int VecReader_Serialize(ExecutionCtx* ectx, void* ctx, Gears_BufferWriter* bw){ VecReaderCtx* readerCtx = ctx; RedisGears_BWWriteBuffer(bw, (char*)readerCtx->vec, VEC_SIZE * sizeof(float)); RedisGears_BWWriteLong(bw, readerCtx->topK); return REDISMODULE_OK; } static int VecReader_Deserialize(ExecutionCtx* ectx, void* ctx, Gears_BufferReader* br){ VecReaderCtx* readerCtx = ctx; size_t dataLen; float* data = (float*)RedisGears_BRReadBuffer(br, &dataLen); RedisModule_Assert(dataLen == VEC_SIZE * sizeof(*data)); readerCtx->topK = RedisGears_BRReadLong(br); memcpy(readerCtx->vec, data, VEC_SIZE * sizeof(*data)); return REDISMODULE_OK; } static Reader* VecReader_CreateReaderCallback(void* arg){ VecReaderCtx* ctx = arg; if(!ctx){ ctx = VecReaderCtx_Create(NULL, 0); } Reader* r = RG_ALLOC(sizeof(*r)); *r = (Reader){ .ctx = ctx, .next = VecReader_Next, .free = VecReader_Free, .serialize = VecReader_Serialize, .deserialize = VecReader_Deserialize, }; return r; } RedisGears_ReaderCallbacks VecReader = { .create = VecReader_CreateReaderCallback, }; static void OnFlush(struct RedisModuleCtx *ctx, RedisModuleEvent eid, uint64_t subevent, void *data){ if(subevent != REDISMODULE_SUBEVENT_FLUSHDB_START){ return; } if(!vecList){ return; } // before flush we need to clean all the Vector Holders and disconnect the keys for(size_t i = 0 ; i < array_len(vecList) ; ++i){ VecsHolder* holder = vecList[i]; for(size_t j = 0 ; j < holder->size ; ++j){ VecDT* vDT = HOLDER_VECDT(holder, j); vDT->holder = NULL; } RG_FREE(holder); } array_free(vecList); vecList = NULL; } int RedisGears_OnLoad(RedisModuleCtx *ctx) { openblas_set_num_threads(1); if(RedisGears_InitAsGearPlugin(ctx, VS_PLUGIN_NAME, REDISGEARSJVM_PLUGIN_VERSION) != REDISMODULE_OK){ RedisModule_Log(ctx, "warning", "Failed initialize RedisGears API"); return REDISMODULE_ERR; } RedisModule_Log(ctx, "warning", "OpenBlac num of threads: %d", openblas_get_num_threads()); staticCtx = RedisModule_GetThreadSafeContext(NULL); RedisModuleTypeMethods vecDT = { .version = REDISMODULE_TYPE_METHOD_VERSION, .rdb_load = VecDT_Load, .rdb_save = VecDT_Save, .free = VecDT_Free, }; vecRedisDT = RedisModule_CreateDataType(ctx, "vec_index", VEC_TYPE_VERSION, &vecDT); if (vecRedisDT == NULL) { RedisModule_Log(ctx, "error", "Could not create vector type"); return REDISMODULE_ERR; } RGM_RegisterReader(VecReader); ScoreRecordType = RedisGears_RecordTypeCreate("ScoreRecord", sizeof(ScoreRecord), ScoreRecord_SendReply, ScoreRecord_RecordSerialize, ScoreRecord_RecordDeserialize, ScoreRecord_RecordFree); HeapRecordType = RedisGears_RecordTypeCreate("HeapRecord", sizeof(HeapRecord), HeapRecord_SendReply, HeapRecord_Serialize, HeapRecord_Deserialize, HeapRecord_Free); ArgType* TopKType = RedisGears_CreateType("TopKType", TopKTypeVersion, TopKArg_ObjectFree, TopKArg_ArgDuplicate, TopKArg_ArgSerialize, TopKArg_ArgDeserialize, TopKArg_ArgToString); RGM_RegisterMap(to_score_records, NULL); RGM_RegisterAccumulator(top_k, TopKType); if (RedisModule_CreateCommand(ctx, "rg.vec_sim", vec_sim_command, "readonly", 0, 0, 0) != REDISMODULE_OK) { RedisModule_Log(ctx, "warning", "could not register command rg.vec_sim"); return REDISMODULE_ERR; } if (RedisModule_CreateCommand(ctx, "rg.vec_add", vec_add_command, "write deny-oom", 1, 1, 1) != REDISMODULE_OK) { RedisModule_Log(ctx, "warning", "could not register command rg.vec_add"); return REDISMODULE_ERR; } RedisModule_SubscribeToServerEvent(ctx, RedisModuleEvent_FlushDB, OnFlush); return REDISMODULE_OK; }
{ "alphanum_fraction": 0.6442170133, "avg_line_length": 29.3602584814, "ext": "c", "hexsha": "59eb1169f5a4e54c213cf5dd2a2d328614b3fd66", "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": "15a637cc5ea4536d663ce6d5b7f29276a97cab8b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "rafie/VecSim", "max_forks_repo_path": "src/vector_similarity.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "15a637cc5ea4536d663ce6d5b7f29276a97cab8b", "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": "rafie/VecSim", "max_issues_repo_path": "src/vector_similarity.c", "max_line_length": 121, "max_stars_count": 1, "max_stars_repo_head_hexsha": "15a637cc5ea4536d663ce6d5b7f29276a97cab8b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "rafie/VecSim", "max_stars_repo_path": "src/vector_similarity.c", "max_stars_repo_stars_event_max_datetime": "2022-01-03T08:56:28.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-03T08:56:28.000Z", "num_tokens": 4858, "size": 18174 }
#include <gsl/gsl_rng.h> #include <easy_rng.h> #include <time.h> #ifndef NRUNS #define NRUNS 10000000 #endif void run_test(const gsl_rng_type *gtype, const easy_rng_type *etype) { gsl_rng *grng = gsl_rng_alloc(gtype); easy_rng *erng = easy_rng_alloc(etype); clock_t gstart, gend; clock_t estart, eend; int i; gstart = clock(); for (i = 0 ; i < NRUNS ; i++) gsl_rng_get(grng); gend = clock(); estart = clock(); for (i = 0 ; i < NRUNS ; i++) easy_rng_get(erng); eend = clock(); gsl_rng_free(grng); easy_rng_free(erng); fprintf(stdout, "Comparing easyRNG's %s with GSL's %s\n", etype->name, gtype->name); fprintf(stdout, "easyRNG %g\n", ((double) (eend - estart))/CLOCKS_PER_SEC); fprintf(stdout, "GSL %g\n", ((double) (gend - gstart))/CLOCKS_PER_SEC); } int main(int argc, char *argv[]) { run_test(gsl_rng_mt19937, easy_rng_mt19937); run_test(gsl_rng_ranlux, easy_rng_ranlux24); run_test(gsl_rng_ranlux389, easy_rng_ranlux48); run_test(gsl_rng_minstd, easy_rng_minstd_rand0); run_test(gsl_rng_fishman20, easy_rng_minstd_rand); return 0; }
{ "alphanum_fraction": 0.7011070111, "avg_line_length": 20.8461538462, "ext": "c", "hexsha": "53211377baf400b0a0165245cbd26841e11d2e60", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-05-05T15:10:38.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-05T15:10:38.000Z", "max_forks_repo_head_hexsha": "5cbb80e3062ec6aedb2a6172fdb83014575f4837", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "tschoonj/easyRNG", "max_forks_repo_path": "tests/test2.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5cbb80e3062ec6aedb2a6172fdb83014575f4837", "max_issues_repo_issues_event_max_datetime": "2020-07-06T16:58:43.000Z", "max_issues_repo_issues_event_min_datetime": "2019-02-13T12:36:45.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "tschoonj/easyRNG", "max_issues_repo_path": "tests/test2.c", "max_line_length": 85, "max_stars_count": 3, "max_stars_repo_head_hexsha": "5cbb80e3062ec6aedb2a6172fdb83014575f4837", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tschoonj/easyRNG", "max_stars_repo_path": "tests/test2.c", "max_stars_repo_stars_event_max_datetime": "2020-11-07T23:31:47.000Z", "max_stars_repo_stars_event_min_datetime": "2016-12-02T15:37:11.000Z", "num_tokens": 355, "size": 1084 }
/* poly/demo.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 <stdio.h> #include <gsl/gsl_poly.h> int main () { int i; double a[6] = { -1, 0, 0, 0, 0, 1 }; /* P(x) = x^5 - 1 */ double z[10]; gsl_poly_complex_workspace * w = gsl_poly_complex_workspace_alloc (6) ; gsl_poly_complex_solve (a, 6, w, z) ; gsl_poly_complex_workspace_free (w) ; for (i = 0; i < 5 ; i++) { printf("z%d = %+.18f %+.18f\n", i, z[2*i], z[2*i+1]) ; } }
{ "alphanum_fraction": 0.6672117743, "avg_line_length": 29.8292682927, "ext": "c", "hexsha": "17dc6937a661422d3f9118313b6134dae540ce59", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/poly/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/poly/demo.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/poly/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 372, "size": 1223 }
/* * Copyright 2016 Maikel Nadolski * * 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 HIDDEN_MARKOV_MODEL_H_ #define HIDDEN_MARKOV_MODEL_H_ #include <Eigen/Dense> #include <gsl_util.h> #include "maikel/hmm/stochastical_conditions.h" namespace maikel { namespace hmm { struct hmm_errors: public std::runtime_error { hmm_errors(std::string s): std::runtime_error(s) {} }; struct dimensions_not_consistent: public hmm_errors { dimensions_not_consistent(const std::string& a): hmm_errors(a) {} }; template <class T> class hidden_markov_model { public: using matrix = typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>; using row_vector = typename Eigen::Matrix<T, 1, Eigen::Dynamic>; using size_type = typename matrix::Index; struct arguments_not_probability_arrays: public hmm_errors { matrix A; matrix B; row_vector pi; arguments_not_probability_arrays( const matrix& A_, const matrix& B_, const row_vector& pi_, const std::string& a): hmm_errors(a), A{A_}, B{B_}, pi{pi_} {} }; hidden_markov_model( const matrix& transition_matrix, const matrix& symbol_matrix, const row_vector& initial_dist ) : A { transition_matrix }, B { symbol_matrix }, pi{ initial_dist }, num_states { B.rows() }, num_symbols { B.cols() } { if (!rows_are_probability_arrays(A) || !rows_are_probability_arrays(B) || !is_probability_array(pi.array())) throw arguments_not_probability_arrays { A, B, pi, "Some inputs in constructor do not have the stochastical property." }; if (A.rows() != A.cols() || A.rows() != B.rows() || A.rows() != pi.cols()) throw dimensions_not_consistent { "Dimensions of input matrices are not consistent with each other." }; } inline size_type states() const noexcept { return num_states; } inline size_type symbols() const noexcept { return num_symbols; } inline const matrix& transition_matrix() const noexcept { return A; } inline const matrix& symbol_probabilities() const noexcept { return B; } inline const row_vector& initial_distribution() const noexcept { return pi; } private: matrix A; matrix B; row_vector pi; size_type num_states; size_type num_symbols; }; } // namespace hmm } // namespace maikel #endif /* HIDDEN_MARKOV_MODEL_H_ */
{ "alphanum_fraction": 0.6147990256, "avg_line_length": 35.6956521739, "ext": "h", "hexsha": "5324a9848f106308ab45c80cb687fa40b22a6ffb", "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": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_path": "include/maikel/hmm/hidden_markov_model.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "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": "maikel/Hidden-Markov-Model", "max_issues_repo_path": "include/maikel/hmm/hidden_markov_model.h", "max_line_length": 98, "max_stars_count": 1, "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_path": "include/maikel/hmm/hidden_markov_model.h", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "num_tokens": 692, "size": 3284 }
#include <gsl/gsl_interp.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_version.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_types.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_statistics_double.h>
{ "alphanum_fraction": 0.7592592593, "avg_line_length": 24.9230769231, "ext": "h", "hexsha": "dab18ed0f036c9b06de144a3e6bc30eec9dc5660", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-10-12T12:27:46.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-02T14:35:08.000Z", "max_forks_repo_head_hexsha": "3c1ac84e49bdb2b873d344110d716396a1cb4637", "max_forks_repo_licenses": [ "EFL-2.0" ], "max_forks_repo_name": "eiffel-wrap-c/wrap_gsl", "max_forks_repo_path": "library/manual_wrapper/c/include/eif_gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3c1ac84e49bdb2b873d344110d716396a1cb4637", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "EFL-2.0" ], "max_issues_repo_name": "eiffel-wrap-c/wrap_gsl", "max_issues_repo_path": "library/manual_wrapper/c/include/eif_gsl.h", "max_line_length": 38, "max_stars_count": null, "max_stars_repo_head_hexsha": "3c1ac84e49bdb2b873d344110d716396a1cb4637", "max_stars_repo_licenses": [ "EFL-2.0" ], "max_stars_repo_name": "eiffel-wrap-c/wrap_gsl", "max_stars_repo_path": "library/manual_wrapper/c/include/eif_gsl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 105, "size": 324 }
/* test.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include <gsl/gsl_math.h> #include <gsl/gsl_bst.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_test.h> enum array_order { ORD_RANDOM = 0, /* random order */ ORD_ASCENDING, /* ascending order */ ORD_DESCENDING, /* descending order */ ORD_BALANCED, /* balanced tree order */ ORD_ZIGZAG, /* zig-zag order */ ORD_ASCENDING_SHIFTED, /* ascending from middle, then beginning */ ORD_END_NODUP, /* end of no-duplicate ordering */ ORD_RANDOM_DUP /* random order with duplicates */ }; /* fill array[] with random integers in [lower,upper] with duplicates allowed */ static void random_integers(const size_t n, const int lower, const int upper, int array[], gsl_rng * r) { size_t i; for (i = 0; i < n; ++i) array[i] = (int) ((upper - lower) * gsl_rng_uniform(r) + lower); } /* fills array[] with a random permutation of the integers between 0 and n - 1 */ static void random_permuted_integers (const size_t n, int array[], gsl_rng * r) { size_t i; for (i = 0; i < n; i++) array[i] = i; for (i = 0; i < n; i++) { size_t j = i + (unsigned) (gsl_rng_uniform(r) * (n - i)); int t = array[j]; array[j] = array[i]; array[i] = t; } } static int compare_ints(const void *pa, const void *pb, void *params) { const int *a = pa; const int *b = pb; (void) params; return (*a < *b) ? -1 : (*a > *b); } /* Generates a list of integers that produce a balanced tree when inserted in order into a binary tree in the usual way. |min| and |max| inclusively bound the values to be inserted. Output is deposited starting at |*array|. */ static void gen_balanced_tree (const int min, const int max, int **array) { int i; if (min > max) return; i = (min + max + 1) / 2; *(*array)++ = i; gen_balanced_tree (min, i - 1, array); gen_balanced_tree (i + 1, max, array); } /* generates a permutation of the integers |0| to |n - 1| */ static void gen_int_array (const size_t n, const enum array_order order, int array[], gsl_rng * r) { size_t i; switch (order) { case ORD_RANDOM: random_permuted_integers (n, array, r); break; case ORD_ASCENDING: for (i = 0; i < n; i++) array[i] = i; break; case ORD_DESCENDING: for (i = 0; i < n; i++) array[i] = n - i - 1; break; case ORD_BALANCED: gen_balanced_tree (0, n - 1, &array); break; case ORD_ZIGZAG: for (i = 0; i < n; i++) { if (i % 2 == 0) array[i] = i / 2; else array[i] = n - i / 2 - 1; } break; case ORD_ASCENDING_SHIFTED: for (i = 0; i < n; i++) { array[i] = i + n / 2; if ((size_t) array[i] >= n) array[i] -= n; } break; case ORD_RANDOM_DUP: random_integers(n, -10, 10, array, r); break; default: assert (0); } } static void check_traverser(const size_t n, const enum array_order order, gsl_bst_trav * trav, int data, const char *desc, const gsl_bst_workspace * w) { int *prev, *cur, *next; prev = gsl_bst_trav_prev(trav); if (prev != NULL) { gsl_test(*prev > data, "bst %s[n=%zu,order=%d] %s traverser ahead of %d, but should be ahead of %d", gsl_bst_name(w), n, order, desc, *prev, data); } gsl_bst_trav_next(trav); cur = gsl_bst_trav_cur(trav); gsl_test(*cur != data, "bst %s[n=%zu,order=%d] %s traverser at %d, but should be at %d", gsl_bst_name(w), n, order, desc, *cur, data); next = gsl_bst_trav_next(trav); if (next != NULL) { gsl_test(*next < data, "bst %s[n=%zu,order=%d] %s traverser behind %d, but should be behind %d", gsl_bst_name(w), n, order, desc, *next, data); } gsl_bst_trav_prev(trav); } static void test_bst_int(const size_t n, const gsl_bst_type * T, const enum array_order order, gsl_rng * r) { int *data = malloc(n * sizeof(int)); int *data_delete = malloc(n * sizeof(int)); int *sorted_data = malloc(n * sizeof(int)); gsl_bst_workspace * w = gsl_bst_alloc(T, NULL, compare_ints, NULL); gsl_bst_trav trav; int *p; int i; size_t nodes; /* generate data to be inserted in tree */ gen_int_array(n, order, data, r); for (i = 0; i < (int) n; ++i) sorted_data[i] = data[i]; gsl_sort_int(sorted_data, 1, n); if (order != ORD_RANDOM_DUP) { /* generate random order to delete data from tree */ gen_int_array(n, ORD_RANDOM, data_delete, r); } else { for (i = 0; i < (int) n; ++i) data_delete[i] = sorted_data[i]; } /* insert data */ for (i = 0; i < (int) n; ++i) { p = gsl_bst_insert(&data[i], w); gsl_test(p != NULL, "bst_int %s[n=%zu,order=%d] insert i=%d", gsl_bst_name(w), n, order, i); } if (order != ORD_RANDOM_DUP) { nodes = gsl_bst_nodes(w); gsl_test(nodes != n, "bst_int %s[n=%zu,order=%d] after insertion count = %zu/%zu", gsl_bst_name(w), n, order, nodes, n); } /* test data was inserted and can be found */ for (i = 0; i < (int) n; ++i) { p = gsl_bst_find(&data[i], w); gsl_test(*p != data[i], "bst_int %s[n=%zu,order=%d] find [%d,%d]", gsl_bst_name(w), n, order, *p, data[i]); p = gsl_bst_trav_find(&data[i], &trav, w); gsl_test(p == NULL, "bst_int %s[n=%zu,order=%d] trav_find unable to find item %d", gsl_bst_name(w), n, order, data[i]); check_traverser(n, order, &trav, data[i], "post-insertion", w); } /* traverse tree in-order */ p = gsl_bst_trav_first(&trav, w); i = 0; while (p != NULL) { int *q = gsl_bst_trav_cur(&trav); gsl_test(*p != sorted_data[i], "bst_int %s[n=%zu,order=%d] traverse i=%d [%d,%d]", gsl_bst_name(w), n, order, i, *p, sorted_data[i]); gsl_test(*p != *q, "bst_int %s[n=%zu,order=%d] traverse cur i=%d [%d,%d]", gsl_bst_name(w), n, order, i, *p, *q); p = gsl_bst_trav_next(&trav); ++i; } gsl_test(i != (int) n, "bst_int %s[n=%zu,order=%d] traverse number=%d", gsl_bst_name(w), n, order, i); /* traverse tree in reverse order */ p = gsl_bst_trav_last(&trav, w); i = n - 1; while (p != NULL) { int *q = gsl_bst_trav_cur(&trav); gsl_test(*p != sorted_data[i], "bst_int %s[n=%zu,order=%d] traverse reverse i=%d [%d,%d]", gsl_bst_name(w), n, order, i, *p, sorted_data[i]); gsl_test(*p != *q, "bst_int %s[n=%zu,order=%d] traverse reverse cur i=%d [%d,%d]", gsl_bst_name(w), n, order, i, *p, *q); p = gsl_bst_trav_prev(&trav); --i; } gsl_test(i != -1, "bst_int %s[n=%zu,order=%d] traverse reverse number=%d", gsl_bst_name(w), n, order, i); /* test traversal during tree modifications */ for (i = 0; i < (int) n; ++i) { gsl_bst_trav x, y, z; gsl_bst_trav_find(&data[i], &x, w); check_traverser(n, order, &x, data[i], "pre-deletion", w); if (data[i] == data_delete[i]) continue; p = gsl_bst_remove(&data_delete[i], w); gsl_test(*p != data_delete[i], "bst_int %s[n=%zu,order=%d] remove i=%d [%d,%d]", gsl_bst_name(w), n, order, i, *p, data_delete[i]); p = gsl_bst_trav_copy(&y, &x); gsl_test(*p != data[i], "bst_int %s[n=%zu,order=%d] copy i=%d [%d,%d]", gsl_bst_name(w), n, order, i, *p, data[i]); /* re-insert item */ p = gsl_bst_trav_insert(&data_delete[i], &z, w); check_traverser(n, order, &x, data[i], "post-deletion", w); check_traverser(n, order, &y, data[i], "copied", w); check_traverser(n, order, &z, data_delete[i], "insertion", w); #if 0 /* delete again */ gsl_bst_remove(&data[i], w); #endif } /* emmpty tree */ gsl_bst_empty(w); nodes = gsl_bst_nodes(w); gsl_test(nodes != 0, "bst_int %s[n=%zu,order=%d] empty count = %zu", gsl_bst_name(w), n, order, nodes); gsl_bst_free(w); free(data); free(data_delete); free(sorted_data); } static void test_bst(const gsl_bst_type * T, gsl_rng * r) { enum array_order order; for (order = 0; order < ORD_END_NODUP; ++order) { test_bst_int(50, T, order, r); test_bst_int(100, T, order, r); test_bst_int(500, T, order, r); } } int main(void) { gsl_rng * r = gsl_rng_alloc(gsl_rng_default); test_bst(gsl_bst_avl, r); test_bst(gsl_bst_rb, r); gsl_rng_free(r); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.5719795684, "avg_line_length": 27.2528409091, "ext": "c", "hexsha": "760afc03330aca0887f726b847abc75367ef73bc", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/bst/test.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/bst/test.c", "max_line_length": 106, "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/bst/test.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": 2987, "size": 9593 }
/* combination/init.c * based on permutation/init.c by Brian Gough * * Copyright (C) 2001 Szymon Jaroszewicz * * 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 <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_combination.h> gsl_combination * gsl_combination_alloc (const size_t n, const size_t k) { gsl_combination * c; if (n == 0) { GSL_ERROR_VAL ("combination parameter n must be positive integer", GSL_EDOM, 0); } if (k > n) { GSL_ERROR_VAL ("combination length k must be an integer less than or equal to n", GSL_EDOM, 0); } c = (gsl_combination *) malloc (sizeof (gsl_combination)); if (c == 0) { GSL_ERROR_VAL ("failed to allocate space for combination struct", GSL_ENOMEM, 0); } if (k > 0) { c->data = (size_t *) malloc (k * sizeof (size_t)); if (c->data == 0) { free (c); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for combination data", GSL_ENOMEM, 0); } } else { c->data = 0; } c->n = n; c->k = k; return c; } gsl_combination * gsl_combination_calloc (const size_t n, const size_t k) { size_t i; gsl_combination * c = gsl_combination_alloc (n, k); if (c == 0) return 0; /* initialize combination to identity */ for (i = 0; i < k; i++) { c->data[i] = i; } return c; } void gsl_combination_init_first (gsl_combination * c) { const size_t k = c->k ; size_t i; /* initialize combination to identity */ for (i = 0; i < k; i++) { c->data[i] = i; } } void gsl_combination_init_last (gsl_combination * c) { const size_t k = c->k ; size_t i; size_t n = c->n; /* initialize combination to identity */ for (i = 0; i < k; i++) { c->data[i] = n - k + i; } } void gsl_combination_free (gsl_combination * c) { if (c->k > 0) free (c->data); free (c); }
{ "alphanum_fraction": 0.6054446461, "avg_line_length": 21.6929133858, "ext": "c", "hexsha": "6bac2d459b12d5c9c7ae908791f7b4f828e9b8c1", "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/combination/init.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/combination/init.c", "max_line_length": 87, "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/combination/init.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": 777, "size": 2755 }
/* Copyright 2016. The Regents of the University of California. * Copyright 2016. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2016 Jonathan Tamir <jtamir@eecs.berkeley.edu> * 2016 Martin Uecker <martin.uecker@med.uni-goettingen.de> */ #include <assert.h> #include <complex.h> #include "misc/misc.h" #ifdef USE_MACPORTS #include <cblas_openblas.h> #else #include <cblas.h> #endif #ifdef USE_CUDA #include "num/gpuops.h" #include <cublas.h> #endif #include "blas.h" void blas_cgemm(char transa, char transb, long M, long N, long K, const complex float alpha, long lda, const complex float A[K][lda], long ldb, const complex float B[N][ldb], const complex float beta, long ldc, complex float C[N][ldc]) { #ifdef USE_CUDA #define CUCOMPLEX(x) (((union { cuComplex cu; complex float std; }){ .std = (x) }).cu) if (cuda_ondevice(A)) { cublasCgemm(transa, transb, M, N, K, CUCOMPLEX(alpha), (const cuComplex*)A, lda, (const cuComplex*)B, ldb, CUCOMPLEX(beta), (cuComplex*)C, ldc); } else #endif cblas_cgemm(CblasColMajor, transa, transb, M, N, K, (void*)&alpha, (void*)A, lda, (void*)B, ldb, (void*)&beta, (void*)C, ldc); } void (blas_matrix_multiply)(long M, long N, long K, complex float C[N][M], const complex float A[K][M], const complex float B[N][K]) { blas_cgemm(CblasNoTrans, CblasNoTrans, M, N, K, 1., M, A, K, B, 0., M, C); } void (blas_csyrk)(char uplo, char trans, long N, long K, const complex float alpha, long lda, const complex float A[][lda], complex float beta, long ldc, complex float C[][ldc]) { assert('U' == uplo); assert(('T' == trans) || ('N' == trans)); cblas_csyrk(CblasColMajor, CblasUpper, ('T' == trans) ? CblasTrans : CblasNoTrans, N, K, (void*)&alpha, (void*)A, lda, (void*)&beta, (void*)C, ldc); }
{ "alphanum_fraction": 0.6343656344, "avg_line_length": 30.8, "ext": "c", "hexsha": "89cb1d0694f0deb5f8fdbec7d76b3c2f2469b115", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-04-05T22:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-05T22:36:49.000Z", "max_forks_repo_head_hexsha": "adff601ac761a240c48113692bd059969767b9f5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "youngwook-mri/bart", "max_forks_repo_path": "src/num/blas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "adff601ac761a240c48113692bd059969767b9f5", "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": "youngwook-mri/bart", "max_issues_repo_path": "src/num/blas.c", "max_line_length": 236, "max_stars_count": 1, "max_stars_repo_head_hexsha": "adff601ac761a240c48113692bd059969767b9f5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "youngwook-mri/bart", "max_stars_repo_path": "src/num/blas.c", "max_stars_repo_stars_event_max_datetime": "2021-08-19T12:21:01.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-19T12:21:01.000Z", "num_tokens": 605, "size": 2002 }
#include <sys/types.h> // per utilizzare variabili di tipo pthread_t #include <stdlib.h> // utilità generale (allocazione, controllo processi, etc.) #include <pthread.h> // per utilizzo dei thread #include <string.h> // per elaborazione su stringhe #include <math.h> #include <gsl/gsl_vector.h> // per usare i vettori #include <gsl/gsl_matrix.h> // per usare le matrici #include <gsl/gsl_eigen.h> // per calcolare autovalori e autovettori #include <gsl/gsl_statistics.h> // per usare funzioni di probabilità #include <gsl/gsl_linalg.h> // per usare funzioni su matrici #include <gsl/gsl_permutation.h> // per usare le permutazioni #define debug 0 // variabile per settare le stampe di controllo #define troncamento 100 // per approssimazione alla 3° cifra significativa dopo la virgola int controllo = 1; // variabile per verificare la chiamata di funzioni double **data_set_origine, **data_set, **data_compression, **autovettori; double *autovalori; int dimensione = 0; struct registro{ // puntatori alle celle per eseguire il prodotto matriciale A*B double *mtx_1, *mtx_2; //mtx_1: riga di A, mtx_2: colonna di B int *indici; // posizione in cui salvare il singolo valore dell'operazione } catalogo; struct gsl{ // puntatori agli autovalori e autovettori di tipo gsl gsl_vector *vector; // autovalori gsl_matrix *matrix; // autovettori } puntatori_gsl; void stampa(int tipo, double **mt1, double *mt2, char nome[], int nr, int nc){ // il tipo indica che tipo di stampa effettuo int i,j = 0; switch(tipo){ case 0: //stampa dimensione printf("%s: %d \n", nome, nr); //Dimensioni break; case 1: //stampa la matrice con il proprio nome printf("Stampa matrice %s: \n", nome); for(i = 0; i < nr; i++){ for(j = 0; j < nc; j++){ if(j == 0){ printf("| "); } printf("%2.2f\t", mt1[i][j]); if(j == nc-1){ printf("|"); } } printf("\n"); } break; case 2://stampa media in forma estesa printf("Stampa valor medio: \n"); for(i = 0; i < nr; i++){ printf("media[%d]=%2.2f \n", i, mt2[i]); } break; case 3: //stampa gli autovalori in forma matriciale printf("Stampa autovalori(covarianza): \n"); for(i = 0; i < dimensione; i++){ if(i == 0){ printf("| "); } printf("%2.4g\t", autovalori[i]); if(i == dimensione-1){ printf("| \n"); } } break; case 5: //stampa errori verifica printf("Errore la verifica non è andata a buon fine\n"); printf("La matrice Verifica è diversa dalla matrice di partenza \n"); break; case 6://stampa matrici monodimensionali in maniera estesa printf("Stampa Matrice Estesa %s: \n", nome); for(i = 0; i < dimensione; i++){ printf("%s[%d]=%2.2f \n", nome, i, mt2[i]); } break; case 7: //stampa matrici bidimensionali in maniera estesa printf("Stampa Matrice Estesa %s : \n", nome); for(i = 0; i < dimensione; i++){ for(j = 0; j < dimensione; j++){ printf("%s[%d][%d]=%2.2f \n", nome, i, j, mt1[i][j]); } } break; } printf("\n"); } void *thread_function(void *candidato){ // singola iterazione del prodotto matriciale int i = 0; int *indici; double *mtx_1, *mtx_2; struct registro *catalogo; // casting degli argomenti della thread_function catalogo=(struct registro*)candidato; mtx_1=catalogo->mtx_1; mtx_2=catalogo->mtx_2; indici=catalogo->indici; /* esecuzione del prodotto matriciale (a singoli elementi): si esegue il singolo prodotto, il risultato lo si salva sulla posizione corrente del'array tmp[0]; infine si somma il precedente risultato al valore presente nella cella 0 di tmp (tmp[0][0] svolgerà il ruolo di sommatore, senza dover creare una variabile temporanea). */ for(i=0; i<dimensione; i++){ if(debug==1){printf("mtx_1[%d] = %2.2f , mtx_2[%d] = %2.2f\n", i, mtx_1[i], i, mtx_2[i]);} mtx_1[i]=mtx_1[i]*mtx_2[i]; if(debug==1){printf("singolo prodotto: %2.2f\n", mtx_1[i]);} if(i>0){ mtx_1[0]=mtx_1[0]+mtx_1[i]; if(debug==1){printf("somma: %2.2f\n", mtx_1[0]);} } } i=0; // inserimento della somma nell'apposita cella della matrice globale: data_compression data_compression[indici[0]][indici[1]]=mtx_1[0]; if(debug==1){ printf("data_compression[%d][%d]=%2.2f\n", indici[0], indici[1], data_compression[indici[0]][indici[1]]); } return NULL; } double *media(int nrighe){ // media sulle righe del data set int i, j = 0; double somma = 0; double *media; media=malloc(nrighe*sizeof(double)); // alloccamento dinamico if(media==NULL){printf("ERRORE: media non alloccata.\n");} for(i=0; i<nrighe; i++){ for(j=0; j<dimensione; j++){ somma = somma+data_set[i][j]; // somma su riga i-esima del data_set if(debug==1){printf("somma = %2.2f\n", somma);} } media[i]=somma/dimensione; // valor medio della i-esima riga del data_set somma=0; // reset per riga successiva if(debug){printf("Media: %2.2f \n", media[i]);} } return media; } double **covarianza(double *media, int nrighe){ // matrice di covarianza del data set int i, j, k = 0; double **covarianza; double *tmp1, *tmp2; // alloccamento dinamico tmp1=malloc(nrighe*sizeof(double)); if(tmp1==NULL){printf("ERRORE - covarianza: tmp1 non alloccato.\n"); exit(0);} tmp2=malloc(nrighe*sizeof(double)); if(tmp2==NULL){printf("ERRORE - covarianza: tmp2 non alloccato.\n"); exit(0);} covarianza=malloc(dimensione*sizeof(double*)); if(covarianza==NULL){printf("ERRORE - covarianza: covarianza non alloccato.\n"); exit(0);} for(i=0; i<dimensione; i++){ covarianza[i]=malloc(dimensione*sizeof(double)); if(covarianza[i]==NULL){printf("ERRORE - covarianza: covarianza[%d] non alloccato.\n", i); exit(0);} } /* dei 4 for, definiamo "principali" quelli riferiti alla variabile 'i' e 'j' in quanto vanno ad identificare la cella (i, j) della matrice di covarianza; i for riferiti alla variabile 'k' sono for di settaggio dei due array temporanei, che andranno a considerare le colonne del data set. Ad ogni ciclo dell' i-for si fisserà una riga (partendo dalla riga 0), e si andrà a "combinare" con tutte le colonne del data set (a partire dalla riga 0). */ for(i=0; i<dimensione; i++){ for(k=0; k<nrighe; k++){ // fissiamo colonna i-esima tmp1[k]=data_set[k][i]; if(debug==1){ stampa(6, NULL, tmp1, "tmp1", 0, 0); } } for(j=0; j<dimensione; j++){ for(k=0; k<nrighe; k++){ // consideriamo colonna j-esima tmp2[k]=data_set[k][j]; if(debug==1){ stampa(6, NULL, tmp2, "tmp2", 0, 0); } } covarianza[i][j]=gsl_stats_covariance(tmp1, 1, tmp2, 1, nrighe); // calcolo della covarianza } if(debug==1){ stampa(7, covarianza, NULL, "Covarianza", 0, 0); } } free(tmp1); free(tmp2); return covarianza; } struct gsl eigen(double **covarianza){ // calcolo autovalori e autovettori della matrice di covarianza int i=0, j=0; gsl_matrix *matrice, *evec; gsl_vector *evel; gsl_eigen_symmv_workspace *campo; struct gsl pointer_gsl; // allocazione matrice=gsl_matrix_alloc(dimensione, dimensione); // alloccamento matrice bid: "dimensione" righe e "dimensione" colonne if(matrice==NULL){printf("ERRORE - eigen: matrice non alloccato"); exit(0);} evec=gsl_matrix_alloc(dimensione, dimensione); // alloccamento matrice bid: "dimensione" righe e "dimensione" colonne if(evec==NULL){printf("ERRORE - eigen: evec non alloccato"); exit(0);} evel=gsl_vector_calloc(dimensione); // alloccamento vettore: "dimensione" posizioni if(evel==NULL){printf("ERRORE - eigen: evel non alloccato"); exit(0);} campo=gsl_eigen_symmv_alloc(dimensione); // alloccamento del workspace, dimensione pari a: "dimensione" if(campo==NULL){printf("ERRORE - eigen: campo non alloccato"); exit(0);} // copiamo "covarianza" nella "matrice" for(i=0; i<dimensione; i++){ for(j=0; j<dimensione; j++){ if(debug==1){printf("covarianza[%d][%d] = %2.2f\n", i, j, covarianza[i][j]);} gsl_matrix_set(matrice, i, j, covarianza[i][j]); // inserimento del valore nella "matrice" if(debug==1){printf("matrice[%d][%d] = %2.2f\n", i, j, gsl_matrix_get(matrice, i, j));} } } controllo=gsl_eigen_symmv(matrice, evel, evec, campo); // calcolo degli autovalori e autovettori if(controllo!=0){printf("ERRORE - eigen: gsl_eigen_symmv fallito.\n"); exit(0);} // salvataggio dei puntatori agli autovalori e autovettori nella struttura "gsl" pointer_gsl.vector=evel; pointer_gsl.matrix=evec; gsl_matrix_free(matrice); gsl_eigen_symmv_free(campo); return pointer_gsl; } void ordinamento(gsl_matrix *vettori){ // ordinamento decrescente degli autovalori int i,j = 0; double tmp = 0; for(i=0; i<dimensione; i++){ if(autovalori[i]<0){ autovalori[i]=autovalori[i]*(-1); } } /* dato che c'è una corrispondenza biunivoca fra l'array degli autovalori e la matrice degli autovettori, allora ordinando gli autovalori si ordinano anche gli autovettori, per mantenere la precedente proprietà. */ for(i = 0; i < dimensione; i++){ for(j = 0; j < dimensione; j++){ if(debug==1){printf("autovalori[%d] = %2.2f , autovalori[%d] = %2.2f\n", j, autovalori[j], i, autovalori[i]);} if(autovalori[j] < autovalori[i]){ tmp=autovalori[i]; if(debug==1){printf("tmp = %2.2f\n", tmp);} autovalori[i]=autovalori[j]; autovalori[j]=tmp; if(debug==1){printf("autovalori[%d] = %2.2f , autovalori[%d] = %2.2f\n", j, autovalori[j], i, autovalori[i]);} gsl_matrix_swap_columns(vettori, i, j); if(controllo!=0){printf("ERRORE - ordinamento: gsl_matrix_swap_columns fallito.\n"); exit(0);} } } tmp=0; } } double **sottrazione_matriciale(int nrighe, double *media){ // data set "differenziato" int i, j = 0; double **sottrazione; // alloccamento dinamico sottrazione=malloc(nrighe*sizeof(double*)); if(sottrazione==NULL){printf("ERRORE - sottrazione_matriciale: sottrazione non alloccato.\n"); exit(0);} for(i=0; i<nrighe; i++){ sottrazione[i]=malloc(dimensione*sizeof(double)); if(sottrazione[i]==NULL){printf("ERRORE - sottrazione_matriciale: sottrazione[%d] non alloccato.\n", i); exit(0);} } // ogni riga del data set viene differenziato per la media della riga stessa for(i=0; i<nrighe; i++){ for(j=0; j<dimensione; j++){ sottrazione[i][j]=data_set[i][j]-media[i]; if(debug==1){printf("data_set[%d][%d] = %2.2f , media[%d] = %2.2f , sottrazione[%d][%d] = %2.2f\n", i, j, data_set[i][j], i, media[i], i, j, sottrazione[i][j]); } } } return sottrazione; } int prodotto_matriciale(int righe_1, int colonne_1, int righe_2, int colonne_2, double **matrice_1, double **matrice_2){ //Funzione per fare il prodotto matriciale int i, i_1, j_1, contatore, fine = 0; int *indici; double *mtx_1, *mtx_2; pthread_t *thread; struct registro *enciclopedia; // array di strutture registro if(colonne_1 != righe_2){ printf("ERRORE - prodotto_matriciale: non è soddisfatta la condizione del prodotto matriciale.\n"); return -1; } enciclopedia=malloc(righe_1*colonne_2*sizeof(struct registro)); //creazione struttura if(enciclopedia==NULL){printf("ERRORE - prodotto_matriciale: enciclopedia non alloccata.\n"); exit(0);} /* Definiamo come "prodotto", il prodotto dei valori (in stessa posizione) fra due array, e successiva somma dei singoli prodotti. Definiamo come "singola iterazione" o "singola procedura" il prodotto fra la riga i-esima della matrice A per la colonna j-esima della matrice B, al variare di i e j. */ // settaggio dei parametri da inviare ai thread (obbligatori, altrimenti parte il segmentation fault) contatore=0; i_1=0; j_1=0; /* Il seguente while serve a riempire l'array di strutture che contengono: la riga di A, la colonna di B e gli indici di posizione in cui salvare il risultato della singola procedura del prodotto matriciale. */ while(fine==0){ // alloccamento dinamico di due array "temporanei" e salvataggio indirizzi nell'array tmp mtx_1=malloc(colonne_1*sizeof(double)); // riga di A if(mtx_1==NULL){printf("ERRORE - prodotto_matriciale: mtx_1 non alloccato.\n"); exit(0);} mtx_2=malloc(righe_2*sizeof(double*)); // colonna di B if(mtx_2==NULL){printf("ERRORE - prodotto_matriciale: mtx_2 non alloccato.\n"); exit(0);} indici=malloc(2*sizeof(int)); // array degli indici di posizione del data_compression if(indici==NULL){printf("ERRORE - prodotto_matriciale: indici non alloccato.\n"); exit(0);} if(debug==1){ printf("contatore = %d, colonne_2=%d, righe_1=%d, i_1=%d, j_1=%d\n", contatore, colonne_2, righe_1, i_1, j_1); } for(i = 0; i < colonne_1; i++){ mtx_1[i]=matrice_1[i_1][i]; // copia della riga i_1 di A in mtx_1 mtx_2[i]=matrice_2[i][j_1]; // copia della colonna j_1 di B in mtx_2 } if(debug==1){ stampa(6, NULL, mtx_1, "MTX_1", 0, 0); stampa(6, NULL, mtx_2, "MTX_2", 0, 0); } // salvataggio dimensioni ed indici di posizione nella singola struttura indici[0]=i_1; indici[1]=j_1; // salvataggio dei parametri in una struttura "registro" enciclopedia[contatore].mtx_1 = mtx_1; enciclopedia[contatore].mtx_2 = mtx_2; enciclopedia[contatore].indici = indici; contatore++; // rappresenta l'indice dell'array di struttura if(debug==1){ printf("contatore = %d\n", contatore); } if(debug==1){ printf("j_1+1 = %d , colonne_2 = %d , i_1+1 = %d , righe_1 = %d\n", j_1+1, colonne_2, i_1+1, righe_1); } if(j_1+1<colonne_2){ // andiamo alla colonna successiva di B j_1++; if(debug==1){ printf("j_1 = %d\n", j_1); } }else if(i_1+1<righe_1){ // andiamo alla riga successiva di A i_1++; j_1=0; // la riga parte dalla colonna 0 if(debug==1){ printf("i_1 = %d\n", i_1); } }else{ fine=1; // sono stati passati tutti i valori, il while è finito } } contatore=0; i=0; i_1=0; j_1=0; fine=0; // alloccamento array di thread thread=malloc(righe_1*colonne_2*sizeof(pthread_t)); if(thread==NULL){ printf("ERRORE - prodotto_matriciale: thread non alloccato.\n"); exit(0); } // verifica del corretto contenuto delle strutture if(debug==1){ int j = 0; for(i=0; i<righe_1*colonne_2; i++){ printf("Stampa del contenuto delle strutture.\n"); printf("------------\n"); for(j=0; j<colonne_1; j++){ printf("enciclopedia[%d].mtx_1[%d]= %2.2f\n", i, j, enciclopedia[i].mtx_1[j]); } for(j=0; j<colonne_1; j++){ printf("enciclopedia[%d].mtx_2[%d]= %2.2f\n", i, j, enciclopedia[i].mtx_2[j]); } for(j=0; j<2; j++){ printf("enciclopedia[%d].indici[%d]=%d\n", i, j, enciclopedia[i].indici[j]); } } printf("------------\n"); } for(i=0; i<righe_1*colonne_2; i++){ /* chiamata del singolo thread, gli argomenti sono: riga della matrice 1, colonna della matrice 2, indice della riga considerata e indice della colonna considerata. */ //printf("------------\n"); controllo=pthread_create(&thread[i], NULL, (void*)thread_function, (void*)&enciclopedia[i]); if(controllo!=0){printf("ERRORE - prodotto_matriciale: pthread_create fallito.\n"); exit(0);} //printf("------------\n"); } controllo=pthread_join(thread[(righe_1*colonne_2)-1], NULL); // il main attende l'ultimo thread prima di proseguire if(controllo!=0){printf("ERRORE - prodotto_matriciale: pthread_join fallito.\n"); exit(0);} free(mtx_1); free(mtx_2); free(indici); free(enciclopedia); return 0; } double **inversione_matriciale(gsl_matrix *evec){ // matrice degli autovettori invertita int i, j = 0; int *segno; double **inversione; gsl_matrix *inverse; gsl_permutation *permutazione; // alloccamento dinamico inversione=malloc(dimensione*sizeof(double*)); if(inversione==NULL){printf("ERRORE - inversione_matriciale: inversione non alloccato.\n"); exit(0);} for(i=0; i<dimensione; i++){ inversione[i]=malloc(dimensione*sizeof(double)); if(inversione[i]==NULL){printf("ERRORE - inversione_matriciale: inversione[%d] non alloccato.\n", i); exit(0);} } inverse=gsl_matrix_alloc(dimensione, dimensione); //alloccamento della matrice inversa if(inverse==NULL){printf("ERRORE - inversione_matriciale: inverse non alloccato.\n"); exit(0);} permutazione=gsl_permutation_calloc(dimensione); // alloccamento dell'array di permutazione if(permutazione==NULL){printf("ERRORE - inversione_matriciale: permutazione non alloccato.\n"); exit(0);} segno=malloc(1*sizeof(int)); // inizializzazione della variabile if(segno==NULL){printf("ERRORE - inversione_matriciale: segno non alloccato.\n"); exit(0);} controllo=gsl_linalg_LU_decomp(evec, permutazione, segno); //decompoposizione (obbligatorio) if(controllo!=0){printf("ERRORE - inversione_matriciale: gsl_linalg_LU_decomp fallito.\n");} controllo=gsl_linalg_LU_invert(evec, permutazione, inverse); //inversione matriciale if(controllo!=0){printf("ERRORE - inversione_matriciale: gsl_linalg_LU_invert fallito.\n");} // matrice inversa inserita in una matrice "non di libreria" for(i=0; i<dimensione; i++){ for(j=0; j<dimensione; j++){ inversione[i][j]=gsl_matrix_get(inverse, i, j); } } gsl_matrix_free(inverse); gsl_permutation_free(permutazione); free(segno); return inversione; } double **addizione_matriciale(int nrighe, double *media){ // data compression "addizionato" int i, j = 0; double **addizione; // alloccamento dinamico addizione=malloc(nrighe*sizeof(double*)); if(addizione==NULL){printf("ERRORE - addizione_matriciale: addizione non alloccato.\n"); exit(0);} for(i=0; i<nrighe; i++){ addizione[i]=malloc(dimensione*sizeof(double)); if(addizione[i]==NULL){printf("ERRORE - addizione_matriciale: addizione[%d] non alloccato.\n", i); exit(0);} } // ogni riga del data compression viene addizzionato per la media (della stessa riga) del data set for(i=0; i<nrighe; i++){ for(j=0; j<dimensione; j++){ addizione[i][j]=data_compression[i][j]+media[i]; if(debug==1){printf("data_compression[%d][%d] = %2.2f , media[%d] = %2.2f , addizione[%d][%d] = %2.2f\n", i, j, data_compression[i][j], i, media[i], i, j, addizione[i][j]); } } } return addizione; } double **inversione_operazione(int nrighe, double *media, gsl_matrix *evec){ // invertiamo l'algoritmo double **verifica; // verifica = data_compression*autovettori(invertiti) + media_righe_data_set = data_set // operazione di inversione della matrice verifica=inversione_matriciale(evec); //stampa(1, verifica, NULL, "Inversa", dimensione, 0); // operazione di prodotto matriciale if(0 != prodotto_matriciale(nrighe, dimensione, dimensione, dimensione, data_compression, verifica)){ printf("ERRORE - inversione_operazione: funzione prodotto_matriciale ha riportato un errore, esecuzione arrestata.\n"); exit(0); } //stampa(1, data_compression, NULL, "Prodotto Matriciale", nrighe, 0); verifica=addizione_matriciale(nrighe, media); // operazione di somma matriciale return verifica; } void trasponi(int nr, int nc){ // esegue la trasposizione della matrice int i, j; j = 0; for(j = 0; j < nc; j++){ for(i = 0; i < nr; i++){ data_set[j][i] = data_set_origine[i][j]; } } } void ottieni(char stringa[], int riga){ // estrazione del data set int set=0, last_set=0; int i, j=0, k; char buf[100]; double a; k=0; for(i = 0; i < strlen(stringa); i++){ //per leggere tutti i caratteri if( (((int)stringa[i]) == 43) || (((int)stringa[i]) == 45) || (((int)stringa[i]) == 46) || ((((int)stringa[i]) > 47) && (((int)stringa[i]) < 58))){ set=1; //dico che erano caratteri buf[j]=stringa[i]; //salvo il numero j++; //incremento il puntatore }else{ set=0; } if((set==0 && last_set==1) || (set==1 && i == (strlen(stringa)-1))){ //controllo se ho letto tutto il numero a=atof(buf); //converto la stringa in un double data_set_origine[riga][k]=a; //salvo il numero k++; //incremento la colonna strcpy(buf, ""); //svuoto il buf j=0;//pongo il puntatore del buf a 0 così da poter leggere il numero seguente } last_set=set; //dico qual'era il valore precedente } } int colonne(char stringa[]){ //conto il numero di colonne int set=0, last_set=0; //variabili per puntare il carattere e il penultimo carattere int i, j=0; //variabili locali, j è il numero di colonne for(i = 0; i < strlen(stringa); i++){ /*controllo se il carattere in questione è un numero, il segno + o -, oppure il .*/ if( (((int)stringa[i]) == 43) || (((int)stringa[i]) == 45) || (((int)stringa[i]) == 46) || ((((int)stringa[i]) > 47) && (((int)stringa[i]) < 58))){ set=1; }else{ set=0; } if((last_set == 1 && set == 0)||(set == 1 && i == (strlen(stringa) -1))){ //controllo se ho finito di leggere il numero j++; } last_set=set; } return j; //ritorno il numero di colonne } int lettura(){ // funzione per leggere il file in input FILE *fp; // file per la lettura char pathname[1000]; //percorso file char buf[2000]; char *s; int i=0, nrighe=0, ncolonne=1; int j=0; /*prendo in ingresso il nome del file*/ printf("Inserisci l'indirizzo del file: \n"); scanf("%s", pathname); if( (fp = fopen(pathname, "r")) == NULL ){ // apro il file e controllo se è avvenuto con successo printf("ERRORE - lettura: apertura file %s fallito.\n", pathname); exit(0); } /*inizio la lettura del file*/ while(1){ // conto il numero di righe e colonne stpcpy(buf, ""); s = fgets(buf, sizeof(buf), fp); if(s == NULL) break; // se la linea è vuota ho letto tutto il file nrighe++; // conto le righe if(j == 0){ ncolonne=colonne(buf); j++; } } data_set_origine=malloc(nrighe*sizeof(double*));//allocco la memoria del data set data_set=malloc(ncolonne*sizeof(double*)); if(data_set == NULL){ printf("ERRORE - lettura: data_set non alloccato.\n"); exit(0); } if(data_set_origine == NULL){ printf("ERRORE - lettura: data_set non alloccato.\n"); exit(0); } for(i = 0; i < nrighe; i++){//alloco tutta la memoria data_set_origine[i]=malloc(ncolonne*sizeof(double)); data_set[i]=malloc(nrighe*sizeof(double)); if(data_set[i] == NULL){ printf("ERRORE - lettura: data_set[%d] non alloccato.\n", i); exit(0); } if(data_set_origine[i] == NULL){ printf("ERRORE - lettura: data_set_origine[%d] non alloccato.\n", i); exit(0); } } rewind(fp); for(i = 0; i < nrighe; i++){ stpcpy(buf, ""); s = fgets(buf, sizeof(buf), fp); ottieni(buf, i); } fclose(fp); trasponi(nrighe, ncolonne); dimensione = nrighe; return ncolonne; } int main(int argc, char **argv){ int nrighe, i, j = 0; //variabili di gestione double *valor_medio, **matrice_covarianza, **sottrazione, **verifica; //array per il salvataggio dei dati struct gsl pointer_gsl; //inizializzazione struttura if(debug){printf("MODALITA' DEBUG ATTIVA\n");} nrighe=lettura(); // apertura e lettura del data set, nrighe=ncolonne perchè abbiamo trasposto la matrice stampa(0, NULL, NULL, "nrighe", nrighe, 0); stampa(0, NULL, NULL, "Dimensione del Data_set", dimensione, 0); // stampa dimensioni del data set //stampa(1, data_set_origine, NULL, "Data Set", dimensione, nrighe); stampa(1, data_set, NULL, "Data Set Trasposto", nrighe, dimensione); // alloccamento dinamico data_compression=malloc(nrighe*sizeof(double*)); if(data_compression==NULL){printf("ERRORE - main: data_compression non alloccato.\n"); exit(0);} for(i=0; i<nrighe; i++){ data_compression[i]=malloc(dimensione*sizeof(double)); if(data_compression[i]==NULL){printf("ERRORE - main: data_compression[%d] non alloccato.\n", i); exit(0);} } autovalori=malloc(dimensione*sizeof(double)); if(autovalori==NULL){printf("ERRORE - main: autovalori non alloccato.\n"); exit(0);} autovettori=malloc(dimensione*sizeof(double*)); if(autovettori==NULL){printf("ERRORE - main: autovettori non alloccato.\n"); exit(0);} for(i=0; i<dimensione; i++){ autovettori[i]=malloc(dimensione*sizeof(double)); if(autovettori==NULL){printf("ERRORE - main: autovettori[%d] non alloccato.\n", i); exit(0);} } valor_medio=media(nrighe); // calcolo dei valor medi //stampa(2, NULL, valor_medio, NULL, nrighe, 0); matrice_covarianza=covarianza(valor_medio, nrighe); // calcolo della matrice di covarianza //stampa(1, matrice_covarianza, NULL, "Covarianza", dimensione, dimensione); pointer_gsl=eigen(matrice_covarianza); // calcolo degli autovalori e autovettori for(i=0; i<dimensione; i++){ // settaggio degli autovalori nell'apposito array autovalori[i]=gsl_vector_get(pointer_gsl.vector, i); } //stampa(3, NULL, NULL, NULL, 0, 0); // stampa autovalori (non ordinanti) gsl_vector_free(pointer_gsl.vector); ordinamento(pointer_gsl.matrix); // ordinamento decrescente di autovalori e autovettori for(i=0; i<dimensione; i++){ // settaggio degli autovettori negll'apposito array for(j=0; j<dimensione; j++){ autovettori[i][j]=gsl_matrix_get(pointer_gsl.matrix, i, j); // estrazione del valore da "evec" if(autovettori[i]==NULL){printf("ERRORE - main: gsl_matrix_get fallito.\n"); exit(0);} } } //stampa(3, NULL, NULL, NULL, 0, 0); // stampa autovalori //stampa(1, autovettori, NULL, "Autovettori", dimensione, dimensione); // stampa autovettori sottrazione=sottrazione_matriciale(nrighe, valor_medio); // operazione di sottrazione matriciale //stampa(1, sottrazione, NULL, "Sottrazione", nrighe, 0); if(0 != prodotto_matriciale(nrighe, dimensione, dimensione, dimensione, sottrazione, autovettori)){ // operazione di prodotto matriciale printf("ERRORE - main: funzione prodotto_matriciale ha riportato un errore, esecuzione arrestata.\n"); return 0; } stampa(1, data_compression, NULL, "Data Compression", nrighe, dimensione); free(sottrazione); verifica=inversione_operazione(nrighe, valor_medio, pointer_gsl.matrix); // operazione inversa (ricavo il data set) stampa(1, verifica, NULL, "Verifica", nrighe, dimensione); gsl_matrix_free(pointer_gsl.matrix); stampa(1, data_set, NULL, "Dataset", nrighe, dimensione); for(i=0; i<nrighe; i++){ // verifica della buona riuscita dell'operazione d'inversione for(j=0; j<dimensione; j++){ //tronco alla 3° cifra decimale per trascurare piccole variazioni, dovute ad errori di approssimazione if((floor(data_set[i][j]*troncamento)/troncamento) != ((floor(verifica[i][j]*troncamento))/troncamento)){ stampa(5, NULL, NULL, NULL, 0, 0); } } } printf("programma terminato.\n"); return 0; }
{ "alphanum_fraction": 0.6524752475, "avg_line_length": 35.8344283837, "ext": "c", "hexsha": "289fbc7bfea9296cfc50e5163c558e0a2a8f56b0", "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": "cedda6504c1a8b740dbaddb352f440052c21830a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wilsonjefferson/CE_OS", "max_forks_repo_path": "project/mining.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "cedda6504c1a8b740dbaddb352f440052c21830a", "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": "wilsonjefferson/CE_OS", "max_issues_repo_path": "project/mining.c", "max_line_length": 164, "max_stars_count": null, "max_stars_repo_head_hexsha": "cedda6504c1a8b740dbaddb352f440052c21830a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wilsonjefferson/CE_OS", "max_stars_repo_path": "project/mining.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9287, "size": 27270 }
#ifndef __ARNOLDI_Implicit_restart_Arnoldi_H__ #define __ARNOLDI_Implicit_restart_Arnoldi_H__ #include "Macros.h" #include "timer.h" #include "cuda_supp.h" #include "memory_operations.h" #include "Arnoldi_Driver.h" #include "Select_Shifts.h" #include "QR_Shifts.h" #include "Matrix_Vector_emulator.h" #include "file_operations.h" //to set number of threads in openblas #include <cblas.h> extern "C" int openblas_get_num_threads(void); extern "C" void openblas_set_num_threads(int); real Implicit_restart_Arnoldi_GPU_data(cublasHandle_t handle, bool verbose, int N, user_map_vector Axb, void *user_struct, char which[2], int k, int m, complex real* eigenvaluesA, real tol, int max_iter, real *eigenvectors_real=NULL, real *eigenvectors_imag=NULL, int BLASTreads=1); real Implicit_restart_Arnoldi_GPU_data_Matrix_Exponent(cublasHandle_t handle, bool verbose, int N, user_map_vector Axb_exponent_invert, void *user_struct_exponent_invert, user_map_vector Axb, void *user_struct, char which[2], char which_exponent[2], int k, int m, complex real* eigenvaluesA, real tol, int max_iter, bool is_rotated, real *eigenvectors_real_d=NULL, real *eigenvectors_imag_d=NULL, int BLASThreads=1); #endif
{ "alphanum_fraction": 0.8095238095, "avg_line_length": 46.0384615385, "ext": "h", "hexsha": "3a070be274b5d85d8da3698c4afa8eb54a6808ae", "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": "094c168f153e36f00ac9103675416ddb9ee6b586", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "evstigneevnm/NS3DPeriodic", "max_forks_repo_path": "Source/Arnoldi/Implicit_restart_Arnoldi.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "094c168f153e36f00ac9103675416ddb9ee6b586", "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": "evstigneevnm/NS3DPeriodic", "max_issues_repo_path": "Source/Arnoldi/Implicit_restart_Arnoldi.h", "max_line_length": 417, "max_stars_count": null, "max_stars_repo_head_hexsha": "094c168f153e36f00ac9103675416ddb9ee6b586", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "evstigneevnm/NS3DPeriodic", "max_stars_repo_path": "Source/Arnoldi/Implicit_restart_Arnoldi.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 337, "size": 1197 }
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights // reserved. See files LICENSE and NOTICE for details. // // This file is part of CEED, a collection of benchmarks, miniapps, software // libraries and APIs for efficient high-order finite element and spectral // element discretizations for exascale applications. For more information and // source code availability see http://github.com/ceed. // // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, // a collaborative effort of two U.S. Department of Energy organizations (Office // of Science and the National Nuclear Security Administration) responsible for // the planning and preparation of a capable exascale ecosystem, including // software, applications, hardware, advanced system engineering and early // testbed platforms, in support of the nation's exascale computing imperative. // libCEED + PETSc Example: CEED BPs 3-6 with Multigrid // // This example demonstrates a simple usage of libCEED with PETSc to solve the // CEED BP benchmark problems, see http://ceed.exascaleproject.org/bps. // // The code uses higher level communication protocols in DMPlex. // // Build with: // // make multigrid [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>] // // Sample runs: // // multigrid -problem bp3 // multigrid -problem bp4 // multigrid -problem bp5 -ceed /cpu/self // multigrid -problem bp6 -ceed /gpu/cuda // //TESTARGS -ceed {ceed_resource} -test -problem bp3 -degree 3 /// @file /// CEED BPs 1-6 multigrid example using PETSc const char help[] = "Solve CEED BPs using p-multigrid with PETSc and DMPlex\n"; #include <stdbool.h> #include <string.h> #include <ceed.h> #include <petsc.h> #include <petscdmplex.h> #include <petscksp.h> #include <petscsys.h> #include "bps.h" #include "include/bpsproblemdata.h" #include "include/petscmacros.h" #include "include/petscutils.h" #include "include/matops.h" #include "include/structs.h" #include "include/libceedsetup.h" #if PETSC_VERSION_LT(3,12,0) #ifdef PETSC_HAVE_CUDA #include <petsccuda.h> // Note: With PETSc prior to version 3.12.0, providing the source path to // include 'cublas_v2.h' will be needed to use 'petsccuda.h'. #endif #endif int main(int argc, char **argv) { PetscInt ierr; MPI_Comm comm; char filename[PETSC_MAX_PATH_LEN], ceed_resource[PETSC_MAX_PATH_LEN] = "/cpu/self"; double my_rt_start, my_rt, rt_min, rt_max; PetscInt degree = 3, q_extra, *l_size, *xl_size, *g_size, dim = 3, fine_level, mesh_elem[3] = {3, 3, 3}, num_comp_u = 1, num_levels = degree, *level_degrees; PetscScalar *r; PetscScalar eps = 1.0; PetscBool test_mode, benchmark_mode, read_mesh, write_solution; PetscLogStage solve_stage; DM *dm, dm_orig; SNES snes_dummy; KSP ksp; PC pc; Mat *mat_O, *mat_pr, mat_coarse; Vec *X, *X_loc, *mult, rhs, rhs_loc; PetscMemType mem_type; UserO *user_O; UserProlongRestr *user_pr; Ceed ceed; CeedData *ceed_data; CeedVector rhs_ceed, target; CeedQFunction qf_error, qf_restrict, qf_prolong; CeedOperator op_error; BPType bp_choice; CoarsenType coarsen; ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr; comm = PETSC_COMM_WORLD; // Parse command line options ierr = PetscOptionsBegin(comm, NULL, "CEED BPs in PETSc", NULL); CHKERRQ(ierr); bp_choice = CEED_BP3; ierr = PetscOptionsEnum("-problem", "CEED benchmark problem to solve", NULL, bp_types, (PetscEnum)bp_choice, (PetscEnum *)&bp_choice, NULL); CHKERRQ(ierr); num_comp_u = bp_options[bp_choice].num_comp_u; test_mode = PETSC_FALSE; ierr = PetscOptionsBool("-test", "Testing mode (do not print unless error is large)", NULL, test_mode, &test_mode, NULL); CHKERRQ(ierr); benchmark_mode = PETSC_FALSE; ierr = PetscOptionsBool("-benchmark", "Benchmarking mode (prints benchmark statistics)", NULL, benchmark_mode, &benchmark_mode, NULL); CHKERRQ(ierr); write_solution = PETSC_FALSE; ierr = PetscOptionsBool("-write_solution", "Write solution for visualization", NULL, write_solution, &write_solution, NULL); CHKERRQ(ierr); ierr = PetscOptionsScalar("-eps", "Epsilon parameter for Kershaw mesh transformation", NULL, eps, &eps, NULL); if (eps > 1 || eps <= 0) SETERRQ1(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "-eps %D must be (0,1]", eps); degree = test_mode ? 3 : 2; ierr = PetscOptionsInt("-degree", "Polynomial degree of tensor product basis", NULL, degree, &degree, NULL); CHKERRQ(ierr); if (degree < 1) SETERRQ1(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "-degree %D must be at least 1", degree); q_extra = bp_options[bp_choice].q_extra; ierr = PetscOptionsInt("-q_extra", "Number of extra quadrature points", NULL, q_extra, &q_extra, NULL); CHKERRQ(ierr); ierr = PetscOptionsString("-ceed", "CEED resource specifier", NULL, ceed_resource, ceed_resource, sizeof(ceed_resource), NULL); CHKERRQ(ierr); coarsen = COARSEN_UNIFORM; ierr = PetscOptionsEnum("-coarsen", "Coarsening strategy to use", NULL, coarsen_types, (PetscEnum)coarsen, (PetscEnum *)&coarsen, NULL); CHKERRQ(ierr); read_mesh = PETSC_FALSE; ierr = PetscOptionsString("-mesh", "Read mesh from file", NULL, filename, filename, sizeof(filename), &read_mesh); CHKERRQ(ierr); if (!read_mesh) { PetscInt tmp = dim; ierr = PetscOptionsIntArray("-cells","Number of cells per dimension", NULL, mesh_elem, &tmp, NULL); CHKERRQ(ierr); } ierr = PetscOptionsEnd(); CHKERRQ(ierr); // Set up libCEED CeedInit(ceed_resource, &ceed); CeedMemType mem_type_backend; CeedGetPreferredMemType(ceed, &mem_type_backend); // Setup DM if (read_mesh) { ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, filename, PETSC_TRUE, &dm_orig); CHKERRQ(ierr); } else { ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, dim, PETSC_FALSE, mesh_elem, NULL, NULL, NULL, PETSC_TRUE, &dm_orig); CHKERRQ(ierr); } { DM dm_dist = NULL; PetscPartitioner part; ierr = DMPlexGetPartitioner(dm_orig, &part); CHKERRQ(ierr); ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr); ierr = DMPlexDistribute(dm_orig, 0, NULL, &dm_dist); CHKERRQ(ierr); if (dm_dist) { ierr = DMDestroy(&dm_orig); CHKERRQ(ierr); dm_orig = dm_dist; } } // Apply Kershaw mesh transformation ierr = Kershaw(dm_orig, eps); CHKERRQ(ierr); VecType vec_type; switch (mem_type_backend) { case CEED_MEM_HOST: vec_type = VECSTANDARD; break; case CEED_MEM_DEVICE: { const char *resolved; CeedGetResource(ceed, &resolved); if (strstr(resolved, "/gpu/cuda")) vec_type = VECCUDA; else if (strstr(resolved, "/gpu/hip/occa")) vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678 else if (strstr(resolved, "/gpu/hip")) vec_type = VECHIP; else vec_type = VECSTANDARD; } } ierr = DMSetVecType(dm_orig, vec_type); CHKERRQ(ierr); ierr = DMSetFromOptions(dm_orig); CHKERRQ(ierr); // Allocate arrays for PETSc objects for each level switch (coarsen) { case COARSEN_UNIFORM: num_levels = degree; break; case COARSEN_LOGARITHMIC: num_levels = ceil(log(degree)/log(2)) + 1; break; } ierr = PetscMalloc1(num_levels, &level_degrees); CHKERRQ(ierr); fine_level = num_levels - 1; switch (coarsen) { case COARSEN_UNIFORM: for (int i=0; i<num_levels; i++) level_degrees[i] = i + 1; break; case COARSEN_LOGARITHMIC: for (int i=0; i<num_levels - 1; i++) level_degrees[i] = pow(2,i); level_degrees[fine_level] = degree; break; } ierr = PetscMalloc1(num_levels, &dm); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &X); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &X_loc); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &mult); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &user_O); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &user_pr); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &mat_O); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &mat_pr); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &l_size); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &xl_size); CHKERRQ(ierr); ierr = PetscMalloc1(num_levels, &g_size); CHKERRQ(ierr); // Setup DM and Operator Mat Shells for each level for (CeedInt i=0; i<num_levels; i++) { // Create DM ierr = DMClone(dm_orig, &dm[i]); CHKERRQ(ierr); ierr = DMGetVecType(dm_orig, &vec_type); CHKERRQ(ierr); ierr = DMSetVecType(dm[i], vec_type); CHKERRQ(ierr); PetscInt dim; ierr = DMGetDimension(dm[i], &dim); CHKERRQ(ierr); ierr = SetupDMByDegree(dm[i], level_degrees[i], num_comp_u, dim, bp_options[bp_choice].enforce_bc, bp_options[bp_choice].bc_func); CHKERRQ(ierr); // Create vectors ierr = DMCreateGlobalVector(dm[i], &X[i]); CHKERRQ(ierr); ierr = VecGetLocalSize(X[i], &l_size[i]); CHKERRQ(ierr); ierr = VecGetSize(X[i], &g_size[i]); CHKERRQ(ierr); ierr = DMCreateLocalVector(dm[i], &X_loc[i]); CHKERRQ(ierr); ierr = VecGetSize(X_loc[i], &xl_size[i]); CHKERRQ(ierr); // Operator ierr = PetscMalloc1(1, &user_O[i]); CHKERRQ(ierr); ierr = MatCreateShell(comm, l_size[i], l_size[i], g_size[i], g_size[i], user_O[i], &mat_O[i]); CHKERRQ(ierr); ierr = MatShellSetOperation(mat_O[i], MATOP_MULT, (void(*)(void))MatMult_Ceed); CHKERRQ(ierr); ierr = MatShellSetOperation(mat_O[i], MATOP_GET_DIAGONAL, (void(*)(void))MatGetDiag); CHKERRQ(ierr); ierr = MatShellSetVecType(mat_O[i], vec_type); CHKERRQ(ierr); // Level transfers if (i > 0) { // Interp ierr = PetscMalloc1(1, &user_pr[i]); CHKERRQ(ierr); ierr = MatCreateShell(comm, l_size[i], l_size[i-1], g_size[i], g_size[i-1], user_pr[i], &mat_pr[i]); CHKERRQ(ierr); ierr = MatShellSetOperation(mat_pr[i], MATOP_MULT, (void(*)(void))MatMult_Prolong); CHKERRQ(ierr); ierr = MatShellSetOperation(mat_pr[i], MATOP_MULT_TRANSPOSE, (void(*)(void))MatMult_Restrict); CHKERRQ(ierr); ierr = MatShellSetVecType(mat_pr[i], vec_type); CHKERRQ(ierr); } } ierr = VecDuplicate(X[fine_level], &rhs); CHKERRQ(ierr); // Print global grid information if (!test_mode) { PetscInt P = degree + 1, Q = P + q_extra; const char *used_resource; CeedGetResource(ceed, &used_resource); ierr = VecGetType(X[0], &vec_type); CHKERRQ(ierr); ierr = PetscPrintf(comm, "\n-- CEED Benchmark Problem %d -- libCEED + PETSc + PCMG --\n" " PETSc:\n" " PETSc Vec Type : %s\n" " libCEED:\n" " libCEED Backend : %s\n" " libCEED Backend MemType : %s\n" " Mesh:\n" " Number of 1D Basis Nodes (p) : %d\n" " Number of 1D Quadrature Points (q) : %d\n" " Global Nodes : %D\n" " Owned Nodes : %D\n" " DoF per node : %D\n" " Multigrid:\n" " Number of Levels : %d\n", bp_choice+1, vec_type, used_resource, CeedMemTypes[mem_type_backend], P, Q, g_size[fine_level]/num_comp_u, l_size[fine_level]/num_comp_u, num_comp_u, num_levels); CHKERRQ(ierr); } // Create RHS vector ierr = VecDuplicate(X_loc[fine_level], &rhs_loc); CHKERRQ(ierr); ierr = VecZeroEntries(rhs_loc); CHKERRQ(ierr); ierr = VecGetArrayAndMemType(rhs_loc, &r, &mem_type); CHKERRQ(ierr); CeedVectorCreate(ceed, xl_size[fine_level], &rhs_ceed); CeedVectorSetArray(rhs_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, r); // Set up libCEED operators on each level ierr = PetscMalloc1(num_levels, &ceed_data); CHKERRQ(ierr); for (int i=0; i<num_levels; i++) { // Print level information if (!test_mode && (i == 0 || i == fine_level)) { ierr = PetscPrintf(comm," Level %D (%s):\n" " Number of 1D Basis Nodes (p) : %d\n" " Global Nodes : %D\n" " Owned Nodes : %D\n", i, (i? "fine" : "coarse"), level_degrees[i] + 1, g_size[i]/num_comp_u, l_size[i]/num_comp_u); CHKERRQ(ierr); } ierr = PetscMalloc1(1, &ceed_data[i]); CHKERRQ(ierr); ierr = SetupLibceedByDegree(dm[i], ceed, level_degrees[i], dim, q_extra, dim, num_comp_u, g_size[i], xl_size[i], bp_options[bp_choice], ceed_data[i], i==(fine_level), rhs_ceed, &target); CHKERRQ(ierr); } // Gather RHS CeedVectorTakeArray(rhs_ceed, MemTypeP2C(mem_type), NULL); ierr = VecRestoreArrayAndMemType(rhs_loc, &r); CHKERRQ(ierr); ierr = VecZeroEntries(rhs); CHKERRQ(ierr); ierr = DMLocalToGlobal(dm[fine_level], rhs_loc, ADD_VALUES, rhs); CHKERRQ(ierr); CeedVectorDestroy(&rhs_ceed); // Create the restriction/interpolation QFunction CeedQFunctionCreateIdentity(ceed, num_comp_u, CEED_EVAL_NONE, CEED_EVAL_INTERP, &qf_restrict); CeedQFunctionCreateIdentity(ceed, num_comp_u, CEED_EVAL_INTERP, CEED_EVAL_NONE, &qf_prolong); // Set up libCEED level transfer operators ierr = CeedLevelTransferSetup(ceed, num_levels, num_comp_u, ceed_data, level_degrees, qf_restrict, qf_prolong); CHKERRQ(ierr); // Create the error QFunction CeedQFunctionCreateInterior(ceed, 1, bp_options[bp_choice].error, bp_options[bp_choice].error_loc, &qf_error); CeedQFunctionAddInput(qf_error, "u", num_comp_u, CEED_EVAL_INTERP); CeedQFunctionAddInput(qf_error, "true_soln", num_comp_u, CEED_EVAL_NONE); CeedQFunctionAddOutput(qf_error, "error", num_comp_u, CEED_EVAL_NONE); // Create the error operator CeedOperatorCreate(ceed, qf_error, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE, &op_error); CeedOperatorSetField(op_error, "u", ceed_data[fine_level]->elem_restr_u, ceed_data[fine_level]->basis_u, CEED_VECTOR_ACTIVE); CeedOperatorSetField(op_error, "true_soln", ceed_data[fine_level]->elem_restr_u_i, CEED_BASIS_COLLOCATED, target); CeedOperatorSetField(op_error, "error", ceed_data[fine_level]->elem_restr_u_i, CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE); // Calculate multiplicity for (int i=0; i<num_levels; i++) { PetscScalar *x; // CEED vector ierr = VecZeroEntries(X_loc[i]); CHKERRQ(ierr); ierr = VecGetArray(X_loc[i], &x); CHKERRQ(ierr); CeedVectorSetArray(ceed_data[i]->x_ceed, CEED_MEM_HOST, CEED_USE_POINTER, x); // Multiplicity CeedElemRestrictionGetMultiplicity(ceed_data[i]->elem_restr_u, ceed_data[i]->x_ceed); CeedVectorSyncArray(ceed_data[i]->x_ceed, CEED_MEM_HOST); // Restore vector ierr = VecRestoreArray(X_loc[i], &x); CHKERRQ(ierr); // Creat mult vector ierr = VecDuplicate(X_loc[i], &mult[i]); CHKERRQ(ierr); // Local-to-global ierr = VecZeroEntries(X[i]); CHKERRQ(ierr); ierr = DMLocalToGlobal(dm[i], X_loc[i], ADD_VALUES, X[i]); CHKERRQ(ierr); ierr = VecZeroEntries(X_loc[i]); CHKERRQ(ierr); // Global-to-local ierr = DMGlobalToLocal(dm[i], X[i], INSERT_VALUES, mult[i]); CHKERRQ(ierr); ierr = VecZeroEntries(X[i]); CHKERRQ(ierr); // Multiplicity scaling ierr = VecReciprocal(mult[i]); } // Set up Mat for (int i=0; i<num_levels; i++) { // User Operator user_O[i]->comm = comm; user_O[i]->dm = dm[i]; user_O[i]->X_loc = X_loc[i]; ierr = VecDuplicate(X_loc[i], &user_O[i]->Y_loc); CHKERRQ(ierr); user_O[i]->x_ceed = ceed_data[i]->x_ceed; user_O[i]->y_ceed = ceed_data[i]->y_ceed; user_O[i]->op = ceed_data[i]->op_apply; user_O[i]->ceed = ceed; if (i > 0) { // Prolongation/Restriction Operator user_pr[i]->comm = comm; user_pr[i]->dmf = dm[i]; user_pr[i]->dmc = dm[i-1]; user_pr[i]->loc_vec_c = X_loc[i-1]; user_pr[i]->loc_vec_f = user_O[i]->Y_loc; user_pr[i]->mult_vec = mult[i]; user_pr[i]->ceed_vec_c = user_O[i-1]->x_ceed; user_pr[i]->ceed_vec_f = user_O[i]->y_ceed; user_pr[i]->op_prolong = ceed_data[i]->op_prolong; user_pr[i]->op_restrict = ceed_data[i]->op_restrict; user_pr[i]->ceed = ceed; } } // Setup dummy SNES for AMG coarse solve ierr = SNESCreate(comm, &snes_dummy); CHKERRQ(ierr); ierr = SNESSetDM(snes_dummy, dm[0]); CHKERRQ(ierr); ierr = SNESSetSolution(snes_dummy, X[0]); CHKERRQ(ierr); // -- Jacobian matrix ierr = DMSetMatType(dm[0], MATAIJ); CHKERRQ(ierr); ierr = DMCreateMatrix(dm[0], &mat_coarse); CHKERRQ(ierr); ierr = SNESSetJacobian(snes_dummy, mat_coarse, mat_coarse, NULL, NULL); CHKERRQ(ierr); // -- Residual evaluation function ierr = SNESSetFunction(snes_dummy, X[0], FormResidual_Ceed, user_O[0]); CHKERRQ(ierr); // -- Form Jacobian ierr = SNESComputeJacobianDefaultColor(snes_dummy, X[0], mat_O[0], mat_coarse, NULL); CHKERRQ(ierr); // Set up KSP ierr = KSPCreate(comm, &ksp); CHKERRQ(ierr); { ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr); ierr = KSPSetNormType(ksp, KSP_NORM_NATURAL); CHKERRQ(ierr); ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT); CHKERRQ(ierr); } ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr); ierr = KSPSetOperators(ksp, mat_O[fine_level], mat_O[fine_level]); CHKERRQ(ierr); // Set up PCMG ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr); PCMGCycleType pcmg_cycle_type = PC_MG_CYCLE_V; { ierr = PCSetType(pc, PCMG); CHKERRQ(ierr); // PCMG levels ierr = PCMGSetLevels(pc, num_levels, NULL); CHKERRQ(ierr); for (int i=0; i<num_levels; i++) { // Smoother KSP smoother; PC smoother_pc; ierr = PCMGGetSmoother(pc, i, &smoother); CHKERRQ(ierr); ierr = KSPSetType(smoother, KSPCHEBYSHEV); CHKERRQ(ierr); ierr = KSPChebyshevEstEigSet(smoother, 0, 0.1, 0, 1.1); CHKERRQ(ierr); ierr = KSPChebyshevEstEigSetUseNoisy(smoother, PETSC_TRUE); CHKERRQ(ierr); ierr = KSPSetOperators(smoother, mat_O[i], mat_O[i]); CHKERRQ(ierr); ierr = KSPGetPC(smoother, &smoother_pc); CHKERRQ(ierr); ierr = PCSetType(smoother_pc, PCJACOBI); CHKERRQ(ierr); ierr = PCJacobiSetType(smoother_pc, PC_JACOBI_DIAGONAL); CHKERRQ(ierr); // Work vector if (i < num_levels - 1) { ierr = PCMGSetX(pc, i, X[i]); CHKERRQ(ierr); } // Level transfers if (i > 0) { // Interpolation ierr = PCMGSetInterpolation(pc, i, mat_pr[i]); CHKERRQ(ierr); } // Coarse solve KSP coarse; PC coarse_pc; ierr = PCMGGetCoarseSolve(pc, &coarse); CHKERRQ(ierr); ierr = KSPSetType(coarse, KSPPREONLY); CHKERRQ(ierr); ierr = KSPSetOperators(coarse, mat_coarse, mat_coarse); CHKERRQ(ierr); ierr = KSPGetPC(coarse, &coarse_pc); CHKERRQ(ierr); ierr = PCSetType(coarse_pc, PCGAMG); CHKERRQ(ierr); ierr = KSPSetOptionsPrefix(coarse, "coarse_"); CHKERRQ(ierr); ierr = PCSetOptionsPrefix(coarse_pc, "coarse_"); CHKERRQ(ierr); ierr = KSPSetFromOptions(coarse); CHKERRQ(ierr); ierr = PCSetFromOptions(coarse_pc); CHKERRQ(ierr); } // PCMG options ierr = PCMGSetType(pc, PC_MG_MULTIPLICATIVE); CHKERRQ(ierr); ierr = PCMGSetNumberSmooth(pc, 3); CHKERRQ(ierr); ierr = PCMGSetCycleType(pc, pcmg_cycle_type); CHKERRQ(ierr); } // First run, if benchmarking if (benchmark_mode) { ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 1); CHKERRQ(ierr); ierr = VecZeroEntries(X[fine_level]); CHKERRQ(ierr); my_rt_start = MPI_Wtime(); ierr = KSPSolve(ksp, rhs, X[fine_level]); CHKERRQ(ierr); my_rt = MPI_Wtime() - my_rt_start; ierr = MPI_Allreduce(MPI_IN_PLACE, &my_rt, 1, MPI_DOUBLE, MPI_MIN, comm); CHKERRQ(ierr); // Set maxits based on first iteration timing if (my_rt > 0.02) { ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 5); CHKERRQ(ierr); } else { ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 20); CHKERRQ(ierr); } } // Timed solve ierr = VecZeroEntries(X[fine_level]); CHKERRQ(ierr); ierr = PetscBarrier((PetscObject)ksp); CHKERRQ(ierr); // -- Performance logging ierr = PetscLogStageRegister("Solve Stage", &solve_stage); CHKERRQ(ierr); ierr = PetscLogStagePush(solve_stage); CHKERRQ(ierr); // -- Solve my_rt_start = MPI_Wtime(); ierr = KSPSolve(ksp, rhs, X[fine_level]); CHKERRQ(ierr); my_rt = MPI_Wtime() - my_rt_start; // -- Performance logging ierr = PetscLogStagePop(); // Output results { KSPType ksp_type; PCMGType pcmg_type; KSPConvergedReason reason; PetscReal rnorm; PetscInt its; ierr = KSPGetType(ksp, &ksp_type); CHKERRQ(ierr); ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr); ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr); ierr = KSPGetResidualNorm(ksp, &rnorm); CHKERRQ(ierr); ierr = PCMGGetType(pc, &pcmg_type); CHKERRQ(ierr); if (!test_mode || reason < 0 || rnorm > 1e-8) { ierr = PetscPrintf(comm, " KSP:\n" " KSP Type : %s\n" " KSP Convergence : %s\n" " Total KSP Iterations : %D\n" " Final rnorm : %e\n", ksp_type, KSPConvergedReasons[reason], its, (double)rnorm); CHKERRQ(ierr); ierr = PetscPrintf(comm, " PCMG:\n" " PCMG Type : %s\n" " PCMG Cycle Type : %s\n", PCMGTypes[pcmg_type], PCMGCycleTypes[pcmg_cycle_type]); CHKERRQ(ierr); } if (!test_mode) { ierr = PetscPrintf(comm," Performance:\n"); CHKERRQ(ierr); } { PetscReal max_error; ierr = ComputeErrorMax(user_O[fine_level], op_error, X[fine_level], target, &max_error); CHKERRQ(ierr); PetscReal tol = 5e-2; if (!test_mode || max_error > tol) { ierr = MPI_Allreduce(&my_rt, &rt_min, 1, MPI_DOUBLE, MPI_MIN, comm); CHKERRQ(ierr); ierr = MPI_Allreduce(&my_rt, &rt_max, 1, MPI_DOUBLE, MPI_MAX, comm); CHKERRQ(ierr); ierr = PetscPrintf(comm, " Pointwise Error (max) : %e\n" " CG Solve Time : %g (%g) sec\n", (double)max_error, rt_max, rt_min); CHKERRQ(ierr); } } if (benchmark_mode && (!test_mode)) { ierr = PetscPrintf(comm, " DoFs/Sec in CG : %g (%g) million\n", 1e-6*g_size[fine_level]*its/rt_max, 1e-6*g_size[fine_level]*its/rt_min); CHKERRQ(ierr); } } if (write_solution) { PetscViewer vtk_viewer_soln; ierr = PetscViewerCreate(comm, &vtk_viewer_soln); CHKERRQ(ierr); ierr = PetscViewerSetType(vtk_viewer_soln, PETSCVIEWERVTK); CHKERRQ(ierr); ierr = PetscViewerFileSetName(vtk_viewer_soln, "solution.vtu"); CHKERRQ(ierr); ierr = VecView(X[fine_level], vtk_viewer_soln); CHKERRQ(ierr); ierr = PetscViewerDestroy(&vtk_viewer_soln); CHKERRQ(ierr); } // Cleanup for (int i=0; i<num_levels; i++) { ierr = VecDestroy(&X[i]); CHKERRQ(ierr); ierr = VecDestroy(&X_loc[i]); CHKERRQ(ierr); ierr = VecDestroy(&mult[i]); CHKERRQ(ierr); ierr = VecDestroy(&user_O[i]->Y_loc); CHKERRQ(ierr); ierr = MatDestroy(&mat_O[i]); CHKERRQ(ierr); ierr = PetscFree(user_O[i]); CHKERRQ(ierr); if (i > 0) { ierr = MatDestroy(&mat_pr[i]); CHKERRQ(ierr); ierr = PetscFree(user_pr[i]); CHKERRQ(ierr); } ierr = CeedDataDestroy(i, ceed_data[i]); CHKERRQ(ierr); ierr = DMDestroy(&dm[i]); CHKERRQ(ierr); } ierr = PetscFree(level_degrees); CHKERRQ(ierr); ierr = PetscFree(dm); CHKERRQ(ierr); ierr = PetscFree(X); CHKERRQ(ierr); ierr = PetscFree(X_loc); CHKERRQ(ierr); ierr = PetscFree(mult); CHKERRQ(ierr); ierr = PetscFree(mat_O); CHKERRQ(ierr); ierr = PetscFree(mat_pr); CHKERRQ(ierr); ierr = PetscFree(ceed_data); CHKERRQ(ierr); ierr = PetscFree(user_O); CHKERRQ(ierr); ierr = PetscFree(user_pr); CHKERRQ(ierr); ierr = PetscFree(l_size); CHKERRQ(ierr); ierr = PetscFree(xl_size); CHKERRQ(ierr); ierr = PetscFree(g_size); CHKERRQ(ierr); ierr = VecDestroy(&rhs); CHKERRQ(ierr); ierr = VecDestroy(&rhs_loc); CHKERRQ(ierr); ierr = MatDestroy(&mat_coarse); CHKERRQ(ierr); ierr = KSPDestroy(&ksp); CHKERRQ(ierr); ierr = SNESDestroy(&snes_dummy); CHKERRQ(ierr); ierr = DMDestroy(&dm_orig); CHKERRQ(ierr); CeedVectorDestroy(&target); CeedQFunctionDestroy(&qf_error); CeedQFunctionDestroy(&qf_restrict); CeedQFunctionDestroy(&qf_prolong); CeedOperatorDestroy(&op_error); CeedDestroy(&ceed); return PetscFinalize(); }
{ "alphanum_fraction": 0.614527027, "avg_line_length": 40.2416918429, "ext": "c", "hexsha": "5c1ddb07bd5cbec42d95d4bc1ba0e34ad117bb3b", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/petsc/multigrid.c", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/petsc/multigrid.c", "max_line_length": 94, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/petsc/multigrid.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 7363, "size": 26640 }
/* learn.c */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_multifit.h> #include "learn.h" #include "feature.h" #include "imatrix.h" #include "dmatrix.h" #include "util.h" #include "likelihood.h" #include "hyper.h" void mvslda_learn(document *data, double **resp, double *alpha, double beta, double nu2, double sigma2, int nclass, int nlex, int dlenmax, int nresp, int maxiter, double **phi, double **theta, double **eta, int **n_mz, int **n_zw, FILE *likp, FILE *hyperp, unsigned long int random_seed){ document *dp; int ndocs; int *n_m; int *n_z; int ***topics; int word_index; int word_num; double sum_alpha; double *left; double *center; double *log_right; double *p_z; double *log_p_z; double *cum_sum_p_z; double log_Z, sum_p_r, sum_empirical_z; double temp_prediction; double lik; double **temp_phi; double **temp_theta; double **empirical_z; int z; int it; int m, w, t, i, j, k; const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); // count data length for(dp = data, ndocs = 0;(dp->len) != -1;dp++, ndocs++) ; // initialize buffers if((n_m = calloc(ndocs,sizeof(int))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate n_m.\n"); return; } if((n_z = calloc(nclass,sizeof(int))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate n_z.\n"); return; } if((left = calloc(nclass,sizeof(double))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate left.\n"); return; } if((center = calloc(nclass,sizeof(double))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate center.\n"); return; } if((log_right = calloc(nclass,sizeof(double))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate log_cright.\n"); return; } if((p_z = calloc(nclass,sizeof(double))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate p_z.\n"); return; } if((log_p_z = calloc(nclass,sizeof(double))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate log_p_z.\n"); return; } if((cum_sum_p_z = calloc((nclass+1),sizeof(double))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate cum_sum_p_z.\n"); return; } if((topics = calloc(ndocs,sizeof(int **))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate topics.\n"); return; } if((empirical_z = dmatrix(ndocs, nclass)) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate empirical_z.\n"); return; } if((temp_phi = dmatrix(nlex, nclass)) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate temp_phi.\n"); exit(1); } if((temp_theta = dmatrix(ndocs, nclass)) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate temp_theta.\n"); exit(1); } printf("Number of documents = %d\n",ndocs); printf("Number of unique words = %d\n",nlex); printf("Number of latent classes = %d\n",nclass); printf("Number of responses = %d\n",nresp); printf("Number of iteration = %d\n",maxiter); // choose an arbitrary topic as first topic for word gsl_rng_set(r, random_seed); for(dp = data, m = 0;(dp->len) != -1;dp++, m++){ if((topics[m] = calloc((dp->len), sizeof(int *))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate topics[m].\n"); return; } for(w = 0;w < (dp->len);w++){ if((topics[m][w] = calloc((dp->cnt[w]), sizeof(int))) == NULL){ fprintf(stderr,"mvslda_learn:: cannot allocate topics[m][w].\n"); return; } word_index = dp->id[w]; word_num = dp->cnt[w]; for(i = 0;i < word_num;i++){ z = (int)gsl_rng_uniform_int(r, nclass); n_mz[m][z] += 1; n_m[m] += 1; n_zw[z][word_index] += 1; n_z[z] += 1; topics[m][w][i] = z; } } } // initialize eta ([nclass, nresp]) for(k = 0;k < nclass;k++) for(t = 0;t < nresp;t++) eta[k][t] = 0.0; // learning main for(it = 0;it < maxiter;it++){ printf("iteration %2d/%3d..\n", it + 1, maxiter); fflush(stdout); sum_alpha = 0.0; for(k = 0;k < nclass;k++) sum_alpha += alpha[k]; for (dp = data, m = 0; (dp->len) != -1; dp++, m++){ // for words for(w = 0;w < (dp->len);w++){ word_index = dp->id[w]; word_num = dp->cnt[w]; for(i = 0;i < word_num;i++){ z = topics[m][w][i]; n_mz[m][z] -= 1; n_m[m] -= 1; n_zw[z][word_index] -= 1; n_z[z] -= 1; // compute conditional distribution log_p_z // log_p_z left ... theta term for(k = 0;k < nclass;k++){ left[k] = (double)n_mz[m][k] + alpha[k]; left[k] /= ((double)n_m[m] + sum_alpha); } // log_p_z center ... phi term for(k = 0;k < nclass;k++){ center[k] = (double)n_zw[k][word_index] + beta; center[k] /= ((double)n_z[k] + (double)nlex * beta); } // temporal log_p_z (left and center) for(k = 0; k < nclass;k++){ log_p_z[k] = log(left[k]) + log(center[k]); } // p_z right ... eta term sum_empirical_z = 0.0; for(k = 0; k < nclass;k++){ empirical_z[m][k] = (double)n_mz[m][k]; sum_empirical_z += (double)n_mz[m][k]; } for(k = 0; k < nclass;k++){ empirical_z[m][k] = empirical_z[m][k] / sum_empirical_z; } for(t = 0; t < nresp; t++){ temp_prediction = 0.0; for(k = 0;k < nclass;k++){ temp_prediction += eta[k][t] * empirical_z[m][k]; // dot(eta, z_d) } for(k = 0;k < nclass;k++){ log_right[k] = 1.0; log_right[k] *= 1.0 / (2 * sigma2); log_right[k] *= (eta[k][t] / (double)n_m[m]); log_right[k] *= (2 * (resp[m][t] - temp_prediction) - (eta[k][t] / (double)n_m[m])); log_p_z[k] += log_right[k]; } } // conditional distribution log_p_z // log_Z = logsumexp(logP_k1 + logP_k2 + ... logP_kK) log_Z = logsumexp(log_p_z, nclass); for(k = 0;k < nclass;k++){ p_z[k] = exp(log_p_z[k] - log_Z); // normalize to obtain probabilities } // random sampling from p_z z = sampling_multinomial(r, p_z, cum_sum_p_z, nclass); // update buffers n_mz[m][z] += 1; n_m[m] += 1; n_zw[z][word_index] += 1; n_z[z] += 1; topics[m][w][i] = z; } } } // for eta update //least squares for dot(Z, eta) = resp for(m = 0; m < ndocs; m++){ sum_empirical_z = 0.0; for(k = 0; k < nclass;k++){ empirical_z[m][k] = (double)n_mz[m][k]; sum_empirical_z += (double)n_mz[m][k]; } for(k = 0; k < nclass;k++){ empirical_z[m][k] = empirical_z[m][k] / sum_empirical_z; } } for(t = 0; t < nresp; t++){ double chisq; gsl_matrix *Z, *cov; gsl_vector *y, *c; gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (ndocs, nclass); Z = gsl_matrix_alloc(ndocs, nclass); cov = gsl_matrix_alloc(nclass, nclass); y = gsl_vector_alloc(ndocs); c = gsl_vector_alloc(nclass); for(m = 0;m < ndocs;m++){ gsl_vector_set(y, m, resp[m][t]); for(k = 0;k < nclass;k++){ gsl_matrix_set(Z, m, k, empirical_z[m][k]); } } gsl_multifit_linear(Z, y, c, cov, &chisq, work); for(k = 0;k < nclass;k++){ eta[k][t] = gsl_vector_get(c, k); } gsl_multifit_linear_free(work); gsl_matrix_free(Z); gsl_matrix_free(cov); gsl_vector_free(y); gsl_vector_free(c); } // update hyperparameters. update_alpha(alpha, n_m, n_mz, ndocs, nclass); beta = update_beta(beta, n_z, n_zw, nclass, nlex); // compute likelihood. lik = loglikelihood(n_mz, n_zw, n_m, nclass, nlex, ndocs, nresp, resp, alpha, beta, eta, empirical_z, nu2, sigma2); printf("\tlikelihood ... %.8f\n",lik); printf("\talpha = \n\t"); for(k = 0;k < nclass;k++) printf("%.8f ",alpha[k]); printf("\n\tbeta ... %.2f\n",beta); fprintf(likp,"%.8f\n",lik); for(k = 0;k < nclass;k++) fprintf(hyperp,"%.8f,",alpha[k]); fprintf(hyperp,"%.8f\n",beta); } // compute matrix phi ([nlex, nclass] matrix) for(w = 0;w < nlex;w++) for(k = 0;k < nclass;k++) temp_phi[w][k] = (double)n_zw[k][w] + beta; normalize_matrix_col(phi, temp_phi, nlex, nclass); // compute matrix theta ([ndocs, nclass]) for(m = 0;m < ndocs;m++) for(k = 0;k < nclass;k++) temp_theta[m][k] = (double)n_mz[m][k] + alpha[k]; normalize_matrix_row(theta, temp_theta, ndocs, nclass); free(n_m); free(n_z); free(left); free(center); free(log_right); free(p_z); free(log_p_z); free(cum_sum_p_z); for(dp = data, m = 0;(dp->len) != -1;dp++, m++){ for(w = 0;w < (dp->len);w++){ free(topics[m][w]); } free(topics[m]); } free(topics); free_dmatrix(temp_phi, nlex); free_dmatrix(temp_theta, ndocs); free_dmatrix(empirical_z, ndocs); return; } int sampling_multinomial(gsl_rng *r, double *p, double *cum_sum_p, int len_p){ int k, z; double sampling; cum_sum_p[0] = 0.0; for(k = 0;k < len_p;k++){ cum_sum_p[k+1] = cum_sum_p[k] + p[k]; } sampling = gsl_rng_uniform(r); for(k = 0;k < len_p;k++){ if((sampling >= cum_sum_p[k]) && (sampling < cum_sum_p[k+1])){ z = k; break; } } return z; }
{ "alphanum_fraction": 0.4718234981, "avg_line_length": 35.1588785047, "ext": "c", "hexsha": "2871dce7add65922b146db4426992c6b6cc23990", "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": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "khigashi1987/mvsLDA", "max_forks_repo_path": "src/learn.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "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": "khigashi1987/mvsLDA", "max_issues_repo_path": "src/learn.c", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "khigashi1987/mvsLDA", "max_stars_repo_path": "src/learn.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3051, "size": 11286 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_rng.h> #include <math.h> #include <time.h> #include <stdbool.h> #include "bb_smc.h" /* ========================================================== Last update: 1.5.20 -- v2.0 ABC-SMC (parallel version) Author: Marco Esposito =========================================================== */ // =========== Define some constants ============= #define size_data 50 #define a0 0.5 #define b0 0.5 #define std_ker 0.3 #define striding_size 1 #define n 20 // ===================================== // ARGUMENT NUMBER 1: time at which the simulation starts // ARGUMENT NUMBER 2: seed // ARGUMENT NUMBER 3: number of particles to consider // for the simulation (lesser for shorter runs) int main(int argc, char *argv[]) { if (argc != 4) { printf("argc = %d\n", argc); printf("Usage: %s\n", argv[0]); printf(" %s [parameters] \n", argv[0]); exit(1); } /* ==================== VARIABLES DECLARATION ======================== */ int time = atoi(argv[1]); int seed = atoi(argv[2]); int n_particles = atoi(argv[3]); double theta_star; double theta; double weight; double epsilon_t; int status; double* weights; weights = malloc((n_particles) * sizeof(double)); int sample_accepted; /* ==================================================================== */ /* ============== IMPORT DATA =========== */ int y[size_data]; status = import_data_BB(y, size_data); if (status == 1) { printf("Data not found\n"); exit(1); } double mean_y = mean_int(y, size_data); // printf("(MAIN) -- mean_y: %f\n", mean_y); /* ======================================== */ /* =========== READ THRESHOLD ============ */ status = read_threshold(&epsilon_t, time); if (status == 1) { printf("Threshold not found\n"); exit(1); } /* ======================================== */ /* ================== set up GSL RNG =================== */ gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set (r, seed+101); // set seed /* ===================================================== */ sample_accepted = 1; /* =========================================================== */ /* ================= START THE ABC ROUND ===================== */ /* =========================================================== */ while (sample_accepted == 1) { // Select particle status = select_particle(weights, &theta, time, n_particles, r); if (status == 1) { printf("File with particles at time %d, %d particles not present\n", time, n_particles); exit(1); } // Perturb the parameter status = ker_perturb(&theta_star, r, theta, a0, b0, std_ker); if (status == 1) { continue; } // - If the distance function is too large, start over // - If all the conditions are fulfilled, the sample is accepted sample_accepted = verify_par_BB(theta_star, mean_y, r, size_data, n, epsilon_t, time, seed); if (sample_accepted == 1) { continue; } } //END OF ABC ROUND (WHILE LOOP) -- PARTICLE WAS ACCEPTED calculate_weight_BB(&weight, weights, theta, theta_star, n_particles, a0, b0, std_ker); write_particles_BB(theta_star, time, seed, striding_size, weight); free(weights); return 0; //return of main } //End of the program
{ "alphanum_fraction": 0.4944989593, "avg_line_length": 25.4772727273, "ext": "c", "hexsha": "e84bf5b73813a527fa340866227ec191a0d45d77", "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": "137dd743498c3ff554d971d83f0ade4045049d0a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "espoma/Data_Science", "max_forks_repo_path": "bb_model/smc_bbmodel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a", "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": "espoma/Data_Science", "max_issues_repo_path": "bb_model/smc_bbmodel.c", "max_line_length": 95, "max_stars_count": 5, "max_stars_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "espoma/Data_Science", "max_stars_repo_path": "bb_model/smc_bbmodel.c", "max_stars_repo_stars_event_max_datetime": "2022-01-28T09:06:19.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-27T12:57:31.000Z", "num_tokens": 801, "size": 3363 }
/* * This file is part of the Visual Computing Library (VCL) release under the * license. * * Copyright (c) 2017 Basil Fierz * * 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 // VCL configuration #include <vcl/config/global.h> // C++ Standard library #include <memory> #include <vector> // GSL #include <gsl/gsl> // VCL #include <vcl/hid/windows/hid.h> #include <vcl/hid/spacenavigator.h> namespace Vcl { namespace HID { namespace Windows { //! Implementation of a 3Dconnexion space mouse class SpaceNavigatorHID : public AbstractHID, public SpaceNavigator { private: struct InputData { //! Current time to live for telling //! if the device was unplugged while sending data int timeToLive; //! Indicate if the data is dirty bool isDirty; //! Axis data std::array<float,6> axes; //! Check if the data is zero bool isZero() { return (0 == axes[0] && 0 == axes[1] && 0 == axes[2] && 0 == axes[3] && 0 == axes[4] && 0 == axes[5] ); } //! Maximum time to live static const int MaxTimeToLive = 5; }; public: SpaceNavigatorHID(std::unique_ptr<GenericHID> dev, bool poll_3d_mouse = false); //! Reset device when activating the program void onActivateApp(BOOL active, DWORD dwThreadID); //! Handle device input bool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override; private: /*! * \brief Does all the preprocessing of the rawinput device data before * finally calling the move3D method. * * If polling is enabled (_poll3DMouse == true) this method is called * from the windows timer message handler * If polling is not enabled (_poll3DMouse == false) this method is * called directly from the WM_INPUT handler */ void on3DMouseInput(); /*! * \brief onSpaceMouseMove is invoked when new 3d mouse data is * available. * * \param motion_data Contains the displacement data, using a * right-handed coordinate system with z down. * See 'Programing for the 3dmouse' document * available at www.3dconnexion.com. * Entries 0, 1, 2 is the incremental pan zoom * displacement vector (x,y,z). * Entries 3, 4, 5 is the incremental rotation vector * (NOT Euler angles). */ void onSpaceMouseMove(std::array<float, 6> motion_data); /*! * \brief onSpaceMouseKeyDown processes the 3d mouse key presses * * \param virtual_key 3d mouse key code */ void onSpaceMouseKeyDown(UINT virtual_key); /*! * \brief onSpaceMouseKeyUp processes the 3d mouse key releases * * \param virtual_key 3d mouse key code */ void onSpaceMouseKeyUp(UINT virtual_key); private: //! Process a raw input message bool translateRawInputData(UINT input_code, PRAWINPUT raw_input); //! Axis input data InputData _deviceData; //! Button input data uint32_t _keystate{ 0 }; //! Last time the data was updated. //! Use to calculate distance traveled since last event DWORD _last3DMouseInputTime{ 0 }; private: // Polling support methods //! Start the timer void startTimer(HWND hwnd); //! Timer callback void onTimer(UINT_PTR event_id); //! Kill the currently running timer void killPollingTimer(); private: // Polling support //! 3D mouse is in polling mode bool _poll3DMouse{ false }; //! Polling period. Default is 50 Hz) UINT _pollingPeriod3DMouse{ 20 }; //! 3DMouse data polling timer //! Only used if _poll3DMouse == true UINT_PTR _timer3DMouse{ 0 }; }; }}}
{ "alphanum_fraction": 0.6796941376, "avg_line_length": 29.7974683544, "ext": "h", "hexsha": "897dea644f05f6c34e8b6edcfac59913ac39d8f8", "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": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bfierz/vcl.hid", "max_forks_repo_path": "src/vcl/hid/windows/spacenavigator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "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": "bfierz/vcl.hid", "max_issues_repo_path": "src/vcl/hid/windows/spacenavigator.h", "max_line_length": 87, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bfierz/vcl.hid", "max_stars_repo_path": "src/vcl/hid/windows/spacenavigator.h", "max_stars_repo_stars_event_max_datetime": "2020-03-26T20:39:34.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-26T20:39:34.000Z", "num_tokens": 1216, "size": 4708 }
#include <stdio.h> #include <gsl/gsl_statistics.h> #include <stdlib.h> #include <float.h> #include <assert.h> #ifndef N #define N 64 #endif #define K N/2 #ifndef S #define S K/2 #endif #ifndef SEED #define SEED 1 #endif #include <klee/klee.h> int main(int argc, char* argv[]) { double data[K], w[K]; int i, j; srand(SEED); int index[K]; for (i=0; i<K; i++) index[i]=i; for (i=0; i<K-1; i++){ j = rand()%(K-1); int tmp = index[i]; index[i] = index[j]; index[j] = tmp; } // read concrete input file char *inname = argv[1]; FILE *infile = fopen(inname, "r"); float cinput[N]; i=0; while(i<N && fscanf(infile, "%f", &cinput[i])>0){ i++; } assert(i>=N); fclose(infile); // read concrete inputs for (i = 0; i < K-S; i++){ w[index[i]]=cinput[index[i]]; } for (i = 0; i<K; i++){ data[i] = cinput[i+K]; } // read symbolic inputs float sinput[K]; klee_make_symbolic(&sinput, sizeof(sinput), "sinput"); for (i = 0 ; i <S ; i++){ w[index[K-1-i]] = sinput[i] / FLT_MAX * 100; } double wsd, wmean; wmean = gsl_stats_wmean(w, 1, data, 1, K); wsd = gsl_stats_wsd_m(w, 1, data, 1, K, wmean); return 0; }
{ "alphanum_fraction": 0.5543568465, "avg_line_length": 16.7361111111, "ext": "c", "hexsha": "9e4455a8202275b9cbb425adaf3fa1e2d56e3685", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_path": "benchmarks/gsl/wsd-m/wsd-m-SYMBOLIC-sample.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_path": "benchmarks/gsl/wsd-m/wsd-m-SYMBOLIC-sample.c", "max_line_length": 56, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_path": "benchmarks/gsl/wsd-m/wsd-m-SYMBOLIC-sample.c", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "num_tokens": 437, "size": 1205 }
/* * BaseMaster.h * * Created on: Aug 7, 2014 * Author: thardin */ #ifndef BASEMASTER_H_ #define BASEMASTER_H_ #include "FMIClient.h" #include <zmq.hpp> #ifdef USE_GPL #include <gsl/gsl_multiroots.h> #include "common/fmigo_storage.h" using namespace fmigo_storage; #endif #include <chrono> namespace fmitcp_master { class BaseMaster { int rendezvous; //t1 = time at which to perform next step std::chrono::high_resolution_clock::time_point t1; #ifdef USE_MPI std::string m_mpi_str; #endif protected: std::vector<FMIClient*> m_clients; std::vector<WeakConnection> m_weakConnections; OutputRefsType clientWeakRefs; InputRefsValuesType initialNonReals; //for loop solver #ifdef USE_GPL class FmigoStorage m_fmigoStorage;//(std::vector<size_t>(0)); #endif public: zmq::socket_t rep_socket; bool initing, paused, running; bool zmqControl; int m_pendingRequests; double t; //current time explicit BaseMaster(zmq::context_t &context, std::vector<FMIClient*> clients, std::vector<WeakConnection> weakConnections); virtual ~BaseMaster() { info("%i rendezvous\n", rendezvous); int messages = 0; for(auto client: m_clients) messages += client->messages; info("%i messages\n", messages); } #ifdef USE_GPL static int loop_residual_f(const gsl_vector *x, void *params, gsl_vector *f); inline FmigoStorage & get_storage(){return m_fmigoStorage;} void storage_alloc(const std::vector<FMIClient*> &clients){ vector<size_t> states({}); vector<size_t> indicators({}); for(auto client: clients) { states.push_back(client->getNumContinuousStates()); indicators.push_back(client->getNumEventIndicators()); } get_storage().allocate_storage(states,indicators); } #endif virtual std::string getFieldNames() const {return "";} virtual void writeFields(bool last, FILE *outfile) {} void solveLoops(); virtual void prepare() {}; virtual void runIteration(double t, double dt) = 0; #define on(name) void name(FMIClient* slave) {} on(onSlaveInstantiated) on(onSlaveInitialized) on(onSlaveTerminated) on(onSlaveFreed) on(onSlaveStepped) on(onSlaveGotVersion) on(onSlaveSetReal) on(onSlaveGotState) on(onSlaveSetState) on(onSlaveFreedState) on(onSlaveDirectionalDerivative) //T is needed because func maybe of a function in Client (from which FMIClient is derived) void queueMessage(std::vector<FMIClient*> fmus, std::string str) { for (auto it = fmus.begin(); it != fmus.end(); it++) { (*it)->queueMessage(str); } } //like queueMessage() but only for one FMU void queueMessage(FMIClient *fmu, std::string str) { fmu->queueMessage(str); } //queueMessage() followed by wait() (blocking) void sendWait(std::vector<FMIClient*> fmus, std::string str) { queueMessage(fmus, str); wait(); } //like sendWait() but only for one FMU (blocking) void sendWait(FMIClient *fmu, std::string str) { queueMessage(fmu, str); wait(); } void wait(); void resetT1(); //wait for t1, advance t1 by timeStep void waitupT1(double timeStep); void handleZmqControl(); void queueValueRequests(); //if cset_set == true then only delete values for FMUs whose ID is in cset void deleteCachedValues(bool cset_set = false, const fmitcp::int_set& cset = fmitcp::int_set()); }; }; #endif /* BASEMASTER_H_ */
{ "alphanum_fraction": 0.6154440154, "avg_line_length": 30.3515625, "ext": "h", "hexsha": "eb1c3878cac74782d368c6ecf7a82c816c73a82a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-20T15:50:01.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-20T15:50:01.000Z", "max_forks_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Tjoppen/fmigo", "max_forks_repo_path": "include/master/BaseMaster.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "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": "Tjoppen/fmigo", "max_issues_repo_path": "include/master/BaseMaster.h", "max_line_length": 131, "max_stars_count": 7, "max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Tjoppen/fmigo", "max_stars_repo_path": "include/master/BaseMaster.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 914, "size": 3885 }
#pragma once #include <gsl/pointers> // contains gsl::not_null class Consultant; class PaymentCalculator { public: double calculate() const { return {}; } void setConsultant(const Consultant &c) { consultant_ = &consultant_; } void setTaxPercentage(double tax) { taxPercentage_ = tax; } private: gsl::not_null<const Consultant *> consultant_; double taxPercentage_; };
{ "alphanum_fraction": 0.7242268041, "avg_line_length": 20.4210526316, "ext": "h", "hexsha": "7a8dc4d5139a41470352459ed09935176eb5376a", "lang": "C", "max_forks_count": 64, "max_forks_repo_forks_event_max_datetime": "2022-03-14T12:32:29.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-01T02:18:55.000Z", "max_forks_repo_head_hexsha": "eb0f7a52ef1253d9b0091714eee9c94c156b02bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbellizio/Software-Architecture-with-Cpp", "max_forks_repo_path": "Chapter02/state/PaymentCalculatorV2.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "eb0f7a52ef1253d9b0091714eee9c94c156b02bc", "max_issues_repo_issues_event_max_datetime": "2022-02-15T12:16:54.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-26T05:48:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbellizio/Software-Architecture-with-Cpp", "max_issues_repo_path": "Chapter02/state/PaymentCalculatorV2.h", "max_line_length": 73, "max_stars_count": 193, "max_stars_repo_head_hexsha": "eb0f7a52ef1253d9b0091714eee9c94c156b02bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbellizio/Software-Architecture-with-Cpp", "max_stars_repo_path": "Chapter02/state/PaymentCalculatorV2.h", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:25:00.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-27T00:46:13.000Z", "num_tokens": 90, "size": 388 }
/* histogram/file.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_block.h> #include <gsl/gsl_histogram.h> int gsl_histogram_fread (FILE * stream, gsl_histogram * h) { int status = gsl_block_raw_fread (stream, h->range, h->n + 1, 1); if (status) return status; status = gsl_block_raw_fread (stream, h->bin, h->n, 1); return status; } int gsl_histogram_fwrite (FILE * stream, const gsl_histogram * h) { int status = gsl_block_raw_fwrite (stream, h->range, h->n + 1, 1); if (status) return status; status = gsl_block_raw_fwrite (stream, h->bin, h->n, 1); return status; } int gsl_histogram_fprintf (FILE * stream, const gsl_histogram * h, const char *range_format, const char *bin_format) { size_t i; const size_t n = h->n; for (i = 0; i < n; i++) { int status = fprintf (stream, range_format, h->range[i]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc (' ', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } status = fprintf (stream, range_format, h->range[i + 1]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc (' ', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } status = fprintf (stream, bin_format, h->bin[i]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc ('\n', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } } return GSL_SUCCESS; } int gsl_histogram_fscanf (FILE * stream, gsl_histogram * h) { size_t i; const size_t n = h->n; double upper; for (i = 0; i < n; i++) { int status = fscanf (stream, "%lg %lg %lg", h->range + i, &upper, h->bin + i); if (status != 3) { GSL_ERROR ("fscanf failed", GSL_EFAILED); } } h->range[n] = upper; return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6348803481, "avg_line_length": 21.546875, "ext": "c", "hexsha": "031d81f4ba5d5cde5dd1b6699f5e04a090fb65de", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/file.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/file.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/histogram/file.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": 803, "size": 2758 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_zgemv (const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY) { #define BASE double #include "source_gemv_c.h" #undef BASE }
{ "alphanum_fraction": 0.7068062827, "avg_line_length": 25.4666666667, "ext": "c", "hexsha": "7f3fb75ac8578125217f8dabb075749940548726", "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/zgemv.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/zgemv.c", "max_line_length": 77, "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/zgemv.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": 115, "size": 382 }
/* * dotProduct.c * * An MPI program that computes the inner product of two vectors * * Written by cetinsamet -*- cetin.samet@metu.edu.tr * April, 2019 * */ #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <cblas.h> int main(int argc, char *argv[]) { int i; int rank, size; double minStart, maxEnd; double dotP, locDotP; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int ORDER = atoi(argv[1]); int locSize = ORDER / size; double* locU; locU = (double*) malloc(locSize * sizeof(double)); double* locV; locV = (double*) malloc(locSize * sizeof(double)); for (i = 0; i < locSize; ++i) { locU[i] = i; locV[i] = i; } double pStart = MPI_Wtime(); // <-- Start Time locDotP = cblas_ddot(locSize, locU, 1, locV, 1); MPI_Reduce(&locDotP, &dotP, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); double pEnd = MPI_Wtime(); // <-- Stop Time MPI_Reduce(&pStart, &minStart, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); MPI_Reduce(&pEnd, &maxEnd, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) printf("Dot product: %f\tVector size: %d\tElapsed time: %f\n", dotP, ORDER, maxEnd - minStart); MPI_Finalize(); return 0; }
{ "alphanum_fraction": 0.6061285501, "avg_line_length": 25.2452830189, "ext": "c", "hexsha": "ab4a042d178005e343c35c34269251b141e036cf", "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": "6de9cc56949fb348a9c40aea7d9be40528e51ddc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cetinsamet/dot-product", "max_forks_repo_path": "dotProduct.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6de9cc56949fb348a9c40aea7d9be40528e51ddc", "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": "cetinsamet/dot-product", "max_issues_repo_path": "dotProduct.c", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "6de9cc56949fb348a9c40aea7d9be40528e51ddc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cetinsamet/dot-product", "max_stars_repo_path": "dotProduct.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 428, "size": 1338 }
#ifndef CTETRA_DOS_H #define CTETRA_DOS_H #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "input.h" #include "ecache.h" #include "tetra.h" #include "submesh.h" #include "fermi.h" double* Tetra_AllDosList(InputFn Efn, int na, int nb, int nc, int num_bands, gsl_matrix *R, double *Es, int num_dos); double* Tetra_DosList(InputFn Efn, int na, int nb, int nc, int num_bands, gsl_matrix *R, double *Es, int num_dos); double* Tetra_DosEnergyDerivList(InputFn Efn, int na, int nb, int nc, int num_bands, gsl_matrix *R, double *Es, int num_dos, double num_electrons, double *fermi, double *dos_fermi, double *dos_deriv_fermi); double Tetra_TotalDos(double E, EnergyCache *Ecache); double Tetra_TotalDosEnergyDeriv(double E, EnergyCache *Ecache); double DosContrib(double E, double E1, double E2, double E3, double E4, double num_tetra); double DosEnergyDerivContrib(double E, double E1, double E2, double E3, double E4, double num_tetra); #endif // CTETRA_DOS_H
{ "alphanum_fraction": 0.7640232108, "avg_line_length": 43.0833333333, "ext": "h", "hexsha": "6e1e7ceacb93251c35bbcf615ead443ff4b38056", "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": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_path": "dos.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_path": "dos.h", "max_line_length": 206, "max_stars_count": null, "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_path": "dos.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 326, "size": 1034 }
/* matrix/gsl_matrix_complex_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_COMPLEX_DOUBLE_H__ #define __GSL_MATRIX_COMPLEX_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_complex_double.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; double * data; gsl_block_complex * block; int owner; } gsl_matrix_complex ; typedef struct { gsl_matrix_complex matrix; } _gsl_matrix_complex_view; typedef _gsl_matrix_complex_view gsl_matrix_complex_view; typedef struct { gsl_matrix_complex matrix; } _gsl_matrix_complex_const_view; typedef const _gsl_matrix_complex_const_view gsl_matrix_complex_const_view; /* Allocation */ GSL_EXPORT gsl_matrix_complex * gsl_matrix_complex_alloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_complex * gsl_matrix_complex_calloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_complex * gsl_matrix_complex_alloc_from_block (gsl_block_complex * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_EXPORT gsl_matrix_complex * gsl_matrix_complex_alloc_from_matrix (gsl_matrix_complex * b, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_EXPORT gsl_vector_complex * gsl_vector_complex_alloc_row_from_matrix (gsl_matrix_complex * m, const size_t i); GSL_EXPORT gsl_vector_complex * gsl_vector_complex_alloc_col_from_matrix (gsl_matrix_complex * m, const size_t j); GSL_EXPORT void gsl_matrix_complex_free (gsl_matrix_complex * m); /* Views */ GSL_EXPORT _gsl_matrix_complex_view gsl_matrix_complex_submatrix (gsl_matrix_complex * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_complex_view gsl_matrix_complex_row (gsl_matrix_complex * m, const size_t i); GSL_EXPORT _gsl_vector_complex_view gsl_matrix_complex_column (gsl_matrix_complex * m, const size_t j); GSL_EXPORT _gsl_vector_complex_view gsl_matrix_complex_diagonal (gsl_matrix_complex * m); GSL_EXPORT _gsl_vector_complex_view gsl_matrix_complex_subdiagonal (gsl_matrix_complex * m, const size_t k); GSL_EXPORT _gsl_vector_complex_view gsl_matrix_complex_superdiagonal (gsl_matrix_complex * m, const size_t k); GSL_EXPORT _gsl_matrix_complex_view gsl_matrix_complex_view_array (double * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_view gsl_matrix_complex_view_array_with_tda (double * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_complex_view gsl_matrix_complex_view_vector (gsl_vector_complex * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_view gsl_matrix_complex_view_vector_with_tda (gsl_vector_complex * v, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_complex_const_view gsl_matrix_complex_const_submatrix (const gsl_matrix_complex * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_complex_const_view gsl_matrix_complex_const_row (const gsl_matrix_complex * m, const size_t i); GSL_EXPORT _gsl_vector_complex_const_view gsl_matrix_complex_const_column (const gsl_matrix_complex * m, const size_t j); GSL_EXPORT _gsl_vector_complex_const_view gsl_matrix_complex_const_diagonal (const gsl_matrix_complex * m); GSL_EXPORT _gsl_vector_complex_const_view gsl_matrix_complex_const_subdiagonal (const gsl_matrix_complex * m, const size_t k); GSL_EXPORT _gsl_vector_complex_const_view gsl_matrix_complex_const_superdiagonal (const gsl_matrix_complex * m, const size_t k); GSL_EXPORT _gsl_matrix_complex_const_view gsl_matrix_complex_const_view_array (const double * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_const_view gsl_matrix_complex_const_view_array_with_tda (const double * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_complex_const_view gsl_matrix_complex_const_view_vector (const gsl_vector_complex * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_complex_const_view gsl_matrix_complex_const_view_vector_with_tda (const gsl_vector_complex * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_EXPORT gsl_complex gsl_matrix_complex_get(const gsl_matrix_complex * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_complex_set(gsl_matrix_complex * m, const size_t i, const size_t j, const gsl_complex x); GSL_EXPORT gsl_complex * gsl_matrix_complex_ptr(gsl_matrix_complex * m, const size_t i, const size_t j); GSL_EXPORT const gsl_complex * gsl_matrix_complex_const_ptr(const gsl_matrix_complex * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_complex_set_zero (gsl_matrix_complex * m); GSL_EXPORT void gsl_matrix_complex_set_identity (gsl_matrix_complex * m); GSL_EXPORT void gsl_matrix_complex_set_all (gsl_matrix_complex * m, gsl_complex x); GSL_EXPORT int gsl_matrix_complex_fread (FILE * stream, gsl_matrix_complex * m) ; GSL_EXPORT int gsl_matrix_complex_fwrite (FILE * stream, const gsl_matrix_complex * m) ; GSL_EXPORT int gsl_matrix_complex_fscanf (FILE * stream, gsl_matrix_complex * m); GSL_EXPORT int gsl_matrix_complex_fprintf (FILE * stream, const gsl_matrix_complex * m, const char * format); GSL_EXPORT int gsl_matrix_complex_memcpy(gsl_matrix_complex * dest, const gsl_matrix_complex * src); GSL_EXPORT int gsl_matrix_complex_swap(gsl_matrix_complex * m1, gsl_matrix_complex * m2); GSL_EXPORT int gsl_matrix_complex_swap_rows(gsl_matrix_complex * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_complex_swap_columns(gsl_matrix_complex * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_complex_swap_rowcol(gsl_matrix_complex * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_complex_transpose (gsl_matrix_complex * m); GSL_EXPORT int gsl_matrix_complex_transpose_memcpy (gsl_matrix_complex * dest, const gsl_matrix_complex * src); GSL_EXPORT int gsl_matrix_complex_isnull (const gsl_matrix_complex * m); GSL_EXPORT int gsl_matrix_complex_add (gsl_matrix_complex * a, const gsl_matrix_complex * b); GSL_EXPORT int gsl_matrix_complex_sub (gsl_matrix_complex * a, const gsl_matrix_complex * b); GSL_EXPORT int gsl_matrix_complex_mul_elements (gsl_matrix_complex * a, const gsl_matrix_complex * b); GSL_EXPORT int gsl_matrix_complex_div_elements (gsl_matrix_complex * a, const gsl_matrix_complex * b); GSL_EXPORT int gsl_matrix_complex_scale (gsl_matrix_complex * a, const gsl_complex x); GSL_EXPORT int gsl_matrix_complex_add_constant (gsl_matrix_complex * a, const gsl_complex x); GSL_EXPORT int gsl_matrix_complex_add_diagonal (gsl_matrix_complex * a, const gsl_complex x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_EXPORT int gsl_matrix_complex_get_row(gsl_vector_complex * v, const gsl_matrix_complex * m, const size_t i); GSL_EXPORT int gsl_matrix_complex_get_col(gsl_vector_complex * v, const gsl_matrix_complex * m, const size_t j); GSL_EXPORT int gsl_matrix_complex_set_row(gsl_matrix_complex * m, const size_t i, const gsl_vector_complex * v); GSL_EXPORT int gsl_matrix_complex_set_col(gsl_matrix_complex * m, const size_t j, const gsl_vector_complex * v); #ifdef HAVE_INLINE extern inline gsl_complex gsl_matrix_complex_get(const gsl_matrix_complex * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK gsl_complex zero = {{0,0}}; if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ; } #endif return *(gsl_complex *)(m->data + 2*(i * m->tda + j)) ; } extern inline void gsl_matrix_complex_set(gsl_matrix_complex * m, const size_t i, const size_t j, const gsl_complex x) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif *(gsl_complex *)(m->data + 2*(i * m->tda + j)) = x ; } extern inline gsl_complex * gsl_matrix_complex_ptr(gsl_matrix_complex * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (gsl_complex *)(m->data + 2*(i * m->tda + j)) ; } extern inline const gsl_complex * gsl_matrix_complex_const_ptr(const gsl_matrix_complex * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const gsl_complex *)(m->data + 2*(i * m->tda + j)) ; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_MATRIX_COMPLEX_DOUBLE_H__ */
{ "alphanum_fraction": 0.6842969493, "avg_line_length": 34.2337278107, "ext": "h", "hexsha": "87dda05a44c420778fb87656055a12dacf8051f7", "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_matrix_complex_double.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_matrix_complex_double.h", "max_line_length": 122, "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_matrix_complex_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2687, "size": 11571 }
/*========================================================== * pca.c - Principal component analysis of diffraction data * * Calculates the two main components of the data * by Principal Component Analysis, as detailed in * Bernhardt et.al (2016), Biophys. J. * * The calling syntax is: * * pca(data, mask, qx, qy, w, phi, m, n) * * Copyright 2017 Institute for X-ray Physics (University of Göttingen) * * 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. * *========================================================*/ #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, int m, int n) { int col; int 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); */ }
{ "alphanum_fraction": 0.5855811672, "avg_line_length": 32.1102362205, "ext": "c", "hexsha": "076743762e3cde9ca4e78a1d35e74b14e3cd1bf3", "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/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/pca.c", "max_line_length": 95, "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/pca.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1113, "size": 4078 }
/* Leaf bindings for the GNU Scientific Library Note that the GSL is GPL, not LGPL!. If you include this code in the libprim build, the result will be covered under the GPL. */ #ifndef _LEAF_GSL_H_ #define _LEAF_GSL_H_ #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_poly.h> #include <leaf/grid.h> /* Direct gsl_ -> grid_ adapters. */ int grid_linalg_SV_decomp(grid *A, grid *V, grid *S, grid *work); int grid_linalg_SV_solve(grid *gU, grid *gV, grid *gS, grid *gb, grid *gx); int grid_blas_dgemv(int transA, double alpha, grid *gA, grid *gx, double beta, grid *gy); int grid_blas_dgemm(int transA, int transB, double alpha, grid *gA, grid *gB, double beta, grid *gC); int grid_unfold(grid *gA, grid *gx, grid *gout); #endif
{ "alphanum_fraction": 0.7188264059, "avg_line_length": 31.4615384615, "ext": "h", "hexsha": "e39ee3779582a7242433990533213a8a3833bdf9", "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": "22df73f8cf2e848559a879ea9139abdc1b5d2239", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "zwizwa/libprim", "max_forks_repo_path": "zl/gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "22df73f8cf2e848559a879ea9139abdc1b5d2239", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "zwizwa/libprim", "max_issues_repo_path": "zl/gsl.h", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "22df73f8cf2e848559a879ea9139abdc1b5d2239", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "zwizwa/libprim", "max_stars_repo_path": "zl/gsl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 264, "size": 818 }
#ifndef __RNG_H__ #define __RNG_H__ #include <gsl/gsl_rng.h> extern const gsl_rng_type *rng_T; extern gsl_rng *rng_R; #endif
{ "alphanum_fraction": 0.792, "avg_line_length": 17.8571428571, "ext": "h", "hexsha": "7cc081bb3622b9a218ea0eca57172adc536d0de3", "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": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ai-ku/scode", "max_forks_repo_path": "rng.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_issues_repo_issues_event_max_datetime": "2015-02-03T17:43:04.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-06T18:20:04.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ai-ku/scode", "max_issues_repo_path": "rng.h", "max_line_length": 33, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ai-ku/scode", "max_stars_repo_path": "rng.h", "max_stars_repo_stars_event_max_datetime": "2016-07-21T18:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T16:46:05.000Z", "num_tokens": 39, "size": 125 }
#include <stdio.h> #include <gsl/gsl_fit.h> int main (void) { int n = 11; double x[11] = {10.0, 8.0, 13.0, 9.0,11.0,14.0,6.0,4.0 ,12.0,7.0,5.0}; double y[11] = { 8.04, 6.95,7.68, 8.81, 8.33,9.96,7.24,4.26,10.84,4.82,5.68 }; double c0, c1, cov00, cov01, cov11, sumsq; gsl_fit_linear (x, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); printf ("best fit: Y = %g + %g X\n", c0, c1); printf ("covariance matrix:\n"); printf ("[ %g, %g\n %g, %g]\n", cov00, cov01, cov01, cov11); printf ("sumsq = %g\n", sumsq); printf ("\n"); return 0; }
{ "alphanum_fraction": 0.4783281734, "avg_line_length": 23.9259259259, "ext": "c", "hexsha": "a8a3dcbff72d2790cd1122987f206ceff1949d63", "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": "587283fd972d0060815dde82a57667e74765c9ae", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marketmodelbrokendown/1", "max_forks_repo_path": "notebook/demo/src/demo_fit.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_issues_repo_issues_event_max_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marketmodelbrokendown/1", "max_issues_repo_path": "notebook/demo/src/demo_fit.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marketmodelbrokendown/1", "max_stars_repo_path": "notebook/demo/src/demo_fit.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 291, "size": 646 }
#include <stdio.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_matrix_double.h> int main() { int ret; gsl_matrix A; double data[9]; int i, j; memset(&A, 0, sizeof(gsl_matrix)); A.size1 = 3; A.size2 = 3; A.tda = 3; A.data = data; gsl_matrix_set(&A, 0, 0, 34.0); gsl_matrix_set(&A, 0, 1, 4.0); gsl_matrix_set(&A, 0, 2, 14.0); gsl_matrix_set(&A, 1, 0, 1.0); gsl_matrix_set(&A, 1, 1, 8.0); gsl_matrix_set(&A, 1, 2, 3.0); gsl_matrix_set(&A, 2, 0, 7.0); gsl_matrix_set(&A, 2, 1, 1.0); gsl_matrix_set(&A, 2, 2, 8.0); for (i=0; i<A.size1; i++) { printf((i==0) ? "A = (" : " ("); for (j=0; j<A.size2; j++) { printf(" %12.5g ", gsl_matrix_get(&A, i, j)); } printf(")\n"); } printf("\n"); ret = gsl_linalg_cholesky_decomp(&A); for (i=0; i<A.size1; i++) { printf((i==0) ? "L = (" : " ("); for (j=0; j<A.size2; j++) { printf(" %12.5g ", (j <= i) ? gsl_matrix_get(&A, i, j) : 0.0); } printf(")\n"); } printf("\n"); return 0; }
{ "alphanum_fraction": 0.5409356725, "avg_line_length": 19.358490566, "ext": "c", "hexsha": "83a281097c3b48101c8b78d4fa880f7da9fb0a64", "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/chol-demo.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/chol-demo.c", "max_line_length": 65, "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/chol-demo.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": 452, "size": 1026 }
#include <pygsl/solver.h> #include <gsl/gsl_multiroots.h> static PyObject * module = NULL; /* accessor methods */ #define _SOLVER_METH(solver, name) \ static PyObject* \ PyGSL_multiroot_ ## solver ## _ ## name(PyGSL_solver *self, PyObject *args) \ { return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multiroot_## solver ## _ ## name); } #define FSOLVER(name) _SOLVER_METH(fsolver, name) #define FDFSOLVER(name) _SOLVER_METH(fdfsolver, name) #define BSOLVER_METH(name) _SOLVER_METH(fsolver, name) _SOLVER_METH(fdfsolver, name) BSOLVER_METH(root) BSOLVER_METH(f) BSOLVER_METH(dx) static PyObject* PyGSL_multiroot_fsolver_test_residual(PyGSL_solver *self, PyObject *args) { int flag; double epsabs; gsl_multiroot_fsolver *s = self->solver; if(!PyArg_ParseTuple(args, "d", &epsabs)) return NULL; flag = gsl_multiroot_test_residual(s->f, epsabs); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multiroot_fdfsolver_test_residual(PyGSL_solver *self, PyObject *args) { int flag; double epsabs; gsl_multiroot_fdfsolver *s = self->solver; if(!PyArg_ParseTuple(args, "d", &epsabs)) return NULL; flag = gsl_multiroot_test_residual(s->f, epsabs); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multiroot_fsolver_test_delta(PyGSL_solver *self, PyObject *args) { int flag; double epsabs, epsrel; gsl_multiroot_fsolver *s = self->solver; if(!PyArg_ParseTuple(args, "dd", &epsabs, &epsrel)) return NULL; flag = gsl_multiroot_test_delta(s->dx, s->x, epsabs, epsrel); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multiroot_fdfsolver_test_delta(PyGSL_solver *self, PyObject *args) { int flag; double epsabs, epsrel; gsl_multiroot_fdfsolver *s = self->solver; if(!PyArg_ParseTuple(args, "dd", &epsabs, &epsrel)) return NULL; flag = gsl_multiroot_test_delta(s->dx, s->x, epsabs, epsrel); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } int PyGSL_multiroot_function_wrap(const gsl_vector *x, void *params, gsl_vector *f) { int flag; PyGSL_solver *p = (PyGSL_solver *) params; FUNC_MESS_BEGIN(); if(PyGSL_DEBUG_LEVEL() > 2){ gsl_vector_fprintf(stderr, x, "x = %d"); } flag = PyGSL_function_wrap_Op_On(x, f, p->cbs[0], p->args, x->size, x->size, __FUNCTION__); FUNC_MESS_END(); return flag; } int PyGSL_multiroot_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *J) { int flag; PyGSL_solver *p = (PyGSL_solver *) params; FUNC_MESS_BEGIN(); flag = PyGSL_function_wrap_Op_Opn(x, J, p->cbs[1], p->args, x->size, x->size, __FUNCTION__); FUNC_MESS_END(); return flag; } int PyGSL_multiroot_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) { int flag; PyGSL_solver *p = (PyGSL_solver *) params; FUNC_MESS_BEGIN(); flag = PyGSL_function_wrap_Op_On_Opn(x, f, J, p->cbs[2], p->args, x->size, x->size, __FUNCTION__); FUNC_MESS_END(); return flag; } PyObject * PyGSL_multiroot_fsolver_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) { gsl_multiroot_function * c_sys; struct pygsl_solver_n_set info = {0, NULL, (set_m_t) gsl_multiroot_fsolver_set}; PyObject * tmp; FUNC_MESS_BEGIN(); if(self->c_sys == NULL){ if((c_sys = calloc(1, sizeof(gsl_multiroot_function))) == NULL){ PyGSL_ERROR_NULL("Could not allocate the memory for the c_sys", GSL_ENOMEM); } c_sys->n =self->problem_dimensions[0]; c_sys->f =PyGSL_multiroot_function_wrap; c_sys->params=(void*)self; info.c_sys = c_sys; }else{ info.c_sys = self->c_sys; } tmp = PyGSL_solver_n_set(self, pyargs, kw, &info); FUNC_MESS_END(); return tmp; } PyObject * PyGSL_multiroot_fdfsolver_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) { gsl_multiroot_function_fdf * c_sys; struct pygsl_solver_n_set info = {1, NULL, (set_m_t)gsl_multiroot_fdfsolver_set}; PyObject * tmp; FUNC_MESS_BEGIN(); if(self->c_sys == NULL){ if((c_sys = calloc(1, sizeof(gsl_multiroot_function_fdf))) == NULL){ PyGSL_ERROR_NULL("Could not allocate the memory for the c_sys", GSL_ENOMEM); } c_sys->n=self->problem_dimensions[0]; c_sys->f = PyGSL_multiroot_function_wrap; c_sys->df = PyGSL_multiroot_function_wrap_df; c_sys->fdf = PyGSL_multiroot_function_wrap_fdf; c_sys->params=(void*)self; info.c_sys = c_sys; }else{ info.c_sys = self->c_sys; } tmp = PyGSL_solver_n_set(self, pyargs, kw, &info); FUNC_MESS_END(); return tmp; } static PyMethodDef PyGSL_multiroot_fmethods[] = { {"dx", (PyCFunction)PyGSL_multiroot_fsolver_dx, METH_NOARGS, NULL}, {"f", (PyCFunction)PyGSL_multiroot_fsolver_f, METH_NOARGS, NULL}, {"root", (PyCFunction)PyGSL_multiroot_fsolver_root, METH_NOARGS, NULL}, {"set", (PyCFunction)PyGSL_multiroot_fsolver_set, METH_VARARGS|METH_KEYWORDS, NULL}, {"test_delta", (PyCFunction)PyGSL_multiroot_fsolver_test_delta, METH_VARARGS, NULL}, {"test_residual", (PyCFunction)PyGSL_multiroot_fsolver_test_residual, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static PyMethodDef PyGSL_multiroot_fdfmethods[] = { {"dx", (PyCFunction)PyGSL_multiroot_fdfsolver_dx, METH_NOARGS, NULL}, {"f", (PyCFunction)PyGSL_multiroot_fdfsolver_f, METH_NOARGS, NULL}, {"root", (PyCFunction)PyGSL_multiroot_fdfsolver_root, METH_NOARGS, NULL}, {"set", (PyCFunction)PyGSL_multiroot_fdfsolver_set, METH_VARARGS|METH_KEYWORDS, NULL}, {"test_delta", (PyCFunction)PyGSL_multiroot_fdfsolver_test_delta, METH_VARARGS, NULL}, {"test_residual", (PyCFunction)PyGSL_multiroot_fdfsolver_test_residual, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static const char multiroot_f_type_name[] = "F-MultiRootSolver"; static const char multiroot_fdf_type_name[] = "FdF-MultiRootSolver"; const struct _SolverStatic multiroot_solver_f = {{(void_m_t) gsl_multiroot_fsolver_free, /* gsl_multiroot_fsolver_restart */ (void_m_t) NULL, (name_m_t) gsl_multiroot_fsolver_name, (int_m_t) gsl_multiroot_fsolver_iterate}, 1, PyGSL_multiroot_fmethods, multiroot_f_type_name}, multiroot_solver_fdf = {{(void_m_t) gsl_multiroot_fdfsolver_free, /* gsl_multiroot_fdfsolver_restart (void_m_t) */ NULL, (name_m_t) gsl_multiroot_fdfsolver_name, (int_m_t) gsl_multiroot_fdfsolver_iterate}, 3, PyGSL_multiroot_fdfmethods, multiroot_fdf_type_name}; static PyObject* PyGSL_multiroot_f_init(PyObject *self, PyObject *args, const gsl_multiroot_fsolver_type * type) { PyObject *tmp=NULL; solver_alloc_struct s = {type, (void_an_t) gsl_multiroot_fsolver_alloc, &multiroot_solver_f}; FUNC_MESS_BEGIN(); tmp = PyGSL_solver_dn_init(self, args, &s, 1); FUNC_MESS_END(); return tmp; } static PyObject* PyGSL_multiroot_fdf_init(PyObject *self, PyObject *args, const gsl_multiroot_fdfsolver_type * type) { PyObject *tmp=NULL; solver_alloc_struct s = {type, (void_an_t) gsl_multiroot_fdfsolver_alloc, &multiroot_solver_fdf}; FUNC_MESS_BEGIN(); tmp = PyGSL_solver_dn_init(self, args, &s, 1); FUNC_MESS_END(); return tmp; } #define AMROOTS_F(name) \ static PyObject* PyGSL_multiroot_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ FUNC_MESS_BEGIN(); \ tmp = PyGSL_multiroot_f_init(self, args, gsl_multiroot_fsolver_ ## name); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } #define AMROOTS_FDF(name) \ static PyObject* PyGSL_multiroot_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ FUNC_MESS_BEGIN(); \ tmp = PyGSL_multiroot_fdf_init(self, args, gsl_multiroot_fdfsolver_ ## name); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } AMROOTS_F(dnewton) AMROOTS_F(broyden) AMROOTS_F(hybrid) AMROOTS_F(hybrids) AMROOTS_FDF(newton) AMROOTS_FDF(gnewton) AMROOTS_FDF(hybridj) AMROOTS_FDF(hybridsj) static PyObject * PyGSL_multiroot_test_delta(PyObject * self, PyObject * args) { return PyGSL_solver_vvdd_i(self, args, gsl_multiroot_test_delta); } static PyObject * PyGSL_multiroot_test_residual(PyObject * self, PyObject * args) { return PyGSL_solver_vd_i(self, args, gsl_multiroot_test_residual); } static PyMethodDef mMethods[] = { /* solvers */ {"dnewton" , PyGSL_multiroot_init_dnewton, METH_VARARGS, NULL}, {"broyden" , PyGSL_multiroot_init_broyden, METH_VARARGS, NULL}, {"hybrid" , PyGSL_multiroot_init_hybrid , METH_VARARGS, NULL}, {"hybrids" , PyGSL_multiroot_init_hybrids, METH_VARARGS, NULL}, {"newton" , PyGSL_multiroot_init_newton , METH_VARARGS, NULL}, {"gnewton" , PyGSL_multiroot_init_gnewton, METH_VARARGS, NULL}, {"hybridj" , PyGSL_multiroot_init_hybridj, METH_VARARGS, NULL}, {"hybridsj", PyGSL_multiroot_init_hybridsj, METH_VARARGS, NULL}, /* mutliroot funcs */ {"test_delta", PyGSL_multiroot_test_delta, METH_VARARGS, NULL}, {"test_residual", PyGSL_multiroot_test_residual, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static const char PyGSL_multiroot_module_doc[] = "XXX Missing\n"; void initmultiroot(void) { PyObject* m, *dict, *item; FUNC_MESS_BEGIN(); m=Py_InitModule("multiroot", mMethods); module = m; assert(m); init_pygsl() import_pygsl_solver(); assert(PyGSL_API); dict = PyModule_GetDict(m); if(!dict) goto fail; if (!(item = PyString_FromString((char*)PyGSL_multiroot_module_doc))){ PyErr_SetString(PyExc_ImportError, "I could not generate module doc string!"); goto fail; } if (PyDict_SetItemString(dict, "__doc__", item) != 0){ PyErr_SetString(PyExc_ImportError, "I could not init doc string!"); goto fail; } FUNC_MESS_END(); fail: FUNC_MESS("FAIL"); return; }
{ "alphanum_fraction": 0.6299876956, "avg_line_length": 34.5835866261, "ext": "c", "hexsha": "8c15b317ff89f8515537b155f8c893315144513b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multiroot.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multiroot.c", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multiroot.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3125, "size": 11378 }
#ifndef ARRUS_CORE_COMMON_COLLECTIONS_H #define ARRUS_CORE_COMMON_COLLECTIONS_H #include <string> #include <vector> #include <numeric> #include <unordered_set> #include <type_traits> #include <bitset> #include <stdexcept> #include <gsl/span> #include <boost/range/combine.hpp> namespace arrus { /** * Returns an array of range [start, end). */ template<typename T> inline std::vector<T> getRange(T start, T end, T step = 1) { std::vector<T> values; for(T i = start; i < end; i += step) { values.push_back(i); } return values; } template<typename Out, typename In> inline std::vector<Out> castTo(std::vector<In> values) { std::vector<Out> result(values.size()); std::transform( std::begin(values), std::end(values), std::begin(result), [](In &value) { return Out(value); } ); return result; } template<typename Out, typename Iterator> inline std::vector<Out> castTo(const Iterator begin, const Iterator end) { std::vector<Out> result; std::transform(begin, end, std::back_inserter(result), [](auto &value) { return Out(value); }); return result; } /** * Returns an array that holds given value n times. */ template<typename T> inline std::vector<T> getNTimes(const T value, size_t n) { std::vector<T> values; for(size_t i = 0; i < n; ++i) { values.push_back(value); } return values; } template<typename T> inline size_t countUnique(const std::vector<T> &values) { return std::unordered_set<T>(std::begin(values), std::end(values)).size(); } template<typename T> inline bool setContains(const std::unordered_set<T> &set, const T &value) { return set.find(value) != set.end(); } template<typename T, typename U> inline std::vector<std::pair<T, U>> zip(const std::vector<T> &a, const std::vector<U> &b) { if(a.size() != b.size()) { throw std::runtime_error("Zipped vectors should have the same size."); } std::vector<std::pair<T, U>> res; res.reserve(a.size()); for(const auto &[x, y] : boost::combine(a, b)) { res.emplace_back(x, y); } return res; } template<typename R> inline std::vector<R> generate(size_t nElements, std::function<R(size_t)> transformation) { std::vector<R> result; result.reserve(nElements); for(size_t i = 0; i < nElements; ++i) { result.emplace_back(transformation(i)); } return result; } template<typename T> inline std::vector<T> concat(const std::vector<T> &a, const std::vector<T> &b) { std::vector<T> result; result.reserve(a.size() + b.size()); result.insert(std::begin(result), std::begin(a), std::end(a)); result.insert(std::end(result), std::begin(b), std::end(b)); return result; } template<typename T> inline std::vector<T> concat(const std::vector<std::vector<T>> &a) { std::vector<T> result; size_t totalSize = 0; for(const auto &v : a) { totalSize += v.size(); } result.reserve(totalSize); for(const auto &vec : a) { result.insert(std::end(result), std::begin(vec), std::end(vec)); } return result; } template<typename T> inline std::vector<T> permute(const std::vector<T> &input, const std::vector<unsigned short> &perm) { std::vector<T> output(perm.size()); for(size_t i = 0; i < static_cast<size_t>(perm.size()); ++i) { output[perm[i]] = input[i]; } return output; } template<int size> inline std::bitset<size> toBitset(const std::vector<bool> &in) { std::bitset<size> result; for(size_t i = 0; i < size; ++i) { result[i] = in[i]; } return result; } template<typename Map, typename K> inline bool containsKey(Map map, const K &key) { return map.find(key) != std::end(map); } template<typename T> inline void setValuesInRange(std::vector<T> &container, size_t start, size_t end, const T &value) { for(size_t i = start; i < end; ++i) { container[i] = value; } } template<size_t N> inline void setValuesInRange(std::bitset<N> &container, size_t start, size_t end, const bool &value) { for(size_t i = start; i < end; ++i) { container[i] = value; } } template<typename T> inline void setValuesInRange(std::vector<T> &container, size_t start, size_t end, const std::function<T(size_t)> &generator) { for(size_t i = start; i < end; ++i) { container[i] = generator(i); } } template<typename T> inline void setValuesInRange(std::vector<T> &container, size_t start, size_t end, const std::vector<T>& source) { if(source.size != end-start) { throw std::runtime_error("Source vector should have exactly " + std::to_string(end-start) + " elements " "when assigning it to the selected range."); } for(size_t i = start; i < end; ++i) { container[i] = source[i-start]; } } template<class InputIt, class T, class BinaryOp> inline T reduce(InputIt first, InputIt last, T init, BinaryOp binaryOp) { T result = init; for(auto it = first; it != last; ++it) { result = binaryOp(result, *it); } return result; } } #endif //ARRUS_CORE_COMMON_COLLECTIONS_H
{ "alphanum_fraction": 0.6236620795, "avg_line_length": 26.9690721649, "ext": "h", "hexsha": "186a92777ad45a8b11d6b50e693a7b84a6ef030e", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": [ "BSL-1.0", "MIT" ], "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_path": "arrus/core/common/collections.h", "max_issues_count": 60, "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_licenses": [ "BSL-1.0", "MIT" ], "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_path": "arrus/core/common/collections.h", "max_line_length": 102, "max_stars_count": 11, "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": [ "BSL-1.0", "MIT" ], "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_path": "arrus/core/common/collections.h", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "num_tokens": 1365, "size": 5232 }
#include <math.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_siman.h> /* set up parameters for this simulated annealing run */ /* how many points do we try before stepping */ #define N_TRIES 200 /* how many iterations for each T? */ #define ITERS_FIXED_T 1000 /* max step size in random walk */ #define STEP_SIZE 1.0 /* Boltzmann constant */ #define K 1.0 /* initial temperature */ #define T_INITIAL 0.008 /* damping factor for temperature */ #define MU_T 1.003 #define T_MIN 2.0e-6 gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; /* now some functions to test in one dimension */ double E1(void *xp) { double x = * ((double *) xp); return exp(-pow((x-1.0),2.0))*sin(8*x); } double M1(void *xp, void *yp) { double x = *((double *) xp); double y = *((double *) yp); return fabs(x - y); } void S1(const gsl_rng * r, void *xp, double step_size) { double old_x = *((double *) xp); double new_x; double u = gsl_rng_uniform(r); new_x = u * 2 * step_size - step_size + old_x; memcpy(xp, &new_x, sizeof(new_x)); } void P1(void *xp) { printf ("%12g", *((double *) xp)); } int main(int argc, char *argv[]) { const gsl_rng_type * T; gsl_rng * r; double x_initial = 15.5; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_siman_solve(r, &x_initial, E1, S1, M1, P1, NULL, NULL, NULL, sizeof(double), params); gsl_rng_free (r); return 0; }
{ "alphanum_fraction": 0.6049461002, "avg_line_length": 19, "ext": "c", "hexsha": "50f08e06ef9fb8bb1349822c3132d9c2093e5d1f", "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/siman.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/siman.c", "max_line_length": 56, "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/siman.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": 463, "size": 1577 }
/* * \file base.h * \brief Header file with base requirements for codes * * */ #ifndef BASE_H #define BASE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <getopt.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <bzlib.h> #include <hdf5.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #define NAME_LENGTH 256 #define LONG_LENGTH 3000 #endif /* BASE_H */
{ "alphanum_fraction": 0.6810344828, "avg_line_length": 14.9677419355, "ext": "h", "hexsha": "b8a96b9407f886b2853618dd43380efb2a3d629d", "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": "e19b8ec8996eaa801ae462528db03e8d04532fc8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rcanasv/astrolibc", "max_forks_repo_path": "src/base.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e19b8ec8996eaa801ae462528db03e8d04532fc8", "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": "rcanasv/astrolibc", "max_issues_repo_path": "src/base.h", "max_line_length": 54, "max_stars_count": null, "max_stars_repo_head_hexsha": "e19b8ec8996eaa801ae462528db03e8d04532fc8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rcanasv/astrolibc", "max_stars_repo_path": "src/base.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 130, "size": 464 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #else #include "CustomSolver.h" #endif #include "ValueGrad.h" #include "BooleanNodes.h" #include "BooleanDAG.h" #include "NodeVisitor.h" #include "VarStore.h" #include <map> #include <set> #include "SymbolicEvaluator.h" #include "Interface.h" #include <iostream> using namespace std; class BoolAutoDiff: public NodeVisitor, public SymbolicEvaluator { BooleanDAG& bdag; map<string, int>& floatCtrls; // Maps float ctrl names to indices within grad vector int nctrls; // number of float ctrls gsl_vector* ctrls; // ctrl values vector<ValueGrad*> values; // Keeps track of values along with gradients for each node vector<DistanceGrad*> distances; // Keeps track of distance metric for boolean nodes Interface* inputValues; public: int DEFAULT_INP = -32; BoolAutoDiff(BooleanDAG& bdag_p, map<string, int>& floatCtrls_p); ~BoolAutoDiff(void); virtual void visit( SRC_node& node ); virtual void visit( DST_node& node ); virtual void visit( CTRL_node& node ); virtual void visit( PLUS_node& node ); virtual void visit( TIMES_node& node ); virtual void visit( ARRACC_node& node ); virtual void visit( DIV_node& node ); virtual void visit( MOD_node& node ); virtual void visit( NEG_node& node ); virtual void visit( CONST_node& node ); virtual void visit( LT_node& node ); virtual void visit( EQ_node& node ); virtual void visit( AND_node& node ); virtual void visit( OR_node& node ); virtual void visit( NOT_node& node ); virtual void visit( ARRASS_node& node ); virtual void visit( UFUN_node& node ); virtual void visit( TUPLE_R_node& node ); virtual void visit( ASSERT_node& node ); virtual void setInputs(Interface* inputValues_p); virtual void run(const gsl_vector* ctrls_p, const set<int>& nodesSubset); virtual void run(const gsl_vector* ctrls_p); virtual double getErrorOnConstraint(int nodeid, gsl_vector* grad); double getSqrtError(bool_node* node, gsl_vector* grad); double getAssertError(bool_node* node, gsl_vector* grad); double getBoolCtrlError(bool_node* node, gsl_vector* grad); double getBoolExprError(bool_node* node, gsl_vector* grad); virtual double getErrorOnConstraint(int nodeid); double getSqrtError(bool_node* node); double getAssertError(bool_node* node); double getBoolCtrlError(bool_node* node); double getBoolExprError(bool_node* node); virtual double getErrorForAsserts(const set<int>& assertIds, gsl_vector* grad); virtual double getErrorForAssert(int assertId, gsl_vector* grad); double computeSingleError(int nodeid, double errorSoFar, const gsl_vector* errorGradSoFar, gsl_vector* grad); void setvalue(bool_node& bn, ValueGrad* v) { values[bn.id] = v; } ValueGrad* v(bool_node& bn) { ValueGrad* val = values[bn.id]; if (val == NULL) { gsl_vector* g = gsl_vector_alloc(nctrls); val = new ValueGrad(0, g); setvalue(bn, val); } return val; } ValueGrad* v(bool_node* bn) { return v(*bn); } void setdistance(bool_node& bn, DistanceGrad* d) { distances[bn.id] = d; } DistanceGrad* d(bool_node& bn) { DistanceGrad* dist = distances[bn.id]; if (dist == NULL) { gsl_vector* g = gsl_vector_alloc(nctrls); dist = new DistanceGrad(0, g); setdistance(bn, dist); } return dist; } DistanceGrad* d(bool_node* bn) { return d(*bn); } virtual double dist(int nid) { DistanceGrad* dg = d(bdag[nid]); return dg->dist; } virtual double dist(int nid, gsl_vector* grad) { DistanceGrad* dg = d(bdag[nid]); gsl_vector_memcpy(grad, dg->grad); return dg->dist; } virtual void print() { /*for (int i = 0; i < bdag.size(); i++) { if (bdag[i]->type == bool_node::ASSERT) { DistanceGrad* dist = d(bdag[i]->mother); if (dist->set) { double gmag = gsl_blas_dnrm2(dist->grad); if (dist->dist < 0.1) { cout << bdag[i]->mother->lprint() << endl; cout << dist->printFull() << endl; } } } } return;*/ for (int i = 0; i < bdag.size(); i++) { cout << bdag[i]->lprint() << " "; if (bdag[i]->getOtype() == OutType::FLOAT) { if (v(bdag[i])->set) { cout << v(bdag[i])->print() << endl; } else { cout << "UNSET" << endl; } } else { if (d(bdag[i])->set) { cout << d(bdag[i])->print() << endl; } else { cout << "UNSET" << endl; } } } } virtual void printFull() { for (int i = 0; i < bdag.size(); i++) { cout << bdag[i]->lprint() << endl; if (bdag[i]->getOtype() == OutType::FLOAT) { if (v(bdag[i])->set) { cout << v(bdag[i])->printFull() << endl; } else { cout << "UNSET" <<endl; } } else { if(d(bdag[i])->set) { cout << d(bdag[i])->printFull() << endl; } else { cout << "UNSET" << endl; } } if (bdag[i]->type == bool_node::PLUS) { cout << v(bdag[i]->mother())->getVal() << " + " << v(bdag[i]->father())->getVal() << endl; } } } bool isFloat(bool_node& bn) { return (bn.getOtype() == OutType::FLOAT); } bool isFloat(bool_node* bn) { return (bn->getOtype() == OutType::FLOAT); } int getInputValue(bool_node& bn) { if (inputValues->hasValue(bn.id)) { int val = inputValues->getValue(bn.id); return val; } else { return DEFAULT_INP; } } int getInputValue(bool_node* bn) { return getInputValue(*bn); } };
{ "alphanum_fraction": 0.6434814953, "avg_line_length": 25.9758454106, "ext": "h", "hexsha": "a7e20d44f25996e815c100f7260a4d06e9ab3b58", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/BoolAutoDiff.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/BoolAutoDiff.h", "max_line_length": 113, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/BoolAutoDiff.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 1569, "size": 5377 }
/* specfunc/gsl_sf_result.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #ifndef __GSL_SF_RESULT_H__ #define __GSL_SF_RESULT_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 struct gsl_sf_result_struct { double val; double err; }; typedef struct gsl_sf_result_struct gsl_sf_result; #define GSL_SF_RESULT_SET(r,v,e) do { (r)->val=(v); (r)->err=(e); } while(0) struct gsl_sf_result_e10_struct { double val; double err; int e10; }; typedef struct gsl_sf_result_e10_struct gsl_sf_result_e10; GSL_EXPORT int gsl_sf_result_smash_e(const gsl_sf_result_e10 * re, gsl_sf_result * r); __END_DECLS #endif /* __GSL_SF_RESULT_H__ */
{ "alphanum_fraction": 0.7438118812, "avg_line_length": 26.064516129, "ext": "h", "hexsha": "305b75ad5bfdf170011362245e0781e7f6e43c8d", "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_sf_result.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_sf_result.h", "max_line_length": 86, "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_sf_result.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 425, "size": 1616 }
#pragma once #include <gsl/span.h> #include <msgpack.hpp> #include <type_traits> #include <typeindex> #include <unordered_map> #include <cstddef> // somehow needed for size_t? namespace meta { using packer = msgpack::packer<std::ostream>; using unpacker = msgpack::unpacker; struct Attribute { std::type_index typeindex; const void *data; }; struct Field { const char *name; const char *qualName; std::type_index typeindex; std::size_t offset; void *(*getPtr)(void *object); gsl::span<const Attribute> attributes; template <typename T> T *getAs(void *object) const { return reinterpret_cast<T *>(getPtr(object)); } template <typename T> const T *getAttribute() const { for (auto&& a : attributes) { if (a.typeindex == std::type_index{ typeid(T) }) { return static_cast<const T*>(a.data); } } return nullptr; } }; struct Enumerator { const char *name; uint64_t value; gsl::span<const Attribute> attributes; template <typename T> const T *getAttribute() const { for (auto&& a : attributes) { if (a.typeindex == std::type_index{ typeid(T) }) { return static_cast<const T*>(a.data); } } return nullptr; } }; enum class TypeKind { Enum, Struct, Union }; struct Enum; struct Record; struct Type { const char *name; TypeKind kind; gsl::span<const Attribute> attributes; void (*serialize)(packer &, const void *); void (*deserialize)(unpacker &, void *); template <typename T> const T *as() const { if (kind == T::t_kind) return static_cast<const T *>(this); return nullptr; } }; struct Record : public Type { static constexpr TypeKind t_kind = TypeKind::Struct; Record(const char *name, gsl::span<const Field> public_fields_, gsl::span<const std::type_index> bases_, gsl::span<const Attribute> attributes_, void (*serialize_)(packer &, const void *), void (*deserialize_)(unpacker &, void *)) : Type{name, t_kind, attributes_, serialize_, deserialize_}, publicFields{public_fields_}, bases{bases_} {} gsl::span<const Field> publicFields; gsl::span<const std::type_index> bases; }; struct Enum : public Type { static constexpr TypeKind t_kind = TypeKind::Enum; Enum(const char *name, gsl::span<const Enumerator> enumerators_, uint64_t (*getValue_)(const void *e), void (*setValue_)(void *, uint64_t), gsl::span<const Attribute> attributes_, void (*serialize_)(packer &, const void *), void (*deserialize_)(unpacker &, void *)) : Type{name, t_kind, attributes_, serialize_, deserialize_}, enumerators{enumerators_}, getValue{getValue_}, setValue{setValue_} {} gsl::span<const Enumerator> enumerators; int findEnumeratorIndex(const void *obj) const { auto v = getValue(obj); for (int i = 0; i < enumerators.size(); ++i) { if (enumerators[i].value == v) return i; } return -1; } const Enumerator *findEnumerator(const void *obj) const { int i = findEnumeratorIndex(obj); if (i < 0) return nullptr; return &enumerators[i]; } // manipulation functions uint64_t (*getValue)(const void *obj); void (*setValue)(void *obj, uint64_t value); }; template <typename T> const Type *typeOf(); const Type *typeOf(std::type_index ti); template <typename T> void serialize(packer& p, const T& data) { serialize(p, typeOf<T>(), &data); } template <typename T> void serialize_dynamic(packer& p, const T& data) { // always use the dynamic type serialize(p, typeOf(typeid(data)), &data); } inline void serialize(packer& p, const Type* ty, const void* data) { if (!ty) return; ty->serialize(p, data); } // enum value-to-string and string-to-value template <typename T, typename = std::enable_if_t<std::is_enum<T>::value>> const char *getEnumeratorName(T constant); template <typename T, typename = std::enable_if_t<std::is_enum<T>::value>> T getEnumeratorValue(const char *name); }
{ "alphanum_fraction": 0.6628256513, "avg_line_length": 26.7919463087, "ext": "h", "hexsha": "3f24416f84cf6b717ea0c456a31bd8f8524ab916", "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": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ennis/autograph-pipelines", "max_forks_repo_path": "src/Editor/Meta.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "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": "ennis/autograph-pipelines", "max_issues_repo_path": "src/Editor/Meta.h", "max_line_length": 74, "max_stars_count": 1, "max_stars_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ennis/autograph-pipelines", "max_stars_repo_path": "src/Editor/Meta.h", "max_stars_repo_stars_event_max_datetime": "2021-04-24T12:29:42.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-24T12:29:42.000Z", "num_tokens": 1016, "size": 3992 }
// align.h // // prototypes for align.cc // // dw, 12/12/3 #include <gsl/gsl_matrix.h> #include "pdb.h" #include <map> // find rigid body transformation z=Rx+t minimizing // least squares error ||y-z||**2 // find rigid body transformation z=Rx+t minimizing // least squares error ||y-z||**2 void align(gsl_matrix_const_view , gsl_matrix_const_view, gsl_matrix *, gsl_vector *, double *); double align(vector<atom>&, vector<atom>&, map<int, int>&, int, vector<atom>&, vector<atom>&, map<int, int>&, int);
{ "alphanum_fraction": 0.6776699029, "avg_line_length": 24.5238095238, "ext": "h", "hexsha": "67f809f264cc93e146ab0cedabf6bc7d107e5701", "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": "a30e907e83fa5bbfb934d951b7c663b622104fcc", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "tecdatalab/biostructure", "max_forks_repo_path": "db/Updater/generators/LZerD/stats/align.h", "max_issues_count": 15, "max_issues_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "max_issues_repo_issues_event_max_datetime": "2022-02-27T05:23:59.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-17T16:13:39.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "tecdatalab/legacy", "max_issues_repo_path": "core/LZerD/stats/align.h", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "tecdatalab/legacy", "max_stars_repo_path": "core/LZerD/stats/align.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 144, "size": 515 }
/* Copyright (c) 2015, Patrick Weltevrede All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_sort_float.h> #include <gsl/gsl_statistics_float.h> #include <gsl/gsl_integration.h> #include "psrsalsa.h" int filterPApoints(datafile_definition *datafile, verbose_definition verbose) { int dPa_polnr; long i, j, nrpoints; float *olddata; if(datafile->poltype != POLTYPE_ILVPAdPA && datafile->poltype != POLTYPE_PAdPA && datafile->poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR filterPApoints: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl."); return 0; } if(datafile->poltype == POLTYPE_ILVPAdPA && datafile->NrPols != 5) { printerror(verbose.debug, "ERROR filterPApoints: 5 polarization channels were expected, but there are only %ld.", datafile->NrPols); return 0; }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl && datafile->NrPols != 8) { printerror(verbose.debug, "ERROR filterPApoints: 8 polarization channels were expected, but there are only %ld.", datafile->NrPols); return 0; }else if(datafile->poltype == POLTYPE_PAdPA && datafile->NrPols != 2) { printerror(verbose.debug, "ERROR filterPApoints: 2 polarization channels were expected, but there are only %ld.", datafile->NrPols); return 0; } if(datafile->NrSubints > 1 || datafile->NrFreqChan > 1) { printerror(verbose.debug, "ERROR filterPApoints: Can only do this opperation if there is one subint and one frequency channel."); return 0; } if(datafile->tsampMode != TSAMPMODE_LONGITUDELIST) { printerror(verbose.debug, "ERROR filterPApoints: Expected pulse longitudes to be defined."); return 0; } if(datafile->poltype == POLTYPE_ILVPAdPA || datafile->poltype == POLTYPE_ILVPAdPATEldEl) { dPa_polnr = 4; }else if(datafile->poltype == POLTYPE_PAdPA) { dPa_polnr = 1; } nrpoints = 0; for(i = 0; i < datafile->NrBins; i++) { if(datafile->data[i+dPa_polnr*datafile->NrBins] > 0) { nrpoints++; } } if(verbose.verbose) printf("Keeping %ld significant PA points\n", nrpoints); olddata = datafile->data; datafile->data = (float *)malloc(nrpoints*datafile->NrPols*sizeof(float)); if(datafile->data == NULL) { printerror(verbose.debug, "ERROR filterPApoints: Memory allocation error."); return 0; } j = 0; for(i = 0; i < datafile->NrBins; i++) { if(olddata[i+dPa_polnr*datafile->NrBins] > 0) { if(datafile->poltype == POLTYPE_ILVPAdPA) { datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins]; datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins]; datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins]; datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins]; datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins]; }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl) { datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins]; datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins]; datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins]; datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins]; datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins]; datafile->data[j+5*nrpoints] = olddata[i+5*datafile->NrBins]; datafile->data[j+6*nrpoints] = olddata[i+6*datafile->NrBins]; datafile->data[j+7*nrpoints] = olddata[i+7*datafile->NrBins]; }else { datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins]; datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins]; } datafile->tsamp_list[j] = datafile->tsamp_list[i]; j++; } } free(olddata); datafile->NrBins = nrpoints; return datafile->NrBins; } int make_paswing_fromIQUV(datafile_definition *datafile, int extended, pulselongitude_regions_definition onpulse, int normalize, int correctLbias, float correctQV, float correctV, int nolongitudes, float loffset, float paoffset, datafile_definition *rms_file, float rebin_factor, verbose_definition verbose) { int indent, rms_file_specified; long i, j, NrOffpulseBins, pulsenr, freqnr, output_nr_pols; float ymax, baseline_intensity, RMSQ, RMSU, *Loffpulse, *Poffpulse, medianL, medianP, *newdata, *newdata_rms; rms_file_specified = 1; if(rms_file == NULL) { rms_file = datafile; rms_file_specified = 0; } if(verbose.verbose) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); printf("Constructing PA and degree of linear polarization"); if(extended) printf(", total polarization and ellipticity"); if(rms_file_specified) printf(" (using a seperate file to determine the off-pulse rms)"); printf("\n"); for(indent = 0; indent < verbose.indent; indent++) printf(" "); printf(" Reference frequency for PA is "); if(datafile->isDeFarad) { if((datafile->freq_ref > -1.1 && datafile->freq_ref < -0.9) || (datafile->freq_ref > 0.99e10 && datafile->freq_ref < 1.01e10)) printf("infinity\n"); else if(datafile->freq_ref < 0) printf("unknown\n"); else printf("%f MHz\n", datafile->freq_ref); }else { if(datafile->NrFreqChan == 1) printf("%lf MHz\n", get_centre_frequency(*datafile, verbose)); else printf("observing frequencies of individual frequency channels\n"); } for(indent = 0; indent < verbose.indent; indent++) printf(" "); printf(" "); switch(correctLbias) { case -1: printf("No L de-bias applied"); break; case 0: printf("De-bias L using median noise subtraction"); break; case 1: printf("De-bias L using Wardle & Kronberg correction"); break; default: printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Undefined L de-bias method specified."); return 0; } if(correctQV != 1 || correctV != 1) printf(", Q correction factor %f, V correction factor %f", 1.0/correctQV, 1.0/(correctQV*correctV)); if(normalize) printf(", output is normalised"); if(loffset != 0) printf(", pulse longitude shifted by %f deg\n", loffset); if(paoffset != 0) printf(", PA shifted by %f deg\n", paoffset); printf("\n"); if(extended) { printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Total polarization is computed, and the median off-pulse value is subtracted (probably not a very good idea)."); } } if(datafile->NrPols != 4 || rms_file->NrPols != 4) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Expected 4 input polarizations."); return 0; } if(datafile->poltype != POLTYPE_STOKES) { if(datafile->poltype == POLTYPE_UNKNOWN) { printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Polarization state unknown, it is assumed the data are Stokes parameters."); }else { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Convert data into Stokes parameters first."); return 0; } } if(rms_file_specified) { if(rms_file->poltype != POLTYPE_STOKES) { if(rms_file->poltype == POLTYPE_UNKNOWN) { printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Polarization state of the data to be used to determine the off-pulse rms is unknown, it is assumed the data are Stokes parameters."); }else { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Convert data to be used to determine the off-pulse rms into Stokes parameters first."); return 0; } } } if(datafile->tsampMode != TSAMPMODE_FIXEDTSAMP) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Expects input to have a regular sampling."); return 0; } if(correctQV == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: correctQV is set to zero, you probably want this to be 1."); return 0; } if(correctV == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: correctV is set to zero, you probably want this to be 1."); return 0; } if(datafile->isDebase == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase."); return 0; }else if(datafile->isDebase != 1) { fflush(stdout); printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Unknown baseline state. It is assumed the baseline has already removed from the data."); } if(rms_file_specified) { if(rms_file->isDebase == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase."); return 0; }else if(rms_file->isDebase != 1) { fflush(stdout); printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Unknown baseline state. It is assumed the baseline has already removed from the data."); } } if(rms_file_specified) { if(datafile->NrSubints != rms_file->NrSubints) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Number of subintegrations is different in the data to be used to determine the off-pulse rms."); return 0; } if(datafile->NrFreqChan != rms_file->NrFreqChan) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Number of frequency channels is different in the data to be used to determine the off-pulse rms (%ld != %ld).", rms_file->NrFreqChan, datafile->NrFreqChan); return 0; } if(correctLbias == 0) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Subtracting the median of L is not supported when a separate file is used for the offpulse statistics."); return 0; } if(extended) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Subtracting the median of P is not supported when a separate file is used for the offpulse statistics."); return 0; } } if(datafile->offpulse_rms != NULL) { free(datafile->offpulse_rms); } Loffpulse = (float *)malloc((rms_file->NrBins)*sizeof(float)); Poffpulse = (float *)malloc((rms_file->NrBins)*sizeof(float)); if(extended) { output_nr_pols = 8; }else { output_nr_pols = 5; } newdata = (float *)malloc(datafile->NrBins*datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float)); if(rms_file_specified) { newdata_rms = (float *)malloc(rms_file->NrBins*rms_file->NrSubints*rms_file->NrFreqChan*output_nr_pols*sizeof(float)); }else { newdata_rms = newdata; } datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float)); if(Loffpulse == NULL || Poffpulse == NULL || newdata == NULL || datafile->offpulse_rms == NULL || newdata_rms == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Memory allocation error."); return 0; } if(nolongitudes == 0) { datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double)); if(datafile->tsamp_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Memory allocation error."); return 0; } for(j = 0; j < (datafile->NrBins); j++) { datafile->tsamp_list[j] = get_pulse_longitude(*datafile, 0, j, verbose); datafile->tsamp_list[j] += loffset; } } if(normalize && (datafile->NrSubints > 1 || datafile->NrFreqChan > 1)) { fflush(stdout); printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Normalization will cause all subintegrations/frequency channels to be normalised individually. This may not be desired."); } long sindex_I, sindex_Q, sindex_U, sindex_V, sindex_I_rms, sindex_Q_rms, sindex_U_rms, sindex_V_rms, newindex_I, newindex_L, newindex_V, newindex_Pa, newindex_dPa, newindex_T, newindex_Ell, newindex_dEll, newindex_L_rms, newindex_T_rms; for(pulsenr = 0; pulsenr < datafile->NrSubints; pulsenr++) { for(freqnr = 0; freqnr < datafile->NrFreqChan; freqnr++) { sindex_I = datafile->NrBins*(0+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan)); sindex_Q = datafile->NrBins*(1+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan)); sindex_U = datafile->NrBins*(2+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan)); sindex_V = datafile->NrBins*(3+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan)); newindex_I = datafile->NrBins*(0+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); newindex_L = datafile->NrBins*(1+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); newindex_V = datafile->NrBins*(2+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); newindex_Pa = datafile->NrBins*(3+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); newindex_dPa = datafile->NrBins*(4+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); if(extended) { newindex_T = datafile->NrBins*(5+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); newindex_Ell = datafile->NrBins*(6+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); newindex_dEll = datafile->NrBins*(7+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr)); } if(rms_file_specified) { sindex_I_rms = rms_file->NrBins*(0+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan)); sindex_Q_rms = rms_file->NrBins*(1+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan)); sindex_U_rms = rms_file->NrBins*(2+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan)); sindex_V_rms = rms_file->NrBins*(3+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan)); newindex_L_rms = rms_file->NrBins*(1+output_nr_pols*(freqnr+rms_file->NrFreqChan*pulsenr)); if(extended) { newindex_T_rms = rms_file->NrBins*(5+output_nr_pols*(freqnr+rms_file->NrFreqChan*pulsenr)); } }else { sindex_I_rms = sindex_I; sindex_Q_rms = sindex_Q; sindex_U_rms = sindex_U; sindex_V_rms = sindex_V; newindex_L_rms = newindex_L; if(extended) { newindex_T_rms = newindex_T; } } if(normalize == 0) { ymax = 1; }else { ymax = datafile->data[sindex_I]; for(j = 1; j < (datafile->NrBins); j++) { if(datafile->data[sindex_I+j] > ymax) ymax = datafile->data[sindex_I+j]; } } if(ymax == 0) ymax = 1; for(j = 0; j < (datafile->NrBins); j++) { datafile->data[sindex_I + j] /= ymax; datafile->data[sindex_Q + j] /= correctQV*ymax; datafile->data[sindex_U + j] /= ymax; datafile->data[sindex_V + j] /= correctV*correctQV*ymax; newdata[j+newindex_L] = sqrt((datafile->data[sindex_Q+j])*(datafile->data[sindex_Q+j])+(datafile->data[sindex_U+j])*(datafile->data[sindex_U+j])); if(extended) { newdata[j+newindex_T] = sqrt(newdata[j+newindex_L]*newdata[j+newindex_L]+datafile->data[sindex_V+j]*datafile->data[sindex_V+j]); } } if(rms_file_specified) { for(j = 0; j < (rms_file->NrBins); j++) { rms_file->data[sindex_I_rms + j] /= ymax; rms_file->data[sindex_Q_rms + j] /= correctQV*ymax; rms_file->data[sindex_U_rms + j] /= ymax; rms_file->data[sindex_V_rms + j] /= correctV*correctQV*ymax; newdata_rms[j+newindex_L_rms] = sqrt((rms_file->data[sindex_Q_rms+j])*(rms_file->data[sindex_Q_rms+j])+(rms_file->data[sindex_U_rms+j])*(rms_file->data[sindex_U_rms+j])); if(extended) { newdata_rms[j+newindex_T_rms] = sqrt(newdata[j+newindex_L_rms]*newdata[j+newindex_L_rms]+rms_file->data[sindex_V_rms+j]*rms_file->data[sindex_V_rms+j]); } } } datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0; datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0; datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0; datafile->offpulse_rms[3+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; datafile->offpulse_rms[4+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; if(extended) { datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = 0; datafile->offpulse_rms[6+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; datafile->offpulse_rms[7+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; } baseline_intensity = 0; RMSQ = 0; RMSU = 0; NrOffpulseBins = 0; for(i = 0; i < (rms_file->NrBins); i++) { Loffpulse[i] = 0; if(checkRegions(i, &onpulse, 0, verbose) == 0) { NrOffpulseBins++; baseline_intensity += rms_file->data[sindex_I_rms+i]; RMSQ += (rms_file->data[sindex_Q_rms+i])*(rms_file->data[sindex_Q_rms+i]); RMSU += (rms_file->data[sindex_U_rms+i])*(rms_file->data[sindex_U_rms+i]); datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (rms_file->data[sindex_I_rms+i])*(rms_file->data[sindex_I_rms+i]); datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (newdata_rms[i+newindex_L_rms])*(newdata_rms[i+newindex_L_rms]); datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (rms_file->data[sindex_V_rms+i])*(rms_file->data[sindex_V_rms+i]); if(extended) { datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] += (newdata_rms[i+newindex_L_rms])*(newdata_rms[i+newindex_L_rms]) + (rms_file->data[sindex_V_rms+i])*(rms_file->data[sindex_V_rms+i]); } Loffpulse[NrOffpulseBins-1] = newdata_rms[i+newindex_L_rms]; if(extended) Poffpulse[NrOffpulseBins-1] = newdata_rms[i+newindex_T_rms]; } } baseline_intensity /= (float)NrOffpulseBins; RMSQ = sqrt(RMSQ/(float)NrOffpulseBins); RMSU = sqrt(RMSU/(float)NrOffpulseBins); datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins); datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins); datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins); if(extended) { datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = sqrt(datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]/(float)NrOffpulseBins); } if(rms_file_specified) { float scale = 1.0/sqrt(rebin_factor); RMSQ *= scale; RMSU *= scale; datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale; datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale; datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale; if(extended) { datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] *= scale; } } if(verbose.verbose) { if((freqnr == 0 && pulsenr == 0) || verbose.debug) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " PA conversion output for subint %ld frequency channel %ld:\n", pulsenr, freqnr); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Average baseline Stokes I: %f\n", baseline_intensity); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS I: %f\n", datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS Q: %f\n", RMSQ); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS U: %f\n", RMSU); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS V: %f\n", datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS L (before de-bias): %f\n", datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]); if(extended) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS sqrt(Q^2+U^2+V^2): %f\n", datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)]); } } } gsl_sort_float (Loffpulse, 1, NrOffpulseBins); medianL = gsl_stats_float_median_from_sorted_data(Loffpulse, 1, NrOffpulseBins); fflush(stdout); if((verbose.verbose && freqnr == 0 && pulsenr == 0) || verbose.debug) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Median L: %f\n", medianL); } if(extended) { gsl_sort_float (Poffpulse, 1, NrOffpulseBins); medianP = gsl_stats_float_median_from_sorted_data(Poffpulse, 1, NrOffpulseBins); fflush(stdout); if((verbose.verbose && freqnr == 0 && pulsenr == 0) || verbose.debug) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Median sqrt(Q^2+U^2+V^2): %f\n", medianP); } } for(j = 0; j < (datafile->NrBins); j++) { if(correctLbias == 1) { float junk = (0.5*(RMSQ+RMSU)/newdata[j+newindex_L]); if(junk < 1) newdata[j+newindex_L] *= sqrt(1.0-junk*junk); else newdata[j+newindex_L] = 0.0; }else if(correctLbias == 0) { newdata[j+newindex_L] -= medianL; } if(extended) newdata[j+newindex_T] -= medianP; } for(i = 0; i < (datafile->NrBins); i++) { newdata[i+newindex_Pa] = 90.0*atan2(datafile->data[sindex_U+i],datafile->data[sindex_Q+i])/M_PI; if(paoffset) { newdata[i+newindex_Pa] += paoffset; newdata[i+newindex_Pa] = derotate_180_small_double(newdata[i+newindex_Pa]); } if(datafile->data[i+sindex_Q] != 0 || datafile->data[i+sindex_U] != 0) { newdata[i+newindex_dPa] = sqrt((datafile->data[sindex_Q+i]*RMSU)*(datafile->data[sindex_Q+i]*RMSU) + (datafile->data[sindex_U+i]*RMSQ)*(datafile->data[sindex_U+i]*RMSQ)); newdata[i+newindex_dPa] /= 2.0*(datafile->data[i+sindex_Q]*datafile->data[i+sindex_Q] + datafile->data[i+sindex_U]*datafile->data[i+sindex_U]); newdata[i+newindex_dPa] *= 180.0/M_PI; }else { newdata[i+newindex_dPa] = 0; } if(extended) { newdata[i+newindex_Ell] = 0; newdata[i+newindex_dEll] = 0; } } for(j = 0; j < (datafile->NrBins); j++) { newdata[j+newindex_I] = datafile->data[j+sindex_I]; newdata[j+newindex_V] = datafile->data[j+sindex_V]; } } } free(datafile->data); datafile->data = newdata; if(rms_file_specified) { free(newdata_rms); } if(nolongitudes == 0) { datafile->tsampMode = TSAMPMODE_LONGITUDELIST; } datafile->NrPols = output_nr_pols; if(extended) { datafile->poltype = POLTYPE_ILVPAdPATEldEl; }else { datafile->poltype = POLTYPE_ILVPAdPA; } free(Loffpulse); free(Poffpulse); return 1; } int writePPOLHeader(datafile_definition datafile, int argc, char **argv, verbose_definition verbose) { char *txt; txt = malloc(10000); if(txt == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR writePPOLHeader: Memory allocation error."); return 0; } constructCommandLineString(txt, 10000, argc, argv, verbose); fprintf(datafile.fptr_hdr, "#ppol file: %s\n", txt); free(txt); return 1; } int readPPOLHeader(datafile_definition *datafile, int extended, verbose_definition verbose) { float dummy_float; int ret, maxlinelength, nrwords; char *txt, *ret_ptr, *word_ptr; maxlinelength = 2000; txt = malloc(maxlinelength); if(txt == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error."); return 0; } datafile->isFolded = 1; datafile->foldMode = FOLDMODE_FIXEDPERIOD; datafile->fixedPeriod = 0; datafile->tsampMode = TSAMPMODE_LONGITUDELIST; datafile->fixedtsamp = 0; datafile->tsubMode = TSUBMODE_FIXEDTSUB; if(datafile->tsub_list != NULL) free(datafile->tsub_list); datafile->tsub_list = (double *)malloc(sizeof(double)); if(datafile->tsub_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error"); return 0; } datafile->tsub_list[0] = 0; datafile->NrSubints = 1; datafile->NrFreqChan = 1; datafile->datastart = 0; rewind(datafile->fptr); ret = fread(txt, 1, 3, datafile->fptr); txt[3] = 0; if(ret != 3) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: cannot read from file."); free(txt); return 0; } if(strcmp(txt, "#pp") != 0 ) { fflush(stdout); printwarning(verbose.debug, "WARNING readPPOLHeader: File does not appear to be in PPOL or PPOLSHORT format. I will try to load file, but this will probably fail. Did you run ppol first?"); } skipallhashedlines(datafile); datafile->NrBins = 0; dummy_float = 0; do { ret_ptr = fgets(txt, maxlinelength, datafile->fptr); if(ret_ptr != NULL) { if(txt[0] != '#') { if(extended) { word_ptr = pickWordFromString(txt, 2, &nrwords, 1, ' ', verbose); if(nrwords != 10 && nrwords != 14) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Line should have 10 or 14 words, got %d", nrwords); if(nrwords == 3) printerror(verbose.debug, " Maybe file is in format %s?", returnFileFormat_str(PPOL_SHORT_format)); printerror(verbose.debug, " Line: '%s'.", txt); free(txt); return 0; } if(nrwords == 10) { datafile->poltype = POLTYPE_ILVPAdPA; datafile->NrPols = 5; }else { datafile->poltype = POLTYPE_ILVPAdPATEldEl; datafile->NrPols = 8; } }else { word_ptr = pickWordFromString(txt, 1, &nrwords, 1, ' ', verbose); if(nrwords != 3) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Line should have 3 words, got %d", nrwords); if(nrwords == 10) printerror(verbose.debug, " Maybe file is in format %s?", returnFileFormat_str(PPOL_format)); printerror(verbose.debug, " Line: '%s'.", txt); free(txt); return 0; } } ret = sscanf(word_ptr, "%f", &dummy_float); if(ret != 1) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Cannot interpret as a float: '%s'.", txt); free(txt); return 0; } if(dummy_float >= 360) { fflush(stdout); printwarning(verbose.debug, "WARNING: IGNORING POINTS AT PULSE LONGITUDES > 360 deg."); }else { (datafile->NrBins)++; } } } }while(ret_ptr != NULL && dummy_float < 360); if(extended == 0) { datafile->poltype = POLTYPE_PAdPA; datafile->NrPols = 2; } fflush(stdout); if(verbose.verbose) fprintf(stdout, "Going to load %ld points from %s\n", datafile->NrBins, datafile->filename); if(datafile->NrBins == 0) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: No data in %s", datafile->filename); free(txt); return 0; } fseek(datafile->fptr, datafile->datastart, SEEK_SET); free(txt); if(datafile->offpulse_rms != NULL) { free(datafile->offpulse_rms); datafile->offpulse_rms = NULL; } if(extended) { datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*datafile->NrPols*sizeof(float)); if(datafile->offpulse_rms == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error"); return 0; } } datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double)); if(datafile->tsamp_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error"); return 0; } return 1; } int readPPOLfile(datafile_definition *datafile, float *data, int extended, float add_longitude_shift, verbose_definition verbose) { int maxlinelength; long i, k, dummy_long; char *txt, *ret_ptr; if(datafile->NrBins == 0) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLfile: No data in %s", datafile->filename); return 0; } maxlinelength = 2000; txt = malloc(maxlinelength); if(txt == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLfile: Memory allocation error."); return 0; } fseek(datafile->fptr, datafile->datastart, SEEK_SET); k = 0; if(extended) { datafile->offpulse_rms[3] = -1; datafile->offpulse_rms[4] = -1; if(datafile->NrPols == 8) { datafile->offpulse_rms[6] = -1; datafile->offpulse_rms[7] = -1; } } for(i = 0; i < datafile->NrBins; i++) { ret_ptr = fgets(txt, maxlinelength, datafile->fptr); if(ret_ptr == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLfile: Cannot read next line, should not happen after successfully reading in header"); free(txt); return 0; } if(txt[0] != '#') { if(extended == 0) { sscanf(txt, "%lf %f %f", &(datafile->tsamp_list[k]), &(data[k]), &(data[k+datafile->NrBins])); }else { if(datafile->NrPols == 8) { sscanf(txt, "%ld %lf %f %f %f %f %f %f %f %f %f %f %f %f", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins]), &(data[k+5*datafile->NrBins]), &(datafile->offpulse_rms[5]), &(data[k+6*datafile->NrBins]), &(data[k+7*datafile->NrBins])); }else { sscanf(txt, "%ld %lf %f %f %f %f %f %f %f %f", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins])); } } datafile->tsamp_list[k] += add_longitude_shift; if(datafile->tsamp_list[k] >= 0 && datafile->tsamp_list[k] < 360) { k++; }else { fflush(stdout); printwarning(verbose.debug, "WARNING readPPOLfile: IGNORING POINTS AT PULSE LONGITUDES > 360 deg."); } } } if(k != datafile->NrBins) { fflush(stdout); printerror(verbose.debug, "WARNING readPPOLfile: The nr of bins read in is different as determined from header. Something is wrong."); return 0; } fflush(stdout); if(verbose.verbose) fprintf(stdout, "readPPOLfile: Accepted %ld points\n", datafile->NrBins); free(txt); return 1; } int writePPOLfile(datafile_definition datafile, float *data, int extended, int onlysignificantPA, int twoprofiles, float PAoffset, verbose_definition verbose) { long j; if(datafile.poltype != POLTYPE_ILVPAdPA && datafile.poltype != POLTYPE_PAdPA && datafile.poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR writePPOLfile: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl (it is %d).", datafile.poltype); return 0; } if(datafile.poltype == POLTYPE_ILVPAdPA && datafile.NrPols != 5) { printerror(verbose.debug, "ERROR writePPOLfile: 5 polarization channels were expected, but there are %ld.", datafile.NrPols); return 0; }else if(datafile.poltype == POLTYPE_PAdPA && datafile.NrPols != 2) { printerror(verbose.debug, "ERROR writePPOLfile: 2 polarization channels were expected, but there are %ld.", datafile.NrPols); return 0; }else if(datafile.poltype == POLTYPE_ILVPAdPATEldEl && datafile.NrPols != 8) { printerror(verbose.debug, "ERROR writePPOLfile: 8 polarization channels were expected, but there are %ld.", datafile.NrPols); return 0; } if(datafile.NrSubints > 1 || datafile.NrFreqChan > 1) { printerror(verbose.debug, "ERROR writePPOLfile: Can only do this opperation if there is one subint and one frequency channel."); return 0; } if(datafile.tsampMode != TSAMPMODE_LONGITUDELIST) { printerror(verbose.debug, "ERROR writePPOLfile: Expected pulse longitudes to be defined."); return 0; } int pa_offset, dpa_offset; if(datafile.poltype == POLTYPE_ILVPAdPA || datafile.poltype == POLTYPE_ILVPAdPATEldEl) { pa_offset = 3; dpa_offset = 4; }else if(datafile.poltype == POLTYPE_PAdPA) { pa_offset = 0; dpa_offset = 1; } for(j = 0; j < datafile.NrBins; j++) { if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) { if(extended) { fprintf(datafile.fptr, "%ld %e %e %e %e %e %e %e %e %e", j, datafile.tsamp_list[j], data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]); if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) fprintf(datafile.fptr, " %e %e %e %e", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]); fprintf(datafile.fptr, "\n"); }else { fprintf(datafile.fptr, "%e %e %e\n", datafile.tsamp_list[j], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]); } } } if(twoprofiles) { for(j = 0; j < datafile.NrBins; j++) { if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) { if(extended) { fprintf(datafile.fptr, "%ld %e %e %e %e %e %e %e %e %e", j, datafile.tsamp_list[j]+360, data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]); if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) fprintf(datafile.fptr, " %e %e %e %e", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]); fprintf(datafile.fptr, "\n"); }else { fprintf(datafile.fptr, "%e %e %e\n", datafile.tsamp_list[j]+360, data[j]+PAoffset, data[j+dpa_offset*datafile.NrBins]); } } } } return 1; }
{ "alphanum_fraction": 0.6861646433, "avg_line_length": 47.1789052069, "ext": "c", "hexsha": "393ea22da10936e432e4a1ea070145001b3c3e34", "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": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_path": "src/lib/psrio_paswing.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "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": "David-McKenna/psrsalsa", "max_issues_repo_path": "src/lib/psrio_paswing.c", "max_line_length": 755, "max_stars_count": null, "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_path": "src/lib/psrio_paswing.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10960, "size": 35337 }
#include <getopt.h> #include <stdio.h> #include <list> #include <gsl/gsl_rng.h> //#include "utils.h" #include "data.h" #include "model.h" // helper function to write out per-user info void log_user(FILE* file, Data *data, int user, int heldout, double rmse, double mae, double rank, int first, double crr, double ncrr, double ndcg, bool stats); void log_item(FILE* file, Data *data, int item, int heldout, double rmse, double mae, double rank, int first, double crr, double ncrr, double ndcg, bool stats); // helper function to sort predictions properly bool prediction_compare(const pair<double,int>& itemA, const pair<double, int>& itemB); // take a prediction function as an argument void eval(Model* model, double (Model::*prediction)(int,int), string outdir, Data* data, bool stats, unsigned long int seed, bool verbose, string label, bool write_rankings, bool mapped_ids);
{ "alphanum_fraction": 0.734375, "avg_line_length": 40.7272727273, "ext": "h", "hexsha": "1afd4fa015955408d09caf5f2a38d82f675c7093", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-04-06T20:17:32.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-13T00:22:21.000Z", "max_forks_repo_head_hexsha": "a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ajbc/spf", "max_forks_repo_path": "src/eval.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5", "max_issues_repo_issues_event_max_datetime": "2017-02-09T11:39:46.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-29T10:43:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ajbc/spf", "max_issues_repo_path": "src/eval.h", "max_line_length": 191, "max_stars_count": 28, "max_stars_repo_head_hexsha": "a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ajbc/spf", "max_stars_repo_path": "src/eval.h", "max_stars_repo_stars_event_max_datetime": "2021-09-08T19:56:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-08T23:07:07.000Z", "num_tokens": 231, "size": 896 }
#ifndef VM_CALL_STACK_H #define VM_CALL_STACK_H #include "function/WasmFunction.h" #include "utilities/SimpleVector.h" #include "utilities/ListStack.h" #include "vm/alloc/StackResource.h" #include <gsl/span> #include <sstream> namespace wasm { namespace ex { template <class Container, class Index> decltype(auto) at(Container&& c, const Index& index) { using std::size; if(index < size(std::forward<Container>(c))) return std::forward<Container>(c)[index]; throw std::out_of_range("Out-of-bounds container access in wasm::ex::at()."); } } /* namespace ex */ namespace detail { auto make_stack_size_guard(auto& stack) { auto initial_stack_size = stack.size(); return make_scope_guard([&stack, initial_stack_size]() { assert(stack.size() >= initial_stack_size); if(stack.size() > initial_stack_size) stack.pop_n(stack.size() - initial_stack_size); }); } } /* namespace detail */ struct BadBranchError: std::logic_error { private: static std::string make_mesage(std::size_t depth, std::size_t limit) { std::ostringstream s; s << "Invald branch depth (" << depth << ") to non-existant block. "; s << "(max depth is " << limit << ')'; return s.str(); } public: BadBranchError(std::size_t branch_depth, std::size_t limit): std::logic_error(make_message(branch_depth, limit)), depth(branch_depth) { } const std::size_t depth; }; std::ostream& operator<<(std::ostream& os, const SimpleStack<WasmValue>& stack) { os << "Stack(["; if(stack.size() > 0u) { os << stack.front(); for(auto pos = std::next(stack.begin()); pos != stack.end(); ++pos) os << ", " << *pos; } os << "])"; return os; } std::ostream& operator<<(std::ostream& os, const SimpleStack<TaggedWasmValue>& stack) { os << "Stack(["; if(stack.size() > 0u) { os << stack.front(); for(auto pos = std::next(stack.begin()); pos != stack.end(); ++pos) os << ", " << *pos; } os << "])"; return os; } template <class T> struct Block { using stack_type = SimpleStack<T>; Block(const char* label_pos, std::size_t return_count, StackResource& resource): label(label_pos), arity(return_count), stack(resource) { } bool is_bottom() const { if(not label) { assert(not arity); return true; } return false; } const char* const label; const std::size_t arity; stack_type stack; }; template <class T> std::ostream& operator<<(std::ostream& os, const Block<T>& block) { os << "Block(label = " << block.label; os << ", arity = " << block.arity; os << ", stack = " << block.stack; os << ')'; return os; } template <class T> struct WasmStackFrame { using value_type = T; using block_type = Block<value_type>; using block_list_type = std::forward_list< block_type, pmr::polymorphic_allocator<block_type> >; using locals_vector_type = gsl::span<value_type>; using stack_type = SimpleStack<value_type>; using block_iterator = block_list_type::iterator; using const_block_iterator = block_list_type::const_iterator; WasmStackFrame(const WasmFunction& func, StackResource& r): code_(func), locals_(locals_count(func) + param_count(signature(func))), blocks_(r) { blocks_.emplace_front(nullptr, 0u, get_resource()); } WasmStackFrame(CodeView code, gsl::span<T> locals, StackResource& r): return_address_(), locals_(locals), blocks_(r) { blocks_.push_front(nullptr, 0u, get_resource()); } ~WasmStackFrame() { while(not blocks_.empty()) blocks_.pop_front(); } block_iterator block_at(std::size_t depth) { std::size_t count = 0; for(auto pos = blocks_.begin(); pos != blocks_.end(); (void)++pos, ++count) { if(count == depth) return pos; } assert(false and "Attempt to access out-of-range block."); } const char* branch_depth(wasm_uint32_t depth) { return branch(block_at(depth)); } const char* try_branch_top() const { assert(blocks_.begin() != blocks.end()) if(blocks_.front().is_bottom()) return nullptr; else return branch_top(); } [[nodiscard]] const char* branch(const_block_iterator pos) { assert(pos != blocks_.end()); // get the label auto code_pos = pos->label; auto arity = pos->arity; auto& dest_stack = pos->stack; auto& src_stack = current_stack(*this); assert(&src_stack != &dest_stack); assert(arity <= dest_stack.size()); assert(arity <= src_stack.size()); std::copy(src_stack.begin(), src_stack.begin() + arity, dest_stack.begin()); // TODO: assert(src_stack.size() == arity) for 'IF ... END' blocks while(blocks_.begin() != pos) blocks_.pop_front(); return code_pos; } void push_block(const char* label, gsl::span<const LanguageType> signature) { assert( (label[-1] == static_cast<char>(OpCode::END)) or (label[-(1 + (std::ptrdiff_t)sizeof(wasm_uint32_t))] == static_cast<char>(OpCode::ELSE)) ); auto guard_ = make_stack_size_guard(stack()); for(const auto& type: signature) { // push return values onto the stack tp::visit_value_type( [&](auto WasmValue::* p) { stack_emplace_top(p, 0); }, type ); } blocks_.emplace_front(label, signature.size(), get_resource()); } [[nodiscard]] const char* branch_top() { assert(not blocks_.empty()); assert(not blocks_.front().is_bottom()); return branch(blocks_.begin()); } T& local_at(wasm_uint32_t index) { return ex::at(locals_, index); } const T& local_at(wasm_uint32_t index) const { return ex::at(locals_, index); } T& stack_at(wasm_uint32_t index) { return ex::at(stack(), index); } const T& stack_at(wasm_uint32_t index) { return ex::at(stack(), index); } template <class U> const std::decay_t<U>& stack_at(wasm_uint32_t index, U WasmValue::* p) const { return stack().at().get(p); } template <class U> const U& stack_at(wasm_uint32_t index, const U WasmValue::* p) const { return stack().at(index).get(p); } template <class U> U& stack_at(wasm_uint32_t index, U WasmValue::* p) { return stack().at(index).get(p); } T& stack_top() { return stack().at(0u); } const T& stack_top() const { return stack().at(0u); } template <class U> const std::decay_t<U>& stack_top(U WasmValue::* p) const { return stack_top().get(p); } template <class U> const U& stack_top(const U WasmValue::* p) const { return stack_top().get(p); } template <class U> U& stack_top(U WasmValue::* p) { return stack_top().get(p); } std::pair<const T&, const T&> stack_top_2() const { return std::pair<const T&, const T&>(stack_at(1u), stack_at(0u)); } std::pair<T&, T&> stack_top_2() const { return std::pair<T&, T&>(stack_at(1u), stack_at(0u)); } template <class L, class R> std::pair<const std::decay_t<L>&, const std::decay_t<R>&> stack_top_2(L WasmValue::* l, R WasmValue::* r) const { return std::pair<const std::decay_t<L>&, const std::decay_t<R>&>( stack_at(1u).get(l), stack_at(0u).get(r) ); } template <class U> void stack_pop_2_push_1(U WasmValue::* mem, U value) { stack_pop(); stack_pop_1_push_1(mem, value); } template <class U> void stack_pop_1_push_1(U WasmValue::* mem, U value) { stack().replace_top(mem, value); } T stack_pop() { return stack().pop(); } template <class U> U stack_pop(U WasmValue::* mem) { auto v = stack_top(mem); stack_pop(); return v; } template <class ... Args> T stack_emplace_top(Args&& ... args) { return stack().emplace(std::forward<Args>(args)...); } void stack_pop_n(std::size_t n) { stack().pop_n(n); } auto stack_size() const { return stack().size(); } const WasmFunction* function() { return self.code_.function(); } friend std::ostream& operator<<(std::ostream& os, const WasmStackFrame& frame) { os << "StackFrame("; os << "function = "; write_declataion(os, function(frame)); os << ", locals = " << frame.locals_; os << ", stack = ["; const char* delim = ""; for(const auto& block: frame_.blocks_) { const auto& stack = block.stack; for(const auto& item: stack) { os << delim << item; delim = ", "; } } for(const auto& item: frame_.stack_) { os << delim << item; delim = ", "; } os << "])"; return os; } bool is_function_call() const { return static_cast<bool>(function()); } std::optional<WasmInstruction> next_instruction() const { return code_.next_instruction(); } void advance(const WasmInstruction& instr) { assert(next_instruction()); if(not is_next_instruction(instr)) throw std::logic_error("Instruction does not match program counter on call stack."); code_.advance(instr); } bool is_next_instruction(const WasmInstruction& instr) const { return instr.source().data() == code_.data(); } private: const auto& stack() const { assert(not blocks_.empty()); return blocks_.front().stack; } auto& stack() { assert(not blocks_.empty()); return blocks_.front().stack; } StackResource& get_resource() { std::memory_resource* rsc = blocks_.get_allocator().resource(); assert(rsc); assert(static_cast<bool>(dynamic_cast<StackResource*>(rsc))); return *static_cast<StackResource*>(rsc); } CodeView code_; const gsl::span<T> locals_; block_list_type blocks_; }; template <class T> struct WasmCallStack { using frame_stack_type = ListStack< WasmStackFrame<T>, pmr::polymorphic_allocator<WasmStackFrame<T>> >; using frame_iterator = list_type::const_iterator; WasmCallStack(StackResource& const WasmStackFrame<T>& current_frame() const { assert(not frames_.empty()); return frames_.top(); } CodeView call_function(const Function& func, const WasmInstruction& call_instr) { assert(call_instr.opcode() == OpCode::CALL); if(func.is_wasm_function()) { return call_wasm_function(func.get_wasm_function(), call_instr); } else { call_c_function(func.get_c_function()); return call_instr.after(); } } CodeView call_wasm_function(const WasmFunction& func, const WasmInstruction& call_instr) { assert(call_instr.opcode() == OpCode::CALL); auto& stack = frames_.empty() ? frames_.top().stack() : base_stack_; auto func_sig = signature(func); auto arg_types = param_types(func_sig); auto locals_types = locals(func); auto ret_count = return_count(func); if(stack.size() < arg_types.size()) assert(false); // TODO: throw an exception // push zero-initialized locals onto the stack. auto guard_ = make_stack_size_guard(stack); for(LanguageType type: locals_types) { tp::visit_value_type( [&](auto WasmValue::* p) { stack.emplace(p, 0); }, type ); } auto return_address = call_instr.after().pos(); auto locals_vector_size = locals_types.size() + arg_types.size(); auto locals_pos = stack.data() + (stack.size() - locals_vector_size); gsl::span<T> locals_vector(locals_pos, locals_vector_size); frames_.emplace(func, return_address, locals_vector); return CodeView(func); } void return_from_expression() { assert(frames_.size() == 1u); _recurse_return_from_frame_unchecked(); } [[nodiscard]] CodeView end_block() { if(const char* p = top_frame().try_branch_top(); p) { } } [[nodiscard]] CodeView return_from_function() { auto& frame = top_frame(); assert(frame.is_function_call()); auto ret_types = return_types(signature(*frame.funtion())); assert(frame.stack_size() >= ret_types.size()); CodeView ret_addr = top_frame().return_address(); _recurse_return_from_frame(return_types); return ret_addr; } [[nodiscard]] CodeView call_table_function(const WasmTable& table, const WasmFunctionSignature& sig, const WasmInstruction& instr) { assert(instr.opcode() == OpCode::CALL_INDIRECT); assert(frames_.empty() or top_frame().can_exectute_instruction(instr)); auto& stack = top_stack(); wasm_uint32_t offset = reinterpret_cast<const wasm_uint32_t&>(stack.top().get(tp::i32_c)); const TableFunction& func = table.at(offset); if(func.is_null()) throw NullTableFunctionError(); if(func.is_wasm_function()) { auto& f = func.get_wasm_function(); if(signature(f) != sig) throw BadTableFunctionSignature(); stack.pop(); return call_wasm_function(func.get_wasm_function()); } assert(func.is_c_function()); auto& f = func.get_c_function(); if(f.signature() != sig) throw BadTableFunctionSignature(); { /* scope */ auto stack_size = stack.size(); auto guard_ = make_scope_guard( [&, stack_size]{ // poor man's check to make sure the c function call // doesn't modify 'this'. assert(stack.size() == stack_size); } call_c_function(f, offset); } /* /scope */ return instr.after(); } void call_c_function(const CFunction& cfunc) const { const auto& sig = cfunc.signature(); auto param_types = param_types(sig); auto return_types = return_types(sig); auto& stack = top_stack(); assert(stack.size() >= param_types.size()); auto args = gsl::span<const T>(stack.data(), stack.size()).last(param_types.size()); { auto guard_ = make_stack_size_guard(stack()); for(LanguageType value_tp: return_types) stack.emplace(value_tp); auto results = gsl::span<T>(stack.data(), stack.size()).last(return_types.size()); cfunc(results, args); } assert(stack.size() >= return_types.size() + param_types.size()); std::rotate( stack.begin(), stack.begin() + return_types.size(), stack.begin() + return_types.size() + param_types.size() ); stack.pop_n(param_types.size()); } std::optional<WasmInstruction> next_instruction() const { return top_frame().next_instruction(); } void execute(const WasmInstruction& instr, const WasmModule& module) const { if(not top_frame().is_next_instruction()) throw std::logic_error("Instruction does not match program counter on call stack."); CodeView next = instr.execute(*this, module); top_frame().code_.advance(next); } private: WasmStackFrame<T>& top_frame() { if(frames_.empty()) throw std::out_of_range("Attempt to access out-of-bounds call stack frame."); return frames_.top(); } SimpleStack<T>& top_stack() { if(frames_.empty()) return base_stack_; return frames_.top().stack(); } std::pair<WasmStackFrame<T>&, WasmStackFrame<T>&> top_two_frames() { if(frames_.empty()) throw std::out_of_range("Attempt to access out-of-bounds frame."); auto pos = frames_.begin(); const auto& hi = *pos++; if(pos == frames_.end()) throw std::out_of_range("Attempt to access out-of-bounds frame."); const auto& lo = *pos++; return std::pair<WasmStackFrame&, WasmStackFrame&>(lo, hi); } void _recurse_return_from_frame_unchecked() { if(auto& stack = top_frame().stack(); stack.empty()) { frames_.pop(); } else { T ret_v = stack.pop(); _recurse_return_from_frame_unchecked(); top_stack().emplace(ret_v); } } void _recurse_return_from_frame(const gsl::span<const LanguageType>& return_types, std::size_t index = 0u) { assert(not frames_.empty()); if(index < return_types.size()) { // one of the return values from the callee's frame tp::visit_value_type( [&](auto WasmValue::* p) { auto ret_v = top_frame().stack_at(index, p); // keep recursing until we exhaust the return // values. Once we've done that, pop the callee's // frame, and then pop the locals vector and arguments // off the caller's stack. _recurse_return_from_frame(return_types, index); // now that we've popped the callee's frame from the call stack, // and the locals vector off of the caller's frame's stack, push // the return values onto the callee's frame's stack. // // note that there may be no frame below the one we popped, in which // case, the return values are pushed onto 'this->base_stack_' top_stack().stack_emplace_top(p, ret_v); }, return_types[return_types.size() - index] ); } else { const auto* func_p = top_frame.function(); assert(func_p); const auto& func = *func_p; std::size_t total_locals = param_count(func) + locals_count(func); // pop the top frame frames_.pop_front(); assert(not frames_.empty()); auto& new_top_frame = frames_.front(); assert(new_top_frame.stack_size() >= total_locals); // pop the locals (args + locals) vector of the frame we just popped // off of the stack. note that the locals vector of the current frame // lives on the stack of the previous frame. new_top_frame.stack_pop_n(total_locals); // push the return values of the frame we just popped... // ... by simply returning from _recurse_return_from_frame(). each // recursive call which took the if() branch above will push the return // values onto the new frame. } } const StackResource& stack_resource() const { return base_stack_.get_resource(); } StackResource& stack_resource() { return base_stack_.get_resource(); } frame_stack_type frames_; SimpleStack<T> base_stack_; }; template <class T> const T& local_at(const WasmCallStack<T>& self, std::size_t idx) { auto locals = locals(current_frame(self)); if(idx >= locals.size()) throw ValidationError<std::out_of_range>("Attempt to access out-of-bounds local."); return locals[idx]; } template <class T> T& local_at(WasmCallStack<T>& self, std::size_t idx) { auto locals = locals(current_frame(self)); if(idx >= locals.size()) throw ValidationError<std::out_of_range>("Attempt to access out-of-bounds local."); return locals[idx]; } template <class T> const auto& current_stack(const WasmCallStack<T>& self, std::size_t idx) { return current_stack(current_frame(self)); } template <class T> auto& current_stack(WasmCallStack<T>& self, std::size_t idx) { return current_stack(current_frame(self)); } } /* namespace wasm */ #endif /* VM_CALL_STACK_H */
{ "alphanum_fraction": 0.6802292589, "avg_line_length": 26.2232142857, "ext": "h", "hexsha": "43869dcf61c45c855b76509d0f3643e6f5aed525", "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": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_path": "include/vm/CallStack.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "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": "tvanslyke/wasm-cpp", "max_issues_repo_path": "include/vm/CallStack.h", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_path": "include/vm/CallStack.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4762, "size": 17622 }
// The MIT License (MIT) // // Copyright (c) 2018 Mateusz Pusz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <gsl/gsl_assert> #include <units/bits/math_concepts.h> #include <units/bits/pow.h> #include <units/bits/ratio_maths.h> namespace units::detail { struct decimal_fp { double significant; std::intmax_t exponent; }; [[nodiscard]] constexpr decimal_fp to_decimal(double v) noexcept { if (v == 0) { return {.significant = 0.0, .exponent = 0}; } double significant = abs(v); std::intmax_t exponent = 0; while (significant < 1) { significant *= 10.0; --exponent; } while (significant >= 10) { significant /= 10.0; ++exponent; } if (v < 0) { significant = -significant; } return {.significant = significant, .exponent = exponent}; } /* approximate natural log as https://math.stackexchange.com/a/977836 far slower than std::log but works at compile time with similar accuracy */ [[nodiscard]] constexpr double constexpr_log(double v) noexcept { Expects(v > 0); // lookup table to speed up convergence for all significant values // significant values of 7 and greater benefit mostly as they now converge in 5 terms compared to O(10)-O(100) // required without the table // // using python: // >>> import math // >>> for i in range(1, 100): // ... print(f"/* log({i:>2d}) = */ {math.log(i):.16f},") constexpr std::array<double, 99> log_table{ /* log( 1) = */ 0.0000000000000000, /* log( 2) = */ 0.6931471805599453, /* log( 3) = */ 1.0986122886681098, /* log( 4) = */ 1.3862943611198906, /* log( 5) = */ 1.6094379124341003, /* log( 6) = */ 1.7917594692280550, /* log( 7) = */ 1.9459101490553132, /* log( 8) = */ 2.0794415416798357, /* log( 9) = */ 2.1972245773362196, /* log(10) = */ 2.3025850929940459, /* log(11) = */ 2.3978952727983707, /* log(12) = */ 2.4849066497880004, /* log(13) = */ 2.5649493574615367, /* log(14) = */ 2.6390573296152584, /* log(15) = */ 2.7080502011022101, /* log(16) = */ 2.7725887222397811, /* log(17) = */ 2.8332133440562162, /* log(18) = */ 2.8903717578961645, /* log(19) = */ 2.9444389791664403, /* log(20) = */ 2.9957322735539909, /* log(21) = */ 3.0445224377234230, /* log(22) = */ 3.0910424533583161, /* log(23) = */ 3.1354942159291497, /* log(24) = */ 3.1780538303479458, /* log(25) = */ 3.2188758248682006, /* log(26) = */ 3.2580965380214821, /* log(27) = */ 3.2958368660043291, /* log(28) = */ 3.3322045101752038, /* log(29) = */ 3.3672958299864741, /* log(30) = */ 3.4011973816621555, /* log(31) = */ 3.4339872044851463, /* log(32) = */ 3.4657359027997265, /* log(33) = */ 3.4965075614664802, /* log(34) = */ 3.5263605246161616, /* log(35) = */ 3.5553480614894135, /* log(36) = */ 3.5835189384561099, /* log(37) = */ 3.6109179126442243, /* log(38) = */ 3.6375861597263857, /* log(39) = */ 3.6635616461296463, /* log(40) = */ 3.6888794541139363, /* log(41) = */ 3.7135720667043080, /* log(42) = */ 3.7376696182833684, /* log(43) = */ 3.7612001156935624, /* log(44) = */ 3.7841896339182610, /* log(45) = */ 3.8066624897703196, /* log(46) = */ 3.8286413964890951, /* log(47) = */ 3.8501476017100584, /* log(48) = */ 3.8712010109078911, /* log(49) = */ 3.8918202981106265, /* log(50) = */ 3.9120230054281460, /* log(51) = */ 3.9318256327243257, /* log(52) = */ 3.9512437185814275, /* log(53) = */ 3.9702919135521220, /* log(54) = */ 3.9889840465642745, /* log(55) = */ 4.0073331852324712, /* log(56) = */ 4.0253516907351496, /* log(57) = */ 4.0430512678345503, /* log(58) = */ 4.0604430105464191, /* log(59) = */ 4.0775374439057197, /* log(60) = */ 4.0943445622221004, /* log(61) = */ 4.1108738641733114, /* log(62) = */ 4.1271343850450917, /* log(63) = */ 4.1431347263915326, /* log(64) = */ 4.1588830833596715, /* log(65) = */ 4.1743872698956368, /* log(66) = */ 4.1896547420264252, /* log(67) = */ 4.2046926193909657, /* log(68) = */ 4.2195077051761070, /* log(69) = */ 4.2341065045972597, /* log(70) = */ 4.2484952420493594, /* log(71) = */ 4.2626798770413155, /* log(72) = */ 4.2766661190160553, /* log(73) = */ 4.2904594411483910, /* log(74) = */ 4.3040650932041702, /* log(75) = */ 4.3174881135363101, /* log(76) = */ 4.3307333402863311, /* log(77) = */ 4.3438054218536841, /* log(78) = */ 4.3567088266895917, /* log(79) = */ 4.3694478524670215, /* log(80) = */ 4.3820266346738812, /* log(81) = */ 4.3944491546724391, /* log(82) = */ 4.4067192472642533, /* log(83) = */ 4.4188406077965983, /* log(84) = */ 4.4308167988433134, /* log(85) = */ 4.4426512564903167, /* log(86) = */ 4.4543472962535073, /* log(87) = */ 4.4659081186545837, /* log(88) = */ 4.4773368144782069, /* log(89) = */ 4.4886363697321396, /* log(90) = */ 4.4998096703302650, /* log(91) = */ 4.5108595065168497, /* log(92) = */ 4.5217885770490405, /* log(93) = */ 4.5325994931532563, /* log(94) = */ 4.5432947822700038, /* log(95) = */ 4.5538768916005408, /* log(96) = */ 4.5643481914678361, /* log(97) = */ 4.5747109785033828, /* log(98) = */ 4.5849674786705723, /* log(99) = */ 4.5951198501345898, }; decimal_fp x = to_decimal(v); // dividing the significant by nearest lower value in [1.0, 1.1, 1.2, ..., 9.9] will greatly improve convergence x.significant *= 10; const auto isignificant = static_cast<std::size_t>(x.significant); x.significant /= static_cast<double>(isignificant); const double result = static_cast<double>(x.exponent - 1) * log_table[9] + log_table[isignificant - 1]; // 1.0 <= significant < 1.1 converges rapidly const double y = (x.significant - 1) / (x.significant + 1); const double y_squared = y * y; double sum = 0; // 5 terms are needed for convergence to machine precision in the worst case scenario for (int k = 4; k > 0; --k) { sum = y_squared * (1 / (2 * static_cast<double>(k) + 1) + sum); } sum = 2 * y * (1 + sum); // k = 0 term return result + sum; } /* approximate e^x as Taylor series e^x = 1 + x/1! + x^2/2! + x^3/3! +... where N is the order of the Taylor series use https://math.stackexchange.com/a/1988927 to improve convergence for large values larger Factor values improve convergence for all values but reduce the precision */ template<std::size_t N, std::intmax_t Factor = 256> requires gt_zero<Factor> [[nodiscard]] constexpr double constexpr_exp(double v) noexcept { if constexpr (N == 0) { return 1.0; } else { constexpr auto coefficients = []() { std::array<double, N> coeffs; std::size_t factorial = 1; for (std::size_t i = 0; i < N; ++i) { factorial *= i + 1; coeffs[i] = 1.0 / static_cast<double>(factorial); } return coeffs; }(); const double x = v / static_cast<double>(Factor); double result = 0; for (auto i = static_cast<std::intmax_t>(N - 1); i >= 0; --i) { result = x * (coefficients[static_cast<std::size_t>(i)] + result); } // for factors of power of 2 this should be replaced by log2(Factor) multiplications by the compiler return pow_impl<Factor>(1 + result); } } // default template arguments provide reasonable precision even for fairly large exponents // see constexpr_exp for template arguments template<std::size_t ExpOrder = 10, std::intmax_t Factor = 128> [[nodiscard]] constexpr double constexpr_pow(double v, double exponent) noexcept { const double x = exponent * constexpr_log(v); return constexpr_exp<ExpOrder, Factor>(x); } } // namespace units::detail
{ "alphanum_fraction": 0.6089608517, "avg_line_length": 37.2603305785, "ext": "h", "hexsha": "53e4fdf46b79ae0f6000c31fe5fb0c158f6ef171", "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": "112cce1c6521831ec0b0f996c4958432cf5cfb13", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "go2sh/units", "max_forks_repo_path": "src/include/units/bits/constexpr_math.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "112cce1c6521831ec0b0f996c4958432cf5cfb13", "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": "go2sh/units", "max_issues_repo_path": "src/include/units/bits/constexpr_math.h", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "112cce1c6521831ec0b0f996c4958432cf5cfb13", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "go2sh/units", "max_stars_repo_path": "src/include/units/bits/constexpr_math.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3087, "size": 9017 }
#ifndef DEINOS_CHESS_H #define DEINOS_CHESS_H #include <optional> #include <array> #include <vector> #include <string> #include <cassert> #include <iostream> #include <gsl/gsl_assert> #include <cstddef> namespace chess { enum class Almnt : uint8_t; enum class AlRes : uint8_t; enum class GameResult : uint8_t; enum class Side : uint8_t; struct Piece; class Square; struct MoveRecord; class Move; class Position; //Alignment (i.e. White or Black) enum class Almnt : uint8_t {White = 0, Black = 1}; constexpr Almnt operator!(const Almnt& a) {return (a == Almnt::White ? Almnt::Black : Almnt::White);} inline uint8_t as_index(Almnt a) {return static_cast<uint8_t>(a);} //Alignment Result (for cases where "None" is an option) enum class AlRes : uint8_t {White = 0, Black = 1, None = 2}; //Utility to avoid constant Empty checks inline bool operator==(AlRes ar, Almnt a) {return static_cast<uint8_t>(ar) == static_cast<uint8_t>(a);} inline bool operator==(Almnt a, AlRes ar) {return ar == a;} inline bool operator!=(AlRes ar, Almnt a) {return !(ar == a);} inline bool operator!=(Almnt a, AlRes ar) {return !(ar == a);} //Game Result enum class GameResult : uint8_t {White = 0, Black = 1, Draw = 2}; inline float evaluate(GameResult gr) { switch (gr) { case GameResult::White: return 1.0f; case GameResult::Black: return 0.0f; case GameResult::Draw: return 0.5f; default: return 0.5f; } } inline GameResult victory(Almnt a) {return static_cast<GameResult>(a);} inline AlRes victor(GameResult gr) {return static_cast<AlRes>(gr);} //Side of Board enum class Side : uint8_t {Kingside = 0, Queenside = 1}; //The contents of a square (i.e. a chess piece or empty) struct Piece { enum class Type : uint8_t {Empty, Pawn, Knight, Bishop, Rook, Queen, King}; constexpr Piece() = default; constexpr Piece(Almnt a, Type t) : data((static_cast<std::byte>(t) << 1) | static_cast<std::byte>(a)) {} inline AlRes almnt_res() const {return (type() == Type::Empty ? AlRes::None : static_cast<AlRes>(almnt()));} inline Almnt almnt() const {return static_cast<Almnt>(data & std::byte{0x01});} inline Type type() const {return static_cast<Type>(data >> 1);} private: constexpr Piece(uint8_t d) : data(std::byte{d}) {} inline uint8_t raw() const {return static_cast<uint8_t>(data);} std::byte data = std::byte{0}; friend class Position; }; bool operator==(Piece, Piece); bool operator!=(Piece, Piece); std::ostream& operator<<(std::ostream& os, Piece::Type t); std::ostream& operator<<(std::ostream& os, Piece p); //White uppercase, black lowercase //A bounds checked index into a chess position class Square{ public: constexpr Square() = default; constexpr Square(const char* name){ //this must be a zstring TODO constexpr std::array<char, 8> files {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; constexpr std::array<char, 8> ranks {'1', '2', '3', '4', '5', '6', '7', '8'}; uint8_t file = 255; uint8_t rank = 255; for (int i = 0; i < 8; i++) { if (files[i] == name[0]) file = i; if (ranks[i] == name[1]) rank = i; } assert(file != 255); assert(rank != 255); data = (std::byte{rank} << 3) | std::byte{file}; } std::optional<Square> translate(int files, int ranks) const; //TODO consider changing type to int8_t inline uint8_t file() const {return std::to_integer<uint8_t>(data & std::byte{0b00000111});} inline uint8_t rank() const {return std::to_integer<uint8_t>((data & std::byte{0b00111000}) >> 3);} explicit operator std::string () const; private: constexpr Square(uint8_t file, uint8_t rank) : data((std::byte{rank} << 3) | std::byte{file}) { assert(file < 8); assert(rank < 8); } constexpr Square(std::byte d) : data(d) {} //construct from raw data std::byte data = std::byte{0}; friend class MoveRecord; friend bool operator==(Square, Square); }; bool operator==(Square, Square); bool operator!=(Square, Square); constexpr std::array<Square, 64> all_squares { "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", }; //stores information necessary to reconstruct a move from a position struct MoveRecord { private: inline uint8_t promo_index() const {return static_cast<uint8_t>(data2) >> 6;} public: constexpr static std::array<Piece::Type, 4> promo_types {Piece::Type::Knight, Piece::Type::Bishop, Piece::Type::Rook, Piece::Type::Queen}; static_assert(sizeof(Square) == 1); constexpr MoveRecord(Square t_initial, Square t_final) : data1(reinterpret_cast<std::byte&>(t_initial)), data2(reinterpret_cast<std::byte&>(t_final)) {} MoveRecord(Square t_initial, Square t_final, Piece::Type t_promo_type); inline Square initial() const {return Square(data1 & std::byte{0x3F});} inline Square final() const {return Square(data2 & std::byte{0x3F});} inline bool is_promo() const {return (data1 & std::byte{0b11000000}) != std::byte{0};} inline std::optional<Piece::Type> promo_type() const { return is_promo() ? std::make_optional<Piece::Type>(promo_types[promo_index()]) : std::nullopt; }; std::string to_string() const; private: std::byte data1 = std::byte{0}; //initial square and promotion existence flag std::byte data2 = std::byte{0}; //final square and promotion type flag }; bool operator==(const MoveRecord&, const MoveRecord&); inline bool operator!=(const MoveRecord& mr1, const MoveRecord& mr2) {return !(mr1 == mr2);} inline std::ostream& operator<<(std::ostream& os, const MoveRecord& mr) {os << mr.to_string(); return os;} //64 half-byte uints stored in 32B struct HalfByteBoard { private: inline uint8_t get_front(int i) const {return data[i] >> 4;} inline uint8_t get_back(int i) const {return data[i] & 0x0F;} inline void set_front(int i, uint8_t val) {data[i] = (val << 4) | (data[i] & 0x0F);} inline void set_back(int i, uint8_t val) {data[i] = val | (data[i] & 0xF0);} public: inline uint8_t get(int i) const { assert(i >= 0); assert(i < 64); if (i % 2 == 0) return get_front(i / 2); else return get_back(i / 2); } inline uint8_t get(int file, int rank) const {return get(rank * 8 + file);} inline void set(int i, uint8_t val) { assert(i >= 0); assert(i < 64); assert(val <= 0x0F); if (i % 2 == 0) set_front(i / 2, val); else set_back(i / 2, val); } inline void set(int file, int rank, uint8_t val) {set(rank * 8 + file, val);} private: std::array<uint8_t, 32> data = {0}; friend bool operator==(const HalfByteBoard&, const HalfByteBoard&); }; inline bool operator==(const HalfByteBoard& hbb1, const HalfByteBoard& hbb2) {return hbb1.data == hbb2.data;} inline bool operator!=(const HalfByteBoard& hbb1, const HalfByteBoard& hbb2) {return !(hbb1 == hbb2);} //Equivalent to a chess position recorded in Forsyth-Edwards Notaion class Position { public: constexpr Position() = default; Position(const std::string& fen); //construct from FEN representation Position(const Position&, const Move&); //generate new position by applying a move static Position std_start(); //inline Piece& operator[] (Square s) {return m_board[s.file()][s.rank()];} //inline Piece operator[] (Square s) const {return m_board[s.file()][s.rank()];} inline Piece at(Square s) const {return Piece(m_board.get(s.file(), s.rank()));} //inline Piece at(Square s) const {return m_board[s.file()][s.rank()];} inline Piece at(int index) const {return Piece(m_board.get(index));} //inline Piece at(int index) const {return m_board[index % 8][index / 8];} inline void set(Square s, Piece p) {m_board.set(s.file(), s.rank(), p.raw());} //inline void set(Square s, Piece p) {m_board[s.file()][s.rank()] = p;} inline void set(int index, Piece p) {m_board.set(index, p.raw());} //inline void set(int index, Piece p) {m_board[index % 8][index / 8] = p;} inline bool can_castle(Almnt a, Side s) const {return m_castle[(int) a][(int) s];} //TODO use as_index inline bool& mut_castle(Almnt a, Side s){return m_castle[(int) a][(int) s];} inline Almnt to_move() const {return m_to_move;} inline std::optional<Square> en_passant_target() const {return m_en_passant_target;} inline int hm_clock() const {return m_hm_clock;} inline int fm_count() const {return m_fm_count;} std::string as_fen() const; explicit operator std::string() const; friend std::ostream& operator<<(std::ostream& os, const Position& pos); friend bool operator==(const Position&, const Position&); private: static_assert(sizeof(Piece) == 1); HalfByteBoard m_board; //std::array<std::array<Piece, 8>, 8> m_board = {Piece()}; Almnt m_to_move = Almnt::White; std::array<std::array<bool, 2>, 2> m_castle = {{false}}; //"permitted to castle" flags indexed by enum values //std::optional<GameResult> m_result = std::nullopt; std::optional<Square> m_en_passant_target = std::nullopt; short m_hm_clock = 0; short m_fm_count = 1; }; bool operator==(const Position&, const Position&); bool operator!=(const Position&, const Position&); std::ostream& operator<<(std::ostream& os, const Position& pos); //A wrapper for a position and move record, representing a single move class Move { //TODO: test code public: //constexpr Move() = default; //default constructor //Move(Square initial, Square final, Piece moved, Piece captured); //normal move //Move(const Position& pos, const std::string& name); //N.B this constructor does not support castling, promotion or en passant //void set_castling(); //castling 1.must be a king moving 2.must not capture 3.can only set once //void set_promotion(Piece::Type); //pawn promotion //void set_en_passant(); //en_passant constexpr Move(const Position& t_pos, const MoveRecord& t_record) : m_pos(t_pos), m_record(t_record) { if (moved().type() == Piece::Type::Empty) {std::cerr << *this << std::endl << t_pos << std::endl; throw std::exception();} if (captured().almnt_res() == moved().almnt()) {std::cerr << *this << " capt: " << captured() << " mr: " << m_record << std::endl << t_pos << std::endl; throw std::exception();} assert(moved().type() != Piece::Type::Empty); assert(captured().almnt_res() != moved().almnt()); } //inline Square initial_square() const {return m_initial_square;} inline Square initial_sq() const {return m_record.initial();} //inline Square final_square() const {return m_final_square;} inline Square final_sq() const {return m_record.final();} //inline Piece moved_piece() const {return m_moved_piece;} inline Piece moved() const {return m_pos.at(initial_sq());} //inline Piece captured_piece() const {return m_captured_piece;} inline Piece captured() const {return m_pos.at(final_sq());} //returns empty piece if en passant //inline bool is_en_passant() const {return m_is_en_passant;} bool is_en_passant() const; //inline bool is_castling() const {return m_is_castling;} bool is_castling() const; //inline bool is_promotion() const {return m_promoted_to.type() != Piece::Type::Empty;} inline bool is_promotion() const {return m_record.is_promo();} //inline Piece promoted_to() const {return m_promoted_to;} inline std::optional<Piece::Type> promo_type() const {return m_record.promo_type();} inline const MoveRecord& record() const {return m_record;} inline Position apply() const {return Position(m_pos, *this);} explicit operator std::string() const; friend std::ostream& operator<<(std::ostream& os, const Move& mv); std::string to_xboard() const; private: //Square m_initial_square; //Square m_final_square; //Piece m_moved_piece; //Piece m_captured_piece; //Piece m_promoted_to; //bool m_is_castling = false; //bool m_is_en_passant = false; const Position& m_pos; const MoveRecord& m_record; friend bool operator==(const Move&, const Move&); }; bool operator==(const Move&, const Move&); bool operator!=(const Move&, const Move&); std::ostream& operator<<(std::ostream& os, const Move& mv); //std::optional<Move> find_move(const std::string& t_name, const AnalysedPosition& apos); //std::optional<Move> move_from_fen(const std::string& fen, const Position& curr_pos, const std::vector<Move>& moves); } #endif
{ "alphanum_fraction": 0.6731968655, "avg_line_length": 43.8807017544, "ext": "h", "hexsha": "f185d03b60247466e765c3af8551e9fb7efcef0a", "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": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Ayals4/deinos", "max_forks_repo_path": "deinos/chess.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "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": "Ayals4/deinos", "max_issues_repo_path": "deinos/chess.h", "max_line_length": 180, "max_stars_count": 1, "max_stars_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Ayals4/deinos", "max_stars_repo_path": "deinos/chess.h", "max_stars_repo_stars_event_max_datetime": "2020-01-05T00:44:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-05T00:44:30.000Z", "num_tokens": 3812, "size": 12506 }
#include <petsc.h> static PetscErrorCode SetInitialCondition(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){ u[0] = x[0]; return 0; } static PetscErrorCode PrintFVGradients(DM dm){ PetscFunctionBeginUser; PetscErrorCode ierr; // Convert the dm to a plex DM plex; DMConvert(dm, DMPLEX, &plex); // Get the start/end PetscInt fStart; PetscInt fEnd; ierr = DMPlexGetHeightStratum(plex, 1, &fStart, &fEnd);CHKERRQ(ierr); // Extract the cell geometry, and the dm that holds the information Vec faceGeometry; DM dmFace; ierr = DMPlexGetGeometryFVM(plex, &faceGeometry, NULL, NULL);CHKERRQ(ierr); ierr = VecGetDM(faceGeometry, &dmFace);CHKERRQ(ierr); const PetscScalar *facegeom; ierr = VecGetArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr); // Get the dim PetscInt dim; ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr); // March over each cell volume for (PetscInt f = fStart; f < fEnd; ++f) { PetscFVFaceGeom *fg; ierr = DMPlexPointLocalRead(dmFace, f, facegeom, &fg);CHKERRQ(ierr); printf("Face Grad %d: ", f); for(PetscInt d =0; d< dim; d++){ printf("%f/%f, ", fg->grad[0][d], fg->grad[1][d]); } printf("\n"); } PetscFunctionReturn(0); } int main(int argc, char **argv) { DM dm; PetscErrorCode ierr; ierr = PetscInitialize(&argc, &argv, NULL, "HELP");if (ierr) return(ierr); ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, 2, PETSC_FALSE, NULL, NULL, NULL, NULL, PETSC_TRUE, &dm);CHKERRQ(ierr); ierr = DMViewFromOptions(dm, NULL, "-dm_view");CHKERRQ(ierr); ierr = DMSetFromOptions(dm);CHKERRQ(ierr); { DM gdm; ierr = DMPlexConstructGhostCells(dm, NULL, NULL, &gdm);CHKERRQ(ierr); ierr = DMDestroy(&dm);CHKERRQ(ierr); dm = gdm; } ierr = DMViewFromOptions(dm, NULL, "-dm_view_ghost");CHKERRQ(ierr); PetscFV fvm; PetscDS ds; ierr = PetscFVCreate(PETSC_COMM_WORLD, &fvm);CHKERRQ(ierr); ierr = PetscFVSetFromOptions(fvm);CHKERRQ(ierr); ierr = PetscFVSetNumComponents(fvm, 1);CHKERRQ(ierr); ierr = PetscFVSetSpatialDimension(fvm, 2);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) fvm, "outputField");CHKERRQ(ierr); /* FV is now structured with one field having all physics as components */ ierr = DMAddField(dm, NULL, (PetscObject) fvm);CHKERRQ(ierr); ierr = PetscFVDestroy(&fvm);CHKERRQ(ierr); ierr = DMCreateDS(dm);CHKERRQ(ierr); ierr = DMGetDS(dm, &ds);CHKERRQ(ierr); Vec X; PetscErrorCode (*func[1]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetInitialCondition}; ierr = DMCreateGlobalVector(dm, &X);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) X, "solution");CHKERRQ(ierr); ierr = DMProjectFunction(dm, 0.0, func, NULL, INSERT_ALL_VALUES, X);CHKERRQ(ierr); ierr = VecViewFromOptions(X, NULL, "-vec_view");CHKERRQ(ierr); PrintFVGradients(dm); ierr = VecDestroy(&X);CHKERRQ(ierr); ierr = DMDestroy(&dm);CHKERRQ(ierr); return PetscFinalize(); }
{ "alphanum_fraction": 0.6513075965, "avg_line_length": 31.801980198, "ext": "c", "hexsha": "2fcf99d20c7ccbf6fa018e91ada2371d3b07b4d7", "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": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_path": "fvOutput.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "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": "mmcgurn/MattFlowCases", "max_issues_repo_path": "fvOutput.c", "max_line_length": 150, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_path": "fvOutput.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 924, "size": 3212 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_cswap (const int N, void *X, const int incX, void *Y, const int incY) { #define BASE float #include "source_swap_c.h" #undef BASE }
{ "alphanum_fraction": 0.7169811321, "avg_line_length": 17.6666666667, "ext": "c", "hexsha": "a965a3ce622e77632bac3d2e5a7a99e71dcbcbd5", "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/cswap.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/cswap.c", "max_line_length": 75, "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/cswap.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": 68, "size": 212 }