Search is not available for this dataset
text
string
meta
dict
#ifndef SurrogateHeatFluidDriver_h #define SurrogateHeatFluidDriver_h #include <memory> #include <vector> #include "Teuchos_ParameterList.hpp" #include "Teuchos_RCP.hpp" #include <gsl/gsl> #include "Assembly_Model.h" #include "Single_Pin_Subchannel.h" #include "Single_Pin_Conduction.h" namespace enrico { //! Driver for coupled subchannel/heat conduction simulations. This driver //! decouples the fluid and solid phase in an explicit manner (i.e. no //! iteration between the convective heat transfer linking the phases within //! a single solve), which is sufficient given that this project targets //! steady-state simulations via fixed point iteration. class SurrogateHeatFluidDriver { public: //@{ //! Typedefs using SP_Assembly = std::shared_ptr<Assembly_Model>; using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>; //@} //! solve the thermal-hydraulic problem for the fluid and solid phases //! for a given power distribution void solve(const std::vector<double>& powers); //! fluid temperature virtual std::vector<double> fluid_temperature() const { return d_pin_temps; } //! fluid density virtual std::vector<double> density() const { return d_pin_densities; } //! solid temperature virtual std::vector<double> solid_temperature() const { return d_solid_temps; } double pressure_bc_; //! System pressure in [MPa] private: // >>> DATA SP_Assembly d_assembly; // Note that for channel-centered equations, Nx and Ny are one greater // than number of pins in each direction. int d_Nx, d_Ny, d_Nz; // Cross sectional area of each channel std::vector<double> d_areas; // Mass flow rate (kg/s) in each channel std::vector<double> d_mdots; //! subchannel solver for a single channel std::unique_ptr<Single_Pin_Subchannel> d_pin_subchannel; //! heat conduction solver for a single rod std::unique_ptr<Single_Pin_Conduction> d_pin_conduction; //! coolant temperature in [K] for each channel, of total length given by the //! product of the number of pins by the number of axial cells std::vector<double> d_pin_temps; //! coolant density in [g/cm^3] for each channel, of total length given by the //! product of the number of pins by the number of axial cells std::vector<double> d_pin_densities; //! solid temperature in [K] std::vector<double> d_solid_temps; public: // Constructor SurrogateHeatFluidDriver(SP_Assembly assembly, RCP_PL subchannel_params, RCP_PL conduction_params, const std::vector<double>& dz); //! heat source std::vector<double> d_pin_powers; private: //! Set up the sizes of solution arrays void generate_arrays(); int channel_index(int ix, int iy) const { Expects(ix < d_Nx); Expects(iy < d_Ny); return ix + d_Nx * iy; } // Solve the fluid flow equations void solve_fluid(const std::vector<double>& power); // Solve the solid equations void solve_heat(const std::vector<double>& power, const std::vector<double>& channel_temp, std::vector<double>& fuel_temp); }; //---------------------------------------------------------------------------// } // end namespace enrico //---------------------------------------------------------------------------// #endif // SurrogateHeatFluidDriver_h //---------------------------------------------------------------------------// // end of SurrogateHeatFluidDriver.h //---------------------------------------------------------------------------//
{ "alphanum_fraction": 0.6527422563, "avg_line_length": 30.6, "ext": "h", "hexsha": "f7d8355ba4fb251fcd2d83006e447117d0ba3c7f", "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": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sphamil/enrico", "max_forks_repo_path": "include/smrt/surrogate_heat_fluid_driver.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "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": "sphamil/enrico", "max_issues_repo_path": "include/smrt/surrogate_heat_fluid_driver.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sphamil/enrico", "max_stars_repo_path": "include/smrt/surrogate_heat_fluid_driver.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 796, "size": 3519 }
#include <stdio.h> #include <gsl/gsl_spline.h> void spline_interp(long data_size, long out_size, \ double *data_x, double *data_y, \ double *out_x, double *out_y) { // initialize gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, data_size); gsl_spline_init(spline, data_x, data_y, data_size); // evaluate int ii; for (ii=0; ii < out_size; ii++) { out_y[ii] = gsl_spline_eval (spline, out_x[ii], acc); } // free memory gsl_spline_free(spline); gsl_interp_accel_free(acc); }
{ "alphanum_fraction": 0.6567656766, "avg_line_length": 26.347826087, "ext": "c", "hexsha": "c82e728105b6e60147d57cd7309a6e171c3be763", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2022-01-25T10:17:02.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-05T20:00:00.000Z", "max_forks_repo_head_hexsha": "1459f8e6a855d183a4a3b08e4fcd36d2d14f5285", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jyoo1042/gwsurrogate", "max_forks_repo_path": "gwsurrogate/spline_interp_Cwrapper/_spline_interp.c", "max_issues_count": 23, "max_issues_repo_head_hexsha": "1459f8e6a855d183a4a3b08e4fcd36d2d14f5285", "max_issues_repo_issues_event_max_datetime": "2022-02-02T09:35:08.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-24T07:39:21.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jyoo1042/gwsurrogate", "max_issues_repo_path": "gwsurrogate/spline_interp_Cwrapper/_spline_interp.c", "max_line_length": 76, "max_stars_count": 11, "max_stars_repo_head_hexsha": "d32fbd4506c664ab7b7c6048edbd51835b17b644", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thompsonphys/gwsurrogate", "max_stars_repo_path": "gwsurrogate/spline_interp_Cwrapper/_spline_interp.c", "max_stars_repo_stars_event_max_datetime": "2021-11-01T07:40:04.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-11T12:52:52.000Z", "num_tokens": 172, "size": 606 }
#ifndef __Q_INCS #define __Q_INCS #include <alloca.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <float.h> // #include <gsl/gsl_vector.h> // #include <gsl/gsl_matrix.h> // #include <gsl/gsl_blas.h> // #include <gsl/gsl_linalg.h> #include <inttypes.h> #include <limits.h> // TODO P4 do not think this is needed:#include <malloc.h> #include <math.h> #include <memory.h> #include <omp.h> #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #ifndef MAC_OSX // TODO P1 Is this needed?#include <sys/sysinfo.h> #endif #include <sys/time.h> #include <time.h> #include <unistd.h> #include "q_macros.h" #endif
{ "alphanum_fraction": 0.7006622517, "avg_line_length": 21.5714285714, "ext": "h", "hexsha": "e8002a17807ccfc6e4436a08bc56fe64386b947a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "subramon/qlu", "max_forks_repo_path": "UTILS/inc/q_incs.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "subramon/qlu", "max_issues_repo_path": "UTILS/inc/q_incs.h", "max_line_length": 58, "max_stars_count": null, "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "subramon/qlu", "max_stars_repo_path": "UTILS/inc/q_incs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 220, "size": 755 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" /*! \file snIa_heating.c * \brief routines for heating by type Ia supernovae */ #if defined(SNIA_HEATING) static struct snheatingdata_in { MyDouble Pos[3]; MyFloat Density; MyFloat Energy; MyFloat Hsml; int NodeList[NODELISTLENGTH]; } *SnheatingdataIn, *SnheatingdataGet; static double hubble_a, ascale, a3inv; void snIa_heating(void) { int i, j, k; int ndone_flag, ndone; int ngrp, sendTask, recvTask, place, nexport, nimport, dummy; double dt; MPI_Status status; if(ThisTask == 0) { printf("Beginning snIa heating\n"); fflush(stdout); } CPU_Step[CPU_MISC] += measure_time(); if(All.ComovingIntegrationOn) { ascale = All.Time; a3inv = 1.0 / (ascale * ascale * ascale); hubble_a = hubble_function(All.Time); } else hubble_a = ascale = a3inv = 1; /* allocate buffers to arrange communication */ Ngblist = (int *) mymalloc(NumPart * sizeof(int)); All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + 2 * sizeof(struct snheatingdata_in))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); /** Let's first spread the feedback energy */ i = FirstActiveParticle; /* first particle for this task */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ for(nexport = 0; i >= 0; i = NextActiveParticle[i]) if(P[i].Type == 4) if(snIaheating_evaluate(i, 0, &nexport, Send_count) < 0) break; #ifdef MYSORT mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); #else qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); #endif MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++) { Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask]; nimport += Recv_count[j]; if(j > 0) { Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1]; } } SnheatingdataGet = (struct snheatingdata_in *) mymalloc(nimport * sizeof(struct snheatingdata_in)); SnheatingdataIn = (struct snheatingdata_in *) mymalloc(nexport * sizeof(struct snheatingdata_in)); for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; for(k = 0; k < 3; k++) SnheatingdataIn[j].Pos[k] = P[place].Pos[k]; SnheatingdataIn[j].Hsml = PPP[place].Hsml; SnheatingdataIn[j].Density = P[place].DensAroundStar; dt = (P[place].TimeBin ? (1 << P[place].TimeBin) : 0) * All.Timebase_interval / hubble_a; SnheatingdataIn[j].Energy = All.SnIaHeatingRate * dt * P[place].Mass; memcpy(SnheatingdataIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange particle data */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* get the particles */ MPI_Sendrecv(&SnheatingdataIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct snheatingdata_in), MPI_BYTE, recvTask, TAG_DENS_A, &SnheatingdataGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct snheatingdata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, &status); } } } myfree(SnheatingdataIn); /* now do the particles that were sent to us */ for(j = 0; j < nimport; j++) snIaheating_evaluate(j, 1, &dummy, &dummy); if(i < 0) ndone_flag = 1; else ndone_flag = 0; MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); myfree(SnheatingdataGet); } while(ndone < NTask); myfree(DataNodeList); myfree(DataIndexTable); myfree(Ngblist); CPU_Step[CPU_COOLINGSFR] += measure_time(); } int snIaheating_evaluate(int target, int mode, int *nexport, int *nsend_local) { int startnode, numngb, j, n, listindex = 0; MyFloat *pos, h_i, dt, rho; double dx, dy, dz, h_i2, r2, r, u, hinv, hinv3, wk, energy, egy; if(mode == 0) { pos = P[target].Pos; rho = P[target].DensAroundStar; dt = (P[target].TimeBin ? (1 << P[target].TimeBin) : 0) * All.Timebase_interval / hubble_a; energy = All.SnIaHeatingRate * dt * P[target].Mass; h_i = PPP[target].Hsml; } else { pos = SnheatingdataGet[target].Pos; rho = SnheatingdataGet[target].Density; energy = SnheatingdataGet[target].Energy; h_i = SnheatingdataGet[target].Hsml; } /* initialize variables before SPH loop is started */ h_i2 = h_i * h_i; /* Now start the actual SPH computation for this particle */ if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = SnheatingdataGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } while(startnode >= 0) { while(startnode >= 0) { numngb = ngb_treefind_variable(pos, h_i, target, &startnode, mode, nexport, nsend_local); if(numngb < 0) return -1; for(n = 0; n < numngb; n++) { j = Ngblist[n]; if(P[j].Type == 0 && P[j].Mass > 0) { dx = pos[0] - P[j].Pos[0]; dy = pos[1] - P[j].Pos[1]; dz = pos[2] - P[j].Pos[2]; #ifdef PERIODIC /* now find the closest image in the given box size */ if(dx > boxHalf_X) dx -= boxSize_X; if(dx < -boxHalf_X) dx += boxSize_X; if(dy > boxHalf_Y) dy -= boxSize_Y; if(dy < -boxHalf_Y) dy += boxSize_Y; if(dz > boxHalf_Z) dz -= boxSize_Z; if(dz < -boxHalf_Z) dz += boxSize_Z; #endif r2 = dx * dx + dy * dy + dz * dz; if(r2 < h_i2) { r = sqrt(r2); hinv = 1 / h_i; #ifndef TWODIMS hinv3 = hinv * hinv * hinv; #else hinv3 = hinv * hinv / boxSize_Z; #endif u = r * hinv; if(u < 0.5) wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u); else wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u); egy = P[j].Mass * wk / rho * energy; SphP[j].Entropy += egy / P[j].Mass * GAMMA_MINUS1 / pow(SphP[j].d.Density * a3inv, GAMMA_MINUS1); } } } } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = SnheatingdataGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } return 0; } #endif
{ "alphanum_fraction": 0.6099789178, "avg_line_length": 23.2516339869, "ext": "c", "hexsha": "b5d51237ff4148fff3e8a989da2e6e63585ce2ed", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/snIa_heating.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/snIa_heating.c", "max_line_length": 105, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/snIa_heating.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2304, "size": 7115 }
#include "q_incs.h" #include <lapacke.h> #include "eigenvectors.h" int eigenvectors( uint64_t n, double *W, double *A, double **X ) { int status = 0; char jobz = 'V'; /*want eigenvectors, use 'N' for eigenvalues only*/ char uplo = 'U'; /*'U' for upper triangle of X, L for lower triangle of X*/ int N = n; int LDA = N; /* dimensions of X = LDA by N*/ for (uint64_t i = 0; i < n; i++ ) { for (uint64_t j = 0; j < n; j++ ) { A[i * n + j] = X[i][j]; } } status = LAPACKE_dsyev(LAPACK_COL_MAJOR, jobz, uplo, N, A, LDA, W); return status; }
{ "alphanum_fraction": 0.5171875, "avg_line_length": 22.0689655172, "ext": "c", "hexsha": "af05da0d24845d91e2eb24735b1b0e4094ba8bd9", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "subramon/qlu", "max_forks_repo_path": "OPERATORS/PCA/src/eigenvectors.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "subramon/qlu", "max_issues_repo_path": "OPERATORS/PCA/src/eigenvectors.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "subramon/qlu", "max_stars_repo_path": "OPERATORS/PCA/src/eigenvectors.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 225, "size": 640 }
/* statistics/gsl_statistics_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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_STATISTICS_DOUBLE_H__ #define __GSL_STATISTICS_DOUBLE_H__ #include <stddef.h> #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS GSL_EXPORT double gsl_stats_mean (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_variance (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_sd (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_variance_with_fixed_mean (const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_sd_with_fixed_mean (const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_absdev (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_skew (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_kurtosis (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_lag1_autocorrelation (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_covariance (const double data1[], const size_t stride1,const double data2[], const size_t stride2, const size_t n); GSL_EXPORT double gsl_stats_variance_m (const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_sd_m (const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_absdev_m (const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_skew_m_sd (const double data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_kurtosis_m_sd (const double data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_lag1_autocorrelation_m (const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_covariance_m (const double data1[], const size_t stride1,const double data2[], const size_t stride2, const size_t n, const double mean1, const double mean2); /* DEFINED FOR FLOATING POINT TYPES ONLY */ GSL_EXPORT double gsl_stats_wmean (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_wvariance (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_wsd (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_wvariance_with_fixed_mean (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_wsd_with_fixed_mean (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_wabsdev (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_wskew (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_wkurtosis (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_wvariance_m (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double wmean); GSL_EXPORT double gsl_stats_wsd_m (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double wmean); GSL_EXPORT double gsl_stats_wabsdev_m (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double wmean); GSL_EXPORT double gsl_stats_wskew_m_sd (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double wmean, const double wsd); GSL_EXPORT double gsl_stats_wkurtosis_m_sd (const double w[], const size_t wstride, const double data[], const size_t stride, const size_t n, const double wmean, const double wsd); /* END OF FLOATING POINT TYPES */ GSL_EXPORT double gsl_stats_pvariance (const double data1[], const size_t stride1, const size_t n1, const double data2[], const size_t stride2, const size_t n2); GSL_EXPORT double gsl_stats_ttest (const double data1[], const size_t stride1, const size_t n1, const double data2[], const size_t stride2, const size_t n2); GSL_EXPORT double gsl_stats_max (const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_min (const double data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_minmax (double * min, double * max, const double data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_max_index (const double data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_min_index (const double data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_minmax_index (size_t * min_index, size_t * max_index, const double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_median_from_sorted_data (const double sorted_data[], const size_t stride, const size_t n) ; GSL_EXPORT double gsl_stats_quantile_from_sorted_data (const double sorted_data[], const size_t stride, const size_t n, const double f) ; __END_DECLS #endif /* __GSL_STATISTICS_DOUBLE_H__ */
{ "alphanum_fraction": 0.7881200245, "avg_line_length": 68.7578947368, "ext": "h", "hexsha": "43074e9f0faa38d2856f3cc6e0ccf7b877044834", "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_statistics_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_statistics_double.h", "max_line_length": 185, "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_statistics_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1613, "size": 6532 }
#ifndef __INTEGRAL_H__ #define __INTEGRAL_H__ #include "integral.h" #endif #ifndef __GSLEXTRA_H__ #define __GSLEXTRA_H__ #include "../include/gslextra.h" #endif #ifndef __GSLPRINT_H__ #define __GSLPRINT_H__ #include "../include/gslprint.h" #endif #include <gsl/gsl_eigen.h> // calculate the attraction energy matrix element (Z integral) double nuclear_attraction_energy_matrix_element(orbital * a, orbital * b, atomic_orbital * atom_HEAD); // calculate the single electron hamiltonian matrix (core hamiltonian matrix) element double single_electron_hamiltonian_matrix_element(orbital * a, orbital * b, atomic_orbital * atom_HEAD); // calculate the fock matrix element double fock_matrix_element(gsl_quad_tensor * v, gsl_matrix * density_matrix, gsl_matrix * h_matrix, int i, int j, int length); // calculate the Hartree-Fock energy of the system double HF_energy(gsl_quad_tensor * v, gsl_matrix * density_matrix, gsl_matrix * h_matrix, int length); // calculate the kinetic energy matrix void kinetic_energy_matrix(gsl_matrix * dest, orbital * HEAD, int length); // calculate the attraction energy matrix (Z integrals) void nuclear_attraction_energy_matrix(gsl_matrix * dest, orbital * HEAD, atomic_orbital * atom_HEAD, int length); // calculate the single electron hamiltonian matrix (core hamiltonian matrix) void core_hamiltonian_matrix(gsl_matrix * dest, orbital * HEAD, atomic_orbital * atom_HEAD, int length); //obtain the quad tensor of the two-electron Coulomb integrals void two_electron_quad_tensor(gsl_quad_tensor * dest, orbital * HEAD, int length); //obtain the fock matrix void fock_matrix(gsl_matrix * dest, gsl_quad_tensor * v, gsl_matrix * density_matrix, gsl_matrix * h_matrix, int length); // perform initial guess of the coefficient matrix by performing diagonalization of core hamiltonian matrix void initial_guess(gsl_matrix * dest, gsl_matrix * core_hamiltonian, gsl_matrix * S, int length); // calculate density matrix from coefficient matrix and the number of electrons void density_matrix(gsl_matrix * dest, gsl_matrix * coef, int el_num, int length); //perform RHF as well as printing information int RHF_SCF_print(double * tot_energy, gsl_vector * energy, gsl_matrix * coef, orbital * HEAD, atomic_orbital * atom_HEAD, int length, int el_num, int iteration_max, double errmax, int countmax, double alpha, int mixing_type, int SCF_INITIAL_FLAG, int SCF_FOCK_FLAG, int SCF_COEF_FLAG, int FOCK_FLAG); //calculate the nuclei repulsion energy double nuclei_repulsion(atomic_orbital * atomlist_HEAD);
{ "alphanum_fraction": 0.7980314961, "avg_line_length": 46.1818181818, "ext": "h", "hexsha": "7543a96b4e9681c54f1a84790f15e5a75721d91e", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-10-16T03:11:07.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-18T13:50:13.000Z", "max_forks_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Walter-Feng/Hartree-Fock", "max_forks_repo_path": "include/RHF.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "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": "Walter-Feng/Hartree-Fock", "max_issues_repo_path": "include/RHF.h", "max_line_length": 301, "max_stars_count": 7, "max_stars_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Walter-Feng/Hartree-Fock", "max_stars_repo_path": "include/RHF.h", "max_stars_repo_stars_event_max_datetime": "2022-03-23T18:50:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-23T21:27:21.000Z", "num_tokens": 616, "size": 2540 }
#pragma once #include "exp_curve_fitter.h" #include "optimizer_job.h" #include "random_utils.h" #include "schedule_params.h" #include <gsl/gsl-lite.hpp> #include <vector> namespace angonoka::stun { /** How many iterations without improvement before considering optimization complete. */ enum class MaxIdleIters : std::int_fast32_t; /** Optimization algorithm based on stochastic tunneling. This is the primary facade for doing stochastic tunneling optimization. */ class Optimizer { public: /** Constructor. @param params Scheduling parameters @param batch_size Number of iterations per update @param max_idle_iters Stopping condition */ Optimizer( const ScheduleParams& params, BatchSize batch_size, MaxIdleIters max_idle_iters); /** Run stochastic tunneling optimization batch. Does batch_size number of iterations and adjusts the estimated progress accordingly. */ void update() noexcept; /** Checks if the stopping condition has been met. @return True when further improvements are unlikely */ [[nodiscard]] bool has_converged() const noexcept; /** Estimated optimization progress from 0.0 to 1.0. @return Progress from 0.0 to 1.0 */ [[nodiscard]] float estimated_progress() const noexcept; /** The best schedule so far. @return A schedule. */ [[nodiscard]] Schedule schedule() const; /** The best makespan so far. @return Makespan. */ [[nodiscard]] float normalized_makespan() const; /** Reset the optimization to initial state. */ void reset(); /** Get the current ScheduleParams object. @return Schedule parameters. */ [[nodiscard]] const ScheduleParams& params() const; /** Set the ScheduleParams object. @param params ScheduleParams object */ void params(const ScheduleParams& params); private: struct Impl; int16 batch_size; int16 max_idle_iters; int16 idle_iters{0}; int16 epochs{0}; float last_progress{0.F}; float last_makespan{0.F}; ExpCurveFitter exp_curve; /** An optimization job and a PRNG. @var random_utils Random number generator utilities @var job Optimization job */ struct Job { /** Constructor. @param params Scheduling parameters @param batch_size Number of iterations per update */ Job(const ScheduleParams& params, BatchSize batch_size); RandomUtils random_utils; OptimizerJob job; }; std::vector<Job> jobs; }; } // namespace angonoka::stun
{ "alphanum_fraction": 0.6299606721, "avg_line_length": 22.7398373984, "ext": "h", "hexsha": "5af8326b86d9cf57d283c530fba41dbb5bec1719", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_path": "src/stun/optimizer.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_path": "src/stun/optimizer.h", "max_line_length": 70, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_path": "src/stun/optimizer.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "num_tokens": 593, "size": 2797 }
/* multimin/diff.c * * Copyright (C) 2000 David Morrison * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_multimin.h> int gsl_multimin_diff (const gsl_multimin_function * f, const gsl_vector * x, gsl_vector * g) { size_t i, n = f->n; double h = GSL_SQRT_DBL_EPSILON; gsl_vector * x1 = gsl_vector_alloc (n); /* FIXME: pass as argument */ gsl_vector_memcpy (x1, x); for (i = 0; i < n; i++) { double fl, fh; double xi = gsl_vector_get (x, i); double dx = fabs(xi) * h; if (dx == 0.0) dx = h; gsl_vector_set (x1, i, xi + dx); fh = GSL_MULTIMIN_FN_EVAL(f, x1); gsl_vector_set (x1, i, xi - dx); fl = GSL_MULTIMIN_FN_EVAL(f, x1); gsl_vector_set (x1, i, xi); gsl_vector_set (g, i, (fh - fl) / (2.0 * dx)); } gsl_vector_free (x1); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6536030341, "avg_line_length": 26.813559322, "ext": "c", "hexsha": "f6937245206c3ee9768445df93e6b6293fbab307", "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/multimin/diff.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/multimin/diff.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/multimin/diff.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": 451, "size": 1582 }
#include <stdio.h> //#ifndef DARWIN //#include <malloc.h> //#endif #include <stddef.h> #include <Python.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <string.h> #include <math.h> /* void inplace(double* npyArray3D, int npyLength1D, int npylength2D, int npylength2D, double* invec, int n) { int i; for (i=0; i<n; i++) { invec[i] = npyArray3D[i]; } } */ int print_matrix(FILE *f, const gsl_matrix *m) { int status, n = 0; for (size_t i = 0; i < m->size1; i++) { for (size_t j = 0; j < m->size2; j++) { if ((status = fprintf(f,"%g ", gsl_matrix_get(m, i, j))) < 0) return -1; n += status; } if ((status = fprintf(f, "\n")) < 0) return -1; n += status; } return n; } int print_vector(FILE *f, const gsl_vector *m) { int status, n = 0; for (size_t i = 0; i < m->size; i++) { if ((status = fprintf(f, "%g ", gsl_vector_get(m, i))) < 0) return -1; n += status; } return n; } void print_mat(double* mat, int dim1, int dim2) { int i, j; printf("\n"); for (i=0; i<dim1; i++) { for (j=0; j<dim2; j++) { printf("%6.2f,", mat[i*dim1 + j]); } printf("\n"); } } void print_vec(double* vec, int dim1) { int i; printf("\n"); for (i=0; i<dim1; i++) { printf("%6.2f,", vec[i]); } printf("\n"); } int sum(int* npyArray3D, int npyLength1D, int npyLength2D, int npyLength3D) { int i, j, k; int sum = 0; for (i=0; i<npyLength1D; i++) for (j=0; j<npyLength2D; j++) for (k=0; k<npyLength3D; k++) sum += npyArray3D[i*npyLength3D*npyLength2D + k*npyLength2D + j]; return sum; } double get_det(PyObject *A) { int MAT_DIM = 6; int i, signum; double det; int nInts = PyList_Size(A); gsl_matrix *m = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_permutation *p; p = gsl_permutation_alloc(m->size1); for (i=0; i<nInts; i++) { PyObject *oo = PyList_GetItem(A, i); //printf("%6.2f\n",PyFloat_AS_DOUBLE(oo)); gsl_matrix_set (m, i%MAT_DIM, i/MAT_DIM, PyFloat_AS_DOUBLE(oo)); } gsl_linalg_LU_decomp(m, p, &signum); det = gsl_linalg_LU_det(m, signum); //printf("%6.2f\n",det); return det; } double get_overlap(double* gr_icov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double gr_icov_det, double* st_icov, int st_dim1, int st_dim2, double* st_mn, int st_mn_dim, double st_icov_det) { int MAT_DIM = gr_dim1; int i, j, signum; double ApB_det, d_temp, result; gsl_permutation *p; gsl_matrix *A = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *B = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *ApB = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_vector *a = gsl_vector_alloc(MAT_DIM); gsl_vector *b = gsl_vector_alloc(MAT_DIM); gsl_vector *AapBb = gsl_vector_alloc(MAT_DIM); gsl_vector *c = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp2 = gsl_vector_alloc(MAT_DIM); gsl_vector *amc = gsl_vector_alloc(MAT_DIM); //will hold a - c gsl_vector *bmc = gsl_vector_alloc(MAT_DIM); //will hold b - c p = gsl_permutation_alloc(A->size1); //for (l=0; l<1; l++){ //DELETE //Inserting values into matricies and vectors for (i=0; i<MAT_DIM; i++) { for (j=0; j<MAT_DIM; j++) { gsl_matrix_set (A, i, j, gr_icov[i*MAT_DIM + j]); gsl_matrix_set (B, i, j, st_icov[i*MAT_DIM + j]); } } for (i=0; i<MAT_DIM; i++) { gsl_vector_set (a, i, gr_mn[i]); gsl_vector_set (b, i, st_mn[i]); } // Adding A and B together and storing in ApB gsl_matrix_set_zero(ApB); gsl_matrix_add(ApB, A); gsl_matrix_add(ApB, B); // Storing the result A*a + B*b in AapBb gsl_vector_set_zero(AapBb); gsl_blas_dsymv(CblasUpper, 1.0, A, a, 1.0, AapBb); gsl_blas_dsymv(CblasUpper, 1.0, B, b, 1.0, AapBb); // Getting determinant of ApB gsl_linalg_LU_decomp(ApB, p, &signum); //ApB_det = gsl_linalg_LU_det(ApB, signum); ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant // Solve for c gsl_linalg_LU_solve(ApB, p, AapBb, c); // Compute the overlap formula gsl_vector_set_zero(v_temp); gsl_blas_dcopy(a, v_temp); //v_temp holds a gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c gsl_blas_dcopy(v_temp, amc); //amc holds a - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, A, v_temp, 0.0, v_temp2); //v_temp2 holds A (a-c) result = 0.0; gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c) result += d_temp; gsl_vector_set_zero(v_temp); gsl_blas_dcopy(b, v_temp); //v_temp holds b gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c gsl_blas_dcopy(v_temp, bmc); //bmc holds b - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, B, v_temp, 0.0, v_temp2); //v_temp2 holds A (b-c) gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c) result += d_temp; result = -0.5 * result; result = exp(result); result *= sqrt((gr_icov_det * st_icov_det/ApB_det) / pow(2*M_PI, MAT_DIM)); //} //DELETE THIS // Freeing memory gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(ApB); gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(AapBb); gsl_vector_free(c); gsl_vector_free(v_temp); gsl_vector_free(v_temp2); gsl_vector_free(amc); gsl_vector_free(bmc); gsl_permutation_free(p); return result; } double get_overlap2(PyObject *gr_icov, PyObject *gr_mn, double gr_icov_det, PyObject *st_icov, PyObject *st_mn, double st_icov_det) { int MAT_DIM = 6; int i, j, signum; double ApB_det, d_temp, result; PyObject *o1, *o2; gsl_permutation *p; gsl_matrix *A = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *B = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *ApB = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_vector *a = gsl_vector_alloc(MAT_DIM); gsl_vector *b = gsl_vector_alloc(MAT_DIM); gsl_vector *AapBb = gsl_vector_alloc(MAT_DIM); gsl_vector *c = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp2 = gsl_vector_alloc(MAT_DIM); gsl_vector *amc = gsl_vector_alloc(MAT_DIM); //will hold a - c gsl_vector *bmc = gsl_vector_alloc(MAT_DIM); //will hold b - c p = gsl_permutation_alloc(A->size1); //Inserting values into matricies and vectors for (i=0; i<MAT_DIM; i++) { for (j=0; j<MAT_DIM; j++) { o1 = PyList_GetItem(gr_icov, i*MAT_DIM + j); gsl_matrix_set (A, i, j, PyFloat_AS_DOUBLE(o1)); o2 = PyList_GetItem(st_icov, i*MAT_DIM + j); gsl_matrix_set (B, i, j, PyFloat_AS_DOUBLE(o2)); } } for (i=0; i<MAT_DIM; i++) { o1 = PyList_GetItem(gr_mn, i); gsl_vector_set (a, i, PyFloat_AS_DOUBLE(o1)); o2 = PyList_GetItem(st_mn, i); gsl_vector_set (b, i, PyFloat_AS_DOUBLE(o2)); } // Adding A and B together and storing in ApB gsl_matrix_set_zero(ApB); gsl_matrix_add(ApB, A); gsl_matrix_add(ApB, B); // Storing the result A*a + B*b in AapBb gsl_vector_set_zero(AapBb); gsl_blas_dgemv(CblasNoTrans, 1.0, A, a, 1.0, AapBb); gsl_blas_dgemv(CblasNoTrans, 1.0, B, b, 1.0, AapBb); // Getting determinant of ApB gsl_linalg_LU_decomp(ApB, p, &signum); //ApB_det = gsl_linalg_LU_det(ApB, signum); ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant // Solve for c gsl_linalg_LU_solve(ApB, p, AapBb, c); // Compute the overlap formula gsl_vector_set_zero(v_temp); gsl_blas_dcopy(a, v_temp); //v_temp holds a gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c gsl_blas_dcopy(v_temp, amc); //amc holds a - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dgemv(CblasNoTrans, 1.0, A, v_temp, 0.0, v_temp2); //v_temp2 holds A (a-c) result = 0.0; gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c) result += d_temp; gsl_vector_set_zero(v_temp); gsl_blas_dcopy(b, v_temp); //v_temp holds b gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c gsl_blas_dcopy(v_temp, bmc); //bmc holds b - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dgemv(CblasNoTrans, 1.0, B, v_temp, 0.0, v_temp2); //v_temp2 holds A (b-c) gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c) result += d_temp; result = -0.5 * result; result = exp(result); result *= sqrt((gr_icov_det * st_icov_det/ApB_det) / pow(2*M_PI, MAT_DIM)); // Freeing memory gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(ApB); gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(AapBb); gsl_vector_free(c); gsl_vector_free(v_temp); gsl_vector_free(v_temp2); gsl_vector_free(amc); gsl_vector_free(bmc); gsl_permutation_free(p); return result; } /* Main function which performs fastest so far: * --parameters-- * group_icov (6*6 npyArray) the group's inverse covariance matrix * group_mn (1*6 npyArray) which is the group's mean kinematic info * group_icov_det (flt) the determinent of the group_icov * Bs (nstars*6*6) an array of each star's icov matrix * bs: (nstars*6) an array of each star's mean kinematic info * B_dets: (nstars) an array of the determinent of each icov * nstars: (int) number of stars, used to determine the size * of npyArray which will return calculated overlaps) * * returns: (nstars) array of calculated overlaps of every star with 1 group * * todo: instead of calling internal function actually use cblas functions * this will save time on the reallocation and deallocation */ void get_overlaps(double* gr_icov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double gr_icov_det, double* st_icovs, int st_dim1, int st_dim2, int st_dim3, double* st_mns, int st_mn_dim1, int st_mn_dim2, double* st_icov_dets, int st_icov_dets_dim, double* rangevec, int n) { // ALLOCATE MEMORY int star_count = 0; int MAT_DIM = gr_dim1; //Typically set to 6 int i, j, signum; double ApB_det, d_temp, result; gsl_permutation *p; gsl_matrix *A = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *B = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *ApB = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_vector *a = gsl_vector_alloc(MAT_DIM); gsl_vector *b = gsl_vector_alloc(MAT_DIM); gsl_vector *AapBb = gsl_vector_alloc(MAT_DIM); gsl_vector *c = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp2 = gsl_vector_alloc(MAT_DIM); gsl_vector *amc = gsl_vector_alloc(MAT_DIM); //will hold a - c gsl_vector *bmc = gsl_vector_alloc(MAT_DIM); //will hold b - c p = gsl_permutation_alloc(A->size1); // INITIALISE GROUP MATRICES for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) gsl_matrix_set (A, i, j, gr_icov[i*MAT_DIM + j]); for (i=0; i<MAT_DIM; i++) gsl_vector_set (a, i, gr_mn[i]); for (star_count=0; star_count<n; star_count++) { // INITIALISE STAR MATRICES for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) gsl_matrix_set(B,i,j, st_icovs[star_count*MAT_DIM*MAT_DIM+i*MAT_DIM+j]); for (i=0; i<MAT_DIM; i++) gsl_vector_set (b, i, st_mns[star_count*MAT_DIM + i]); // FIND OVERLAP // Adding A and B together and storing in ApB gsl_matrix_set_zero(ApB); gsl_matrix_add(ApB, A); gsl_matrix_add(ApB, B); // Storing the result A*a + B*b in AapBb gsl_vector_set_zero(AapBb); gsl_blas_dsymv(CblasUpper, 1.0, A, a, 1.0, AapBb); gsl_blas_dsymv(CblasUpper, 1.0, B, b, 1.0, AapBb); // Getting determinant of ApB gsl_linalg_LU_decomp(ApB, p, &signum); //ApB_det = gsl_linalg_LU_det(ApB, signum); ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant // Solve for c gsl_linalg_LU_solve(ApB, p, AapBb, c); // Compute the overlap formula gsl_vector_set_zero(v_temp); gsl_blas_dcopy(a, v_temp); //v_temp holds a gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c gsl_blas_dcopy(v_temp, amc); //amc holds a - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, A, v_temp, 0.0, v_temp2); //v_temp2 holds A (a-c) result = 0.0; gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c) result += d_temp; gsl_vector_set_zero(v_temp); gsl_blas_dcopy(b, v_temp); //v_temp holds b gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c gsl_blas_dcopy(v_temp, bmc); //bmc holds b - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, B, v_temp, 0.0, v_temp2); //v_temp2 holds A (b-c) gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c) result += d_temp; result = -0.5 * result; result = exp(result); result *= sqrt((gr_icov_det * st_icov_dets[star_count]/ApB_det) / pow(2*M_PI, MAT_DIM)); // STORE IN 'rangevec' rangevec[star_count] = result; } // DEALLOCATE THE MEMORY gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(ApB); gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(AapBb); gsl_vector_free(c); gsl_vector_free(v_temp); gsl_vector_free(v_temp2); gsl_vector_free(amc); gsl_vector_free(bmc); gsl_permutation_free(p); } /* New main function, speed not yet tested * --parameters-- * group_icov (6*6 npyArray) the group's inverse covariance matrix * group_mn (1*6 npyArray) which is the group's mean kinematic info * group_icov_det (flt) the determinent of the group_icov * Bs (nstars*6*6) an array of each star's icov matrix * bs: (nstars*6) an array of each star's mean kinematic info * B_dets: (nstars) an array of the determinent of each icov * nstars: (int) number of stars, used to determine the size * of npyArray which will return calculated overlaps) * * returns: (nstars) array of calculated overlaps of every star with 1 group * * todo: instead of calling internal function actually use cblas functions * this will save time on the reallocation and deallocation * * look up how to find inverse * look up how to access math.pi */ void new_get_lnoverlaps( double* gr_cov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double* st_covs, int st_dim1, int st_dim2, int st_dim3, double* st_mns, int st_mn_dim1, int st_mn_dim2, double* rangevec, int n ) { //printf("Inside new_get_lnoverlaps function\n"); // ALLOCATE MEMORY int star_count = 0; int MAT_DIM = gr_dim1; //Typically set to 6 int i, j, signum; double d_temp, result, ln_det_BpA; FILE* fout = stdout; gsl_permutation *p1; gsl_matrix *BpA = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //(B+A) //gsl_matrix *BpAi = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //(B+A)^-1 gsl_vector *bma = gsl_vector_alloc(MAT_DIM); //will hold b - a gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); p1 = gsl_permutation_alloc(BpA->size1); //printf("Memory allocated\n"); for (star_count=0; star_count<n; star_count++) { // INITIALISE STAR MATRICES for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) //perform B+A as part of the initialisation gsl_matrix_set( BpA,i,j, st_covs[star_count*MAT_DIM*MAT_DIM+i*MAT_DIM+j] + gr_cov[i*MAT_DIM+j] ); // printf("Printing BpA\n"); // print_matrix(fout, BpA); for (i=0; i<MAT_DIM; i++) { gsl_vector_set( bma, i, st_mns[star_count*MAT_DIM + i] - gr_mn[i] ); } //printf("Printing bma\n"); //print_vec(bma->data, 6); //printf("Matrices initialised\n\n"); result = 6*log(2*M_PI); // To Do! put 6ln(2 pi) in here ^^ // Get inverse of BpA, this line is wrong, fix when have internet gsl_linalg_LU_decomp(BpA, p1, &signum); ln_det_BpA = log(fabs(gsl_linalg_LU_det(BpA, signum))); result += ln_det_BpA; //printf("ln(det(BpA)) added\n"); //printf("%6.2f\n\n",ln_det_BpA); //printf("result so far:\n%6.2f\n",result); //// Solve for c //gsl_linalg_LU_solve(ApB, p, AapBb, c); // Don't use invert, use solve like example above ^^ //gsl_linalg_LU_invert(BpA, p1, BpAi); // gsl_vector_set_zero(v_temp); gsl_linalg_LU_solve(BpA, p1, bma, v_temp); //v_temp holds (B+A)^-1 (b-a) gsl_blas_ddot(v_temp, bma, &d_temp); //d_temp holds (b-a)^T (B+A)-1 (b-a) //printf("Printing bma_BpAi_bma\n"); //printf("%6.2f\n\n", d_temp); result += d_temp; //printf("result after bma_BpAi_bma:\n%6.2f\n",result); result *= -0.5; //printf("Everything calculated\n"); //printf("Final result:\n%6.2f\n", result); // // STORE IN 'rangevec' rangevec[star_count] = result; } // DEALLOCATE THE MEMORY gsl_matrix_free(BpA); //gsl_matrix_free(BpAi); gsl_vector_free(bma); gsl_vector_free(v_temp); gsl_permutation_free(p1); //printf("At end of new_get_lnoverlaps function\n"); }
{ "alphanum_fraction": 0.6351959967, "avg_line_length": 30.0250417362, "ext": "c", "hexsha": "b682b3ed3f68e784ac48ec43dcc9399d6d5c079e", "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": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_path": "playground/overlap_legacy/overlap.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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": "tcrundall/chronostar", "max_issues_repo_path": "playground/overlap_legacy/overlap.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_path": "playground/overlap_legacy/overlap.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6048, "size": 17985 }
#ifdef __cplusplus #include <string> #include <algorithm> #include "halley/data_structures/vector.h" #include <map> #include <set> #include <array> #include <charconv> #include <gsl/gsl> #include <cstddef> #include <limits> #include <memory> #include <chrono> #include <thread> #include <mutex> #include <iomanip> #include <optional> #include <atomic> #include <deque> #include <iostream> #include <sstream> #include <istream> #include <ostream> #endif
{ "alphanum_fraction": 0.7373068433, "avg_line_length": 18.12, "ext": "h", "hexsha": "127ce8261a30819fcffa8a7b0431c36f9d7826be", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/engine/utils/src/prec.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_path": "src/engine/utils/src/prec.h", "max_line_length": 42, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_path": "src/engine/utils/src/prec.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 105, "size": 453 }
#ifndef SIR_H #define SIR_H #include <gsl/gsl_odeiv.h> #include <gsl/gsl_errno.h> #include <iostream> #include "DiffEq_Sim.h" using namespace std; class SIR : public DiffEq_Sim { private: const double beta; const double gamma; public: SIR() : beta(0.0), gamma(0.0) { nbins=3;} SIR(double b, double g): beta(b), gamma(g) { nbins=3; } ~SIR() {}; void initialize( double S, double I, double R) { y = new double[nbins]; y[0] = S; y[1] = I; y[2] = R; } void derivative(double const y[], double dydt[]) { dydt[0] = -beta*y[0]*y[1]; dydt[1] = +beta*y[0]*y[1] - gamma*y[1]; dydt[2] = +gamma*y[1]; } }; #endif
{ "alphanum_fraction": 0.512, "avg_line_length": 20.8333333333, "ext": "h", "hexsha": "59effc687880d42f30e6de9ca85cafe4dbd8bfde", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_path": "src/SIR_Sim.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_path": "src/SIR_Sim.h", "max_line_length": 63, "max_stars_count": 30, "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_path": "src/SIR_Sim.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "num_tokens": 239, "size": 750 }
#include <math.h> #include <galpy_potentials.h> #include <stdio.h> #include <gsl/gsl_sf_gegenbauer.h> #include <gsl/gsl_sf_legendre.h> #ifndef GSL_MAJOR_VERSION #define GSL_MAJOR_VERSION 1 #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif //SCF Disk potential //4 arguments: amp, Acos, Asin, a const int FORCE =1; const int DERIV =2; //Useful Functions //Converts from cylindrical coordinates to spherical static inline void cyl_to_spher(double R, double Z,double *r, double *theta) { *r = sqrt(R*R + Z*Z); *theta = atan2(R, Z); } //Integer power double power(double x, int i) { if (i==0) return 1; return x*power(x,i - 1); } //Calculates xi static inline void calculateXi(double r, double a, double *xi) { *xi = (r - a)/(r + a); } //Potentials, forces, and derivative functions //LCOV_EXCL_START double computePhi(double Acos_val, double Asin_val, double mCos, double mSin, double P, double phiTilde, int m) { return (Acos_val*mCos + Asin_val*mSin)*P*phiTilde; } //LCOV_EXCL_STOP double computeAxiPhi(double Acos_val, double P, double phiTilde) { return Acos_val*P*phiTilde; } double computeF_r(double Acos_val, double Asin_val, double mCos, double mSin, double P, double dphiTilde, int m) { return -(Acos_val*mCos + Asin_val*mSin)*P*dphiTilde; } double computeAxiF_r(double Acos_val, double P, double dphiTilde) { return -Acos_val*P*dphiTilde; } double computeF_theta(double Acos_val, double Asin_val, double mCos, double mSin, double dP, double phiTilde, int m) { return -(Acos_val*mCos + Asin_val*mSin)*dP*phiTilde; } double computeAxiF_theta(double Acos_val, double dP, double phiTilde) { return -Acos_val*dP*phiTilde; } double computeF_phi(double Acos_val, double Asin_val, double mCos, double mSin, double P, double phiTilde, int m) { return m*(Acos_val*mSin - Asin_val*mCos)*P*phiTilde; } double computeAxiF_phi(double Acos_val, double P, double phiTilde) { return 0.; } double computeF_rr(double Acos_val, double Asin_val, double mCos, double mSin, double P, double d2phiTilde, int m) { return -(Acos_val*mCos + Asin_val*mSin)*P*d2phiTilde; } double computeAxiF_rr(double Acos_val, double P, double d2phiTilde) { return -Acos_val*P*d2phiTilde; } double computeF_rphi(double Acos_val, double Asin_val, double mCos, double mSin, double P, double dphiTilde, int m) { return m*(Acos_val*mSin - Asin_val*mCos)*P*dphiTilde; } double computeAxiF_rphi(double Acos_val, double P, double d2phiTilde) { return 0.; } double computeF_phiphi(double Acos_val, double Asin_val, double mCos, double mSin, double P, double phiTilde, int m) { return m*m*(Acos_val*mCos + Asin_val*mSin)*P*phiTilde; } double computeAxiF_phiphi(double Acos_val, double P, double d2phiTilde) { return 0.; } //Calculates the Gegenbauer polynomials void compute_C(double xi, int N, int L, double * C_array) { int l; for (l = 0; l < L; l++) { gsl_sf_gegenpoly_array(N - 1, 3./2 + 2*l, xi, C_array + l*N); } } //Calculates the derivative of the Gegenbauer polynomials void compute_dC(double xi, int N, int L, double * dC_array) { int n,l; for (l = 0; l < L; l++) { *(dC_array +l*N) = 0; if (N != 1) gsl_sf_gegenpoly_array(N - 2, 5./2 + 2*l, xi, dC_array + l*N + 1); for (n = 0; n<N; n++) { *(dC_array +l*N + n) *= 2*(2*l + 3./2); } } } //Calculates the second derivative of the Gegenbauer polynomials void compute_d2C(double xi, int N, int L, double * d2C_array) { int n,l; for (l = 0; l < L; l++) { *(d2C_array +l*N) = 0; if (N >1) *(d2C_array +l*N + 1) = 0; if (N > 2) gsl_sf_gegenpoly_array(N - 3, 7./2 + 2*l, xi, d2C_array + l*N + 2); for (n = 0; n<N; n++) { *(d2C_array +l*N + n) *= 4*(2*l + 3./2)*(2*l + 5./2); } } } //Compute phi_Tilde void compute_phiTilde(double r, double a, int N, int L, double* C, double * phiTilde) { double xi; calculateXi(r, a, &xi); double rterms = -1./(r + a); int n,l; for (l = 0; l < L; l++) { if (l != 0) rterms *= r*a/((a + r)*(a + r)); for (n = 0; n < N; n++) { *(phiTilde + l*N + n) = rterms*(*(C + n + l*N)); } } } //Computes the derivative of phiTilde with respect to r void compute_dphiTilde(double r, double a, int N, int L, double * C, double * dC, double * dphiTilde) { double xi; calculateXi(r, a, &xi); double rterm = 1./(r*power(a + r, 3)); int n,l; for (l = 0; l < L; l++) { if (l != 0) { rterm *= (a*r)/power(a + r, 2) ; } for (n = 0; n < N; n++) { *( dphiTilde + l*N + n) = rterm *(((2*l + 1)*r*(a + r) - l*power(a + r,2))*(*(C + l*N + n)) - 2*a*r*(*(dC + l*N + n))); } } } //Computes the second derivative of phiTilde with respect to r void compute_d2phiTilde(double r, double a, int N, int L, double * C, double * dC,double * d2C, double * d2phiTilde) { double xi; calculateXi(r, a, &xi); double rterm = 1./(r*r) / power(a + r,5); int n,l; for (l = 0; l < L; l++) { if (l != 0) { rterm *= (a*r)/power(a + r, 2); } for (n = 0; n < N; n++) { double C_val = *(C + l*N + n); double dC_val = *(dC + l*N + n); double d2C_val = *(d2C + l*N + n); *( d2phiTilde + l*N + n) = rterm*(C_val*(l*(1 - l)*power(a + r, 4) - (4*l*l + 6*l + 2.)*r*r*power(a + r,2) + l*(4*l + 2)*r*power(a + r,3)) + a*r*((4*r*r + 4*a*r + (8*l + 4)*r*(a + r)- 4*l*power(a + r,2))*dC_val - 4*a*r*d2C_val)); } } } //Computes the associated Legendre polynomials void compute_P(double x, int L, int M, double * P_array) { if (M == 1){ gsl_sf_legendre_Pl_array (L - 1, x, P_array); } else { #if GSL_MAJOR_VERSION == 2 gsl_sf_legendre_array_e(GSL_SF_LEGENDRE_NONE,L - 1, x, -1, P_array); #else int m; for (m = 0; m < M; m++) { gsl_sf_legendre_Plm_array(L - 1, m, x, P_array); P_array += L - m; } #endif } } //Computes the associated Legendre polynomials and its derivative void compute_P_dP(double x, int L, int M, double * P_array, double *dP_array) { if (M == 1){ gsl_sf_legendre_Pl_deriv_array (L - 1, x, P_array, dP_array); } else { #if GSL_MAJOR_VERSION == 2 gsl_sf_legendre_deriv_array_e(GSL_SF_LEGENDRE_NONE, L - 1, x, -1,P_array, dP_array); #else int m; for (m = 0; m < M; m++) { gsl_sf_legendre_Plm_deriv_array(L - 1, m, x, P_array, dP_array); P_array += L - m; dP_array += L - m; } #endif } } typedef struct equations equations; struct equations { double ((**Eq)(double, double, double, double, double, double, int)); double *(*phiTilde); double *(*P); double *Constant; }; typedef struct axi_equations axi_equations; struct axi_equations { double ((**Eq)(double, double, double)); double *(*phiTilde); double *(*P); double *Constant; }; //Compute axi symmetric potentials. void compute(double a, int N, int L, int M, double r, double theta, double phi, double *Acos, int eq_size, axi_equations e, double *F) { int i,n,l; for (i = 0; i < eq_size; i++) { *(F + i) =0; //Initialize each F } for (l = 0; l < L; l++) { for (n = 0; n < N; n++) { double Acos_val = *(Acos + M*l + M*L*n); for (i = 0; i < eq_size; i++) { double (*Eq)(double, double, double) = *(e.Eq + i); double *P = *(e.P + i); double *phiTilde = *(e.phiTilde + i); *(F + i) += (*Eq)(Acos_val, P[l], phiTilde[l*N + n]); } } } //Multiply F by constants for (i = 0; i < eq_size; i++) { double constant = *(e.Constant + i); *(F + i) *= constant*sqrt(4*M_PI); } } //Compute Non Axi symmetric Potentials void computeNonAxi(double a, int N, int L, int M, double r, double theta, double phi, double *Acos, double *Asin, int eq_size, equations e, double *F) { int i,n,l,m; for (i = 0; i < eq_size; i++) { *(F + i) =0; //Initialize each F } int v1counter=0; int v2counter = 0; int Pindex = 0; for (l = 0; l < L; l++) { v1counter = 0; for (m = 0; m<=l; m++) { #if GSL_MAJOR_VERSION == 2 Pindex = v2counter; #else Pindex = v1counter + l; #endif double mCos = cos(m*phi); double mSin = sin(m*phi); for (n = 0; n < N; n++) { double Acos_val = *(Acos +m + M*l + M*L*n); double Asin_val = *(Asin +m + M*l + M*L*n); for (i = 0; i < eq_size; i++) { double (*Eq)(double, double, double, double, double, double, int) = *(e.Eq + i); double *P = *(e.P + i); double *phiTilde = *(e.phiTilde + i); *(F + i) += (*Eq)(Acos_val, Asin_val, mCos, mSin, P[Pindex], phiTilde[l*N + n], m); } } v2counter++; v1counter+=M-m - 1; } } //Multiply F by constants for (i = 0; i < eq_size; i++) { double constant = *(e.Constant + i); *(F + i) *= constant*sqrt(4*M_PI); } } //Compute the Forces void computeForce(double R,double Z, double phi, double t, struct potentialArg * potentialArgs, double * F) { double * args= potentialArgs->args; //Get args double a = *args++; int isNonAxi = (int)*args++; int N = (int)*args++; int L = (int)*args++; int M = (int)*args++; double* Acos = args; double* caching_i = (args + (isNonAxi + 1)*N*L*M); double *Asin; if (isNonAxi == 1) { Asin = args + N*L*M; } double *cached_type = caching_i; double * cached_coords = (caching_i+ 1); double * cached_values = (caching_i + 4); if ((int)*cached_type==FORCE) { if (*cached_coords == R && *(cached_coords + 1) == Z && *(cached_coords + 2) == phi) { *F = *cached_values; *(F + 1) = *(cached_values + 1); *(F + 2) = *(cached_values + 2); return; } } double r; double theta; cyl_to_spher(R, Z, &r, &theta); double xi; calculateXi(r, a, &xi); //Compute the gegenbauer polynomials and its derivative. double *C= (double *) malloc ( N*L * sizeof(double) ); double *dC= (double *) malloc ( N*L * sizeof(double) ); double *phiTilde= (double *) malloc ( N*L * sizeof(double) ); double *dphiTilde= (double *) malloc ( N*L * sizeof(double) ); compute_C(xi, N, L, C); compute_dC(xi, N, L, dC); //Compute phiTilde and its derivative compute_phiTilde(r, a, N, L, C, phiTilde); compute_dphiTilde(r, a, N, L, C, dC, dphiTilde); //Compute Associated Legendre Polynomials int M_eff = M; int size = 0; if (isNonAxi==0) { M_eff = 1; size = L; } else{ size = L*L - L*(L-1)/2; } double *P= (double *) malloc ( size * sizeof(double) ); double *dP= (double *) malloc ( size * sizeof(double) ); compute_P_dP(cos(theta), L, M_eff, P, dP); double (*PhiTilde_Pointer[3]) = {dphiTilde,phiTilde,phiTilde}; double (*P_Pointer[3]) = {P, dP, P}; double Constant[3] = {1., -sin(theta), 1.}; if (isNonAxi == 1) { double (*Eq[3])(double, double, double, double, double, double, int) = {&computeF_r, &computeF_theta, &computeF_phi}; equations e = {Eq,&PhiTilde_Pointer[0], &P_Pointer[0], &Constant[0]}; computeNonAxi(a, N, L, M,r, theta, phi, Acos, Asin, 3, e, F); } else { double (*Eq[3])(double, double, double) = {&computeAxiF_r, &computeAxiF_theta, &computeAxiF_phi}; axi_equations e = {Eq,&PhiTilde_Pointer[0], &P_Pointer[0], &Constant[0]}; compute(a, N, L, M,r, theta, phi, Acos, 3, e, F); } //Caching *cached_type = (double)FORCE; * cached_coords = R; * (cached_coords + 1) = Z; * (cached_coords + 2) = phi; * (cached_values) = *F; * (cached_values + 1) = *(F + 1); * (cached_values + 2) = *(F + 2); // Free memory free(C); free(dC); free(phiTilde); free(dphiTilde); free(P); free(dP); } //Compute the Derivatives void computeDeriv(double R,double Z, double phi, double t, struct potentialArg * potentialArgs, double * F) { double * args= potentialArgs->args; //Get args double a = *args++; int isNonAxi = (int)*args++; int N = (int) *args++; int L = (int) *args++; int M = (int) *args++; double* Acos = args; double * caching_i = (args + (isNonAxi + 1)*N*L*M); double *Asin; if (isNonAxi == 1) { Asin = args + N*L*M; } double *cached_type = caching_i; double * cached_coords = (caching_i+ 1); double * cached_values = (caching_i + 4); if ((int)*cached_type==DERIV) { if (*cached_coords == R && *(cached_coords + 1) == Z && *(cached_coords + 2) == phi) { *F = *cached_values; *(F + 1) = *(cached_values + 1); *(F + 2) = *(cached_values + 2); return; } } double r; double theta; cyl_to_spher(R, Z, &r, &theta); double xi; calculateXi(r, a, &xi); //Compute the gegenbauer polynomials and its derivative. double *C= (double *) malloc ( N*L * sizeof(double) ); double *dC= (double *) malloc ( N*L * sizeof(double) ); double *d2C= (double *) malloc ( N*L * sizeof(double) ); double *phiTilde= (double *) malloc ( N*L * sizeof(double) ); double *dphiTilde= (double *) malloc ( N*L * sizeof(double) ); double *d2phiTilde= (double *) malloc ( N*L * sizeof(double) ); compute_C(xi, N, L, C); compute_dC(xi, N, L, dC); compute_d2C(xi, N, L, d2C); //Compute phiTilde and its derivative compute_phiTilde(r, a, N, L, C, phiTilde); compute_dphiTilde(r, a, N, L, C, dC, dphiTilde); compute_d2phiTilde(r, a, N, L, C, dC, d2C, d2phiTilde); //Compute Associated Legendre Polynomials int M_eff = M; int size = 0; if (isNonAxi==0) { M_eff = 1; size = L; } else{ size = L*L - L*(L-1)/2; } double *P= (double *) malloc ( size * sizeof(double) ); compute_P(cos(theta), L,M_eff, P); double (*PhiTilde_Pointer[3])= {d2phiTilde,phiTilde,dphiTilde}; double (*P_Pointer[3]) = {P, P, P}; double Constant[3] = {1., 1., 1.}; if (isNonAxi==1) { double (*Eq[3])(double, double, double, double, double, double, int) = {&computeF_rr, &computeF_phiphi, &computeF_rphi}; equations e = {Eq,&PhiTilde_Pointer[0],&P_Pointer[0],&Constant[0]}; computeNonAxi(a, N, L, M,r, theta, phi, Acos, Asin, 3, e, F); } else { double (*Eq[3])(double, double, double) = {&computeAxiF_rr, &computeAxiF_phiphi, &computeAxiF_rphi}; axi_equations e = {Eq,&PhiTilde_Pointer[0],&P_Pointer[0],&Constant[0]}; compute(a, N, L, M,r, theta, phi, Acos, 3, e, F); } //Caching *cached_type = (double)DERIV; * cached_coords = R; * (cached_coords + 1) = Z; * (cached_coords + 2) = phi; * (cached_values) = *F; * (cached_values + 1) = *(F + 1); * (cached_values + 2) = *(F + 2); //Free memory free(C); free(dC); free(d2C); free(phiTilde); free(dphiTilde); free(d2phiTilde); free(P); } //Compute the Potential double SCFPotentialEval(double R,double Z, double phi, double t, struct potentialArg * potentialArgs) { double * args= potentialArgs->args; //Get args double a = *args++; int isNonAxi = (int)*args++; int N = (int) *args++; int L = (int) *args++; int M = (int) *args++; double* Acos = args; double* Asin; if (isNonAxi==1) //LCOV_EXCL_START { Asin = args + N*L*M; } //LCOV_EXCL_STOP //convert R,Z to r, theta double r; double theta; cyl_to_spher(R, Z,&r, &theta); double xi; calculateXi(r, a, &xi); //Compute the gegenbauer polynomials and its derivative. double *C= (double *) malloc ( N*L * sizeof(double) ); double *phiTilde= (double *) malloc ( N*L * sizeof(double) ); compute_C(xi, N, L, C); //Compute phiTilde and its derivative compute_phiTilde(r, a, N, L, C, phiTilde); //Compute Associated Legendre Polynomials int M_eff = M; int size = 0; if (isNonAxi==0) { M_eff = 1; size = L; } else{ //LCOV_EXCL_START size = L*L - L*(L-1)/2; } //LCOV_EXCL_STOP double *P= (double *) malloc ( size * sizeof(double) ); compute_P(cos(theta), L,M_eff, P); double potential; double (*PhiTilde_Pointer[1]) = {phiTilde}; double (*P_Pointer[1]) = {P}; double Constant[1] = {1.}; if (isNonAxi==1) //LCOV_EXCL_START { double (*Eq[1])(double, double, double, double, double, double, int) = {&computePhi}; equations e = {Eq,&PhiTilde_Pointer[0],&P_Pointer[0],&Constant[0]}; computeNonAxi(a, N, L, M,r, theta, phi, Acos, Asin, 1, e, &potential); } //LCOV_EXCL_STOP else { double (*Eq[1])(double, double, double) = {&computeAxiPhi}; axi_equations e = {Eq,&PhiTilde_Pointer[0],&P_Pointer[0],&Constant[0]}; compute(a, N, L, M,r, theta, phi, Acos, 1, e, &potential); } //Free memory free(C); free(phiTilde); free(P); return potential; } //Compute the force in the R direction double SCFPotentialRforce(double R,double Z, double phi, double t, struct potentialArg * potentialArgs) { double r; double theta; cyl_to_spher(R, Z, &r, &theta); // The derivatives double dr_dR = R/r; double dtheta_dR = Z/(r*r); double dphi_dR = 0; double F[3]; computeForce(R, Z, phi, t,potentialArgs, &F[0]) ; return *(F + 0)*dr_dR + *(F + 1)*dtheta_dR + *(F + 2)*dphi_dR; } //Compute the force in the z direction double SCFPotentialzforce(double R,double Z, double phi, double t, struct potentialArg * potentialArgs) { double r; double theta; cyl_to_spher(R, Z,&r, &theta); double dr_dz = Z/r; double dtheta_dz = -R/(r*r); double dphi_dz = 0; double F[3]; computeForce(R, Z, phi, t,potentialArgs, &F[0]) ; return *(F + 0)*dr_dz + *(F + 1)*dtheta_dz + *(F + 2)*dphi_dz; } //Compute the force in the phi direction double SCFPotentialphiforce(double R,double Z, double phi, double t, struct potentialArg * potentialArgs) { double r; double theta; cyl_to_spher(R, Z, &r, &theta); double dr_dphi = 0; double dtheta_dphi = 0; double dphi_dphi = 1; double F[3]; computeForce(R, Z, phi, t,potentialArgs, &F[0]) ; return *(F + 0)*dr_dphi + *(F + 1)*dtheta_dphi + *(F + 2)*dphi_dphi; } //Compute the planar force in the R direction double SCFPotentialPlanarRforce(double R,double phi, double t, struct potentialArg * potentialArgs) { return SCFPotentialRforce(R,0., phi,t,potentialArgs); } //Compute the planar force in the phi direction double SCFPotentialPlanarphiforce(double R,double phi, double t, struct potentialArg * potentialArgs) { return SCFPotentialphiforce(R,0., phi,t,potentialArgs); } //Compute the planar double derivative of the potential with respect to R double SCFPotentialPlanarR2deriv(double R, double phi, double t, struct potentialArg * potentialArgs) { double Farray[3]; computeDeriv(R, 0, phi, t,potentialArgs, &Farray[0]) ; return *Farray; } //Compute the planar double derivative of the potential with respect to phi double SCFPotentialPlanarphi2deriv(double R, double phi, double t, struct potentialArg * potentialArgs) { double Farray[3]; computeDeriv(R, 0, phi, t,potentialArgs, &Farray[0]) ; return *(Farray + 1); } //Compute the planar double derivative of the potential with respect to R, Phi double SCFPotentialPlanarRphideriv(double R, double phi, double t, struct potentialArg * potentialArgs) { double Farray[3]; computeDeriv(R, 0, phi, t,potentialArgs, &Farray[0]) ; return *(Farray + 2); }
{ "alphanum_fraction": 0.5420273667, "avg_line_length": 26.3308823529, "ext": "c", "hexsha": "e441c2536a54bbb1178e32d08c61d067350ffd15", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-30T06:14:31.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-30T06:14:31.000Z", "max_forks_repo_head_hexsha": "cabb42bef3b4f88a2f593cdb123452cd41451db3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "BurcuAkbulut/galpy", "max_forks_repo_path": "galpy/potential/potential_c_ext/SCFPotential.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "cabb42bef3b4f88a2f593cdb123452cd41451db3", "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": "BurcuAkbulut/galpy", "max_issues_repo_path": "galpy/potential/potential_c_ext/SCFPotential.c", "max_line_length": 128, "max_stars_count": 1, "max_stars_repo_head_hexsha": "7132eddbf2dab491fe137790e31eacdc604b0534", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "turnergarrow/galpy", "max_stars_repo_path": "galpy/potential/potential_c_ext/SCFPotential.c", "max_stars_repo_stars_event_max_datetime": "2019-02-07T10:58:17.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-07T10:58:17.000Z", "num_tokens": 6784, "size": 21486 }
/* integration/qk21.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_integration.h> /* Gauss quadrature weights and kronrod quadrature abscissae and weights as evaluated with 80 decimal digit arithmetic by L. W. Fullerton, Bell Labs, Nov. 1981. */ static const double xgk[11] = /* abscissae of the 21-point kronrod rule */ { 0.995657163025808080735527280689003, 0.973906528517171720077964012084452, 0.930157491355708226001207180059508, 0.865063366688984510732096688423493, 0.780817726586416897063717578345042, 0.679409568299024406234327365114874, 0.562757134668604683339000099272694, 0.433395394129247190799265943165784, 0.294392862701460198131126603103866, 0.148874338981631210884826001129720, 0.000000000000000000000000000000000 }; /* xgk[1], xgk[3], ... abscissae of the 10-point gauss rule. xgk[0], xgk[2], ... abscissae to optimally extend the 10-point gauss rule */ static const double wg[5] = /* weights of the 10-point gauss rule */ { 0.066671344308688137593568809893332, 0.149451349150580593145776339657697, 0.219086362515982043995534934228163, 0.269266719309996355091226921569469, 0.295524224714752870173892994651338 }; static const double wgk[11] = /* weights of the 21-point kronrod rule */ { 0.011694638867371874278064396062192, 0.032558162307964727478818972459390, 0.054755896574351996031381300244580, 0.075039674810919952767043140916190, 0.093125454583697605535065465083366, 0.109387158802297641899210590325805, 0.123491976262065851077958109831074, 0.134709217311473325928054001771707, 0.142775938577060080797094273138717, 0.147739104901338491374841515972068, 0.149445554002916905664936468389821 }; void gsl_integration_qk21 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc) { double fv1[11], fv2[11]; gsl_integration_qk (11, xgk, wg, wgk, fv1, fv2, f, a, b, result, abserr, resabs, resasc); }
{ "alphanum_fraction": 0.759971254, "avg_line_length": 35.6794871795, "ext": "c", "hexsha": "1e263ed7b5116554306876f50d8cc101fd052c43", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qk21.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qk21.c", "max_line_length": 91, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/integration/qk21.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": 923, "size": 2783 }
#ifndef __GSL_VECTOR_H__ #define __GSL_VECTOR_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <gsl/gsl_vector_complex_long_double.h> #include <gsl/gsl_vector_complex_double.h> #include <gsl/gsl_vector_complex_float.h> #include <gsl/gsl_vector_long_double.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_vector_float.h> #include <gsl/gsl_vector_ulong.h> #include <gsl/gsl_vector_long.h> #include <gsl/gsl_vector_uint.h> #include <gsl/gsl_vector_int.h> #include <gsl/gsl_vector_ushort.h> #include <gsl/gsl_vector_short.h> #include <gsl/gsl_vector_uchar.h> #include <gsl/gsl_vector_char.h> #endif /* __GSL_VECTOR_H__ */
{ "alphanum_fraction": 0.7413394919, "avg_line_length": 24.0555555556, "ext": "h", "hexsha": "a6a361469e15439b283ff1c79d32114eb963f8db", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_vector.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_vector.h", "max_line_length": 49, "max_stars_count": 2, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_vector.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 236, "size": 866 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_roots.h> #include "ccl.h" /* --------- ROUTINE: h_over_h0 --------- INPUT: scale factor, cosmology TASK: Compute E(a)=H(a)/H0 */ static double h_over_h0(double a, ccl_cosmology * cosmo, int *status) { // Check if massive neutrinos are present - if not, we don't need to // compute their contribution double Om_mass_nu; if ((cosmo->params.N_nu_mass)>1e-12) { Om_mass_nu = ccl_Omeganuh2( a, cosmo->params.N_nu_mass, cosmo->params.m_nu, cosmo->params.T_CMB, status) / (cosmo->params.h) / (cosmo->params.h); } else { Om_mass_nu = 0; } /* Calculate h^2 using the formula (eqn 2 in the CCL paper): E(a)^2 = Omega_m a^-3 + Omega_l a^(-3*(1+w0+wa)) exp(3*wa*(a-1)) + Omega_k a^-2 + (Omega_g + Omega_nu_rel) a^-4 + Om_mass_nu */ return sqrt( (cosmo->params.Omega_c + cosmo->params.Omega_b + cosmo->params.Omega_l * pow(a,-3*(cosmo->params.w0+cosmo->params.wa)) * exp(3*cosmo->params.wa*(a-1)) + cosmo->params.Omega_k * a + (cosmo->params.Omega_g + cosmo->params.Omega_nu_rel) / a + Om_mass_nu * a*a*a) / (a*a*a)); } /* --------- ROUTINE: ccl_omega_x --------- INPUT: cosmology object, scale factor, species label TASK: Compute the density relative to critical, Omega(a) for a given species. Possible values for "label": ccl_species_crit_label <- critical (physical) ccl_species_m_label <- matter ccl_species_l_label <- DE ccl_species_g_label <- radiation ccl_species_k_label <- curvature ccl_species_ur_label <- massless neutrinos ccl_species_nu_label <- massive neutrinos */ double ccl_omega_x(ccl_cosmology * cosmo, double a, ccl_species_x_label label, int *status) { // If massive neutrinos are present, compute the phase-space integral and // get OmegaNuh2. If not, set OmegaNuh2 to zero. double OmNuh2; if ((cosmo->params.N_nu_mass) > 0.0001) { // Call the massive neutrino density function just once at this redshift. OmNuh2 = ccl_Omeganuh2(a, cosmo->params.N_nu_mass, cosmo->params.m_nu, cosmo->params.T_CMB, status); } else { OmNuh2 = 0.; } double hnorm = h_over_h0(a, cosmo, status); switch(label) { case ccl_species_crit_label : return 1.; case ccl_species_m_label : return (cosmo->params.Omega_c + cosmo->params.Omega_b) / (a*a*a) / hnorm / hnorm + OmNuh2 / (cosmo->params.h) / (cosmo->params.h) / hnorm / hnorm; case ccl_species_l_label : return cosmo->params.Omega_l * pow(a,-3 * (1 + cosmo->params.w0 + cosmo->params.wa)) * exp(3 * cosmo->params.wa * (a-1)) / hnorm / hnorm; case ccl_species_g_label : return cosmo->params.Omega_g / (a*a*a*a) / hnorm / hnorm; case ccl_species_k_label : return cosmo->params.Omega_k / (a*a) / hnorm / hnorm; case ccl_species_ur_label : return cosmo->params.Omega_nu_rel / (a*a*a*a) / hnorm / hnorm; case ccl_species_nu_label : return OmNuh2 / (cosmo->params.h) / (cosmo->params.h) / hnorm / hnorm; default: *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_omega_x(): Species %d not supported\n", label); return NAN; } } /* --------- ROUTINE: ccl_rho_x --------- INPUT: cosmology object, scale factor, species label TASK: Compute rho_x(a), with x defined by species label. Possible values for "label": ccl_species_crit_label <- critical (physical) ccl_species_m_label <- matter (physical) ccl_species_l_label <- DE (physical) ccl_species_g_label <- radiation (physical) ccl_species_k_label <- curvature (physical) ccl_species_ur_label <- massless neutrinos (physical) ccl_species_nu_label <- massive neutrinos (physical) */ double ccl_rho_x(ccl_cosmology * cosmo, double a, ccl_species_x_label label, int is_comoving, int *status) { double comfac; if (is_comoving) { comfac = a*a*a; } else { comfac = 1.0; } double hnorm = h_over_h0(a, cosmo, status); double rhocrit = ccl_constants.RHO_CRITICAL * (cosmo->params.h) * (cosmo->params.h) * hnorm * hnorm * comfac; return rhocrit * ccl_omega_x(cosmo, a, label, status); } /* --------- ROUTINE: ccl_mu_MG --------- INPUT: cosmology object, scale factor TASK: Compute mu(a) where mu is one of the the parameterizating functions of modifications to GR in the quasistatic approximation. */ double ccl_mu_MG(ccl_cosmology * cosmo, double a, int *status) { // This function can be extended to include other // z-dependences for mu in the future. return cosmo->params.mu_0 * ccl_omega_x(cosmo, a, ccl_species_l_label, status) / cosmo->params.Omega_l; } /* --------- ROUTINE: ccl_Sig_MG --------- INPUT: cosmology object, scale factor TASK: Compute Sigma(a) where Sigma is one of the the parameterizating functions of modifications to GR in the quasistatic approximation. */ double ccl_Sig_MG(ccl_cosmology * cosmo, double a, int *status) { // This function can be extended to include other // z-dependences for Sigma in the future. return cosmo->params.sigma_0 * ccl_omega_x(cosmo, a, ccl_species_l_label, status) / cosmo->params.Omega_l; } // Structure to hold parameters of chi_integrand typedef struct { ccl_cosmology *cosmo; int * status; } chipar; /* --------- ROUTINE: chi_integrand --------- INPUT: scale factor TASK: compute the integrand of the comoving distance */ static double chi_integrand(double a, void * params_void) { ccl_cosmology * cosmo = ((chipar *)params_void)->cosmo; int *status = ((chipar *)params_void)->status; return ccl_constants.CLIGHT_HMPC/(a*a*h_over_h0(a, cosmo, status)); } /* --------- ROUTINE: growth_ode_system --------- INPUT: scale factor TASK: Define the ODE system to be solved in order to compute the growth (of the density) */ static int growth_ode_system(double a,const double y[],double dydt[],void *params) { int status = 0; ccl_cosmology * cosmo = params; double hnorm=h_over_h0(a,cosmo, &status); double om=ccl_omega_x(cosmo, a, ccl_species_m_label, &status); dydt[1]=1.5*hnorm*a*om*y[0]; dydt[0]=y[1]/(a*a*a*hnorm); return status; } /* --------- ROUTINE: growth_ode_system_muSig --------- INPUT: scale factor TASK: Define the ODE system to be solved in order to compute the growth (of the density) * in the case in which we use the mu / Sigma quasistatic parameterisation of modified gravity */ static int growth_ode_system_muSig(double a,const double y[],double dydt[],void *params) { int status = 0; ccl_cosmology * cosmo = params; double hnorm=h_over_h0(a,cosmo, &status); double om=ccl_omega_x(cosmo, a, ccl_species_m_label, &status); double mu = ccl_mu_MG(cosmo, a, &status); dydt[1]=1.5*hnorm*a*om*y[0]*(1. + mu); dydt[0]=y[1]/(a*a*a*hnorm); return status; } /* --------- ROUTINE: df_integrand --------- INPUT: scale factor, spline object TASK: Compute integrand from modified growth function */ static double df_integrand(double a,void * spline_void) { if(a<=0) return 0; else { gsl_spline *df_a_spline=(gsl_spline *)spline_void; return gsl_spline_eval(df_a_spline,a,NULL)/a; } } /* --------- ROUTINE: growth_factor_and_growth_rate --------- INPUT: scale factor, cosmology TASK: compute the growth (D(z)) and the growth rate, logarithmic derivative (f?) */ static int growth_factor_and_growth_rate(double a, double *gf, double *fg, ccl_cosmology *cosmo, int *stat) { if(a < cosmo->gsl_params.EPS_SCALEFAC_GROWTH) { *gf = a; *fg = 1; return 0; } else { int gslstatus; double y[2]; double ainit = cosmo->gsl_params.EPS_SCALEFAC_GROWTH; // if mu0 == 0, call normal growth_ode_system, otherwise call growth_ode_system_muSig if (cosmo->params.mu_0 > 1e-12 || cosmo->params.mu_0 < -1e-12) { gsl_odeiv2_system sys = {growth_ode_system_muSig, NULL, 2, cosmo}; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new( &sys, gsl_odeiv2_step_rkck, 0.1*cosmo->gsl_params.EPS_SCALEFAC_GROWTH, 0, cosmo->gsl_params.ODE_GROWTH_EPSREL); if (d == NULL) { return CCL_ERROR_MEMORY; } y[0] = cosmo->gsl_params.EPS_SCALEFAC_GROWTH; y[1] = ( cosmo->gsl_params.EPS_SCALEFAC_GROWTH * cosmo->gsl_params.EPS_SCALEFAC_GROWTH * cosmo->gsl_params.EPS_SCALEFAC_GROWTH * h_over_h0(cosmo->gsl_params.EPS_SCALEFAC_GROWTH, cosmo, stat)); gslstatus = gsl_odeiv2_driver_apply(d, &ainit, a, y); gsl_odeiv2_driver_free(d); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: growth_factor_and_growth_rate():"); return 0; } *gf = y[0]; *fg = y[1]/(a*a*h_over_h0(a, cosmo, stat)*y[0]); return 0; } else { gsl_odeiv2_system sys = {growth_ode_system, NULL, 2, cosmo}; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new( &sys, gsl_odeiv2_step_rkck, 0.1*cosmo->gsl_params.EPS_SCALEFAC_GROWTH, 0, cosmo->gsl_params.ODE_GROWTH_EPSREL); if (d == NULL) { return CCL_ERROR_MEMORY; } y[0] = cosmo->gsl_params.EPS_SCALEFAC_GROWTH; y[1] = ( cosmo->gsl_params.EPS_SCALEFAC_GROWTH * cosmo->gsl_params.EPS_SCALEFAC_GROWTH * cosmo->gsl_params.EPS_SCALEFAC_GROWTH* h_over_h0(cosmo->gsl_params.EPS_SCALEFAC_GROWTH, cosmo, stat)); gslstatus = gsl_odeiv2_driver_apply(d, &ainit, a, y); gsl_odeiv2_driver_free(d); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: growth_factor_and_growth_rate():"); return 0; } *gf = y[0]; *fg = y[1]/(a*a*h_over_h0(a, cosmo, stat)*y[0]); return 0; } } } /* --------- ROUTINE: compute_chi --------- INPUT: scale factor, cosmology OUTPUT: chi -> radial comoving distance TASK: compute radial comoving distance at a */ void compute_chi(double a, ccl_cosmology *cosmo, double * chi, int * stat) { int gslstatus; double result; chipar p; p.cosmo=cosmo; p.status=stat; gsl_integration_cquad_workspace * workspace = NULL; gsl_function F; F.function = &chi_integrand; F.params = &p; workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (workspace == NULL) { *stat = CCL_ERROR_MEMORY; } else { //TODO: CQUAD is great, but slower than other methods. This could be sped up if it becomes an issue. gslstatus=gsl_integration_cquad( &F, a, 1.0, 0.0, cosmo->gsl_params.INTEGRATION_DISTANCE_EPSREL, workspace, &result, NULL, NULL); *chi=result/cosmo->params.h; if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: compute_chi():"); *stat = CCL_ERROR_COMPUTECHI; } } gsl_integration_cquad_workspace_free(workspace); } //Root finding for a(chi) typedef struct { double chi; ccl_cosmology *cosmo; int * status; } Fpar; static double fzero(double a,void *params) { double chi,chia,a_use=a; chi=((Fpar *)params)->chi; compute_chi(a_use,((Fpar *)params)->cosmo,&chia, ((Fpar *)params)->status); return chi-chia; } static double dfzero(double a,void *params) { ccl_cosmology *cosmo=((Fpar *)params)->cosmo; int *stat = ((Fpar *)params)->status; chipar p; p.cosmo=cosmo; p.status=stat; return chi_integrand(a,&p)/cosmo->params.h; } static void fdfzero(double a,void *params,double *f,double *df) { *f=fzero(a,params); *df=dfzero(a,params); } /* --------- ROUTINE: a_of_chi --------- INPUT: comoving distance chi, cosmology, stat, a_old, gsl_root_fdfsolver OUTPUT: scale factor TASK: compute the scale factor that corresponds to a given comoving distance chi Note: This routine uses a root solver to find an a such that compute_chi(a) = chi. The root solver uses the derivative of compute_chi (which is chi_integrand) and the value itself. */ static void a_of_chi(double chi, ccl_cosmology *cosmo, int* stat, double *a_old, gsl_root_fdfsolver *s) { if(chi==0) { *a_old=1; } else { Fpar p; gsl_function_fdf FDF; double a_previous,a_current=*a_old; p.cosmo=cosmo; p.chi=chi; p.status=stat; FDF.f=&fzero; FDF.df=&dfzero; FDF.fdf=&fdfzero; FDF.params=&p; gsl_root_fdfsolver_set(s,&FDF,a_current); int iter=0, gslstatus; do { iter++; gslstatus=gsl_root_fdfsolver_iterate(s); if(gslstatus!=GSL_SUCCESS) ccl_raise_gsl_warning(gslstatus, "ccl_background.c: a_of_chi():"); a_previous=a_current; a_current=gsl_root_fdfsolver_root(s); gslstatus=gsl_root_test_delta(a_current, a_previous, 0, cosmo->gsl_params.ROOT_EPSREL); } while(gslstatus==GSL_CONTINUE && iter <= cosmo->gsl_params.ROOT_N_ITERATION); *a_old=a_current; // Allows us to pass a status to h_over_h0 for the neutrino integral calculation. if(gslstatus==GSL_SUCCESS) { *stat = *(p.status); } else { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: a_of_chi():"); *stat = CCL_ERROR_COMPUTECHI; } } } /* ----- ROUTINE: ccl_cosmology_compute_distances ------ INPUT: cosmology TASK: if not already there, make a table of comoving distances and of E(a) */ void ccl_cosmology_compute_distances(ccl_cosmology * cosmo, int *status) { //Do nothing if everything is computed already if(cosmo->computed_distances) return; // Create logarithmically and then linearly-spaced values of the scale factor int na = cosmo->spline_params.A_SPLINE_NA+cosmo->spline_params.A_SPLINE_NLOG-1; double * a = ccl_linlog_spacing( cosmo->spline_params.A_SPLINE_MINLOG, cosmo->spline_params.A_SPLINE_MIN, cosmo->spline_params.A_SPLINE_MAX, cosmo->spline_params.A_SPLINE_NLOG, cosmo->spline_params.A_SPLINE_NA); // Allocate arrays for all three of E(a), chi(a), and a(chi) double *E_a = malloc(sizeof(double)*na); double *chi_a = malloc(sizeof(double)*na); // Allocate E(a) and chi(a) splines gsl_spline * E = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); gsl_spline * chi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); // a(chi) spline allocated below //Check for too little memory if (a == NULL || E_a == NULL || chi_a == NULL || E == NULL || chi == NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); } //Check for messed up scale factor conditions if (!*status){ if ((fabs(a[0]-cosmo->spline_params.A_SPLINE_MINLOG)>1e-5) || (fabs(a[na-1]-cosmo->spline_params.A_SPLINE_MAX)>1e-5) || (a[na-1]>1.0)) { *status = CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error " "creating first logarithmic and then linear spacing in a\n"); } } // Fill in E(a) - note, this step cannot change the status variable if (!*status) for (int i=0; i<na; i++) E_a[i] = h_over_h0(a[i], cosmo, status); // Create a E(a) spline if (!*status){ if (gsl_spline_init(E, a, E_a, na)){ *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating E(a) spline\n"); } } // Compute chi(a) if (!*status){ for (int i=0; i<na; i++) compute_chi(a[i], cosmo, &chi_a[i], status); if (*status){ *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): chi(a) integration error \n"); } } // Initialize chi(a) spline if (!*status){ if (gsl_spline_init(chi, a, chi_a, na)){//in Mpc *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating chi(a) spline\n"); } } if (*status){ //If there was an error, free the GSL splines and return gsl_spline_free(E); // Note: you are allowed to call gsl_free() on NULL gsl_spline_free(chi); E = NULL; chi = NULL; } // Set up the boundaries for the a(chi) spline double dchi, chi0, chif, a0, af; if(!*status){ dchi=5.; chi0=chi_a[na-1]; chif=chi_a[0]; a0=a[na-1]; af=a[0]; } //TODO: The interval in chi (5. Mpc) should be made a macro free(a); //Free these, in preparation for making a(chi) splines free(E_a); free(chi_a); a = NULL; E_a = NULL; chi_a = NULL; //Note: you are allowed to call free() on NULL //////////////////////////////////////////////////////////////////////////////////////////////////// //Below here na (length of some arrays) changes, so this function has to be split at this point. //////////////////////////////////////////////////////////////////////////////////////////////////// na = (int)((chif-chi0)/dchi); dchi = (chif-chi0)/na; // <=5, since na is an integer //Allocate new arrays for a and chi(a) chi_a = ccl_linear_spacing(chi0, chif, na); a = malloc(sizeof(double)*na); //Allocate space for GSL root finders const gsl_root_fdfsolver_type *T=gsl_root_fdfsolver_newton; gsl_root_fdfsolver *s = NULL; gsl_spline *achi; s = gsl_root_fdfsolver_alloc(T); achi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); //Check for too little memory if (!*status){ if (a == NULL || chi_a == NULL || s == NULL || achi == NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); } else if (fabs(chi_a[0]-chi0) > 1e-5 || fabs(chi_a[na-1]-chif) > 1e-5) { //Check for messed up chi conditions *status = CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating linear spacing in chi\n"); } } // Calculate a(chi) if (!*status){ a[0]=a0; a[na-1]=af; for(int i=1;i<na-1;i++) { // we are using the previous value as a guess here to help the root finder // as long as we use small steps in a this should be fine a_of_chi(chi_a[i],cosmo, status, &a0, s); a[i]=a0; } if(*status) { *status = CCL_ERROR_ROOT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): a(chi) root-finding error \n"); } } // Initialize the a(chi) spline if (!*status){ if(gsl_spline_init(achi, chi_a, a, na)){ *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating a(chi) spline\n"); } } free(a); free(chi_a); //Note: you are allowed to call free() on NULL gsl_root_fdfsolver_free(s); if (*status){//If there was an error, free the GSL splines and return gsl_spline_free(E); //Note: you are allowed to call gsl_free() on NULL gsl_spline_free(chi); gsl_spline_free(achi); } if (*status == 0) { //If there were no errors, attach the splines to the cosmo struct and end the function. cosmo->data.E = E; cosmo->data.chi = chi; cosmo->data.achi = achi; cosmo->computed_distances = true; } } /* ----- ROUTINE: ccl_cosmology_distances_from_input ------ INPUT: cosmology, scale factor array, comoving distance chi computed at the scale factor array values TASK: if not already there, make a table of comoving distances from an input array */ void ccl_cosmology_distances_from_input(ccl_cosmology * cosmo, int na, double a[], double chi_a[], double E_a[], int *status) { double *chi_a_reversed = NULL; double *a_reversed = NULL; //Do nothing if everything is computed already if(cosmo->computed_distances) return; // Allocate E(a), chi(a) and a(chi) splines gsl_spline * E = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); gsl_spline * chi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); gsl_spline * achi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); //Check for too little memory if (a == NULL || E_a == NULL || chi_a == NULL || E == NULL || chi == NULL || achi == NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_distances_from_input(): ran out of memory\n"); } // Update the minimum scale factor value used by the user, which is necessary because it is used in ccl_tracers.c cosmo->spline_params.A_SPLINE_MIN = a[0]; // Initialize a E(a) spline if (!*status){ if (gsl_spline_init(E, a, E_a, na)){ *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_distances_from_input(): Error creating E(a) spline\n"); } } // Initialize chi(a) spline if (!*status){ if (gsl_spline_init(chi, a, chi_a, na)){//in Mpc *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_distances_from_input(): Error creating chi(a) spline\n"); } } // Reverse the order of chi(a) so that we can initialize the a(chi) spline, which needs monotonically decreasing x-array. if (!*status) { chi_a_reversed = malloc(na*sizeof(double)); a_reversed = malloc(na*sizeof(double)); if (chi_a_reversed == NULL || a_reversed == NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_distances_from_input(): ran out of memory\n"); } else { for (int i=0; i<na; i++) { chi_a_reversed[i] = chi_a[na-1-i]; a_reversed[i] = a[na-1-i]; } } } // Initialize a(chi) spline if (!*status){ if (gsl_spline_init(achi, chi_a_reversed, a_reversed, na)){ *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_distances_from_input(): Error creating chi(a) spline\n"); } } free(chi_a_reversed); free(a_reversed); if (*status){ //If there was an error, free the GSL splines and return gsl_spline_free(E); // Note: you are allowed to call gsl_free() on NULL gsl_spline_free(chi); gsl_spline_free(achi); E = NULL; chi = NULL; achi = NULL; } if (*status == 0) { //If there were no errors, attach the splines to the cosmo struct and end the function. cosmo->data.E = E; cosmo->data.chi = chi; cosmo->data.achi = achi; cosmo->computed_distances = true; } return; } /* ----- ROUTINE: ccl_cosmology_growth_from_input ------ INPUT: cosmology, scale factor array, growth array, growth rate array TASK: if not already there, create growth splines with the input arrays and store them. */ void ccl_cosmology_growth_from_input(ccl_cosmology* cosmo, int na, double a[], double growth_arr[], double fgrowth_arr[], int* status) { int chistatus; if (cosmo->computed_growth) return; double *growth_normed = NULL; gsl_spline * growth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); gsl_spline * fgrowth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); //The last element corresponds to a=1 (which is checked for in python). double growth0 = growth_arr[na-1]; if (growth == NULL || fgrowth == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_growth_from_input(): ran out of memory\n"); } // Need to normalize the growth factor if (*status == 0) { growth_normed = malloc(na*sizeof(double)); if (growth_normed == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_growth_from_input(): ran out of memory\n"); } } if (*status == 0) { for(int ia=0; ia<na; ia++) growth_normed[ia] = growth_arr[ia]/growth0; chistatus = gsl_spline_init(growth, a, growth_normed, na); if (chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_growth_from_input(): Error creating D(a) spline\n"); } } if (*status == 0) { chistatus = gsl_spline_init(fgrowth, a, fgrowth_arr, na); if (chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_growth_from_input(): Error creating f(a) spline\n"); } } if (*status){ //If there was an error, free the GSL splines and return gsl_spline_free(growth); gsl_spline_free(fgrowth); growth = NULL; fgrowth = NULL; } if (*status == 0) { // assign all the splines we've just made to the structure. cosmo->data.growth = growth; cosmo->data.fgrowth = fgrowth; cosmo->data.growth0 = growth0; cosmo->computed_growth = true; } free(growth_normed); } /* ----- ROUTINE: ccl_cosmology_compute_growth ------ INPUT: cosmology TASK: if not already there, make a table of growth function and growth rate normalize growth to input parameter growth0 */ void ccl_cosmology_compute_growth(ccl_cosmology* cosmo, int* status) { if (cosmo->computed_growth) return; // Create logarithmically and then linearly-spaced values of the scale factor int chistatus = 0, na = cosmo->spline_params.A_SPLINE_NA+cosmo->spline_params.A_SPLINE_NLOG-1; double *a = NULL; gsl_integration_cquad_workspace * workspace = NULL; gsl_function F; gsl_spline *df_a_spline = NULL; double *df_arr = NULL; gsl_spline *df_z_spline = NULL; int status_mg = 0, gslstatus; double growth0, fgrowth0; double *y = NULL; double *y2 = NULL; double df, integ; if (*status == 0) { a = ccl_linlog_spacing( cosmo->spline_params.A_SPLINE_MINLOG, cosmo->spline_params.A_SPLINE_MIN, cosmo->spline_params.A_SPLINE_MAX, cosmo->spline_params.A_SPLINE_NLOG, cosmo->spline_params.A_SPLINE_NA); if (a == NULL || (fabs(a[0]-cosmo->spline_params.A_SPLINE_MINLOG) > 1e-5) || (fabs(a[na-1]-cosmo->spline_params.A_SPLINE_MAX) > 1e-5) || (a[na-1] > 1.0)) { *status = CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): " "Error creating logarithmically and then linear spacing in a\n"); } } if(cosmo->params.has_mgrowth) { if (*status == 0) { df_arr = malloc(na*sizeof(double)); if(df_arr == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\n"); } } // Generate spline for Delta f(z) that we will then interpolate into an array of a if (*status == 0) { df_z_spline = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, cosmo->params.nz_mgrowth); if (df_z_spline == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\n"); } } if (*status == 0) { chistatus = gsl_spline_init(df_z_spline,cosmo->params.z_mgrowth, cosmo->params.df_mgrowth, cosmo->params.nz_mgrowth); if(chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(z) spline\n"); } } if (*status == 0) { for (int i=0; i<na; i++) { if(a[i]>0) { double z=1./a[i]-1.; if(z<=cosmo->params.z_mgrowth[0]) df_arr[i]=cosmo->params.df_mgrowth[0]; else if(z>cosmo->params.z_mgrowth[cosmo->params.nz_mgrowth-1]) df_arr[i]=cosmo->params.df_mgrowth[cosmo->params.nz_mgrowth-1]; else chistatus |= gsl_spline_eval_e(df_z_spline,z,NULL,&df_arr[i]); } else { df_arr[i]=0; } } if(chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error evaluating Delta f(z) spline\n"); } } // Generate Delta(f) spline if (*status == 0) { df_a_spline = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE,na); if (df_a_spline == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\n"); } } if (*status == 0) { chistatus = gsl_spline_init(df_a_spline, a, df_arr, na); if (chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(a) spline\n"); } } if (*status == 0) { workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION); F.function = &df_integrand; F.params = df_a_spline; } } // allocate space for y, which will be all three // of E(a), chi(a), D(a) and f(a) in turn. if (*status == 0) { y = malloc(sizeof(double)*na); if (y == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\n"); } } if (*status == 0) { y2 = malloc(sizeof(double)*na); if (y2 == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\n"); } } if (*status == 0) { // Get the growth factor and growth rate at z=0 chistatus |= growth_factor_and_growth_rate(1., &growth0, &fgrowth0, cosmo, status); // Get the growth factor and growth rate at other redshifts for(int i=0; i<na; i++) { chistatus |= growth_factor_and_growth_rate(a[i], &(y[i]), &(y2[i]), cosmo, status); if(cosmo->params.has_mgrowth) { if(a[i]>0) { // Add modification to f gslstatus = gsl_spline_eval_e(df_a_spline, a[i], NULL, &df); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_cosmology_compute_growth():"); status_mg |= gslstatus; } y2[i] += df; // Multiply D by exp(-int(df)) gslstatus = gsl_integration_cquad( &F, a[i], 1.0, 0.0, cosmo->gsl_params.INTEGRATION_DISTANCE_EPSREL, workspace, &integ, NULL, NULL); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_cosmology_compute_growth():"); status_mg |= gslstatus; } y[i] *= exp(-integ); } } // Normalizing to the growth factor to the growth today y[i] /= growth0; } if (chistatus || status_mg || *status) { if (chistatus) { *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): integral for linear growth factor didn't converge\n"); } if(status_mg) { *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): integral for MG growth factor didn't converge\n"); } } } gsl_spline *growth = NULL; gsl_spline *fgrowth = NULL; if (*status == 0) { growth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); fgrowth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na); if (growth == NULL || fgrowth == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\n"); } } if (*status == 0) { chistatus = gsl_spline_init(growth, a, y, na); if (chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating D(a) spline\n"); } } if (*status == 0) { chistatus = gsl_spline_init(fgrowth, a, y2, na); if (chistatus) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating f(a) spline\n"); } } if (*status == 0) { // assign all the splines we've just made to the structure. cosmo->data.growth = growth; cosmo->data.fgrowth = fgrowth; cosmo->data.growth0 = growth0; cosmo->computed_growth = true; } else { gsl_spline_free(growth); gsl_spline_free(fgrowth); } free(a); free(y); free(y2); free(df_arr); gsl_spline_free(df_z_spline); gsl_spline_free(df_a_spline); gsl_integration_cquad_workspace_free(workspace); } //Expansion rate normalized to 1 today double ccl_h_over_h0(ccl_cosmology * cosmo, double a, int* status) { if(!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_h_over_h0(): distance splines have not been precomputed!"); return NAN; } double h_over_h0; int gslstatus = gsl_spline_eval_e(cosmo->data.E, a, NULL, &h_over_h0); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_h_over_h0():"); *status = gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_h_over_h0(): Scale factor outside interpolation range.\n"); return NAN; } return h_over_h0; } void ccl_h_over_h0s(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_h_over_h0(cosmo, a[i], &_status); *status |= _status; } } // Distance-like function examples, all in Mpc double ccl_comoving_radial_distance(ccl_cosmology * cosmo, double a, int * status) { if((a > (1.0 - 1.e-8)) && (a<=1.0)) { return 0.; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); return NAN; } else { if(!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_comoving_radial_distance(): distance splines have not been precomputed!"); return NAN; } double crd; int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, NULL, &crd); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_comoving_radial_distance():"); *status = gslstatus; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_comoving_radial_distance(): Scale factor outside interpolation range.\n"); return NAN; } return crd; } } void ccl_comoving_radial_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int* status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_comoving_radial_distance(cosmo, a[i], &_status); *status |= _status; } } double ccl_sinn(ccl_cosmology *cosmo, double chi, int *status) { ////// // { sin(x) , if k==1 // sinn(x)={ x , if k==0 // { sinh(x) , if k==-1 switch(cosmo->params.k_sign) { case -1: return sinh(cosmo->params.sqrtk * chi) / cosmo->params.sqrtk; case 1: return sin(cosmo->params.sqrtk*chi) / cosmo->params.sqrtk; case 0: return chi; default: *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_sinn: ill-defined cosmo->params.k_sign = %d", cosmo->params.k_sign); return NAN; } } double ccl_comoving_angular_distance(ccl_cosmology * cosmo, double a, int* status) { if((a > (1.0 - 1.e-8)) && (a<=1.0)) { return 0.; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); return NAN; } else { if (!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_comoving_angular_distance(): distance splines have not been precomputed!"); return NAN; } double chi; int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, NULL, &chi); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_comoving_angular_distance():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_comoving_angular_distance(): Scale factor outside interpolation range.\n"); return NAN; } return ccl_sinn(cosmo,chi,status); } } void ccl_comoving_angular_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int* status) { int _status; for (int i=0; i < na; i++) { _status = 0; output[i] = ccl_comoving_angular_distance(cosmo, a[i], &_status); *status |= _status; } } double ccl_angular_diameter_distance(ccl_cosmology * cosmo, double a1, double a2, int* status) { if(a1>1. || a2>1. || a1<a2) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo,"ccl_background.c: ccl_angular_diameter_distance(): error on input scale factor."); return NAN; } else { if (!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message(cosmo,"ccl_background.c: ccl_angular_diameter_distance(): distance splines have not been precomputed!"); return NAN; } double chi1,chi2; int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a1, NULL, &chi1); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_angular_diameter_distance():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo,"ccl_background.c: ccl_angular_diameter_distance(): Scale factor outside interpolation range.\n"); return NAN; } gslstatus = gsl_spline_eval_e(cosmo->data.chi, a2, NULL, &chi2); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_angular_diameter_distance():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo,"ccl_background.c: ccl_angular_diameter_distance(): Scale factor outside interpolation range.\n"); return NAN; } return a2*ccl_sinn(cosmo,chi2-chi1,status); } } void ccl_angular_diameter_distances(ccl_cosmology * cosmo, int na, double a1[], double a2[], double output[], int* status) { int _status; for (int i=0; i < na; i++) { _status = 0; output[i] = ccl_angular_diameter_distance(cosmo, a1[i], a2[i], &_status); *status |= _status; } } double ccl_luminosity_distance(ccl_cosmology * cosmo, double a, int* status) { return ccl_comoving_angular_distance(cosmo, a, status) / a; } void ccl_luminosity_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_luminosity_distance(cosmo, a[i], &_status); *status |= _status; } } double ccl_distance_modulus(ccl_cosmology * cosmo, double a, int* status) { if((a > (1.0 - 1.e-8)) && (a<=1.0)) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: distance_modulus undefined for a=1.\n"); return NAN; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); return NAN; } else { if (!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_distance_modulus(): distance splines have not been precomputed!"); return NAN; } /* distance modulus = 5 * log10(d) - 5 Since d in CCL is in Mpc, you get 5*log10(10^6) - 5 = 30 - 5 = 25 for the constant. */ return 5 * log10(ccl_luminosity_distance(cosmo, a, status)) + 25; } } void ccl_distance_moduli(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_distance_modulus(cosmo, a[i], &_status); *status |= _status; } } //Scale factor for a given distance double ccl_scale_factor_of_chi(ccl_cosmology * cosmo, double chi, int * status) { if((chi < 1.e-8) && (chi>=0.)) { return 1.; } else if(chi<0.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: distance cannot be smaller than 0.\n"); return NAN; } else { if (!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_scale_factor_of_chi(): distance splines have not been precomputed!"); return NAN; } double a; int gslstatus = gsl_spline_eval_e(cosmo->data.achi, chi, NULL, &a); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_scale_factor_of_chi():"); *status |= gslstatus; } return a; } } void ccl_scale_factor_of_chis(ccl_cosmology * cosmo, int nchi, double chi[], double output[], int * status) { int _status; for (int i=0; i<nchi; i++) { _status = 0; output[i] = ccl_scale_factor_of_chi(cosmo, chi[i], &_status); *status |= _status; } } double ccl_growth_factor(ccl_cosmology * cosmo, double a, int * status) { if(a==1.){ return 1.; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: scale factor cannot be larger than 1."); return NAN; } else { if (!cosmo->computed_growth){ *status = CCL_ERROR_GROWTH_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_growth_factor(): growth factor splines have not been precomputed!"); return NAN; } if (*status != CCL_ERROR_NOT_IMPLEMENTED) { double D; int gslstatus = gsl_spline_eval_e(cosmo->data.growth, a, NULL, &D); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_growth_factor():"); *status |= gslstatus; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_growth_factor(): Scale factor outside interpolation range."); return NAN; } return D; } else { return NAN; } } } void ccl_growth_factors(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_growth_factor(cosmo, a[i], &_status); *status |= _status; } } double ccl_growth_factor_unnorm(ccl_cosmology * cosmo, double a, int * status) { if (!cosmo->computed_growth) { *status = CCL_ERROR_GROWTH_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_growth_factor_unnorm(): growth factor splines have not been precomputed!"); } if (*status != CCL_ERROR_NOT_IMPLEMENTED) { return cosmo->data.growth0 * ccl_growth_factor(cosmo, a, status); } else { return NAN; } } void ccl_growth_factors_unnorm(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_growth_factor_unnorm(cosmo, a[i], &_status); *status |= _status; } } double ccl_growth_rate(ccl_cosmology * cosmo, double a, int * status) { if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); return NAN; } else { if (!cosmo->computed_growth) { *status = CCL_ERROR_GROWTH_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_growth_rate(): growth rate splines have not been precomputed!"); } if(*status != CCL_ERROR_NOT_IMPLEMENTED) { double g; int gslstatus = gsl_spline_eval_e(cosmo->data.fgrowth, a, NULL ,&g); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_growth_rate():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_growth_rate(): Scale factor outside interpolation range.\n"); return NAN; } return g; } else { return NAN; } } } void ccl_growth_rates(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_growth_rate(cosmo, a[i], &_status); *status |= _status; } }
{ "alphanum_fraction": 0.6556804708, "avg_line_length": 31.8030726257, "ext": "c", "hexsha": "43b56d4ad72350ba6f88792d331103bc863acf68", "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": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "borisbolliet/CCL", "max_forks_repo_path": "src/ccl_background.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "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": "borisbolliet/CCL", "max_issues_repo_path": "src/ccl_background.c", "max_line_length": 147, "max_stars_count": null, "max_stars_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "borisbolliet/CCL", "max_stars_repo_path": "src/ccl_background.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 13545, "size": 45542 }
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess // 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. /** \file sht.h * * \brief Contains declaration and particular implementation of sirius::SHT class. */ #ifndef __SHT_H__ #define __SHT_H__ #include <math.h> #include <stddef.h> #include <gsl/gsl_sf_coupling.h> #include <gsl/gsl_sf_legendre.h> #include <string.h> #include <vector> #include "typedefs.h" #include "utils.h" #include "linalg.hpp" #include "LebedevLaikov.h" namespace sirius { /// Spherical harmonics transformation. class SHT // TODO: better name { private: int lmax_; int lmmax_; int num_points_; mdarray<double, 2> coord_; mdarray<double, 2> tp_; std::vector<double> w_; /// backward transformation from Ylm to spherical coordinates mdarray<double_complex, 2> ylm_backward_; /// forward transformation from spherical coordinates to Ylm mdarray<double_complex, 2> ylm_forward_; /// backward transformation from Rlm to spherical coordinates mdarray<double, 2> rlm_backward_; /// forward transformation from spherical coordinates to Rlm mdarray<double, 2> rlm_forward_; int mesh_type_; public: /// Default constructor. SHT(int lmax__) : lmax_(lmax__), mesh_type_(0) { lmmax_ = (lmax_ + 1) * (lmax_ + 1); if (mesh_type_ == 0) num_points_ = Lebedev_Laikov_npoint(2 * lmax_); if (mesh_type_ == 1) num_points_ = lmmax_; std::vector<double> x(num_points_); std::vector<double> y(num_points_); std::vector<double> z(num_points_); coord_ = mdarray<double, 2>(3, num_points_); tp_ = mdarray<double, 2>(2, num_points_); w_.resize(num_points_); if (mesh_type_ == 0) Lebedev_Laikov_sphere(num_points_, &x[0], &y[0], &z[0], &w_[0]); if (mesh_type_ == 1) uniform_coverage(); ylm_backward_ = mdarray<double_complex, 2>(lmmax_, num_points_); ylm_forward_ = mdarray<double_complex, 2>(num_points_, lmmax_); rlm_backward_ = mdarray<double, 2>(lmmax_, num_points_); rlm_forward_ = mdarray<double, 2>(num_points_, lmmax_); for (int itp = 0; itp < num_points_; itp++) { if (mesh_type_ == 0) { coord_(0, itp) = x[itp]; coord_(1, itp) = y[itp]; coord_(2, itp) = z[itp]; auto vs = spherical_coordinates(vector3d<double>(x[itp], y[itp], z[itp])); spherical_harmonics(lmax_, vs[1], vs[2], &ylm_backward_(0, itp)); spherical_harmonics(lmax_, vs[1], vs[2], &rlm_backward_(0, itp)); for (int lm = 0; lm < lmmax_; lm++) { ylm_forward_(itp, lm) = conj(ylm_backward_(lm, itp)) * w_[itp] * fourpi; rlm_forward_(itp, lm) = rlm_backward_(lm, itp) * w_[itp] * fourpi; } } if (mesh_type_ == 1) { double t = tp_(0, itp); double p = tp_(1, itp); coord_(0, itp) = sin(t) * cos(p); coord_(1, itp) = sin(t) * sin(p); coord_(2, itp) = cos(t); spherical_harmonics(lmax_, t, p, &ylm_backward_(0, itp)); spherical_harmonics(lmax_, t, p, &rlm_backward_(0, itp)); for (int lm = 0; lm < lmmax_; lm++) { ylm_forward_(lm, itp) = ylm_backward_(lm, itp); rlm_forward_(lm, itp) = rlm_backward_(lm, itp); } } } if (mesh_type_ == 1) { linalg<CPU>::geinv(lmmax_, ylm_forward_); linalg<CPU>::geinv(lmmax_, rlm_forward_); } #if (__VERIFICATION > 0) { double dr = 0; double dy = 0; for (int lm = 0; lm < lmmax_; lm++) { for (int lm1 = 0; lm1 < lmmax_; lm1++) { double t = 0; double_complex zt(0, 0); for (int itp = 0; itp < num_points_; itp++) { zt += ylm_forward_(itp, lm) * ylm_backward_(lm1, itp); t += rlm_forward_(itp, lm) * rlm_backward_(lm1, itp); } if (lm == lm1) { zt -= 1.0; t -= 1.0; } dr += std::abs(t); dy += std::abs(zt); } } dr = dr / lmmax_ / lmmax_; dy = dy / lmmax_ / lmmax_; if (dr > 1e-15 || dy > 1e-15) { std::stringstream s; s << "spherical mesh error is too big" << std::endl << " real spherical integration error " << dr << std::endl << " complex spherical integration error " << dy; WARNING(s.str()) } std::vector<double> flm(lmmax_); std::vector<double> ftp(num_points_); for (int lm = 0; lm < lmmax_; lm++) { std::memset(&flm[0], 0, lmmax_ * sizeof(double)); flm[lm] = 1.0; backward_transform(lmmax_, &flm[0], 1, lmmax_, &ftp[0]); forward_transform(&ftp[0], 1, lmmax_, lmmax_, &flm[0]); flm[lm] -= 1.0; double t = 0.0; for (int lm1 = 0; lm1 < lmmax_; lm1++) t += std::abs(flm[lm1]); t /= lmmax_; if (t > 1e-15) { std::stringstream s; s << "test of backward / forward real SHT failed" << std::endl << " total error " << t; WARNING(s.str()); } } } #endif } /// Perform a backward transformation from spherical harmonics to spherical coordinates. /** \f[ * f(\theta, \phi, r) = \sum_{\ell m} f_{\ell m}(r) Y_{\ell m}(\theta, \phi) * \f] * * \param [in] ld Size of leading dimension of flm. * \param [in] flm Raw pointer to \f$ f_{\ell m}(r) \f$. * \param [in] nr Number of radial points. * \param [in] lmmax Maximum number of lm- harmonics to take into sum. * \param [out] ftp Raw pointer to \f$ f(\theta, \phi, r) \f$. */ template <typename T> void backward_transform(int ld, T const* flm, int nr, int lmmax, T* ftp); /// Perform a forward transformation from spherical coordinates to spherical harmonics. /** \f[ * f_{\ell m}(r) = \iint f(\theta, \phi, r) Y_{\ell m}^{*}(\theta, \phi) \sin \theta d\phi d\theta = * \sum_{i} f(\theta_i, \phi_i, r) Y_{\ell m}^{*}(\theta_i, \phi_i) w_i * \f] * * \param [in] ftp Raw pointer to \f$ f(\theta, \phi, r) \f$. * \param [in] nr Number of radial points. * \param [in] lmmax Maximum number of lm- coefficients to generate. * \param [in] ld Size of leading dimension of flm. * \param [out] flm Raw pointer to \f$ f_{\ell m}(r) \f$. */ template <typename T> void forward_transform(T const* ftp, int nr, int lmmax, int ld, T* flm); /// Convert form Rlm to Ylm representation. static void convert(int lmax__, double const* f_rlm__, double_complex* f_ylm__); /// Convert from Ylm to Rlm representation. static void convert(int lmax__, double_complex const* f_ylm__, double* f_rlm__); //void rlm_forward_iterative_transform(double *ftp__, int lmmax, int ncol, double* flm) //{ // Timer t("sirius::SHT::rlm_forward_iterative_transform"); // // assert(lmmax <= lmmax_); // mdarray<double, 2> ftp(ftp__, num_points_, ncol); // mdarray<double, 2> ftp1(num_points_, ncol); // // blas<cpu>::gemm(1, 0, lmmax, ncol, num_points_, 1.0, &rlm_forward_(0, 0), num_points_, &ftp(0, 0), num_points_, 0.0, // flm, lmmax); // // for (int i = 0; i < 2; i++) // { // rlm_backward_transform(flm, lmmax, ncol, &ftp1(0, 0)); // double tdiff = 0.0; // for (int ir = 0; ir < ncol; ir++) // { // for (int itp = 0; itp < num_points_; itp++) // { // ftp1(itp, ir) = ftp(itp, ir) - ftp1(itp, ir); // //tdiff += fabs(ftp1(itp, ir)); // } // } // // for (int itp = 0; itp < num_points_; itp++) // { // tdiff += fabs(ftp1(itp, ncol - 1)); // } // std::cout << "iter : " << i << " avg. MT diff = " << tdiff / num_points_ << std::endl; // blas<cpu>::gemm(1, 0, lmmax, ncol, num_points_, 1.0, &rlm_forward_(0, 0), num_points_, &ftp1(0, 0), num_points_, 1.0, // flm, lmmax); // } //} /// Transform Cartesian coordinates [x,y,z] to spherical coordinates [r,theta,phi] static vector3d<double> spherical_coordinates(vector3d<double> vc); /// Generate complex spherical harmonics Ylm static void spherical_harmonics(int lmax, double theta, double phi, double_complex* ylm); /// Generate real spherical harmonics Rlm /** Mathematica code: * \verbatim * R[l_, m_, th_, ph_] := * If[m > 0, std::sqrt[2]*ComplexExpand[Re[SphericalHarmonicY[l, m, th, ph]]], * If[m < 0, std::sqrt[2]*ComplexExpand[Im[SphericalHarmonicY[l, m, th, ph]]], * If[m == 0, ComplexExpand[Re[SphericalHarmonicY[l, 0, th, ph]]]]]] * \endverbatim */ static void spherical_harmonics(int lmax, double theta, double phi, double* rlm); /// Compute element of the transformation matrix from complex to real spherical harmonics. /** Real spherical harmonic can be written as a linear combination of complex harmonics: * * \f[ * R_{\ell m}(\theta, \phi) = \sum_{m'} a^{\ell}_{m' m}Y_{\ell m'}(\theta, \phi) * \f] * where * \f[ * a^{\ell}_{m' m} = \langle Y_{\ell m'} | R_{\ell m} \rangle * \f] * * Transformation from real to complex spherical harmonics is conjugate transpose: * * \f[ * Y_{\ell m}(\theta, \phi) = \sum_{m'} a^{\ell*}_{m m'}R_{\ell m'}(\theta, \phi) * \f] * * Mathematica code: * \verbatim * b[m1_, m2_] := * If[m1 == 0, 1, * If[m1 < 0 && m2 < 0, -I/std::sqrt[2], * If[m1 > 0 && m2 < 0, (-1)^m1*I/std::sqrt[2], * If[m1 < 0 && m2 > 0, (-1)^m2/std::sqrt[2], * If[m1 > 0 && m2 > 0, 1/std::sqrt[2]]]]]] * * a[m1_, m2_] := If[Abs[m1] == Abs[m2], b[m1, m2], 0] * * R[l_, m_, t_, p_] := Sum[a[m1, m]*SphericalHarmonicY[l, m1, t, p], {m1, -l, l}] * \endverbatim */ static inline double_complex ylm_dot_rlm(int l, int m1, int m2) { const double isqrt2 = 0.70710678118654752440; assert(l >= 0 && std::abs(m1) <= l && std::abs(m2) <= l); if (!((m1 == m2) || (m1 == -m2))) { return double_complex(0, 0); } if (m1 == 0) { return double_complex(1, 0); } if (m1 < 0) { if (m2 < 0) { return -double_complex(0, isqrt2); } else { return std::pow(-1.0, m2) * double_complex(isqrt2, 0); } } else { if (m2 < 0) { return pow(-1.0, m1) * double_complex(0, isqrt2); } else { return double_complex(isqrt2, 0); } } } static inline double_complex rlm_dot_ylm(int l, int m1, int m2) { return std::conj(ylm_dot_rlm(l, m2, m1)); } /// Gaunt coefficent of three complex spherical harmonics. /** * \f[ * \langle Y_{\ell_1 m_1} | Y_{\ell_2 m_2} | Y_{\ell_3 m_3} \rangle * \f] */ static double gaunt_ylm(int l1, int l2, int l3, int m1, int m2, int m3); /// Gaunt coefficent of three real spherical harmonics. /** * \f[ * \langle R_{\ell_1 m_1} | R_{\ell_2 m_2} | R_{\ell_3 m_3} \rangle * \f] */ static double gaunt_rlm(int l1, int l2, int l3, int m1, int m2, int m3); /// Gaunt coefficent of two complex and one real spherical harmonics. /** * \f[ * \langle Y_{\ell_1 m_1} | R_{\ell_2 m_2} | Y_{\ell_3 m_3} \rangle * \f] */ static double_complex gaunt_hybrid(int l1, int l2, int l3, int m1, int m2, int m3); void uniform_coverage(); /// Return Clebsch-Gordan coefficient. /** Clebsch-Gordan coefficients arise when two angular momenta are combined into a * total angular momentum. */ static inline double clebsch_gordan(int l1, int l2, int l3, int m1, int m2, int m3) { assert(l1 >= 0); assert(l2 >= 0); assert(l3 >= 0); assert(m1 >= -l1 && m1 <= l1); assert(m2 >= -l2 && m2 <= l2); assert(m3 >= -l3 && m3 <= l3); return pow(-1, l1 - l2 + m3) * sqrt(double(2 * l3 + 1)) * gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, 2 * m1, 2 * m2, -2 * m3); } inline double_complex ylm_backward(int lm, int itp) { return ylm_backward_(lm, itp); } inline double rlm_backward(int lm, int itp) { return rlm_backward_(lm, itp); } inline double coord(int x, int itp) { return coord_(x, itp); } inline int num_points() { return num_points_; } inline int lmax() { return lmax_; } inline int lmmax() { return lmmax_; } static void wigner_d_matrix(int l, double beta, mdarray<double, 2>& d_mtrx__) { long double cos_b2 = std::cos((long double)beta / 2.0L); long double sin_b2 = std::sin((long double)beta / 2.0L); for (int m1 = -l; m1 <= l; m1++) { for (int m2 = -l; m2 <= l; m2++) { long double d = 0; for (int j = 0; j <= std::min(l + m1, l - m2); j++) { if ((l - m2 - j) >= 0 && (l + m1 - j) >= 0 && (j + m2 - m1) >= 0) { long double g = (std::sqrt(Utils::factorial(l + m1)) / Utils::factorial(l - m2 - j)) * (std::sqrt(Utils::factorial(l - m1)) / Utils::factorial(l + m1 - j)) * (std::sqrt(Utils::factorial(l - m2)) / Utils::factorial(j + m2 - m1)) * (std::sqrt(Utils::factorial(l + m2)) / Utils::factorial(j)); d += g * std::pow(-1, j) * std::pow(cos_b2, 2 * l + m1 - m2 - 2 * j) * std::pow(sin_b2, 2 * j + m2 - m1); } } d_mtrx__(m1 + l, m2 + l) = (double)d; } } } static void rotation_matrix_l(int l, vector3d<double> euler_angles, int proper_rotation, double_complex* rot_mtrx__, int ld) { mdarray<double_complex, 2> rot_mtrx(rot_mtrx__, ld, 2 * l + 1); mdarray<double, 2> d_mtrx(2 * l + 1, 2 * l + 1); wigner_d_matrix(l, euler_angles[1], d_mtrx); for (int m1 = -l; m1 <= l; m1++) { for (int m2 = -l; m2 <= l; m2++) { rot_mtrx(m1 + l, m2 + l) = std::exp(double_complex(0, -euler_angles[0] * m1 - euler_angles[2] * m2)) * d_mtrx(m1 + l, m2 + l) * std::pow(proper_rotation, l); } } } static void rotation_matrix_l(int l, vector3d<double> euler_angles, int proper_rotation, double* rot_mtrx__, int ld) { mdarray<double, 2> rot_mtrx_rlm(rot_mtrx__, ld, 2 * l + 1); mdarray<double_complex, 2> rot_mtrx_ylm(2 * l + 1, 2 * l + 1); mdarray<double, 2> d_mtrx(2 * l + 1, 2 * l + 1); wigner_d_matrix(l, euler_angles[1], d_mtrx); for (int m1 = -l; m1 <= l; m1++) { for (int m2 = -l; m2 <= l; m2++) { rot_mtrx_ylm(m1 + l, m2 + l) = std::exp(double_complex(0, -euler_angles[0] * m1 - euler_angles[2] * m2)) * d_mtrx(m1 + l, m2 + l) * std::pow(proper_rotation, l); } } for (int m1 = -l; m1 <= l; m1++) { auto i13 = (m1 == 0) ? std::vector<int>({0}) : std::vector<int>({-m1, m1}); for (int m2 = -l; m2 <= l; m2++) { auto i24 = (m2 == 0) ? std::vector<int>({0}) : std::vector<int>({-m2, m2}); for (int m3: i13) { for (int m4: i24) { rot_mtrx_rlm(m1 + l, m2 + l) += std::real(rlm_dot_ylm(l, m1, m3) * rot_mtrx_ylm(m3 + l, m4 + l) * ylm_dot_rlm(l, m4, m2)); } } } } } static void rotation_matrix(int lmax, vector3d<double> euler_angles, int proper_rotation, mdarray<double_complex, 2>& rotm) { rotm.zero(); for (int l = 0; l <= lmax; l++) { rotation_matrix_l(l, euler_angles, proper_rotation, &rotm(l * l, l * l), rotm.ld()); } } static void rotation_matrix(int lmax, vector3d<double> euler_angles, int proper_rotation, mdarray<double, 2>& rotm) { rotm.zero(); for (int l = 0; l <= lmax; l++) { rotation_matrix_l(l, euler_angles, proper_rotation, &rotm(l * l, l * l), rotm.ld()); } } /// Compute derivative of real-spherical harmonic with respect to theta angle. static double dRlm_dtheta(int lm, double theta, double phi) { switch (lm) { case 0: return 0; case 1: return -(std::sqrt(3/pi)*std::cos(theta)*std::sin(phi))/2.; case 2: return -(std::sqrt(3/pi)*std::sin(theta))/2.; case 3: return -(std::sqrt(3/pi)*std::cos(phi)*std::cos(theta))/2.; case 4: return -(std::sqrt(15/pi)*std::cos(phi)*std::cos(theta)*std::sin(phi)*std::sin(theta)); case 5: return -(std::sqrt(15/pi)*std::cos(2*theta)*std::sin(phi))/2.; case 6: return (-3*std::sqrt(5/pi)*std::cos(theta)*std::sin(theta))/2.; case 7: return -(std::sqrt(15/pi)*std::cos(phi)*std::cos(2*theta))/2.; case 8: return (std::sqrt(15/pi)*std::cos(2*phi)*std::sin(2*theta))/4.; case 9: return (-3*std::sqrt(35/(2.*pi))*std::cos(theta)*std::sin(3*phi)*std::pow(std::sin(theta),2))/4.; case 10: return (std::sqrt(105/pi)*std::sin(2*phi)*(std::sin(theta) - 3*std::sin(3*theta)))/16.; case 11: return (std::sqrt(21/(2.*pi))*std::cos(theta)*(7 - 15*std::cos(2*theta))*std::sin(phi))/8.; case 12: return (-3*std::sqrt(7/pi)*(3 + 5*std::cos(2*theta))*std::sin(theta))/8.; case 13: return (std::sqrt(21/(2.*pi))*std::cos(phi)*std::cos(theta)*(7 - 15*std::cos(2*theta)))/8.; case 14: return (std::sqrt(105/pi)*std::cos(2*phi)*(1 + 3*std::cos(2*theta))*std::sin(theta))/8.; case 15: return (-3*std::sqrt(35/(2.*pi))*std::cos(3*phi)*std::cos(theta)*std::pow(std::sin(theta),2))/4.; case 16: return (-3*std::sqrt(35/pi)*std::cos(theta)*std::sin(4*phi)*std::pow(std::sin(theta),3))/4.; case 17: return (-3*std::sqrt(35/(2.*pi))*(1 + 2*std::cos(2*theta))*std::sin(3*phi)*std::pow(std::sin(theta),2))/4.; case 18: return (3*std::sqrt(5/pi)*(1 - 7*std::cos(2*theta))*std::sin(2*phi)*std::sin(2*theta))/8.; case 19: return (-3*std::sqrt(5/(2.*pi))*(std::cos(2*theta) + 7*std::cos(4*theta))*std::sin(phi))/8.; case 20: return (15*std::cos(theta)*(3 - 7*std::pow(std::cos(theta),2))*std::sin(theta))/(4.*std::sqrt(pi)); case 21: return (-3*std::sqrt(5/(2.*pi))*std::cos(phi)*(std::cos(2*theta) + 7*std::cos(4*theta)))/8.; case 22: return (3*std::sqrt(5/pi)*std::cos(2*phi)*(-2*std::sin(2*theta) + 7*std::sin(4*theta)))/16.; case 23: return (-3*std::sqrt(35/(2.*pi))*std::cos(3*phi)*(1 + 2*std::cos(2*theta))*std::pow(std::sin(theta),2))/4.; case 24: return (3*std::sqrt(35/pi)*std::cos(4*phi)*std::cos(theta)*std::pow(std::sin(theta),3))/4.; default: { TERMINATE_NOT_IMPLEMENTED } } return 0; // make compiler happy } /// Compute derivative of real-spherical harmonic with respect to phi angle and divide by sin(theta). static double dRlm_dphi_sin_theta(int lm, double theta, double phi) { switch (lm) { case 0: return 0; case 1: return -(std::sqrt(3/pi)*std::cos(phi))/2.; case 2: return 0; case 3: return (std::sqrt(3/pi)*std::sin(phi))/2.; case 4: return -(std::sqrt(15/pi)*std::cos(2*phi)*std::sin(theta))/2.; case 5: return -(std::sqrt(15/pi)*std::cos(phi)*std::cos(theta))/2.; case 6: return 0; case 7: return (std::sqrt(15/pi)*std::cos(theta)*std::sin(phi))/2.; case 8: return -(std::sqrt(15/pi)*std::cos(phi)*std::sin(phi)*std::sin(theta)); case 9: return (-3*std::sqrt(35/(2.*pi))*std::cos(3*phi)*std::pow(std::sin(theta),2))/4.; case 10: return -(std::sqrt(105/pi)*std::cos(2*phi)*std::sin(2*theta))/4.; case 11: return -(std::sqrt(21/(2.*pi))*std::cos(phi)*(3 + 5*std::cos(2*theta)))/8.; case 12: return 0; case 13: return (std::sqrt(21/(2.*pi))*(3 + 5*std::cos(2*theta))*std::sin(phi))/8.; case 14: return -(std::sqrt(105/pi)*std::cos(phi)*std::cos(theta)*std::sin(phi)*std::sin(theta)); case 15: return (3*std::sqrt(35/(2.*pi))*std::sin(3*phi)*std::pow(std::sin(theta),2))/4.; case 16: return (-3*std::sqrt(35/pi)*std::cos(4*phi)*std::pow(std::sin(theta),3))/4.; case 17: return (-9*std::sqrt(35/(2.*pi))*std::cos(3*phi)*std::cos(theta)*std::pow(std::sin(theta),2))/4.; case 18: return (-3*std::sqrt(5/pi)*std::cos(2*phi)*(3*std::sin(theta) + 7*std::sin(3*theta)))/16.; case 19: return (-3*std::sqrt(5/(2.*pi))*std::cos(phi)*(9*std::cos(theta) + 7*std::cos(3*theta)))/16.; case 20: return 0; case 21: return (3*std::sqrt(5/(2.*pi))*std::cos(theta)*(1 + 7*std::cos(2*theta))*std::sin(phi))/8.; case 22: return (-3*std::sqrt(5/pi)*std::sin(2*phi)*(3*std::sin(theta) + 7*std::sin(3*theta)))/16.; case 23: return (9*std::sqrt(35/(2.*pi))*std::cos(theta)*std::sin(3*phi)*std::pow(std::sin(theta),2))/4.; case 24: return (-3*std::sqrt(35/pi)*std::sin(4*phi)*std::pow(std::sin(theta),3))/4.; default: { TERMINATE_NOT_IMPLEMENTED } } return 0; // make compiler happy } }; template <> inline void SHT::backward_transform<double>(int ld, double const* flm, int nr, int lmmax, double* ftp) { assert(lmmax <= lmmax_); assert(ld >= lmmax); linalg<CPU>::gemm(1, 0, num_points_, nr, lmmax, &rlm_backward_(0, 0), lmmax_, flm, ld, ftp, num_points_); } template <> inline void SHT::backward_transform<double_complex>(int ld, double_complex const* flm, int nr, int lmmax, double_complex* ftp) { assert(lmmax <= lmmax_); assert(ld >= lmmax); linalg<CPU>::gemm(1, 0, num_points_, nr, lmmax, &ylm_backward_(0, 0), lmmax_, flm, ld, ftp, num_points_); } template <> inline void SHT::forward_transform<double>(double const* ftp, int nr, int lmmax, int ld, double* flm) { assert(lmmax <= lmmax_); assert(ld >= lmmax); linalg<CPU>::gemm(1, 0, lmmax, nr, num_points_, &rlm_forward_(0, 0), num_points_, ftp, num_points_, flm, ld); } template <> inline void SHT::forward_transform<double_complex>(double_complex const* ftp, int nr, int lmmax, int ld, double_complex* flm) { assert(lmmax <= lmmax_); assert(ld >= lmmax); linalg<CPU>::gemm(1, 0, lmmax, nr, num_points_, &ylm_forward_(0, 0), num_points_, ftp, num_points_, flm, ld); } inline double SHT::gaunt_ylm(int l1, int l2, int l3, int m1, int m2, int m3) { assert(l1 >= 0); assert(l2 >= 0); assert(l3 >= 0); assert(m1 >= -l1 && m1 <= l1); assert(m2 >= -l2 && m2 <= l2); assert(m3 >= -l3 && m3 <= l3); return std::pow(-1.0, std::abs(m1)) * std::sqrt(double(2 * l1 + 1) * double(2 * l2 + 1) * double(2 * l3 + 1) / fourpi) * gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, 0, 0, 0) * gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, -2 * m1, 2 * m2, 2 * m3); } inline double SHT::gaunt_rlm(int l1, int l2, int l3, int m1, int m2, int m3) { assert(l1 >= 0); assert(l2 >= 0); assert(l3 >= 0); assert(m1 >= -l1 && m1 <= l1); assert(m2 >= -l2 && m2 <= l2); assert(m3 >= -l3 && m3 <= l3); double d = 0; for (int k1 = -l1; k1 <= l1; k1++) { for (int k2 = -l2; k2 <= l2; k2++) { for (int k3 = -l3; k3 <= l3; k3++) { d += std::real(std::conj(SHT::ylm_dot_rlm(l1, k1, m1)) * SHT::ylm_dot_rlm(l2, k2, m2) * SHT::ylm_dot_rlm(l3, k3, m3)) * SHT::gaunt_ylm(l1, l2, l3, k1, k2, k3); } } } return d; } inline double_complex SHT::gaunt_hybrid(int l1, int l2, int l3, int m1, int m2, int m3) { assert(l1 >= 0); assert(l2 >= 0); assert(l3 >= 0); assert(m1 >= -l1 && m1 <= l1); assert(m2 >= -l2 && m2 <= l2); assert(m3 >= -l3 && m3 <= l3); if (m2 == 0) { return double_complex(gaunt_ylm(l1, l2, l3, m1, m2, m3), 0.0); } else { return (ylm_dot_rlm(l2, m2, m2) * gaunt_ylm(l1, l2, l3, m1, m2, m3) + ylm_dot_rlm(l2, -m2, m2) * gaunt_ylm(l1, l2, l3, m1, -m2, m3)); } } inline vector3d<double> SHT::spherical_coordinates(vector3d<double> vc) { vector3d<double> vs; double eps = 1e-12; vs[0] = vc.length(); if (vs[0] <= eps) { vs[1] = 0.0; vs[2] = 0.0; } else { vs[1] = std::acos(vc[2] / vs[0]); // theta = cos^{-1}(z/r) if (std::abs(vc[0]) > eps || std::abs(vc[1]) > eps) { vs[2] = std::atan2(vc[1], vc[0]); // phi = tan^{-1}(y/x) if (vs[2] < 0.0) vs[2] += twopi; } else { vs[2] = 0.0; } } return vs; } inline void SHT::spherical_harmonics(int lmax, double theta, double phi, double_complex* ylm) { double x = std::cos(theta); std::vector<double> result_array(lmax + 1); for (int l = 0; l <= lmax; l++) { for (int m = 0; m <= l; m++) { double_complex z = std::exp(double_complex(0.0, m * phi)); ylm[Utils::lm_by_l_m(l, m)] = gsl_sf_legendre_sphPlm(l, m, x) * z; if (m % 2) { ylm[Utils::lm_by_l_m(l, -m)] = -std::conj(ylm[Utils::lm_by_l_m(l, m)]); } else { ylm[Utils::lm_by_l_m(l, -m)] = std::conj(ylm[Utils::lm_by_l_m(l, m)]); } } } } inline void SHT::spherical_harmonics(int lmax, double theta, double phi, double* rlm) { int lmmax = (lmax + 1) * (lmax + 1); std::vector<double_complex> ylm(lmmax); spherical_harmonics(lmax, theta, phi, &ylm[0]); double t = std::sqrt(2.0); rlm[0] = y00; for (int l = 1; l <= lmax; l++) { for (int m = -l; m < 0; m++) rlm[Utils::lm_by_l_m(l, m)] = t * ylm[Utils::lm_by_l_m(l, m)].imag(); rlm[Utils::lm_by_l_m(l, 0)] = ylm[Utils::lm_by_l_m(l, 0)].real(); for (int m = 1; m <= l; m++) rlm[Utils::lm_by_l_m(l, m)] = t * ylm[Utils::lm_by_l_m(l, m)].real(); } } inline void SHT::uniform_coverage() { tp_(0, 0) = pi; tp_(1, 0) = 0; for (int k = 1; k < num_points_ - 1; k++) { double hk = -1.0 + double(2 * k) / double(num_points_ - 1); tp_(0, k) = acos(hk); double t = tp_(1, k - 1) + 3.80925122745582 / sqrt(double(num_points_)) / sqrt(1 - hk * hk); tp_(1, k) = fmod(t, twopi); } tp_(0, num_points_ - 1) = 0; tp_(1, num_points_ - 1) = 0; } inline void SHT::convert(int lmax__, double const* f_rlm__, double_complex* f_ylm__) { int lm = 0; for (int l = 0; l <= lmax__; l++) { for (int m = -l; m <= l; m++) { if (m == 0) { f_ylm__[lm] = f_rlm__[lm]; } else { int lm1 = Utils::lm_by_l_m(l, -m); f_ylm__[lm] = ylm_dot_rlm(l, m, m) * f_rlm__[lm] + ylm_dot_rlm(l, m, -m) * f_rlm__[lm1]; } lm++; } } } inline void SHT::convert(int lmax__, double_complex const* f_ylm__, double* f_rlm__) { int lm = 0; for (int l = 0; l <= lmax__; l++) { for (int m = -l; m <= l; m++) { if (m == 0) { f_rlm__[lm] = std::real(f_ylm__[lm]); } else { int lm1 = Utils::lm_by_l_m(l, -m); f_rlm__[lm] = std::real(rlm_dot_ylm(l, m, m) * f_ylm__[lm] + rlm_dot_ylm(l, m, -m) * f_ylm__[lm1]); } lm++; } } } }; #endif // __SHT_H__
{ "alphanum_fraction": 0.4591994854, "avg_line_length": 38.2156424581, "ext": "h", "hexsha": "cb60d6ea1547ef8d83b5272daa38e97003c6e8c6", "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": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "cocteautwins/SIRIUS-develop", "max_forks_repo_path": "src/sht.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "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": "cocteautwins/SIRIUS-develop", "max_issues_repo_path": "src/sht.h", "max_line_length": 136, "max_stars_count": null, "max_stars_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "cocteautwins/SIRIUS-develop", "max_stars_repo_path": "src/sht.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10090, "size": 34203 }
/** * File: model_utils.c * Subroutines to calculate the * various contamination models */ #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_interp.h> #include "model_utils.h" #include "fitsio.h" #include "inout_aper.h" #include "aXe_grism.h" #include "spce_PET.h" #include "spc_wl_calib.h" #include "aXe_errors.h" #include "fringe_conf.h" #include "spc_resp.h" #include "spce_pathlength.h" #include "aper_conf.h" #include "crossdisp_utils.h" #include "spc_FITScards.h" #define MAX(x,y) (((x)>(y))?(x):(y)) #define MIN(x,y) (((x)<(y))?(x):(y)) #define SQR(x) ((x)*(x)) dirim_emission * model_gauss_dirim(dirobject *actdir, beam actbeam, aperture_conf *conf, double psf_offset) { int nx, ny; int ii, jj; double sval=0.0; d_point dpixel; dirim_emission *gauss_dirim = NULL; // check whether something can be done if (actdir->dirim || (conf->psfcoeffs && conf->psfrange) || psf_offset) // return NULL if not return NULL; // dimension the new matrix; // leave one border row more nx = actdir->ix_max - actdir->ix_min + 3; ny = actdir->iy_max - actdir->iy_min + 3; // allocate memory for the structure gauss_dirim = (dirim_emission *) malloc(sizeof(dirim_emission)); // load the image in the gsl gauss_dirim->modimage = gsl_matrix_alloc(nx, ny); // transfer the image dimension gauss_dirim->dim_x = (int)gauss_dirim->modimage->size1; gauss_dirim->dim_y = (int)gauss_dirim->modimage->size2; // compute and store the mean image coordinates gauss_dirim->xmean = (float)(gauss_dirim->dim_x-1) / 2.0; gauss_dirim->ymean = (float)(gauss_dirim->dim_y-1) / 2.0; // go over all pixels in the area for (ii=0; ii < gauss_dirim->dim_x; ii++) { for (jj=0; jj < gauss_dirim->dim_y; jj++) { // fill the dpixel structure with the position // RELATIVE to the reverence position of the beam dpixel.x = (double)ii - gauss_dirim->xmean + actbeam.refpoint.x; dpixel.y = (double)jj - gauss_dirim->ymean + actbeam.refpoint.y; // do a subsampling over the pixel // to get a more appropriate value for the // emission value sval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale); // set the emission value in the matrix gsl_matrix_set(gauss_dirim->modimage, ii, jj, sval); } } // return the matrix return gauss_dirim; } /** * Function: get_calib_function * The function extracts the necessary data for the wavelength * calibration from the configuration file. The wavelength * calibration is assembled for a particular beam of a particular * object. * * Parameters: * @param actspec - the model spectrum this is done for * @param actdir - the dirobject this is done for * @param CONF_file - the full filename of the configuration file * @param conf - the configuration structure * * Returns: * @return wl_calibration - the wavelength calibration */ calib_function * get_calib_function(beamspec *actspec, dirobject *actdir, char CONF_file[], const aperture_conf * conf) { calib_function *wl_calibration; dispstruct *disp; d_point pixel; int for_grism=0; // get the reference point right pixel.x = actdir->refpoint.x - conf->refx; pixel.y = actdir->refpoint.y - conf->refy; // look whether we are for grisms or prisms for_grism = check_for_grism (CONF_file,actspec->beamID); // get the dispersion structure disp = get_dispstruct_at_pos(CONF_file, for_grism, actspec->beamID,pixel); // transform the dispersion structure into the // wavelength calibration wl_calibration = create_calib_from_gsl_vector(for_grism, disp->pol); if (!for_grism) wl_calibration->pr_range = get_prange (CONF_file, actspec->beamID); free_dispstruct(disp); // return the wavelength calibration return wl_calibration; } /** * Function: get_throughput_spec * The function determines the throughput file for a certain * model spectrum. The filename is extracted from the configuration * file. Then the throughput file is loaded into a spectrum structure. * The spectrum structure is returned. * * Parameters: * @param actspec - the model spectrum this is done for * @param CONF_file - the full filename of the configuration file * * Returns: * @return resp - the response function as a spectrum structure */ spectrum * get_throughput_spec(beamspec *actspec, char CONF_file[]) { spectrum *resp; char through_file[MAXCHAR]; char through_file_path[MAXCHAR]; // determine the filename of the throughput file from the configuration get_troughput_table_name(CONF_file, actspec->beamID, through_file); // build up the full filename build_path (AXE_CONFIG_PATH, through_file, through_file_path); // load the throughput into the spectrum struct resp=get_response_function_from_FITS(through_file_path,2); // return the spectrum struct return resp; } /** * Function: compute_tracedata * The function creates a tracedata structure for a specific * beam model. A tracedata structure consists of all relevant * information (position, wavelength, dispersion) for the pixels * along the trace of a specific beam. Since the reference point * remains constant during the modelling of a beam, it is * better to store the relevant data for the use in each pixel. * * Parameters: * @param actbeam - the beam of the model spectrum * @param actdir - the direct object of the model spectrum * @param wl_calibration - the wavelength calibration of the model spectrum * @param actspec - the model spectrum * * Returns: * @return acttrace - the tracedata structure */ tracedata * compute_tracedata(const beam actbeam, const dirobject *actdir, const calib_function *wl_calibration, const beamspec *actspec) { tracedata *acttrace; trace_func *tracefun; gsl_vector *dx; gsl_vector *dy; gsl_vector *xi; gsl_vector *lambda; gsl_vector *dlambda; gsl_vector *flux; gsl_vector *gvalue; double tmp1, tmp2; int dx_min, dx_max; int npoints; int i; int nentries; // allocate space for the tracedata acttrace = (tracedata *)malloc(sizeof(tracedata)); if (acttrace == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "compute_tracedata:" " Could not allocate" " memory for a tracedata object!"); tracefun = actbeam.spec_trace; // use the x-range of the direct obect area to // compute the dx-range for this beam dx_min = MIN(actspec->model_ref.x - actdir->ix_min, actspec->model_ref.x - actdir->ix_max)-5; dx_max = MAX(actspec->model_ref.x - actdir->ix_min, actspec->model_ref.x - actdir->ix_max) + (int)actspec->model->size1+5; // compute the number of points in the dx-range npoints = dx_max - dx_min + 1; // allocate space for the tracedata dx = gsl_vector_alloc(npoints); dy = gsl_vector_alloc(npoints); xi = gsl_vector_alloc(npoints); lambda = gsl_vector_alloc(npoints); dlambda = gsl_vector_alloc(npoints); flux = gsl_vector_alloc(npoints); gvalue = gsl_vector_alloc(npoints); // go over each point in the dx-range for (i=0; i < npoints; i++) { // compute the dx- and dy-values tmp1 = (double)(dx_min + i); tmp2 = tracefun->func (tmp1, tracefun->data); // store dx and dy, and xi (=dx) gsl_vector_set(dx, i, tmp1); gsl_vector_set(dy, i, tmp2); gsl_vector_set(xi, i, tmp1); gsl_vector_set(gvalue, i, 1.0); gsl_vector_set(flux, i, 1.0); } // compute the true xi values abscissa_to_pathlength (tracefun, xi); // go over each point in the dx-range for (i=0; i < npoints; i++) { // compute and store lambda gsl_vector_set(lambda, i, wl_calibration->func(gsl_vector_get(xi, i), wl_calibration->order, wl_calibration->coeffs)); // compute and store dlambda tmp1 = wl_calibration->func(gsl_vector_get(xi, i)-0.5, wl_calibration->order, wl_calibration->coeffs); tmp2 = wl_calibration->func(gsl_vector_get(xi, i)+0.5, wl_calibration->order, wl_calibration->coeffs); gsl_vector_set(dlambda, i, fabs(tmp2-tmp1)); } for (i=0; i < npoints; i++) { if (i == 0) { tmp1 = fabs(gsl_vector_get(lambda,i+1)-gsl_vector_get(lambda,i)); } else if (i == npoints-1) { tmp1 = fabs(gsl_vector_get(lambda,i)-gsl_vector_get(lambda,i-1)); } else { tmp1 = fabs(gsl_vector_get(lambda,i+1) - gsl_vector_get(lambda,i-1)) / 2.0; } gsl_vector_set(dlambda, i, tmp1); } // transfer the quantities to the structure acttrace->npoints = npoints; acttrace->dx_start= dx_min; acttrace->dx = dx; acttrace->dy = dy; acttrace->xi = xi; acttrace->lambda = lambda; acttrace->dlambda = dlambda; acttrace->flux = flux; acttrace->gvalue = gvalue; // for prism data: constrain the tracedata if (wl_calibration->pr_range != NULL) { nentries = get_valid_tracedata(acttrace, wl_calibration); select_tracedata(acttrace, wl_calibration,nentries); } // return the tracestructure return acttrace; } /** * Function: compute_short_tracedata * * Parameters: * @param actbeam - the beam of the model spectrum * @param actdir - the direct object of the model spectrum * @param wl_calibration - the wavelength calibration of the model spectrum * @param actspec - the model spectrum * * Returns: * @return acttrace - the tracedata structure */ tracedata * compute_short_tracedata(const aperture_conf *conf, const beam actbeam, const dirobject *actdir, const calib_function *wl_calibration, const beamspec *actspec) { tracedata *acttrace; trace_func *tracefun; gsl_vector *dx; gsl_vector *dy; gsl_vector *xi; gsl_vector *lambda; gsl_vector *dlambda; gsl_vector *flux; gsl_vector *gvalue; double tmp1, tmp2; int dx_min, dx_max; int npoints; int i; int nentries; int dx0, dx1; // allocate space for the tracedata acttrace = (tracedata *)malloc(sizeof(tracedata)); if (acttrace == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "compute_tracedata:" " Could not allocate" " memory for a tracedata object!"); tracefun = actbeam.spec_trace; dx0 = (double)conf->beam[actspec->beamID].offset.dx0; dx1 = (double)conf->beam[actspec->beamID].offset.dx1; dx_min = MIN(dx0, dx1)-1; dx_max = MAX(dx0, dx1)+1; // use the x-range of the direct obect area to // compute the dx-range for this beam //dx_min = MIN(actspec->model_ref.x - actdir->ix_min, actspec->model_ref.x - actdir->ix_max)-5; //dx_max = MAX(actspec->model_ref.x - actdir->ix_min, actspec->model_ref.x - actdir->ix_max) // + (int)actspec->model->size1+5; // compute the number of points in the dx-range npoints = dx_max - dx_min + 1; // allocate space for the tracedata dx = gsl_vector_alloc(npoints); dy = gsl_vector_alloc(npoints); xi = gsl_vector_alloc(npoints); lambda = gsl_vector_alloc(npoints); dlambda = gsl_vector_alloc(npoints); flux = gsl_vector_alloc(npoints); gvalue = gsl_vector_alloc(npoints); // go over each point in the dx-range for (i=0; i < npoints; i++) { // compute the dx- and dy-values tmp1 = (double)(dx_min + i); tmp2 = tracefun->func (tmp1, tracefun->data); // store dx and dy, and xi (=dx) gsl_vector_set(dx, i, tmp1); gsl_vector_set(dy, i, tmp2); gsl_vector_set(xi, i, tmp1); gsl_vector_set(gvalue, i, 1.0); gsl_vector_set(flux, i, 1.0); } // compute the true xi values abscissa_to_pathlength (tracefun, xi); // go over each point in the dx-range for (i=0; i < npoints; i++) { // compute and store lambda gsl_vector_set(lambda, i, wl_calibration->func(gsl_vector_get(xi, i), wl_calibration->order, wl_calibration->coeffs)); // compute and store dlambda tmp1 = wl_calibration->func(gsl_vector_get(xi, i)-0.5, wl_calibration->order, wl_calibration->coeffs); tmp2 = wl_calibration->func(gsl_vector_get(xi, i)+0.5, wl_calibration->order, wl_calibration->coeffs); gsl_vector_set(dlambda, i, fabs(tmp2-tmp1)); } for (i=0; i < npoints; i++) { if (i == 0) { tmp1 = fabs(gsl_vector_get(lambda,i+1)-gsl_vector_get(lambda,i)); } else if (i == npoints-1) { tmp1 = fabs(gsl_vector_get(lambda,i)-gsl_vector_get(lambda,i-1)); } else { tmp1 = fabs(gsl_vector_get(lambda,i+1) - gsl_vector_get(lambda,i-1)) / 2.0; } gsl_vector_set(dlambda, i, tmp1); } // transfer the quantities to the structure acttrace->npoints = npoints; acttrace->dx_start= dx_min; acttrace->dx = dx; acttrace->dy = dy; acttrace->xi = xi; acttrace->lambda = lambda; acttrace->dlambda = dlambda; acttrace->flux = flux; acttrace->gvalue = gvalue; // for prism data: constrain the tracedata if (wl_calibration->pr_range != NULL) { nentries = get_valid_tracedata(acttrace, wl_calibration); select_tracedata(acttrace, wl_calibration,nentries); } // return the tracestructure return acttrace; } /* * Function: get_valid_tracedata * The derives the number of valid tracedata points for prism data. * For prism data, only tracepoints with a certain offset * from the singularity at tr_length = a_0 is accepted. * * Parameters: * @param acttrace - the tracedata * @param wl_calibration - the calibration structure * * Returns: * @return nentries - the number of valid tracedata points */ double get_valid_tracedata(tracedata *acttrace, const calib_function *wl_calibration) { double lower, upper, a_0, d_xi; int nentries=0; int i=0; // get the lower and upper boundaries of the accepted range lower = gsl_vector_get(wl_calibration->pr_range, 0); upper = gsl_vector_get(wl_calibration->pr_range, 1); // get the a0 coefficient a_0 = wl_calibration->coeffs[0]; // go over all point int he tracedata for (i=0; i < acttrace->npoints; i++) { // compute the offset from the singularity d_xi = gsl_vector_get(acttrace->xi, i) - a_0; // enhance a counter if the offset is within the accepted range if (d_xi >= lower && d_xi <= upper) nentries++; } // return the number of valid data return nentries; } /* * Function: select_tracedata * The function applies additional constraints for prism data. * In prisms not all trace positions can be accepted, since * the odd calibration function results into strange wavelengths * and values close and beyond the singularity. * The function creates a new tracedata structure with values * only from the accepted trace range. * * Parameters: * @param acttrace - the tracedata * @param wl_calibration - the calibration structure * @param nentries - the number of valid entries */ void select_tracedata(tracedata *acttrace, const calib_function *wl_calibration, const int nentries) { gsl_vector *dx; gsl_vector *dy; gsl_vector *xi; gsl_vector *lambda; gsl_vector *dlambda; gsl_vector *flux; gsl_vector *gvalue; double lower, upper, a_0, d_xi; int i=0, iact; // get the lower and upper boundaries of the accepted range lower = gsl_vector_get(wl_calibration->pr_range, 0); upper = gsl_vector_get(wl_calibration->pr_range, 1); // get the a0 coefficient a_0 = wl_calibration->coeffs[0]; // check wehter thereis valid data at all if (nentries < 1) { // if no valid data, set all vectors to NULL dx = NULL; dy = NULL; xi = NULL; lambda = NULL; dlambda = NULL; flux = NULL; gvalue = NULL; acttrace->dx_start = 0.0; } else { // if there is valid data: // allocate space for the new tracedata structure dx = gsl_vector_alloc(nentries); dy = gsl_vector_alloc(nentries); xi = gsl_vector_alloc(nentries); lambda = gsl_vector_alloc(nentries); dlambda = gsl_vector_alloc(nentries); flux = gsl_vector_alloc(nentries); gvalue = gsl_vector_alloc(nentries); // go over all tracedata points iact=0; for (i=0; i < acttrace->npoints; i++) { // compute the offset from the singularity d_xi = gsl_vector_get(acttrace->xi, i) - a_0; // if the offside is in the accepted range if (d_xi >= lower && d_xi <= upper) { // transfer the data from the old to the new structure gsl_vector_set(dx , iact, gsl_vector_get(acttrace->dx, i)); gsl_vector_set(dy , iact, gsl_vector_get(acttrace->dy, i)); gsl_vector_set(xi , iact, gsl_vector_get(acttrace->xi, i)); gsl_vector_set(lambda , iact, gsl_vector_get(acttrace->lambda, i)); gsl_vector_set(dlambda, iact, gsl_vector_get(acttrace->dlambda, i)); gsl_vector_set(gvalue , iact, 1.0); // enhance the counter iact++; } } // set the intitial value acttrace->dx_start = gsl_vector_get(dx, 0); } // set the number of points acttrace->npoints = nentries; // release the old vectors in the structure gsl_vector_free(acttrace->dx); gsl_vector_free(acttrace->dy); gsl_vector_free(acttrace->xi); gsl_vector_free(acttrace->lambda); gsl_vector_free(acttrace->dlambda); gsl_vector_free(acttrace->flux); gsl_vector_free(acttrace->gvalue); // fill the new vectors into the tracedata structure acttrace->dx = dx; acttrace->dy = dy; acttrace->xi = xi; acttrace->lambda = lambda; acttrace->dlambda = dlambda; acttrace->flux = flux; acttrace->gvalue = gvalue; } /* * Function: fill_fluxfrom_SED * This function fills flux values at different wavelengths * into the tracedata structure. The flux values are computed * via the SED in the direct objects. * * Parameters: * @param actdir - the direct object * @param acttrace - the tracedata structure */ void fill_fluxfrom_SED(const dirobject *actdir, tracedata *acttrace) { int i=0; // go over all tracedata points for (i=0; i<acttrace->npoints; i++) // compute and fill in the flux values at each wavelength //gsl_vector_set(acttrace->flux, i, get_flux_from_SED(actdir->SED, gsl_vector_get(acttrace->lambda, i)/10.0)); gsl_vector_set(acttrace->flux, i, get_aveflux_from_SED(actdir->SED, gsl_vector_get(acttrace->lambda, i)/10.0, gsl_vector_get(acttrace->dlambda, i)/10.0)); } /* * Function: print_tracedata * This function prints some tracedata values * onto the screen. Used mainly for debugging * reasons. * * Parameters: * @param acttrace - the tracedata structure */ void print_tracedata(tracedata *acttrace) { int i=0; fprintf(stdout, "Trace starting at: %f\n", acttrace->dx_start); for (i=0; i < acttrace->npoints; i++) { fprintf(stdout, "dx: %f, dy: %f, xi: %f, lambda: %f, dlambda: %f, gdata: %f, flux: %g\n", gsl_vector_get(acttrace->dx, i), gsl_vector_get(acttrace->dy, i),gsl_vector_get(acttrace->xi, i), gsl_vector_get(acttrace->lambda, i), gsl_vector_get(acttrace->dlambda, i), gsl_vector_get(acttrace->gvalue, i), gsl_vector_get(acttrace->flux, i)); } } /** * Function: oblist_to_dirlist * Transforms a list of "object"'s into a list of * "dirobject"'s. The list of "dirobject"'s is terminated * with a NULL-object at the end. * * Parameters: * @param grism_file - the full path to the grism image * @param CONF_file - the full path to the config file * @param npixels - the dimension of the grism image * @param oblist - the object list to start from * @param spec_mod - the model spectra * @param model_scale - the scale for the size of the direct object area * @param int_type - interpolation type * * Returns: * @return dirlist - the dirobject list created */ dirobject ** oblist_to_dirlist(char grism_file[], char CONF_file[], const px_point npixels, object **oblist, spectral_models *spec_mod, const double model_scale, const int int_type) { dirobject **dirlist; aperture_conf *conf; gsl_matrix *drzcoeffs; int nobjects=0; int i=0; int j=0; int beamID; int max_offs; // load the configuration file conf = get_aperture_descriptor (CONF_file); // load the extension numbers get_extension_numbers(grism_file, conf,conf->optkey1,conf->optval1); // get the matrix with the drizzle coefficients drzcoeffs = get_crossdisp_matrix(grism_file, conf->science_numext); if (drzcoeffs->size1 < 2 || !drzcoeffs->size2) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "oblist_to_dirlist:" " Could not get" " the drizzle coefficients in file: %s\n", grism_file); // determine an offset from the PSF_OFFSET max_offs = (int)ceil(get_max_offset(conf)); // determine the number of objects in the object list nobjects = object_list_size(oblist); // allocate space for the dirobject list dirlist = (dirobject **) malloc((nobjects+1) * sizeof(dirobject *)); if (dirlist == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "oblist_to_dirlist:" " Could not allocate" " memory for pointers to %i dirobject objects", nobjects+1); // loop over all objectsconfig->camera for (i = 0; i < nobjects; i++) { // make sure that there are beams in the object if (oblist[i]->nbeams > 0) { // create a dirobject for each object dirlist[j] = fill_dirobject(oblist[i], npixels, drzcoeffs, model_scale, max_offs); fill_spectrum(oblist[i], dirlist[j], spec_mod, int_type); // fill_dpsf_function(conf, dirlist[j]); // fill the xoffset and yoffset values. // within the gaussian models they are dummys. for (beamID=0; beamID < conf->nbeams; beamID++) { dirlist[j]->xy_off[beamID].x = 0.0; dirlist[j]->xy_off[beamID].y = 0.0; } j++; } } // terminate the dirobject list with NULL dirlist[j] = NULL; // release the memory for the drizzle matrix gsl_matrix_free(drzcoeffs); free_aperture_conf(conf); return dirlist; } /** * Function: oblist_to_dirlist2 * Transforms a list of "object"'s into a list of * "dirobject"'s. The list of "dirobject"'s is terminated * with a NULL-object at the end. * * Parameters: * @param grism_file - the full path to the grism image * @param CONF_file - the full path to the config file * @param npixels - the dimension of the grism image * @param oblist - the object list to start from * @param spec_mod - the model spectra * @param obj_mod - te direct emission models * @param model_scale - the scale for the size of the direct object area * @param int_type - interpolation type * * Returns: * @return dirlist - the dirobject list created */ dirobject ** oblist_to_dirlist2(char grism_file[], char CONF_file[], const px_point npixels, object **oblist, spectral_models *spec_mod, object_models *obj_mod, const double model_scale, const int int_type) { dirobject **dirlist; aperture_conf *conf; gsl_matrix *drzcoeffs; int nobjects=0; int i=0; int j=0; int beamID; int max_offs; // load the configuration file conf = get_aperture_descriptor (CONF_file); // load the extension numbers get_extension_numbers(grism_file, conf,conf->optkey1,conf->optval1); // get the matrix with the drizzle coefficients drzcoeffs = get_crossdisp_matrix(grism_file, conf->science_numext); if (drzcoeffs->size1 < 2 || !drzcoeffs->size2) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "oblist_to_dirlist2:" " Could not get" " the drizzle coefficients in file: %s\n", grism_file); // determine an offset from the PSF_OFFSET max_offs = (int)ceil(get_max_offset(conf)); // determine the number of objects in the object list nobjects = object_list_size(oblist); // allocate space for the dirobject list dirlist = (dirobject **) malloc((nobjects+1) * sizeof(dirobject *)); if (dirlist == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "oblist_to_dirlist:" " Could not allocate" " memory for pointers to %i dirobject objects", nobjects+1); // loop over all objectsconfig->camera for (i = 0; i < nobjects; i++) { // make sure that there are beams in the object if (oblist[i]->nbeams > 0) { if (has_aperture_dirim(obj_mod, oblist[i])) dirlist[j] = fill_dirobj_fromdirim(oblist[i], obj_mod); else // create a dirobject for each object dirlist[j] = fill_dirobject(oblist[i], npixels, drzcoeffs, model_scale, max_offs); fill_spectrum(oblist[i], dirlist[j], spec_mod, int_type); // fill_dpsf_function(conf, dirlist[j]); // fill the xoffset and yoffset values. // within the gaussian models they are dummys. for (beamID=0; beamID < conf->nbeams; beamID++) { dirlist[j]->xy_off[beamID].x = 0.0; dirlist[j]->xy_off[beamID].y = 0.0; } j++; } } // terminate the dirobject list with NULL dirlist[j] = NULL; // release the memory for the drizzle matrix gsl_matrix_free(drzcoeffs); free_aperture_conf(conf); return dirlist; } /** * Function: fill_dirobject * Transforms one object into one dirobject. * Either transfers or computes the content * of the dirobject from the object. * * Parameters: * @param actobject - the object to be transformed * @param npixels - the dimension of the grism image * @param drzcoeffs - the drizzle coefficients * @param model_scale - the scale for the size of the direct object area * * Returns: * @return actdir - the dirobject created */ dirobject * fill_dirobject(const object *actobject, const px_point npixels, gsl_matrix *drzcoeffs, const double model_scale, const int max_offset) { dirobject *actdir; d_point dirmod[4]; double delx_a, dely_a; double delx_b, dely_b; gsl_vector *extention; // allocate space for the dirobject actdir = (dirobject *) malloc (sizeof (dirobject)); if (actdir == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "fill_dirobject:" " Could not allocate" " memory for a dirobject object"); // compute the vector of maximum elongation along the large half axis delx_a = model_scale * actobject->beams[0].awidth * cos(actobject->beams[0].aorient); dely_a = model_scale * actobject->beams[0].awidth * sin(actobject->beams[0].aorient); // compute the vector of maximum elongation along the small half axis delx_b = model_scale * actobject->beams[0].bwidth * cos(actobject->beams[0].aorient + M_PI/2.0); dely_b = model_scale * actobject->beams[0].bwidth * sin(actobject->beams[0].aorient + M_PI/2.0); // corner refpoint + large vector + small vector dirmod[0].x = actobject->beams[0].refpoint.x + delx_a + delx_b; dirmod[0].y = actobject->beams[0].refpoint.y + dely_a + dely_b; // corner refpoint + large vector - small vector dirmod[1].x = actobject->beams[0].refpoint.x + delx_a - delx_b; dirmod[1].y = actobject->beams[0].refpoint.y + dely_a - dely_b; // corner refpoint - large vector + small vector dirmod[2].x = actobject->beams[0].refpoint.x - delx_a + delx_b; dirmod[2].y = actobject->beams[0].refpoint.y - dely_a + dely_b; // corner refpoint - large vector - small vector dirmod[3].x = actobject->beams[0].refpoint.x - delx_a - delx_b; dirmod[3].y = actobject->beams[0].refpoint.y - dely_a - dely_b; // transfer refpoint and ID actdir->ID = actobject->ID; actdir->refpoint.x = actobject->beams[0].refpoint.x; actdir->refpoint.y = actobject->beams[0].refpoint.y; // get the extentions on the reference points extention = get_refpoint_ranges(actobject); // derive and store min/max in x/y for the corners actdir->ix_min = (int)floor(MIN(MIN(dirmod[0].x,dirmod[1].x),MIN(dirmod[2].x,dirmod[3].x))+ gsl_vector_get(extention, 0) + 0.5) - max_offset; actdir->ix_max = (int)floor(MAX(MAX(dirmod[0].x,dirmod[1].x),MAX(dirmod[2].x,dirmod[3].x))+ gsl_vector_get(extention, 1) + 0.5) + max_offset; actdir->iy_min = (int)floor(MIN(MIN(dirmod[0].y,dirmod[1].y),MIN(dirmod[2].y,dirmod[3].y))+ gsl_vector_get(extention, 2) + 0.5) - max_offset; actdir->iy_max = (int)floor(MAX(MAX(dirmod[0].y,dirmod[1].y),MAX(dirmod[2].y,dirmod[3].y))+ gsl_vector_get(extention, 3) + 0.5) + max_offset; // derive the distortion scales along the major an minor axis actdir->drzscale = get_axis_scales(actobject->beams[0], drzcoeffs, npixels); actdir->dirim = NULL; // free the memory for the vector gsl_vector_free(extention); // return the dirobject return actdir; } /** * Function: fill_dirobj_fromdirim * Transforms an object which has a direct emission model associated * to into a direct object. The direct object created is returned * * Parameters: * @param actobject - the object to be transformed * @param object_models - the structure with the direct emission models * * Returns: * @return actdir - the dirobject created */ dirobject * fill_dirobj_fromdirim(const object *actobject, object_models *objmodels) { dirobject *actdir; gsl_vector *extention; dirim_emission *dirim; // allocate space for the dirobject actdir = (dirobject *) malloc (sizeof (dirobject)); if (actdir == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "fill_dirobj_fromdirim:" " Could not allocate" " memory for a dirobject object"); // assign a direct emission model to a local variable dirim = get_dirim_emission(objmodels, actobject->beams[0].modimage); // transfer refpoint and ID actdir->ID = actobject->ID; actdir->refpoint.x = actobject->beams[0].refpoint.x; actdir->refpoint.y = actobject->beams[0].refpoint.y; // get the extentions on the reference points extention = get_refpoint_ranges(actobject); // derive and store min/max in x/y for the corners actdir->ix_min = (int)floor(actobject->beams[0].refpoint.x - dirim->xmean + gsl_vector_get(extention, 0) + 0.5); actdir->ix_max = (int)floor(actobject->beams[0].refpoint.x + dirim->xmean + gsl_vector_get(extention, 1) + 0.5); actdir->iy_min = (int)floor(actobject->beams[0].refpoint.y - dirim->ymean + gsl_vector_get(extention, 2) + 0.5); actdir->iy_max = (int)floor(actobject->beams[0].refpoint.y + dirim->ymean + gsl_vector_get(extention, 3) + 0.5); // fix the drizzle scale, since it has no // business in this context actdir->drzscale.x = 1.0; actdir->drzscale.y = 1.0; // store the direct emission // object in the direct object actdir->dirim = dirim; // free the memory for the vector gsl_vector_free(extention); // return the dirobject return actdir; } /** * * Function: get_refpoint_ranges * * Determines the differences of the reference point positions within * the beams of an object. The min/max values in x/y with respect to * the reference point of the first beam are determined and returned * in a vector. * * Parameters: * @param actobject - the object to be transformed * * Returns: * @return ret - the dirobject created */ gsl_vector * get_refpoint_ranges(const object *actobject) { gsl_vector *ret; int j; //d_point reference; // allocate memory ret = gsl_vector_alloc(4); // initialize the vector with the default value gsl_vector_set(ret, 0, actobject->beams[0].refpoint.x); gsl_vector_set(ret, 1, actobject->beams[0].refpoint.x); gsl_vector_set(ret, 2, actobject->beams[0].refpoint.y); gsl_vector_set(ret, 3, actobject->beams[0].refpoint.y); // go over all beams in the object for (j=1; j < actobject->nbeams; j++) { // get the the new absolute mins and maxs in the reference points gsl_vector_set(ret, 0, MIN(gsl_vector_get(ret, 0) , actobject->beams[j].refpoint.x)); gsl_vector_set(ret, 1, MAX(gsl_vector_get(ret, 1) , actobject->beams[j].refpoint.x)); gsl_vector_set(ret, 2, MIN(gsl_vector_get(ret, 2) , actobject->beams[j].refpoint.y)); gsl_vector_set(ret, 3, MAX(gsl_vector_get(ret, 3) , actobject->beams[j].refpoint.y)); } // transform the absolute ranges into relative ones gsl_vector_set(ret, 0, gsl_vector_get(ret, 0) - actobject->beams[0].refpoint.x); gsl_vector_set(ret, 1, gsl_vector_get(ret, 1) - actobject->beams[0].refpoint.x); gsl_vector_set(ret, 2, gsl_vector_get(ret, 2) - actobject->beams[0].refpoint.y); gsl_vector_set(ret, 3, gsl_vector_get(ret, 3) - actobject->beams[0].refpoint.y); // return the result return ret; } /** * Function: fill_spectrum * Transfers the wavelength information from an object * to a dirobject. Store the minimum and maximum wavelength * as well as associated flux values in the structure. * * Parameters: * @param actobject - the object to be transformed * @param actdir - the dirobject to store the flux values in * @param spec_mod - the spectral model list * @param int_type - the interpolation type to be used */ void fill_spectrum(const object *actobject, dirobject *actdir, spectral_models *spec_mod, const int int_type) { energy_distrib *sed=NULL; // double *sed_wavs; // double *sed_flux; beam onebeam; //int i_type=0; // int nwavs=0; //int i = 0; int j = 0; // the data are derived from the 1st non-zero beam in the object; // go along the beams util you find a non-zero beam while (actobject->beams[j].flux == NULL && j < actobject->nbeams) j++; // store this beam onebeam = actobject->beams[j]; // do something only if the first beam has flux values if (onebeam.flux != NULL && j < actobject->nbeams) { if (onebeam.modspec > 0 && spec_mod) { // get the model spectrum sed = get_model_sed(spec_mod, onebeam.modspec); // mark that the SED does NOT come // from broad band colours actdir->bb_sed=0; } else { sed = make_sed_from_beam(onebeam, int_type, actobject->ID); /* // // the code below is a mess!!!! // MUST be re-factorized!! // // determine the number of flux values, allocate space nwavs = (onebeam.flux->size)/2; // determine the number of flux values, allocate space nwavs = (onebeam.flux->size)/2; sed = (energy_distrib*) malloc(sizeof(energy_distrib)); sed_wavs = (double*) malloc(nwavs*sizeof(double)); sed_flux = (double*) malloc(nwavs*sizeof(double)); // transfer the data into the 'local' arrays for (i=0; i<nwavs; i++) { sed_wavs[i] = gsl_vector_get(onebeam.flux, 2*i); sed_flux[i] = gsl_vector_get(onebeam.flux, 2*i+1); } // transfer the vector and length information // to the SED object sed->npoints = nwavs; sed->wavelength = sed_wavs ; sed->flux = sed_flux; // check the interpolation type i_type = check_interp_type(int_type, nwavs, actobject->ID); if (nwavs > 1) { // if possible, allocate and // initialize an interpolation object if (i_type == 2) sed->interp = gsl_interp_alloc (gsl_interp_polynomial, (size_t)nwavs); else if (i_type == 3) sed->interp = gsl_interp_alloc (gsl_interp_cspline, (size_t)nwavs); else sed->interp = gsl_interp_alloc (gsl_interp_linear, (size_t)nwavs); sed->accel = gsl_interp_accel_alloc (); gsl_interp_init (sed->interp, sed->wavelength, sed->flux, (size_t)sed->npoints); } else { // if no interpolation, set // the memeber to NULL sed->interp = NULL; sed->accel= NULL; } */ // mark that the SED DOES come // from broad band colours actdir->bb_sed=1; } } else { // make an error if there are no flux values aXe_message(aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETCONT: " "the OAF does not have flux values\n"); } // transfer the SED object to the direct object actdir->SED = sed; } /** * Function: make_sed_from_beam * * Parameters: * @param onebeam - the object to be transformed * @param int_type - the interpolation type to be used * @param objID - the interpolation type to be used */ energy_distrib * make_sed_from_beam(const beam onebeam, const int int_type, const int objID) { energy_distrib *sed; double *sed_wavs; double *sed_flux; int nwavs; int i_type; int i; // determine the number of flux values, allocate space nwavs = (onebeam.flux->size)/2; // determine the number of flux values, allocate space nwavs = (onebeam.flux->size)/2; sed = (energy_distrib*) malloc(sizeof(energy_distrib)); sed_wavs = (double*) malloc(nwavs*sizeof(double)); sed_flux = (double*) malloc(nwavs*sizeof(double)); // transfer the data into the 'local' arrays for (i=0; i<nwavs; i++) { sed_wavs[i] = gsl_vector_get(onebeam.flux, 2*i); sed_flux[i] = gsl_vector_get(onebeam.flux, 2*i+1); } // transfer the vector and length information // to the SED object sed->npoints = nwavs; sed->wavelength = sed_wavs ; sed->flux = sed_flux; // check the interpolation type i_type = check_interp_type(int_type, nwavs, objID); if (nwavs > 1) { // if possible, allocate and // initialize an interpolation object if (i_type == 2) sed->interp = gsl_interp_alloc (gsl_interp_polynomial, (size_t)nwavs); else if (i_type == 3) sed->interp = gsl_interp_alloc (gsl_interp_cspline, (size_t)nwavs); else sed->interp = gsl_interp_alloc (gsl_interp_linear, (size_t)nwavs); sed->accel = gsl_interp_accel_alloc (); gsl_interp_init (sed->interp, sed->wavelength, sed->flux, (size_t)sed->npoints); } else { // if no interpolation, set // the memeber to NULL sed->interp = NULL; sed->accel = NULL; } // return the sed return sed; } /** * Function: get_dirobject_from_list * The function identifies a dirobject * in a list of dirobjects. The identification * is made on the attribute ID. The identified * dirobject is returned. If no dirobject could * be identified, the NULL object, which is at * the end of each dirobject list, is returned. * * Parameters: * @param dirlist - the dirobject list * @param ID - the ID number to be identified * * Returns: * @return dirobject - the identified dirobject or the 'NULL'-dirobject */ dirobject * get_dirobject_from_list(dirobject ** dirlist, const int ID) { //dirobject * actdir; int i, ndirs = 0; // count the number of dirobjects in the list while (dirlist[ndirs] != NULL) ndirs++; // loop over all dirobject for (i = 0; i < ndirs; i++) { // try to identify a dirobject, // return it in case of a postitive identification if (dirlist[i]->ID == ID) return dirlist[i]; } // return the NULL-dirobject at the end of the list return dirlist[ndirs]; } /** * Function: get_dirobject_meanpos * The function computes the average pixel coos of a * direct object. This is done in a very simple way, by * averaging the maximum and minimum pixel coordinates in * both, x and y. Neither the shape nor the * the intensity in the individual pixels are taken * into account. * * Parameters: * @param actdir - the direct object * * Returns: * @return m_point - the means coo's in x and y */ d_point get_dirobject_meanpos(dirobject *actdir) { d_point m_point; m_point.x = ((double)actdir->ix_max + (double)actdir->ix_min) / 2.0; m_point.y = ((double)actdir->iy_max + (double)actdir->iy_min) / 2.0; return m_point; } /** * Function: get_beam_for_beamspec * The function selects for a given beamspec the corresponding * beam from an object list. The identification is done * via objectID and beamID. An error is thrown in case that * no matching beam could be found. * * Parameters: * @param oblist - the object list to identify a beam from * @param nobjects - the number of objects in the object list * @param actspec - the model spectrum to identify a beam for * * @return actbeam - the identified beam */ beam get_beam_for_beamspec(object **oblist, const int nobjects, const beamspec *actspec) { beam actbeam; int i, j; // set the beam ID to -1 to identify // failed identification actbeam.ID = -1; // go over all objects in the list for (i = 0; i < nobjects; i++) { // search for a matching object ID if (oblist[i]->ID == actspec->objectID) { // go over all beams in the matchin object for (j=0; j < oblist[i]->nbeams; j++) { // search for a matching beam ID if (oblist[i]->beams[j].ID == actspec->beamID) actbeam = oblist[i]->beams[j]; } } } // report an error in case that the identification failed if (actbeam.ID == -1) aXe_message(aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETCONT: " "object ID %i, Beam %c not found\n", actspec->objectID, BEAM(actspec->beamID)); // return the identified beam return actbeam; } /** * Function: get_beamspec_from_list * The functions extracts and returns a specific model beam * out of the list of model beams. The requested model * beam is identified on the basis of the aperture ID and * the beam ID. Without positive identification the last modelled * spectrum in the ist is returned, which is NULL. * * Parameters: * @param speclist - * @param aperID - the object ID of the requested beam * @param beamID - the beam ID of the requested beam * * Returns: * @return ret - the identified beam (or the NULL beam at the end of the list) */ beamspec * get_beamspec_from_list(beamspec **speclist, const int aperID, const int beamID) { //beamspec *ret; int i=0; while (speclist[i] != NULL) { if (speclist[i]->objectID == aperID && speclist[i]->beamID == beamID) { break; } i++; } return speclist[i]; } /** * Function: print_dirobject * Prints the data in a dirobject onto the screens. * "Natural" format is used, which means printed are first * the upper corners, then the refpoint, then * the lower corners. * * Parameters: * @param actdir - the dirobject to be printed */ void print_dirobject(const dirobject * actdir){ int i=0; int npoints=0; fprintf(stdout, "Object ID: %i\n", actdir->ID); fprintf(stdout,"%5i,%5i %5i,%5i\n", actdir->ix_min, actdir->iy_max, actdir->ix_max, actdir->iy_max); fprintf(stdout," %7.1f,%7.1f \n", actdir->refpoint.x, actdir->refpoint.y); fprintf(stdout,"%5i,%5i %5i,%5i\n\n", actdir->ix_min, actdir->iy_min, actdir->ix_max, actdir->iy_min); npoints = actdir->SED->npoints; fprintf(stdout,"Wavelengths:\n"); fprintf(stdout,"Minimum: %.1f,%.3e Maximum: %.1f, %.3e\n", actdir->SED->wavelength[0], actdir->SED->flux[0], actdir->SED->wavelength[npoints-1], actdir->SED->flux[npoints-1]); for (i=0; i<npoints;i++) fprintf(stdout,"Wavelength: %.1f, Flux: %.5e\n", actdir->SED->wavelength[i], actdir->SED->flux[i]); fprintf(stdout,"\n\n"); } /** * Function: check_interp_type * The function checks the requested interpolation type * against the number of flux values in the models. * The interpolation type is adjusted in case that there * are not enough flux values for the reuqested type. * * Parameters: * @param inter_type - the requested interpolation * @param n_flux - the number of flux values * @param ID - the object ID * * Returns: * @return type - the feasable interpolation type */ int check_interp_type(const int inter_type, const int n_flux, const int ID) { int type=0; // for interpolation types other than linear at leas // three flux values must be there if (n_flux < 3 && inter_type > 1) { // make a warnign message if there are // not enough flux value if (inter_type > 2) aXe_message (aXe_M_WARN4, __FILE__, __LINE__, "\naXe_PETCONT: Object: %i: interpolation switched from \"spline\" to \"linear\"!\n", ID); else aXe_message (aXe_M_WARN4, __FILE__, __LINE__, "\naXe_PETCONT: Object: %i: interpolation switched from \"polynomial\" to \"linear\"!\n", ID); // adjust the interpolation type to linear type = 1; } else { // copy the requeted interpolation type // if there are enough flux values type = inter_type; } // return the adjusted type return type; } /** * * Function: free_dirlist * Releases the memory allocated * for a list of dirobjects. * after releasing memory, all elements * are set to NULL/ * * Parameters: * @param dirlist - the list of dirobjects * @paran spec_mod - describes what all to free */ void free_dirlist (dirobject ** dirlist) { int i, ndirs = 0; // count the number of dirobjects while (dirlist[ndirs] != NULL) ndirs++; // go over each item in the list for (i = 0; i < ndirs; i++) { // check for broad band SED if (dirlist[i]->bb_sed) // free the energy distribution free_enerdist (dirlist[i]->SED); // fre the dirobject free (dirlist[i]); // set the dirobject to NULL dirlist[i] = NULL; } // free the list free (dirlist); // set the list to NULL dirlist = NULL; } /** * Function: free_enerdist * The function releases all the memory * of a SED object * * Parameters: * @param sed - the SED object */ void free_enerdist(energy_distrib *sed) { // free the two arrays free(sed->wavelength); free(sed->flux); // free the intepolation // structures if defined if (sed->interp != NULL) gsl_interp_free (sed->interp); if (sed->accel != NULL) gsl_interp_accel_free (sed->accel); // free the object itsel free(sed); } /** * Function: free_speclist * The function releases all the memory * of a list of beamspec's. * * Parameters: * @param speclist - a list of beamspecs * */ void free_speclist(beamspec **speclist) { int i=0; // go over each item in the list while (speclist[i] != NULL) { // free the memory in the matrix gsl_matrix_free (speclist[i]->model); // free the beamspec object itself free (speclist[i]); // set the beamspec to NULL, // increment the counter speclist[i++] = NULL; } // free the memory of the list free(speclist); // set the list to NULL speclist = NULL; } /** * Function: free_tracedata * Releases the memory in * a tracedata structure. * * Parameters: * @param acttrace - the structure to be freed */ void free_tracedata(tracedata *acttrace) { if (acttrace->npoints > 0) { gsl_vector_free(acttrace->dx); gsl_vector_free(acttrace->dy); gsl_vector_free(acttrace->xi); gsl_vector_free(acttrace->lambda); gsl_vector_free(acttrace->dlambda); gsl_vector_free(acttrace->flux); gsl_vector_free(acttrace->gvalue); } free(acttrace); } /** * Function: get_flux_from_SED * The functions returns the flux value at a given * wavelength for a certain SED. * In case that the wavelength is beyound the * wavelength interval where the SED is defined, * the closest model value in wavelength is returned. * Otherwise the interpolated value as defined in the * SED object is returned * * @param sed - the SED-object to derive a flux value from * @param in_wave - the wavelength to compute the flux value for * * @return flux - the flux value for the requested wavelength */ double get_flux_from_SED(const energy_distrib *sed, double in_wave) { double flux=0.0; if (in_wave <= sed->wavelength[0]){ // give the lowest defined value if // the requested wavelength is lower flux = sed->flux[0]; } else if (in_wave > sed->wavelength[sed->npoints-1]){ // give the highest defined value if // the requested wavelength is higher flux = sed->flux[sed->npoints-1];} else { // derive the interpolated value flux = gsl_interp_eval(sed->interp, sed->wavelength, sed->flux, in_wave, sed->accel);} // return the interpolated flux value return flux; } /** * Function: get_aveflux_from_SED * The function computes and returns the integrated flux of a given SED object * over a given interval at a given wavelength position. * Beyond the wavelength interval the SED is defined on, the flux is taken * as constant. * * @param sed - the SED-object to derive a flux value from * @param in_wave - the wavelength to average the flux value at * @param wave_interv - the wavelength interval to average over * * @return flux - the average for the requested wavelength interval */ double get_aveflux_from_SED(const energy_distrib *sed, double in_wave, double wave_interv) { double wav_min=0.0; double wav_max=0.0; double range_1=0.0; double range_2=0.0; double flux=0.0; // check whether there is only one // flux point if (sed->npoints < 2) // return the value at the single // flux point return sed->flux[0]; // compute the interval coundaries wav_min = in_wave - 0.5*wave_interv; wav_max = in_wave + 0.5*wave_interv; // check whether the upper wavelength // interval boundary is just shorter than // the SED range if (wav_max < sed->wavelength[0]){ // give the smallest SED flux value flux = sed->flux[0];} // check whether the lower wavelength // interval boundary is just longer than // the SED range else if (wav_min > sed->wavelength[sed->npoints-1]){ // give the highest defined value flux = sed->flux[sed->npoints-1];} // check whether the interval covers the lower // end covered by the SED else if (wav_min < sed->wavelength[0] && wav_max > sed->wavelength[0]) { // get the lower interval range_1 = sed->wavelength[0] - wav_min; // check whether the upper boundary is // covered by the SED if (wav_max <= sed->wavelength[sed->npoints-1]) { //fprintf(stderr,"got here!\n"); // get the integration interval range_2 = wav_max - sed->wavelength[0]; // average the two integrals flux = (range_1*sed->flux[0] + gsl_interp_eval_integ(sed->interp, sed->wavelength, sed->flux, sed->wavelength[0], wav_max, sed->accel)) / wave_interv; } else { // get the integration interval range_2 = wav_max - sed->wavelength[sed->npoints-1]; // average the three integrals flux = (range_1*sed->flux[0] + range_2*sed->flux[sed->npoints-1] + gsl_interp_eval_integ(sed->interp, sed->wavelength, sed->flux, sed->wavelength[0], sed->wavelength[sed->npoints-1], sed->accel)) / wave_interv; } } // check whether the interval start is beyound // the lower // end covered by the SED else if (wav_min >= sed->wavelength[0] && wav_max >= sed->wavelength[0]) { // check whether the interval is completely // covered by the SED if (wav_max <= sed->wavelength[sed->npoints-1]) { // compute the integral over the SED and the interval flux = gsl_interp_eval_integ(sed->interp, sed->wavelength, sed->flux, wav_min, wav_max, sed->accel) / wave_interv; } // if the interval is partly out // of the SED else { // compute the range which is in range_1 = sed->wavelength[sed->npoints-1] - wav_min; // compute the range which is out range_2 = wav_max - sed->wavelength[sed->npoints-1]; // compute the integrated flux via weighted summation // of the in part and the out part flux = (gsl_interp_eval_integ(sed->interp, sed->wavelength, sed->flux, wav_min, sed->wavelength[sed->npoints-1], sed->accel) + range_2*sed->flux[sed->npoints-1]) / wave_interv; } } // return the integrated flux value return flux; } /** * * Function: get_flambda_from_magab * The subroutine calculates the flambda value for a * mag_AB value given with its wvavelength as input * parameters. * * Parameters: * @param mag - the mag_AB value * @param lambda - the wavelength for mag_AB * * Returns: * @return flambda - the calculated flambda value */ double get_flambda_from_magab(double mag, double lambda) { double flambda=0.0; double fnu=0.0; fnu = pow(10.0, -0.4*(mag+48.6)); flambda = 1.0e+16*LIGHTVEL*fnu/(lambda*lambda); return flambda; } /* * Function: fill_gaussvalues * The function determines the wavelength dependent emission * for a given object at a given point in the gaussian emission model. * The values are filled into the * according vector of the tracedata structure. * * Parameters: * @param dpixel - the coordinates of the point * @param actbeam - the beam to derive * @param actdir - the direct object * @param lambda_ref - the reference wavelength * @param conf - the configuration structure * @param acttrace - the tracedata structure * */ void fill_gaussvalues(const d_point dpixel, const beam actbeam, const dirobject *actdir, const double lambda_ref, const aperture_conf *conf, const double psf_offset, tracedata *acttrace) { beam new_beam; double dpsf=0.0; //double gval=0.0; double lambda=0.0; //double factor=0.0; //double nom=0.0; //double denom=0.0; int i=0; int minpsf_flagg=0; // get the acurate emission value with subgridding //gval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale); //fprintf(stdout, "gvalue: %e %f %f", gval, actdir->drzscale.x, actdir->drzscale.y); // 0: fastest scenario: fill the vector with // identical values: 34s // gsl_vector_set_all(acttrace->gvalue, i, gval); // 1: iterate over the vector and enter the same // value: 35s if (conf->psfrange && conf->psfcoeffs) { // go over all tracedata (that means wavelength) points for (i=0; i < acttrace->npoints; i++) { // derive the wavelength lambda = gsl_vector_get(acttrace->lambda, i)/10.0; // derive the correction of the psf at the wavelength // 3: calculating the psf-offset: 90s dpsf = psf_offset + get_dpsf(lambda_ref, lambda, conf, actbeam); // dpsf=0.0; //fprintf(stdout, "dpsf: %f", dpsf); // derive a beam with the correct widths at the wavelength // 2: creating a new beam with a different size: 50s new_beam = get_newbeam(actbeam,dpsf); // transport the if (new_beam.ID) minpsf_flagg=1; // derive the correction factor for the emission using the correct widths // 4: computing the correction factor for the wavelength: 255s //factor = get_emodel_value(dpixel,new_beam,actdir->drzscale)/get_emodel_value(dpixel,actbeam,actdir->drzscale); //nom = get_emodel_value(dpixel,new_beam,actdir->drzscale); //denom = get_emodel_value(dpixel,actbeam,actdir->drzscale); //if (nom != 0.0 && denom != 0.0) // factor = nom / denom; //else // factor = 1.0; //fprintf(stdout, "factor: %f ", factor); // store the emission value, taking into account the correction //gsl_vector_set(acttrace->gvalue, i, gval*factor); gsl_vector_set_all(acttrace->gvalue, get_sub_emodel_value(dpixel, new_beam, actdir->drzscale)); //fprintf(stdout, "gvalue * factor: %e ", gval*factor); } } else { // derive a beam with the correct widths at the wavelength new_beam = get_newbeam(actbeam,psf_offset); if (new_beam.ID) minpsf_flagg=1; // derive the correction factor for the emission using the correct widths //factor = get_emodel_value(dpixel,new_beam,actdir->drzscale)/get_emodel_value(dpixel,actbeam,actdir->drzscale); //nom = get_emodel_value(dpixel,new_beam,actdir->drzscale); //denom = get_emodel_value(dpixel,actbeam,actdir->drzscale); //if (nom != 0.0 && denom != 0.0) // factor = nom / denom; //else // factor = 1.0; // store the emission value, taking into account the correction //gsl_vector_set_all(acttrace->gvalue, gval*factor); gsl_vector_set_all(acttrace->gvalue, get_sub_emodel_value(dpixel, new_beam, actdir->drzscale)); } if (minpsf_flagg) aXe_message (aXe_M_WARN4, __FILE__, __LINE__, "\naXe_PETCONT: points in PSF of object %i beam %c smaller than PSF_MIN=%f! Set to PSF_MIN\n", actdir->ID, BEAM(actbeam.ID), MINPSF); } /* * Function: get_newbeam * The function creates a new beam with modified widths. * The modification of the width is given as the differential * value. The new beam is used to compute an emission value * for a specific wavelength. * * Parameters: * @param actbeam - the original beam * @param dpsf - the changes in width * * Returns: * @return new_beam - the new beam */ beam get_newbeam(const beam actbeam, const double dpsf) { beam new_beam; new_beam.ID=0; // check the sign of the modification if (dpsf >0.0) { // positive sign: // add (in quadrature) the psf-modification new_beam.awidth = sqrt(SQR(actbeam.awidth) + SQR(dpsf)); new_beam.bwidth = sqrt(SQR(actbeam.bwidth) + SQR(dpsf)); } else { // check whether awidth is big enough if (actbeam.awidth+dpsf < MINPSF) { // set the minimum sign, and set the psf to MINPSF new_beam.ID=1; new_beam.awidth = MINPSF; } else { // negative sign: // subtract (in quadrature) the psf-modification new_beam.awidth = sqrt(SQR(actbeam.awidth) - SQR(dpsf)); } // check whether bwidth is big enough if (actbeam.bwidth+dpsf < MINPSF) { // set the minimum sign, and set the psf to MINPSF new_beam.ID=1; new_beam.bwidth = MINPSF; } else { // negative sign: // subtract (in quadrature) the psf-modification new_beam.bwidth = sqrt(SQR(actbeam.bwidth) - SQR(dpsf)); } } // transfer necessary data new_beam.aorient = actbeam.aorient; new_beam.refpoint = actbeam.refpoint; // return the new beam return new_beam; } /** * Function: get_dpsf * The function computes the difference of the psf width * at two different wavelengths. The dependence of the * psf as a function of the wavelength is supposed to be * a polynomial * * Parameters: * @param lambda_ref - the reference wavelength * @param lambda - the wavelength to evaluate the difference for * @param conf - the configuration structure * * Returns: * @return dpsf - the psf difference */ double get_dpsf(const double lambda_ref, const double lambda, const aperture_conf *conf, const beam actbeam) { double dpsf=0.0; double lmin=0.0; double lmax=0.0; // get the minimum and maximum wavelength // for the dependency lmin = gsl_vector_get(conf->psfrange, 0); lmax = gsl_vector_get(conf->psfrange, 1); // the reference wavelength must be inside of the // area where the polynomial is valid if (lambda_ref < lmin){ aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETCONT:" "Reference wavelength %f" " is smaller than minimum wavelength: %f!\n", lambda_ref, lmin); } else if (lambda_ref > lmax){ aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETCONT:" "Reference wavelength %f" " is larger than maximum wavelength: %f!\n", lambda_ref, lmax); } else{ if (lambda < lmin) // if the target wavelength is larger, // evaluate at the upper border dpsf = get_polyN_gsl(lmin, conf->psfcoeffs) - get_polyN_gsl(lambda_ref, conf->psfcoeffs); else if (lambda > lmax) // if the target wavelength is smaller, // evaluate at the lower border dpsf = get_polyN_gsl(lmax, conf->psfcoeffs) - get_polyN_gsl(lambda_ref, conf->psfcoeffs); else // evaluate the exact position dpsf = get_polyN_gsl(lambda, conf->psfcoeffs) - get_polyN_gsl(lambda_ref, conf->psfcoeffs); } // return the result return dpsf; } /** * Function: get_sub_emodel_value * The function evaluates the emission of a 2D gauss model * with the parameters as given in a beam at a particular position. * This function derives the function values on a series of * grid positions +-.5pixels in x/y around the requested * positions. This avoids rounding problems. * The 1D grisdsize is set by the macro NSUB in the * header file * * Parameters: * @param dpixel - the point to evaluate the emission model * @param actbeam - the beam to set up the model for * @param drzscale - the relative pixelscale at the model position * * Returns: * @return sval - the value of the emission model */ double get_sub_emodel_value(const d_point dpixel, const beam actbeam, const d_point drzscale) { d_point dtmp; double sval = 0.0; double step = 0.0; double offset = 0.0; int irange = 0; int kk=0, ll=0; // convert the number of steps to a local integer irange = (int)NSUB; // compute the step size step = 1.0/(2.0*(double)NSUB); // compute the initial offset offset = step/2.0; for (kk=-irange; kk < irange; kk++) { for (ll=-irange; ll < irange; ll++) { // determine the actual grid position dtmp.x = dpixel.x + (double)kk * step + offset; dtmp.y = dpixel.y + (double)ll * step + offset; // get the value at the grid position sval = sval + get_emodel_value(dtmp, actbeam, drzscale); } } // normalize the result sval = sval *step * step; // return the result return sval; } /** * Function: get_emodel_value * The function evaluates the emission of a 2D gauss model * with the parameters as given in a beam at a particular position. * A different pixelscale at the emission point due to * geometrical distortion can be taken into account. * * Parameters: * @param dpixel - the point to evaluate the emission model * @param actbeam - the beam to set up the model for * @param pixscale - the relative pixelscale at the model position * * Returns: * @return evalue - the value of the emission model */ double get_emodel_value(const d_point dpixel, const beam actbeam, const d_point drzscale) //get_emodel_value(const px_point dpixel, const beam actbeam, const d_point drzscale) { double evalue=0.0; double amod, bmod; double xrel, yrel; double angle; double arg; // apply the correction due to geom. distortion amod = actbeam.awidth / drzscale.x; bmod = actbeam.bwidth / drzscale.y; // make some precalculations xrel = dpixel.x - actbeam.refpoint.x; yrel = dpixel.y - actbeam.refpoint.y; angle = actbeam.aorient; // determine the argument of the exponent arg = SQR(( xrel*cos(angle) + yrel*sin(angle)) / amod) + SQR((-xrel*sin(angle) + yrel*cos(angle)) / bmod); // determine the emission value evalue = 0.5/(amod*bmod*M_PI)*exp(-0.5*arg); // return the emission value return evalue; } double get_psf_WFC(const double lambda) { double psf; psf = 1.2994407614072 + 0.11290883734113e-02*lambda - 0.44245634760175e-06*pow(lambda,2.0); return psf; } double get_psf_HRC(const double lambda) { double psf = 0.0; psf = 8.1986545952891 - 0.82947763250959e-01*lambda + 0.40134114766915e-03*pow(lambda,2.0) - 0.94651169604925e-06*pow(lambda,3.0) + 0.11804479784053e-08*pow(lambda,4.0) - 0.74395828991899e-12*pow(lambda,5.0) + 0.18657361078105e-15*pow(lambda,6.0); return psf; } double get_psf_SBC(const double lambda) { double psf = 0.0; psf = 7.9833718878881 - 0.11283853224345 *lambda + 0.64235625522476e-03*pow(lambda,2.0) - 0.12471899390220e-05*pow(lambda,3.0); return psf; } /** * * Function: get_polyN_gsl * The function evaluates a polynomial * at a given position. * * Parameters: * @param x - the point to evaluate the polynomial * @param params - gsl-vector with the coefficients of the polynomial * * Returns: * @return p - the value of the polynomial */ double get_polyN_gsl (const double x, const gsl_vector *params) { int i; double p=0.0; // go over the gsl-vector and // sum up the individual terms for (i=0; i<(int)params->size; i++) { p += gsl_vector_get(params,i)*pow(x,i); } // return the value return p; }
{ "alphanum_fraction": 0.6506262859, "avg_line_length": 30.0609367894, "ext": "c", "hexsha": "9e10f93a67b72dd46281e2e9d85cf73ba84c8f1b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/model_utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/model_utils.c", "max_line_length": 163, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/model_utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 18632, "size": 66104 }
//This takes the output of window_univar, and applies the 1D FFT to each row or col. //The input dim is which dim to take the 1D FFT along (0->along cols, 1->along rows). //The output Y is power (real-valued), i.e. the FFT squared, Y = X*conj(X) element-wise. //The size of Y must be FxC if dim==0, and RxF if dim==1, where F = nfft/2 + 1. //I tried parallel versions with OpenMP, but much slower (have to make fftw_plan P times!). #include <stdio.h> #include <cblas.h> #include <fftw3.h> #ifdef __cplusplus namespace ov { extern "C" { #endif int fft_squared_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft); int fft_squared_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft); int fft_squared_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft) { const float z = 0.0f; const int F = nfft/2 + 1; int r, c, f; float *X1, *Y1; fftwf_plan plan; //struct timespec tic, toc; //Checks if (R<1) { fprintf(stderr,"error in fft_squared_s: R (nrows X) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in fft_squared_s: C (ncols X) must be positive\n"); return 1; } if (nfft<R && dim==0) { fprintf(stderr,"error in fft_squared_s: nfft must be >= R (winlength)\n"); return 1; } if (nfft<C && dim==1) { fprintf(stderr,"error in fft_squared_s: nfft must be >= C (winlength)\n"); return 1; } //Initialize fftwf X1 = fftwf_alloc_real((size_t)nfft); Y1 = fftwf_alloc_real((size_t)nfft); plan = fftwf_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE); if (!plan) { fprintf(stderr,"error in fft_squared_s: problem creating fftw plan\n"); return 1; } cblas_scopy(nfft-R,&z,0,&X1[R],1); //zero-pad if (dim==0u) { if (iscolmajor) { //clock_gettime(CLOCK_REALTIME,&tic); for (c=0; c<C; c++) { cblas_scopy(R,&X[c*R],1,&X1[0],1); fftwf_execute(plan); //n = c*F; Y[n++] = fmaf(Y1[0],Y1[0],0.0f); //this was ~25% slower //for (f=1; f<F-1; f++, n++) { Y[n] = fmaf(Y1[f],Y1[f],fmaf(Y1[nfft-f],Y1[nfft-f],0.0f)); } //Y[n] = (nfft%2) ? fmaf(Y1[f],Y1[f],fmaf(Y1[nfft-f],Y1[nfft-f],0.0f)) : fmaf(Y1[f],Y1[f],0.0f); //n = c*F; Y[n++] = Y1[0]*Y1[0]; //this was also ~25% slower //for (f=1; f<F-1; f++, n++) { Y[n] = Y1[f]*Y1[f] + Y1[nfft-f]*Y1[nfft-f]; } //Y[n] = (nfft%2) ? Y1[f]*Y1[f] + Y1[nfft-f]*Y1[nfft-f] : Y1[f]*Y1[f]; for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_scopy(F,&Y[c*F],1,&Y1[0],1); } //clock_gettime(CLOCK_REALTIME,&toc); //fprintf(stderr,"elapsed time = %f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6); } else { for (c=0; c<C; c++) { cblas_scopy(R,&X[c],C,&X1[0],1); fftwf_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_scopy(F,&Y[c],C,&Y1[0],1); } } } else if (dim==1u) { if (iscolmajor) { for (r=0; r<R; r++) { cblas_scopy(C,&X[r],R,&X1[0],1); fftwf_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_scopy(F,&Y[r],R,&Y1[0],1); } } else { for (r=0; r<R; r++) { cblas_scopy(C,&X[r*C],1,&X1[0],1); fftwf_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_scopy(F,&Y[r*F],1,&Y1[0],1); } } } else { fprintf(stderr,"error in fft_squared_s: dim must be 0 or 1.\n"); return 1; } fftwf_destroy_plan(plan); fftwf_free(X1); fftwf_free(Y1); return 0; } int fft_squared_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft) { const double z = 0.0; const int F = nfft/2 + 1; int r, c, f; double *X1, *Y1; fftw_plan plan; //Checks if (R<1) { fprintf(stderr,"error in fft_squared_d: R (nrows X) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in fft_squared_d: C (ncols X) must be positive\n"); return 1; } if (nfft<R && dim==0) { fprintf(stderr,"error in fft_squared_s: nfft must be >= R (winlength)\n"); return 1; } if (nfft<C && dim==1) { fprintf(stderr,"error in fft_squared_s: nfft must be >= C (winlength)\n"); return 1; } //Initialize fftw X1 = fftw_alloc_real((size_t)nfft); Y1 = fftw_alloc_real((size_t)nfft); plan = fftw_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE); if (!plan) { fprintf(stderr,"error in fft_squared_d: problem creating fftw plan\n"); return 1; } cblas_dcopy(nfft,&z,0,&X1[0],1); //zero-pad if (dim==0u) { if (iscolmajor) { for (c=0; c<C; c++) { cblas_dcopy(R,&X[c*R],1,&X1[0],1); fftw_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_dcopy(F,&Y[c*F],1,&Y1[0],1); } } else { for (c=0; c<C; c++) { cblas_dcopy(R,&X[c],C,&X1[0],1); fftw_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_dcopy(F,&Y[c],C,&Y1[0],1); } } } else if (dim==1u) { if (iscolmajor) { for (r=0; r<R; r++) { cblas_dcopy(C,&X[r],R,&X1[0],1); fftw_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_dcopy(F,&Y[r],R,&Y1[0],1); } } else { for (r=0; r<R; r++) { cblas_dcopy(C,&X[r*C],1,&X1[0],1); fftw_execute(plan); for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; } for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; } cblas_dcopy(F,&Y[r*F],1,&Y1[0],1); } } } else { fprintf(stderr,"error in fft_squared_d: dim must be 0 or 1.\n"); return 1; } fftw_destroy_plan(plan); fftw_free(X1); fftw_free(Y1); return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4811533052, "avg_line_length": 35.198019802, "ext": "c", "hexsha": "bce175ea640fbb3644ae6cc02c7089c4615af465", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_path": "c/fft_squared.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/dsp", "max_issues_repo_path": "c/fft_squared.c", "max_line_length": 126, "max_stars_count": 1, "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_path": "c/fft_squared.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "num_tokens": 2443, "size": 7110 }
// Copyright 2018 Jeremy Mason // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! \file vector.c //! Contains functions to manipulate vectors. Intended as a relatively less //! painful wrapper around Level 1 CBLAS. #include <cblas.h> // daxpy #include <float.h> // DBL_EPSILON #include <math.h> // exp #include <stdbool.h> // bool #include <stddef.h> // size_t #include <stdio.h> // EOF #include <stdlib.h> // abort #include <string.h> // memcpy #include "sb_matrix.h" // sb_mat_is_finite #include "sb_structs.h" // sb_mat #include "sb_utility.h" // SB_CHK_ERR #include "sb_vector.h" #include "safety.h" /// Constructs a vector with the required capacity. /// /// # Parameters /// - `n_elem`: capacity of the vector /// - `layout`: `c` for a column vector, `r` for a row vector /// /// # Returns /// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_LAYOUT`: `layout` is `c` or `r` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// sb_vec * v = sb_vec_malloc(3, 'r'); /// /// // Fill the vector with some values and print /// double a[] = {1., 4., 2.}; /// sb_vec_subcpy(v, 0, a, 3); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_malloc(size_t n_elem, char layout) { #ifdef SAFE_LAYOUT SB_CHK_ERR(layout != 'c' && layout != 'r', abort(), "sb_vec_malloc: layout must be 'c' or 'r'"); #endif sb_vec * out = malloc(sizeof(sb_vec)); SB_CHK_ERR(!out, return NULL, "sb_vec_malloc: failed to allocate vector"); double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_vec_malloc: failed to allocate data"); out->n_elem = n_elem; out->data = data; out->layout = layout; return out; } /// Constructs a vector with the required capacity and initializes all elements /// to zero. Requires support for the IEC 60559 standard. /// /// # Parameters /// - `n_elem`: capacity of the vector /// - `layout`: `c` for a column vector, `r` for a row vector /// /// # Returns /// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_LAYOUT`: `layout` is `c` or `r` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// sb_vec * v = sb_vec_calloc(3, 'r'); /// /// // Initialized to zeros /// sb_vec_print(v, "v before: ", "%g"); /// /// // Fill the vector with some values and print /// double a[] = {1., 4., 2.}; /// sb_vec_subcpy(v, 0, a, 3); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_calloc(size_t n_elem, char layout) { #ifdef SAFE_LAYOUT SB_CHK_ERR(layout != 'c' && layout != 'r', abort(), "sb_vec_calloc: layout must be 'c' or 'r'"); #endif sb_vec * out = malloc(sizeof(sb_vec)); SB_CHK_ERR(!out, return NULL, "sb_vec_calloc: failed to allocate vector"); double * data = calloc(n_elem, sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_vec_calloc: failed to allocate data"); out->n_elem = n_elem; out->data = data; out->layout = layout; return out; } /// Constructs a vector with the required capacity and initializes elements to /// the first `n_elem` elements of array `a`. The array must contain at least /// `n_elem` elements. /// /// # Parameters /// - `a`: array to be copied into the vector /// - `n_elem`: capacity of the vector /// - `layout`: `c` for a column vector, `r` for a row vector /// /// # Returns /// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `a` is not `NULL` /// - `SAFE_LAYOUT`: `layout` is `c` or `r` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// /// // Construct a vector from the array /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec_print(v, "v: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_of_arr(const double * a, size_t n_elem, char layout) { #ifdef SAFE_MEMORY SB_CHK_ERR(!a, abort(), "sb_vec_of_arr: a cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(layout != 'c' && layout != 'r', abort(), "sb_vec_of_arr: layout must be 'c' or 'r'"); #endif sb_vec * out = malloc(sizeof(sb_vec)); SB_CHK_ERR(!out, return NULL, "sb_vec_of_arr: failed to allocate vector"); double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_vec_of_arr: failed to allocate data"); out->n_elem = n_elem; out->data = memcpy(data, a, n_elem * sizeof(double)); out->layout = layout; return out; } /// Constructs a vector as a deep copy of an existing vector. The state of the /// existing vector must be valid. /// /// # Parameters /// - `v`: pointer to the vector to be copied /// /// # Returns /// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // `v` and `w` contain the same elements /// sb_vec * w = sb_vec_clone(v); /// sb_vec_print(w, "w before: ", "%g"); /// /// // Fill `w` with some values and print /// sb_vec_subcpy(w, 0, a + 3, 3); /// sb_vec_print(w, "w after: ", "%g"); /// /// // `v` is unchanged /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_clone(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_clone: v cannot be NULL"); #endif sb_vec * out = malloc(sizeof(sb_vec)); SB_CHK_ERR(!out, return NULL, "sb_vec_clone: failed to allocate vector"); size_t n_elem = v->n_elem; double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_vec_clone: failed to allocate data"); *out = *v; out->data = memcpy(data, v->data, n_elem * sizeof(double)); return out; } /// Constructs a column vector containing `n_elem` elements in equal intervals /// from `begin` to `end`. Must contain at least one element. /// /// # Parameters /// - `begin`: beginning of the interval /// - `end`: end of the interval /// - `step`: step within the interval /// /// # Returns /// A `sb_vec` pointer to the allocated vector, or `NULL` if the allocation fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_LENGTH`: `v` contains at least two elements /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// sb_vec * v = sb_vec_linear(4., 0., 5); /// sb_vec_print(v, "v: ", "%g"); /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_linear(double begin, double end, size_t n_elem) { #ifdef SAFE_LENGTH SB_CHK_ERR(n_elem < 2, abort(), "sb_vec_range: must contain at least two elements"); #endif sb_vec * out = malloc(sizeof(sb_vec)); SB_CHK_ERR(!out, return NULL, "sb_vec_range: failed to allocate sb_vector"); double * data = malloc(n_elem * sizeof(double)); SB_CHK_ERR(!data, free(out); return NULL, "sb_vec_range: failed to allocate data"); size_t n_elem_1 = n_elem - 1; double step = (end - begin) / n_elem_1; for (size_t a = 0; a < n_elem_1; ++a) { data[a] = fma(a, step, begin); } data[n_elem_1] = end; out->n_elem = n_elem; out->data = data; out->layout = 'c'; return out; } /// Deconstructs a vector. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// No return value /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// /// // Allocates a pointer to vec /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec_print(v, "v: ", "%g"); /// /// sb_vec_free(v); /// // Pointer to `v` is now invalid /// } /// ``` void sb_vec_free(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_free: v cannot be NULL"); #endif free(v->data); free(v); } /// Sets all elements of `v` to zero. Requires support for the IEC 60559 /// standard. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Set all elements to zero /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_set_zero(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_set_zero(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_set_zero: v cannot be NULL"); #endif return memset(v->data, 0, v->n_elem * sizeof(double)); } /// Sets all elements of `v` to `x`. /// /// # Parameters /// - `v`: pointer to the vector /// - `x`: value for the elements /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Set all elements to 8. /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_set_all(v, 8.); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_set_all(sb_vec * v, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_set_all: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] = x; } return v; } /// Sets all elements of `v` to zero, except for the `i`th element which is set /// to one. Requires support for the IEC 60559 standard. /// /// # Parameters /// - `v`: pointer to the vector /// - `i`: index of the element with value one /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: `i` is a valid index /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Set `v` to second basis vector /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_set_basis(v, 1); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_set_basis(sb_vec * v, size_t i) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_set_basis: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(i >= v->n_elem, abort(), "sb_vec_set_basis: index out of bounds"); #endif ((double *) memset(v->data, 0, v->n_elem * sizeof(double)))[i] = 1.; return v; } /// Copies contents of the `src` vector into the `dest` vector. `src` and `dest` /// must have the same length, the same layout, and not overlap in memory. /// /// # Parameters /// - `dest`: pointer to destination vector /// - `src`: const pointer to source vector /// /// # Returns /// A copy of `dest` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `src` and `dest` are not `NULL` /// - `SAFE_LAYOUT`: `src` and `dest` have same layout /// - `SAFE_LENGTH`: `src` and `dest` have same length /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Overwrite elements of `v` and print /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_print(w, "w before: ", "%g"); /// sb_vec_memcpy(v, w); /// sb_vec_print(v, "v after: ", "%g"); /// sb_vec_print(w, "w after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_memcpy(sb_vec * restrict dest, const sb_vec * restrict src) { #ifdef SAFE_MEMORY SB_CHK_ERR(!dest, abort(), "sb_vec_memcpy: dest cannot be NULL"); SB_CHK_ERR(!src, abort(), "sb_vec_memcpy: src cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(dest->layout != src->layout, abort(), "sb_vec_memcpy: dest and src must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(dest->n_elem != src->n_elem, abort(), "sb_vec_memcpy: dest and src must have same length"); #endif memcpy(dest->data, src->data, src->n_elem * sizeof(double)); return dest; } /// Copies `n` elements of array `a` into vector `v` starting at index `i`. `v` /// must have enough capacity, `a` must contain at least `n` elements, and `v` /// and `a` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to destination vector /// - `i`: index of `v` where the copy will start /// - `a`: pointer to elements that will be copied /// - `n`: number of elements to copy /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `a` are not `NULL` /// - `SAFE_LENGTH`: `v` has enough capacity /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Overwrite elements of `v` and print /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_subcpy(v, 1, a + 3, 2); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_subcpy( sb_vec * restrict v, size_t i, const double * restrict a, size_t n) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_subcpy: v cannot be NULL"); SB_CHK_ERR(!a, abort(), "sb_vec_subcpy: a cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem - i < n, abort(), "sb_vec_subcpy: v does not have enough capacity"); #endif memcpy(v->data + i, a, n * sizeof(double)); return v; } /// Swaps the contents of `v` and `w` by exchanging data pointers. Vectors must /// have the same length and layout and not overlap in memory. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// No return value /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` have the same layout /// - `SAFE_LENGTH`: `v` and `w` have the same length /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Print vectors before and after /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_print(w, "w before: ", "%g"); /// /// sb_vec_swap(v, w); /// /// sb_vec_print(v, "v after: ", "%g"); /// sb_vec_print(w, "w after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` void sb_vec_swap(sb_vec * restrict v, sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_swap: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_swap: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != w->layout, abort(), "sb_vec_swap: v and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_swap: v and w must have same length"); #endif double * scratch; SB_SWAP(v->data, w->data, scratch); } /// Swaps the `i`th and `j`th elements of a vector. /// /// # Parameters /// - `v`: pointer to the vector /// - `i`: index of first element /// - `j`: index of second element /// /// # Returns /// No return value /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: `i` and `j` are valid indices /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Print vector before and after /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_swap_elems(v, 0, 1); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` void sb_vec_swap_elems(sb_vec * v, size_t i, size_t j) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_swap_elems: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(i >= v->n_elem, abort(), "sb_vec_swap_elems: index out of bounds"); SB_CHK_ERR(j >= v->n_elem, abort(), "sb_vec_swap_elems: index out of bounds"); #endif double * data = v->data; double scratch; SB_SWAP(data[i], data[j], scratch); } /// Writes the vector `v` to `stream` in a binary format. The data is written /// in the native binary format of the architecture, and may not be portable. /// /// # Parameters /// - `stream`: an open I/O stream /// - `v`: pointer to the vector /// /// # Returns /// `0` on success, or `1` if the write fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Write the vector to file /// FILE * f = fopen("vector.bin", "wb"); /// sb_vec_fwrite(f, v); /// fclose(f); /// /// // Read the vector from file /// FILE * g = fopen("vector.bin", "rb"); /// sb_vec * w = sb_vec_fread(g); /// fclose(g); /// /// // Vectors have the same contents /// sb_vec_print(v, "v: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` int sb_vec_fwrite(FILE * stream, const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_fwrite: v cannot be NULL"); #endif size_t n_write; size_t n_elem = v->n_elem; n_write = fwrite(&n_elem, sizeof(size_t), 1, stream); SB_CHK_ERR(n_write != 1, return 1, "sb_vec_fwrite: fwrite failed"); n_write = fwrite(&(v->layout), sizeof(char), 1, stream); SB_CHK_ERR(n_write != 1, return 1, "sb_vec_fwrite: fwrite failed"); n_write = fwrite(v->data, sizeof(double), n_elem, stream); SB_CHK_ERR(n_write != n_elem, return 1, "sb_vec_fwrite: fwrite failed"); return 0; } /// Reads binary data from `stream` into the vector returned by the function. /// Writes the vector `v` to `stream`. The number of elements, layout, and /// elements are written in a human readable format. /// /// # Parameters /// - `stream`: an open I/O stream /// - `v`: pointer to the vector /// - `format`: a format specifier for the elements /// /// # Returns /// `0` on success, or `1` if the write fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double f[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Write the vector to file /// FILE * f = fopen("vector.txt", "w"); /// sb_vec_fprintf(f, v, "%lg"); /// fclose(f); /// /// // Read the sb_vector from file /// FILE * g = fopen("vector.txt", "r"); /// sb_vec * w = sb_vec_fscanf(g); /// fclose(g); /// /// // Vectors have the same contents /// sb_vec_print(v, "v: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` int sb_vec_fprintf(FILE * stream, const sb_vec * v, const char * format) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_fprintf: v cannot be NULL"); #endif int status; size_t n_elem = v->n_elem; status = fprintf(stream, "%zu %c", n_elem, v->layout); SB_CHK_ERR(status < 0, return 1, "sb_vec_fprintf: fprintf failed"); double * data = v->data; for (size_t a = 0; a < n_elem; ++a) { status = putc(' ', stream); SB_CHK_ERR(status == EOF, return 1, "sb_vec_fprintf: putc failed"); status = fprintf(stream, format, data[a]); SB_CHK_ERR(status < 0, return 1, "sb_vec_fprintf: fprintf failed"); } status = putc('\n', stream); SB_CHK_ERR(status == EOF, return 1, "sb_vec_fprintf: putc failed"); return 0; } /// Prints the vector `v` to stdout. Output is slightly easier to read than for /// `sb_vec_fprintf()`. Mainly indended for debugging. /// /// # Parameters /// - `v`: pointer to the vector /// - `str`: a string to describe the vector /// - `format`: a format specifier for the elements /// /// # Returns /// `0` on success, or `1` if the print fails /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double array[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(array, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(array + 3, 3, 'c'); /// /// // Prints the contents of `v` and `w` to stdout /// sb_vec_print(v, "v: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` int sb_vec_print(const sb_vec * v, const char * str, const char * format) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_print: v cannot be NULL"); #endif int status; status = printf("%s\n", str); SB_CHK_ERR(status < 0, return 1, "sb_vec_print: printf failed"); size_t n_elem = v->n_elem; double * data = v->data; char buffer[128]; char * dec; bool dec_mark[n_elem]; bool any_mark = false; unsigned char length; unsigned char len_head[n_elem]; unsigned char max_head = 0; unsigned char len_tail[n_elem]; unsigned char max_tail = 0; for (size_t a = 0; a < n_elem; ++a) { status = snprintf(buffer, 128, format, data[a]); SB_CHK_ERR(status < 0, return 1, "sb_vec_print: snprintf failed"); dec = strchr(buffer, '.'); if (dec) { dec_mark[a] = true; any_mark = true; length = (unsigned char)(dec - buffer); len_head[a] = length; if (length > max_head) { max_head = length; } length = strlen(buffer) - length - 1; if (length > max_tail) { max_tail = length; } len_tail[a] = length; } else { dec_mark[a] = false; length = strlen(buffer); len_head[a] = length; if (length > max_head) { max_head = length; } len_tail[a] = 0; } } for (size_t a = 0; a < n_elem; ++a) { for (unsigned char s = 0; s < max_head - len_head[a]; ++s) { status = putchar(' '); SB_CHK_ERR(status == EOF, return 1, "sb_vec_print: putchar failed"); } status = printf(format, data[a]); SB_CHK_ERR(status < 0, return 1, "sb_vec_print: printf failed"); if (any_mark && !dec_mark[a]) { status = putchar(' '); SB_CHK_ERR(status == EOF, return 1, "sb_vec_print: putchar failed"); } for (unsigned char s = 0; s < max_tail - len_tail[a]; ++s) { status = putchar(' '); SB_CHK_ERR(status == EOF, return 1, "sb_vec_print: putchar failed"); } status = putchar(v->layout == 'r' ? ' ' : '\n'); SB_CHK_ERR(status == EOF, return 1, "sb_vec_print: putchar failed"); } if (v->layout == 'r') { status = putchar('\n'); SB_CHK_ERR(status == EOF, return 1, "sb_vec_print: putchar failed"); } return 0; } /// The data must be written in the native binary format of the architecture, /// preferably by `sb_vec_fwrite()`. /// /// # Parameters /// - `stream`: an open I/O stream /// /// # Returns /// A `sb_vec` pointer to the sb_vector read from `stream`, or `NULL` if the read or /// memory allocation fails /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Write the vector to file /// FILE * f = fopen("vector.bin", "wb"); /// sb_vec_fwrite(f, v); /// fclose(f); /// /// // Read the vector from file /// FILE * g = fopen("vector.bin", "rb"); /// sb_vec * w = sb_vec_fread(g); /// fclose(g); /// /// // Vectors have the same contents /// sb_vec_print(v, "v: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_fread(FILE * stream) { size_t n_read; size_t n_elem; n_read = fread(&n_elem, sizeof(size_t), 1, stream); SB_CHK_ERR(n_read != 1, return NULL, "sb_vec_fread: fread failed"); char layout; n_read = fread(&layout, sizeof(char), 1, stream); SB_CHK_ERR(n_read != 1, return NULL, "sb_vec_fread: fread failed"); sb_vec * out = sb_vec_malloc(n_elem, layout); SB_CHK_ERR(!out, return NULL, "sb_vec_fread: sb_vec_malloc failed"); n_read = fread(out->data, sizeof(double), n_elem, stream); SB_CHK_ERR(n_read != n_elem, sb_vec_free(out); return NULL, "sb_vec_fread: fread failed"); return out; } /// Reads formatted data from `stream` into the vector returned by the function. /// /// # Parameters /// - `stream`: an open I/O stream /// /// # Returns /// A `sb_vec` pointer to the vector read from `stream`, or `NULL` if the scan or /// memory allocation fails /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Write the vector to file /// FILE * f = fopen("vector.txt", "w"); /// sb_vec_fprintf(f, v, "%lg"); /// fclose(f); /// /// // Read the vector from file /// FILE * g = fopen("vector.txt", "r"); /// sb_vec * w = sb_vec_fscanf(g); /// fclose(g); /// /// // Vectors have the same contents /// sb_vec_print(v, "v: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_fscanf(FILE * stream) { int n_scan; size_t n_elem; char layout; n_scan = fscanf(stream, "%zu %c", &n_elem, &layout); SB_CHK_ERR(n_scan != 2, return NULL, "sb_vec_fscanf: fscanf failed"); sb_vec * out = sb_vec_malloc(n_elem, layout); SB_CHK_ERR(!out, return NULL, "sb_vec_fscanf: sb_vec_malloc failed"); double * data = out->data; for (size_t a = 0; a < n_elem; ++a) { n_scan = fscanf(stream, "%lg", data + a); SB_CHK_ERR(n_scan != 1, sb_vec_free(out); return NULL, "sb_vec_fscanf: fscanf failed"); } return out; } /// Takes the absolute value of every element of the vector. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {-1., 4., -2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Take absolute value /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_abs(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_abs(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_abs: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] = fabs(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_abs: element not finite"); #endif return v; } /// Takes the exponent base `e` of every element of the vector. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <math.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {log(1.), log(4.), log(2.)}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Take exponent base e /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_exp(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_exp(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_exp: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] = exp(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_exp: element not finite"); #endif return v; } /// Takes the logarithm base `e` of every element of the vector. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <math.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {exp(1.), exp(4.), exp(2.)}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Take logarithm base e /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_log(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_log(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_log: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] = log(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_log: element not finite"); #endif return v; } /// Exponentiates every element of the vector `v` by `x`. /// /// # Parameters /// - `v`: pointer to the vector /// - `x`: scalar exponent of the elements /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Exponentiate every element by -1. /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_smul(v, -1.); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_pow(sb_vec * v, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_pow: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] = pow(data[a], x); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_pow: element not finite"); #endif return v; } /// Takes the square root of every element of the vector `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 16., 4.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Take the square root of every element /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_sqrt(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_sqrt(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_sqrt: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] = sqrt(data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_sqrt: element not finite"); #endif return v; } /// Scalar addition of `x` to every element of the vector `v`. /// /// # Parameters /// - `v`: pointer to the vector /// - `x`: scalar added to the elements /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Add 2. to every element /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_sadd(v, 2.); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_sadd(sb_vec * v, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_sadd: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { data[a] += x; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_sadd: element not finite"); #endif return v; } /// Scalar multiplication of `x` with every element of the vector `v`. /// /// # Parameters /// - `v`: pointer to the vector /// - `x`: scalar mutiplier for the elements /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Multiply every element by -1. /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_smul(v, -1.); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_smul(sb_vec * v, double x) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_smul: v cannot be NULL"); #endif cblas_dscal(v->n_elem, x, v->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_smul: elements not finite"); #endif return v; } /// Pointwise addition of elements of the vector `w` to elements of the vector /// `v`. `v` and `w` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` have the same layout /// - `SAFE_LENGTH`: `v` and `w` have the same length /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Add w to v /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_padd(v, w); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_padd(sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_padd: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_padd: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != w->layout, abort(), "sb_vec_padd: v and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_padd: v and w must have same length"); #endif cblas_daxpy(v->n_elem, 1., w->data, 1, v->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_padd: elements not finite"); #endif return v; } /// Pointwise subtraction of elements of the vector `w` from elements of the /// vector `v`. `v` and `w` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` have the same layout /// - `SAFE_LENGTH`: `v` and `w` have the same length /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Subtract w from v /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_psub(v, w); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_psub(sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_psub: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_psub: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != w->layout, abort(), "sb_vec_psub: v and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_psub: v and w must have same length"); #endif cblas_daxpy(v->n_elem, -1., w->data, 1, v->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_psub: elements not finite"); #endif return v; } /// Pointwise multiplication of elements of the vector `v` with elements of the /// vector `w`. `v` and `w` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` have the same layout /// - `SAFE_LENGTH`: `v` and `w` have the same length /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Multiply elements of v by elements of w /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_pmul(v, w); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_pmul(sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_pmul: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_pmul: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != w->layout, abort(), "sb_vec_pmul: v and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_pmul: v and w must have same length"); #endif double * v_data = v->data; double * w_data = w->data; for (size_t a = 0; a < v->n_elem; ++a) { v_data[a] *= w_data[a]; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_pmul: element not finite"); #endif return v; } /// Pointwise division of elements of the vector `v` by elements of the vector /// `w`. `v` and `w` must not overlap in memory. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` have the same layout /// - `SAFE_LENGTH`: `v` and `w` have the same length /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Divide elements of v by elements of w /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_pdiv(v, w); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_vec * sb_vec_pdiv(sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_pdiv: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_pdiv: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != w->layout, abort(), "sb_vec_pdiv: v and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_pdiv: v and w must have same length"); #endif double * v_data = v->data; double * w_data = w->data; for (size_t a = 0; a < v->n_elem; ++a) { v_data[a] /= w_data[a]; } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_pdiv: element not finite"); #endif return v; } /// Performs the operation \f$\mathbf{r} x + y\f$ where `x` and `y` are scalars /// and `r` is modified (result x add y). /// /// # Parameters /// - `r`: pointer to the vector /// - `x`: scalar mutiplier for the elements /// - `y`: scalar summand for the elements /// /// # Returns /// A copy of `r` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `r` is not `NULL` /// - `SAFE_FINITE`: elements of `r` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * r = sb_vec_of_arr(a, 3, 'r'); /// /// // Multiply by -1. and add 2. /// sb_vec_print(r, "r before: ", "%g"); /// sb_vec_rxay(r, -1., 2.); /// sb_vec_print(r, "r after: ", "%g"); /// /// SB_VEC_FREE_ALL(r); /// } /// ``` sb_vec * sb_vec_rxay(sb_vec * r, double x, double y) { #ifdef SAFE_MEMORY SB_CHK_ERR(!r, abort(), "sb_vec_rxay: r cannot be NULL"); #endif double * data = r->data; for (size_t a = 0; a < r->n_elem; ++a) { data[a] = fma(data[a], x, y); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(r), abort(), "sb_vec_rxay: elements not finite"); #endif return r; } /// Performs the operation \f$\mathbf{r} + x \mathbf{v}\f$ where `x` is a /// scalar, `v` is a vector and `r` is modified (result add x vector). `r` and /// `v` must not overlap in memory. /// /// # Parameters /// - `r`: pointer to the first vector /// - `x`: scalar multiplier for `v` /// - `v`: pointer to the second vector /// /// # Returns /// A copy of `r` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `r` and `v` are not `NULL` /// - `SAFE_LAYOUT`: `r` and `v` have the same layout /// - `SAFE_LENGTH`: `r` and `v` have the same length /// - `SAFE_FINITE`: elements of `r` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * r = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * v = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Multiply v by 2. and add to r /// sb_vec_print(r, "r before: ", "%g"); /// sb_vec_raxv(r, 2., v); /// sb_vec_print(r, "r after: ", "%g"); /// /// SB_VEC_FREE_ALL(r, v); /// } /// ``` sb_vec * sb_vec_raxv(sb_vec * restrict r, double x, const sb_vec * restrict v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!r, abort(), "sb_vec_raxv: r cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_vec_raxv: v cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(r->layout != v->layout, abort(), "sb_vec_raxv: r and v must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(r->n_elem != v->n_elem, abort(), "sb_vec_raxv: r and v must have same length"); #endif cblas_daxpy(r->n_elem, x, v->data, 1, r->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(r), abort(), "sb_vec_raxv: elements not finite"); #endif return r; } /// Performs the operation \f$\mathbf{r} \otimes \mathbf{v} - \mathbf{w}\f$ /// where `v` and `w` are vectors, \f$\otimes\f$ is pointwise multiplication, /// and `r` is modified (result v subtract w). `r`, `v` and `w` must not /// overlap in memory. /// /// # Parameters /// - `r`: pointer to the first vector /// - `v`: pointer to the second vector /// - `w`: pointer to the third vector /// /// # Returns /// A copy of `r` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `r`, `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `r`, `v` and `w` have the same layout /// - `SAFE_LENGTH`: `r`, `v` and `w` have the same length /// - `SAFE_FINITE`: elements of `r` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5.}; /// sb_vec * r = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * v = sb_vec_of_arr(a + 1, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 2, 3, 'r'); /// /// // Pointwise multiply r by v and pointwise subtract w /// sb_vec_print(r, "r before: ", "%g"); /// sb_vec_rvsw(r, v, w); /// sb_vec_print(r, "r after: ", "%g"); /// /// SB_VEC_FREE_ALL(r, v, w); /// } /// ``` sb_vec * sb_vec_rvsw( sb_vec * restrict r, const sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!r, abort(), "sb_vec_rvsw: r cannot be NULL"); SB_CHK_ERR(!v, abort(), "sb_vec_rvsw: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_rvsw: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(r->layout != v->layout, abort(), "sb_vec_rvsw: r and v must have same layout"); SB_CHK_ERR(r->layout != w->layout, abort(), "sb_vec_rvsw: r and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(r->n_elem != v->n_elem, abort(), "sb_vec_rvsw: r and v must have same length"); SB_CHK_ERR(r->n_elem != w->n_elem, abort(), "sb_vec_rvsw: r and w must have same length"); #endif double * r_data = r->data; double * v_data = v->data; double * w_data = w->data; for (size_t a = 0; a < r->n_elem; ++a) { r_data[a] = fma(r_data[a], v_data[a], -w_data[a]); } #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(r), abort(), "sb_vec_rvsw: elements not finite"); #endif return r; } /// Finds the sum of the elements of the vector `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// The sum of the elements of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: sum is finite /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Sum the elements of v /// sb_vec_print(v, "v: ", "%g"); /// printf("sum of v: %g\n", sb_vec_sum(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` double sb_vec_sum(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_sum: v cannot be NULL"); #endif double * data = v->data; double out = 0.; for (size_t a = 0; a < v->n_elem; ++a) { out += data[a]; } #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(out), abort(), "sb_vec_sum: sum not finite"); #endif return out; } /// Finds the Euclidean norm of the vector `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// The Euclidean norm of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: norm is finite /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Norm of v /// sb_vec_print(v, "v: ", "%g"); /// printf("norm of v: %g\n", sb_vec_norm(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` double sb_vec_norm(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_norm: v cannot be NULL"); #endif double out = cblas_dnrm2(v->n_elem, v->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(out), abort(), "sb_vec_norm: norm not finite"); #endif return out; } /// Finds the dot product of the vectors `v` and `w`. Layout of `v` and `w` is /// ignored. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// The dot product of `v` and `w` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LENGTH`: `v` and `w` have the same length /// - `SAFE_FINITE`: dot product is finite /// /// # Examples /// ``` /// #include <stdio.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Find the dot product of v and w /// sb_vec_print(v, "v: ", "%g"); /// sb_vec_print(w, "w: ", "%g"); /// printf("dot product: %g\n", sb_vec_dot(v, w)); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` double sb_vec_dot(const sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_dot: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_dot: w cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_dot: v and w must have same length"); #endif double out = cblas_ddot(v->n_elem, v->data, 1, w->data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(out), abort(), "sb_vec_dot: dot product not finite"); #endif return out; } /// Finds the outer product of the vectors `v` and `w` and adds the result to /// the matrix `A`. `v` and `w` must be column and row vectors, respectively, /// and the matrix `A` must have the same number of rows as `v` and the same /// number of columns as `w`. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// - `A`: pointer to the matrix /// /// # Returns /// A copy of `A` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v`, `w` and `A` are not `NULL` /// - `SAFE_LAYOUT`: `v` is a column vector and `w` is a row vector /// - `SAFE_LENGTH`: `v` and `A` have the same number of rows, and `w` and /// `A` have the same number of columns /// - `SAFE_FINITE`: elements of `A` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_matrix.h" /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'c'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // Store the outer product in A /// sb_mat * A = sb_mat_calloc(3, 3); /// sb_mat_print(sb_vec_outer(A, v, w), "A: ", "%g"); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` sb_mat * sb_vec_outer( sb_mat * restrict A, const sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_outer: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_outer: w cannot be NULL"); SB_CHK_ERR(!A, abort(), "sb_vec_outer: A cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c', abort(), "sb_vec_outer: v must be a column vector"); SB_CHK_ERR(w->layout != 'r', abort(), "sb_vec_outer: w must be a row vector"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != A->n_rows, abort(), "sb_vec_outer: v and A must have same number of rows"); SB_CHK_ERR(w->n_elem != A->n_cols, abort(), "sb_vec_outer: w and A must have same number of cols"); #endif cblas_dger(CblasColMajor, v->n_elem, w->n_elem, 1., v->data, 1, w->data, 1, A->data, A->n_rows); #ifdef SAFE_FINITE SB_CHK_ERR(!sb_mat_is_finite(A), abort(), "sb_vec_outer: A is not finite"); #endif return A; } /// Reverses the order of elements in the vector `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Print vector and reverse /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_reverse(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_reverse(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_reverse: v cannot be NULL"); #endif size_t n_elem = v->n_elem; double * data = v->data; size_t b; double scratch; for (size_t a = 0; a < n_elem / 2; ++a) { b = n_elem - a - 1; SB_SWAP(data[a], data[b], scratch); } return v; } // FOR USE ONLY WITH SB_VEC_SORT_INC static int dcmp_inc(const void * pa, const void * pb) { double a = *(const double *)pa; double b = *(const double *)pb; if (a < b) { return -1; } if (b < a) { return 1; } return 0; } /// Sorts the elements of the vector `v` in increasing order. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Sort vector and print /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_sort_inc(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_sort_inc(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_sort_inc: v cannot be NULL"); #endif #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_sort_inc: v is not finite"); #endif qsort(v->data, v->n_elem, sizeof(double), dcmp_inc); return v; } // FOR USE ONLY WITH SB_VEC_SORT_DEC static int dcmp_dec(const void * pa, const void * pb) { double a = *(const double *)pa; double b = *(const double *)pb; if (b < a) { return -1; } if (a < b) { return 1; } return 0; } /// Sorts the elements of the vector `v` in decreasing order. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Sort vector and print /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_sort_dec(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_sort_dec(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_sort_dec: v cannot be NULL"); #endif #ifdef SAFE_FINITE SB_CHK_ERR(!sb_vec_is_finite(v), abort(), "sb_vec_sort_dec: v is not finite"); #endif qsort(v->data, v->n_elem, sizeof(double), dcmp_dec); return v; } /// Transposes the vector `v`. NOTE: This is a non-op when `SAFE_LAYOUT` is not /// defined, possibly leading to unexpected behavior with e.g. sb_vec_print(). /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// A copy of `v` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LAYOUT`: `layout` is `c` or `r` /// /// # Examples /// ``` /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // Print vector and transpose /// sb_vec_print(v, "v before: ", "%g"); /// sb_vec_trans(v); /// sb_vec_print(v, "v after: ", "%g"); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` sb_vec * sb_vec_trans(sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_trans: v cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != 'c' && v->layout != 'r', abort(), "sb_vec_trans: v has invalid layout"); v->layout = (v->layout == 'c' ? 'r' : 'c'); #endif return v; } /// Checks the vectors `v` and `w` for equality of elements. Vectors must have /// the same length and layout. /// /// # Parameters /// - `v`: pointer to the first vector /// - `w`: pointer to the second vector /// /// # Returns /// `1` if `v` and `w` are equal, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` and `w` are not `NULL` /// - `SAFE_LAYOUT`: `v` and `w` have the same layout /// - `SAFE_LENGTH`: `v` and `w` have the same length /// - `SAFE_FINITE`: elements of `v` and `w` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2., 8., 5., 7.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// sb_vec * w = sb_vec_of_arr(a + 3, 3, 'r'); /// /// // v and w are equal after sb_vec_memcpy /// assert(!sb_vec_is_equal(v, w)); /// sb_vec_memcpy(w, v); /// assert( sb_vec_is_equal(v, w)); /// /// SB_VEC_FREE_ALL(v, w); /// } /// ``` int sb_vec_is_equal(const sb_vec * restrict v, const sb_vec * restrict w) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_is_equal: v cannot be NULL"); SB_CHK_ERR(!w, abort(), "sb_vec_is_equal: w cannot be NULL"); #endif #ifdef SAFE_LAYOUT SB_CHK_ERR(v->layout != w->layout, abort(), "sb_vec_is_equal: v and w must have same layout"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem != w->n_elem, abort(), "sb_vec_is_equal: v and w must have same length"); #endif double * v_data = v->data; double * w_data = w->data; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(v_data[a]), abort(), "sb_vec_is_equal: v is not finite"); SB_CHK_ERR(!isfinite(w_data[a]), abort(), "sb_vec_is_equal: w is not finite"); #endif if (v_data[a] != w_data[a]) { return 0; } } return 1; } /// Checks if all elements of the vector `v` are zero. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// `1` if all elements of `v` are zero, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // v is zero after sb_vec_set_zero /// assert(!sb_vec_is_zero(v)); /// sb_vec_set_zero(v); /// assert( sb_vec_is_zero(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` int sb_vec_is_zero(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_is_zero: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { if (data[a] != 0.) { return 0; } } return 1; } /// Checks if all elements of the vector `v` are positive. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// `1` if all elements of `v` are positive, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {-1., -4., -2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // v is positive after sb_vec_abs /// assert(!sb_vec_is_pos(v)); /// sb_vec_abs(v); /// assert( sb_vec_is_pos(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` int sb_vec_is_pos(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_is_pos: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_is_pos: v is not finite"); #endif if (data[a] <= 0.) { return 0; } } return 1; } /// Checks if all elements of the vector `v` are negative. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// `1` if all elements of `v` are negative, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., -4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // v is negative after /// assert(!sb_vec_is_neg(v)); /// sb_vec_smul(sb_vec_abs(v), -1.); /// assert( sb_vec_is_neg(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` int sb_vec_is_neg(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_is_neg: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_is_neg: v is not finite"); #endif if (data[a] >= 0.) { return 0; } } return 1; } /// Checks if all elements of the vector `v` are nonnegative. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// `1` if all elements of `v` are nonnegative, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {0., -1., 4.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // v is nonnegative after /// assert(!sb_vec_is_nonneg(v)); /// sb_vec_abs(v); /// assert( sb_vec_is_nonneg(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` int sb_vec_is_nonneg(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_is_nonneg: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_is_nonneg: v is not finite"); #endif if (data[a] < 0.) { return 0; } } return 1; } /// Checks if all elements of the vector `v` are not infinite or `NaN`. /// /// # Parameters /// - `v`: pointer to the sb_vector /// /// # Returns /// `1` if all elements of `v` are not infinite or `NaN`, and `0` otherwise /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// /// # Examples /// ``` /// #include <assert.h> /// #include <math.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., INFINITY, 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// assert(!sb_vec_is_finite(v)); /// sb_vec_set(v, 1, NAN); /// assert(!sb_vec_is_finite(v)); /// sb_vec_set(v, 1, 4.); /// assert( sb_vec_is_finite(v)); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` int sb_vec_is_finite(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_is_finite: v cannot be NULL"); #endif double * data = v->data; for (size_t a = 0; a < v->n_elem; ++a) { if (!isfinite(data[a])) { return 0; } } return 1; } /// Finds the value of the maximum element of `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// Value of the maximum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // maximum value of v is 4. /// assert(sb_vec_max(v) == 4.); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` double sb_vec_max(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_max: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem == 0, abort(), "sb_vec_max: n_elem must be nonzero"); #endif double * data = v->data; double max_val = -INFINITY; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_max: v is not finite"); #endif if (data[a] > max_val) { max_val = data[a]; } } return max_val; } /// Finds the value of the minimum element of `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// Value of the minimum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // value of min is 1 /// assert(sb_vec_min(v) == 1.); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` double sb_vec_min(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_min: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem == 0, abort(), "sb_vec_min: n_elem must be nonzero"); #endif double * data = v->data; double min_val = INFINITY; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_min: v is not finite"); #endif if (data[a] < min_val) { min_val = data[a]; } } return min_val; } /// Finds the maximum absolute value of the elements of `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// Maximum absolute value of the elements /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., -4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // maximum absolute value of v is 4. /// assert(sb_vec_abs_max(v) == 4.); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` double sb_vec_abs_max(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_abs_max: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem == 0, abort(), "sb_vec_abs_max: n_elem must be nonzero"); #endif double * data = v->data; size_t index = cblas_idamax(v->n_elem, data, 1); #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[index]), abort(), "sb_vec_abs_max: v is not finite"); #endif return fabs(data[index]); } /// Finds the index of the maximum element of `v`. /// /// # Parameters /// - `v`: pointer to the sb_vector /// /// # Returns /// Index of the maximum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // index of max is 1 /// assert(sb_vec_max_index(v) == 1); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` size_t sb_vec_max_index(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_max_index: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem == 0, abort(), "sb_vec_max_index: n_elem must be nonzero"); #endif double * data = v->data; double max_val = -INFINITY; size_t max_ind = 0; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_max_index: v is not finite"); #endif if (data[a] > max_val) { max_val = data[a]; max_ind = a; } } return max_ind; } /// Finds the index of the minimum element of `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// Index of the minimum element /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// - `SAFE_FINITE`: elements of `v` are finite /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., 4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // index of min is 0 /// assert(sb_vec_min_index(v) == 0); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` size_t sb_vec_min_index(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_min_index: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem == 0, abort(), "sb_vec_min_index: n_elem must be nonzero"); #endif double * data = v->data; double min_val = INFINITY; size_t min_ind = 0; for (size_t a = 0; a < v->n_elem; ++a) { #ifdef SAFE_FINITE SB_CHK_ERR(!isfinite(data[a]), abort(), "sb_vec_min_index: v is not finite"); #endif if (data[a] < min_val) { min_val = data[a]; min_ind = a; } } return min_ind; } /// Finds the index of the maximum absolute value of the elements of `v`. /// /// # Parameters /// - `v`: pointer to the vector /// /// # Returns /// Index of the maximum absolute value of the elements /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `v` is not `NULL` /// - `SAFE_LENGTH`: number of elements is nonzero /// /// # Examples /// ``` /// #include <assert.h> /// #include "sb_structs.h" /// #include "sb_vector.h" /// /// int main(void) { /// double a[] = {1., -4., 2.}; /// sb_vec * v = sb_vec_of_arr(a, 3, 'r'); /// /// // index of the maximum absolute value of v is 1 /// assert(sb_vec_abs_max_index(v) == 1); /// /// SB_VEC_FREE_ALL(v); /// } /// ``` size_t sb_vec_abs_max_index(const sb_vec * v) { #ifdef SAFE_MEMORY SB_CHK_ERR(!v, abort(), "sb_vec_abs_min_index: v cannot be NULL"); #endif #ifdef SAFE_LENGTH SB_CHK_ERR(v->n_elem == 0, abort(), "sb_vec_abs_min_index: n_elem must be nonzero"); #endif return cblas_idamax(v->n_elem, v->data, 1); } extern inline double sb_vec_get(const sb_vec * v, size_t i); extern inline void sb_vec_set(sb_vec * v, size_t i, double x); extern inline double * sb_vec_ptr(sb_vec * v, size_t i);
{ "alphanum_fraction": 0.5957389501, "avg_line_length": 27.2391782832, "ext": "c", "hexsha": "3e9ef1289d61fb849bfc7fcad3d679323c6aab22", "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": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_forks_repo_licenses": [ "Apache-2.0", "MIT" ], "max_forks_repo_name": "harharkh/sb_desc", "max_forks_repo_path": "src/vector.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_issues_repo_issues_event_max_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_licenses": [ "Apache-2.0", "MIT" ], "max_issues_repo_name": "harharkh/sb_desc", "max_issues_repo_path": "src/vector.c", "max_line_length": 92, "max_stars_count": 13, "max_stars_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_stars_repo_licenses": [ "Apache-2.0", "MIT" ], "max_stars_repo_name": "harharkh/sb_desc", "max_stars_repo_path": "src/vector.c", "max_stars_repo_stars_event_max_datetime": "2021-12-19T20:06:47.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-08T22:34:35.000Z", "num_tokens": 22898, "size": 74254 }
#ifndef _HEX_GRAPH_H_ #define _HEX_GRAPH_H_ #include <stdlib.h> #include <gsl/gsl_spmatrix.h> struct graph_t { size_t num_vertices; // Number of vertices in the graph gsl_spmatrix* t; // Sparse matrix of size n*n, // t[i][j] == 1 means there is an edge from i to j gsl_spmatrix* o; // Sparse matrix of size 2*n, one line per player // o[p][i] == 1 means that the vertex i is owned by p }; #endif // _HEX_GRAPH_H_
{ "alphanum_fraction": 0.6133056133, "avg_line_length": 30.0625, "ext": "h", "hexsha": "478ab3f470b6773778c7357dcf5f34cd45804779", "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": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "src/graph.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": "src/graph.h", "max_line_length": 77, "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": "src/graph.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 138, "size": 481 }
#pragma once #include "Cesium3DTiles/Library.h" #include "Cesium3DTiles/RasterOverlay.h" #include "Cesium3DTiles/RasterOverlayTileProvider.h" #include <gsl/span> #include <memory> #include <vector> namespace Cesium3DTiles { class Tileset; /** * @brief A collection of {@link RasterOverlay} instances that are associated * with a {@link Tileset}. * * The raster overlay instances may be added to the raster overlay collection * of a tileset that is returned with {@link Tileset::getOverlays}. When the * tileset is loaded, one {@link RasterOverlayTileProvider} will be created * for each raster overlay that had been added. The raster overlay tile provider * instances will be passed to the {@link RasterOverlayTile} instances that * they create when the tiles are updated. */ class CESIUM3DTILES_API RasterOverlayCollection final { public: /** * @brief Creates a new instance. * * @param tileset The tileset to which this instance belongs */ RasterOverlayCollection(Tileset& tileset) noexcept; ~RasterOverlayCollection(); /** * @brief Adds the given {@link RasterOverlay} to this collection. * * @param pOverlay The pointer to the overlay. This may not be `nullptr`. */ void add(std::unique_ptr<RasterOverlay>&& pOverlay); /** * @brief Remove the given {@link RasterOverlay} from this collection. */ void remove(RasterOverlay* pOverlay) noexcept; /** * @brief A constant iterator for {@link RasterOverlay} instances. */ typedef std::vector<std::unique_ptr<RasterOverlay>>::const_iterator const_iterator; /** * @brief Returns an iterator at the beginning of this collection. */ const_iterator begin() const noexcept { return this->_overlays.begin(); } /** * @brief Returns an iterator at the end of this collection. */ const_iterator end() const noexcept { return this->_overlays.end(); } /** * @brief Gets the number of overlays in the collection. */ size_t size() const noexcept { return this->_overlays.size(); } private: Tileset* _pTileset; std::vector<std::unique_ptr<RasterOverlay>> _overlays; }; } // namespace Cesium3DTiles
{ "alphanum_fraction": 0.7188081937, "avg_line_length": 28.64, "ext": "h", "hexsha": "6a55d2da06de2a50bde943ba75062858e15b233f", "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": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "zy6p/cesium-native", "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/RasterOverlayCollection.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "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": "zy6p/cesium-native", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/RasterOverlayCollection.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "zy6p/cesium-native", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/RasterOverlayCollection.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": 521, "size": 2148 }
#pragma once #include "table.h" #include <gsl/span> #include <new> template <typename T> T* CreateTypeBuffer(std::size_t rowCount) { return new T[rowCount](); } template <typename T> struct CreateTypeBuffers { }; template <typename... Ts> struct CreateTypeBuffers<std::tuple<Ts...>> { static void** exec(std::size_t rowCount) { return new void* [sizeof...(Ts)]{ CreateTypeBuffer<Ts>(rowCount)... }; } }; template <typename... Ts> Table CreateTable(std::size_t rowCount) { using ColumnList = ColumnListT<Ts...>; return { .columns = ColumnList(), .instanceData = CreateTypeBuffers<typename ColumnList::types>::exec(rowCount), .rowCount = 0, .rowCapacity = rowCount, .cellMetas = ColumnList::metas.data(), }; } class TableFactory { public: Table Alloc(gsl::span<const CellMeta> metas) { const auto rowCapacity = 128; const auto columnCount = metas.size(); auto columns = static_cast<ColumnId*>(malloc(columnCount * sizeof(ColumnId))); auto instances = new void*[columnCount]; auto cellMetas = static_cast<CellMeta*>(malloc(columnCount * sizeof(CellMeta))); auto index = 0; for (const auto& meta : metas) { new(columns + index) ColumnId(meta.id); instances[index] = std::calloc(rowCapacity, meta.storageBytes); new(cellMetas + index) CellMeta(meta); ++index; } Table ret = {}; ret.columns = ColumnList(columns, columnCount); ret.cellMetas = cellMetas; ret.instanceData = instances; ret.rowCapacity = rowCapacity; return ret; } void Free(const Table& /*table*/) { } };
{ "alphanum_fraction": 0.6178861789, "avg_line_length": 27.3333333333, "ext": "h", "hexsha": "122b49f163a55809a0c4b6093eee6d936d4af435", "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": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zestier/lime", "max_forks_repo_path": "inc/lime/placeholder.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "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": "zestier/lime", "max_issues_repo_path": "inc/lime/placeholder.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zestier/lime", "max_stars_repo_path": "inc/lime/placeholder.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 403, "size": 1722 }
/* vector/gsl_vector_complex_long_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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__ #define __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_vector_long_double.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_block_complex_long_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 size; size_t stride; long double *data; gsl_block_complex_long_double *block; int owner; } gsl_vector_complex_long_double; typedef struct { gsl_vector_complex_long_double vector; } _gsl_vector_complex_long_double_view; typedef _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_view; typedef struct { gsl_vector_complex_long_double vector; } _gsl_vector_complex_long_double_const_view; typedef const _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_view; /* Allocation */ gsl_vector_complex_long_double *gsl_vector_complex_long_double_alloc (const size_t n); gsl_vector_complex_long_double *gsl_vector_complex_long_double_calloc (const size_t n); gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, const size_t offset, const size_t n, const size_t stride); gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_from_vector (gsl_vector_complex_long_double * v, const size_t offset, const size_t n, const size_t stride); void gsl_vector_complex_long_double_free (gsl_vector_complex_long_double * v); /* Views */ _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_view_array (long double *base, size_t n); _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_view_array_with_stride (long double *base, size_t stride, size_t n); _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_view_array (const long double *base, size_t n); _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_view_array_with_stride (const long double *base, size_t stride, size_t n); _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_subvector (gsl_vector_complex_long_double *base, size_t i, size_t n); _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_subvector_with_stride (gsl_vector_complex_long_double *v, size_t i, size_t stride, size_t n); _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_subvector (const gsl_vector_complex_long_double *base, size_t i, size_t n); _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_subvector_with_stride (const gsl_vector_complex_long_double *v, size_t i, size_t stride, size_t n); _gsl_vector_long_double_view gsl_vector_complex_long_double_real (gsl_vector_complex_long_double *v); _gsl_vector_long_double_view gsl_vector_complex_long_double_imag (gsl_vector_complex_long_double *v); _gsl_vector_long_double_const_view gsl_vector_complex_long_double_const_real (const gsl_vector_complex_long_double *v); _gsl_vector_long_double_const_view gsl_vector_complex_long_double_const_imag (const gsl_vector_complex_long_double *v); /* Operations */ gsl_complex_long_double gsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v, const size_t i); void gsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v, const size_t i, gsl_complex_long_double z); gsl_complex_long_double *gsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v, const size_t i); const gsl_complex_long_double *gsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v, const size_t i); void gsl_vector_complex_long_double_set_zero (gsl_vector_complex_long_double * v); void gsl_vector_complex_long_double_set_all (gsl_vector_complex_long_double * v, gsl_complex_long_double z); int gsl_vector_complex_long_double_set_basis (gsl_vector_complex_long_double * v, size_t i); int gsl_vector_complex_long_double_fread (FILE * stream, gsl_vector_complex_long_double * v); int gsl_vector_complex_long_double_fwrite (FILE * stream, const gsl_vector_complex_long_double * v); int gsl_vector_complex_long_double_fscanf (FILE * stream, gsl_vector_complex_long_double * v); int gsl_vector_complex_long_double_fprintf (FILE * stream, const gsl_vector_complex_long_double * v, const char *format); int gsl_vector_complex_long_double_memcpy (gsl_vector_complex_long_double * dest, const gsl_vector_complex_long_double * src); int gsl_vector_complex_long_double_reverse (gsl_vector_complex_long_double * v); int gsl_vector_complex_long_double_swap (gsl_vector_complex_long_double * v, gsl_vector_complex_long_double * w); int gsl_vector_complex_long_double_swap_elements (gsl_vector_complex_long_double * v, const size_t i, const size_t j); int gsl_vector_complex_long_double_isnull (const gsl_vector_complex_long_double * v); extern int gsl_check_range; #ifdef HAVE_INLINE extern inline gsl_complex_long_double gsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v, const size_t i) { #ifndef GSL_RANGE_CHECK_OFF if (i >= v->size) { const gsl_complex_long_double zero = {{0, 0}}; GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero); } #endif return *GSL_COMPLEX_LONG_DOUBLE_AT (v, i); } extern inline void gsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v, const size_t i, gsl_complex_long_double z) { #ifndef GSL_RANGE_CHECK_OFF if (i >= v->size) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif *GSL_COMPLEX_LONG_DOUBLE_AT (v, i) = z; } extern inline gsl_complex_long_double * gsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v, const size_t i) { #ifndef GSL_RANGE_CHECK_OFF if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_LONG_DOUBLE_AT (v, i); } extern inline const gsl_complex_long_double * gsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v, const size_t i) { #ifndef GSL_RANGE_CHECK_OFF if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_LONG_DOUBLE_AT (v, i); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__ */
{ "alphanum_fraction": 0.7075052607, "avg_line_length": 34.7723577236, "ext": "h", "hexsha": "fdb6059904005b8e3f24106646bc9ec69b90497d", "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/vector/gsl_vector_complex_long_double.h", "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/vector/gsl_vector_complex_long_double.h", "max_line_length": 126, "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/vector/gsl_vector_complex_long_double.h", "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": 1783, "size": 8554 }
#include <RInside.h> #include <gsl/gsl_rng.h> void inclusiveValue ( struct INCV &incv, double *deltaIn, struct PAR &par, struct VAR &var, double *nu //======================================================= ); void inclusiveValue ( //======================================================= struct INCV &incv, double *expDeltaIn, double **expMu, struct VAR &var //======================================================= ); void choicePath ( //======================================================= struct PRED &predOut, struct VAR &var, struct DIAG &diag //======================================================= ); void initializeMu ( //======================================================= double ***expMuOut, struct PAR &par, struct RND &rnd, struct VAR &var //======================================================= ); void initializeMui ( //======================================================= double **expMu, double *nu, struct PAR &par, struct VAR &var //======================================================= ); void transProb ( //======================================================= struct VAR &var, struct INCV &incv //======================================================= ); void expectedValuefun ( //======================================================= double *expectValuefun, double *valuefunIn, double *weight, struct INCV &incv //======================================================= ); void bellmanOperator (//======================================================= double *valuefunOut, double *valuefunIn, struct VAR &var, struct INCV &incv //======================================================= ); void nfpBellman (//======================================================= double *valuefunOut, double *valuefunIn, struct VAR &var, struct DIAG &diag, struct INCV &incv //======================================================= ); int findNeighbor ( //======================================================= int &n_neighbor, double **paramHistIn, struct PAR &par //======================================================= ); void moveHistory ( int &imh, int &vmh, int &n_neighbor, int &n_adjust ); void moveHistory2 ( int &vmh, int &n_neighbor ); void computeMatrices (double **invPHI, double **XZPHIZXZ, double **X, double **Z, double **Z_t ); void printMCMC ( int &mcID, int &vmh, int &imh, int &seed, int &accept, int &neighborNew, int &n_neighbor, double &llh, double &pllh, struct PAR &par_a, struct DIAG &diag, FILE *fileout ); void mcmcDiag ( char *filenameEstim, int &imh, int &mcID, int &seed, struct DIAG &diag, struct POST &post, RInside &R ); void mcmcRunLength ( char *filenameEstim, int &imh, int &mcID, int &seed, struct DIAG &diag, struct POST &post, RInside &R ); void printOutput ( char *filenameEstim, int &imh, int &mcID, int &seed, struct DIAG &diag, struct POST &post ); Rcpp::NumericMatrix createMatrix ( double **param, const int m, const int n ); Rcpp::NumericMatrix createMatrix ( //======================================================= double **param, const int m1, const int m2, const int n //======================================================= ); void posteriorMean ( //======================================================= int &imh, struct DIAG &diag, struct POST &post //======================================================= ); void readData ( int &mcID, FILE* inpData, struct VAR &var, struct DATA &data ); void readRand ( int &mcID, FILE* inpRand, struct RND rnd ); void readSeed ( double ***paramSeed, char* filenameSeed ); void initialize ( int &mcID, int &seed, int &imh, int &vmh, int &n_neighbor, int &neighborPast, int &ptAccpt, struct FXP &fxp, struct PAR &par_a, struct PAR &par_c, struct VAR &var, struct DATA &data, struct DIAG &diag, struct HIST &hist, gsl_rng *rng ); void reinitialize ( int &imh, int &vmh, int &n_neighbor, int &neighborPast, int &ptAccpt, struct FXP &fxp, struct PAR &par_a, struct DIAG &diag, struct HIST &hist ); void resetHistory ( int indx, struct HIST &hist ); void resetHistParam ( int idFirst, int idLast, struct HIST &hist ); void memoryAllocate ( double **jump, struct FXP &fxp, struct PAR &par_c, struct PAR &par_a, struct RND &rnd, struct VAR &var, struct DATA &data, struct HIST &hist, struct INCV &incv, struct POST &post, struct PRED &pred ); void memoryDeallocate ( double **jump, struct FXP &fxp, struct PAR &par_c, struct PAR &par_a, struct RND &rnd, struct VAR &var, struct DATA &data, struct HIST &hist, struct INCV &incv, struct POST &post, struct PRED &pred );
{ "alphanum_fraction": 0.4812473662, "avg_line_length": 16.3092783505, "ext": "h", "hexsha": "d0252d0d624cc782746718164e810da09a3e3a55", "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": "b3c52e19600faefc8ec853f0d2bd18f2293e2897", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "foolish3/DDCM", "max_forks_repo_path": "PFP/functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3c52e19600faefc8ec853f0d2bd18f2293e2897", "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": "foolish3/DDCM", "max_issues_repo_path": "PFP/functions.h", "max_line_length": 58, "max_stars_count": 4, "max_stars_repo_head_hexsha": "b3c52e19600faefc8ec853f0d2bd18f2293e2897", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "foolish3/DDCM", "max_stars_repo_path": "PFP/functions.h", "max_stars_repo_stars_event_max_datetime": "2020-05-04T03:26:32.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-29T04:59:03.000Z", "num_tokens": 1085, "size": 4746 }
#ifndef EXOBJ_H #define EXOBJ_H #include <unistd.h> #include <iostream> #include <fstream> #include <float.h> #include <math.h> #include <complex> #include <vector> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_multimin.h> //#include <string> #include <SQuIDS/SQuIDS.h> #include <nuSQuIDS/nuSQuIDS.h> namespace nusquids{ // NeutrinoDISCrossSectionsFromTablesExtended // Is basically a copy of the default NeutrinoDISCrossSectionsFromTables but instead of // returning error when the energy is lower that the low energy value in the tables it returns zero. // This is effectively true for the range of energies given in the nuSQuIDS default tables(Emin=1e2GeV) // This allows to use a wider range of the energy to compute atmospheric oscillations as it's shown in the // main.cpp example. class NeutrinoDISCrossSectionsFromTablesExtended : public NeutrinoDISCrossSectionsFromTables { public : NeutrinoDISCrossSectionsFromTablesExtended():NeutrinoDISCrossSectionsFromTables(){} double TotalCrossSection(double Enu, NeutrinoFlavor flavor, NeutrinoType neutype, Current current) const override; double SingleDifferentialCrossSection(double E1, double E2, NeutrinoFlavor flavor, NeutrinoType neutype, Current current) const override; }; } #endif
{ "alphanum_fraction": 0.7895142637, "avg_line_length": 31.6341463415, "ext": "h", "hexsha": "9673fcf289f1d99e78e4dce717ff9413258db50b", "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": "b0cf4b18d10751aed924c6bb8f8db55ef2ed3732", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "arguelles/nuSQUIDSDecay", "max_forks_repo_path": "include/exCross.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b0cf4b18d10751aed924c6bb8f8db55ef2ed3732", "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": "arguelles/nuSQUIDSDecay", "max_issues_repo_path": "include/exCross.h", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "b0cf4b18d10751aed924c6bb8f8db55ef2ed3732", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "arguelles/nuSQUIDSDecay", "max_stars_repo_path": "include/exCross.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 324, "size": 1297 }
/* fp-win.c * * Author: Brian Gladman * * 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 <float.h> #include <config.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_errno.h> const char *fp_env_string = "round-to-nearest,double-precision,mask-all"; int gsl_ieee_set_mode (int precision, int rounding, int exception_mask) { unsigned int old, mode = _DN_SAVE, mask = _MCW_DN | _MCW_RC | _MCW_EM; switch(precision) { case GSL_IEEE_SINGLE_PRECISION: mode |= _PC_24; break; case GSL_IEEE_EXTENDED_PRECISION: mode |= _PC_64; break; case GSL_IEEE_DOUBLE_PRECISION: default: mode |= _PC_53; } /* precison control is disabled on Windows x64 with MSVC but is allowed by the Intel compiler */ #if !defined( _WIN64 ) || defined( __ICL ) mask |= _MCW_PC; #endif switch(rounding) { case GSL_IEEE_ROUND_DOWN: mode |= _RC_DOWN; break; case GSL_IEEE_ROUND_UP: mode |= _RC_UP; break; case GSL_IEEE_ROUND_TO_ZERO: mode |= _RC_CHOP; break; case GSL_IEEE_ROUND_TO_NEAREST: default: mode |= _RC_NEAR; } if(exception_mask & GSL_IEEE_MASK_INVALID) mode |= _EM_INVALID; if(exception_mask & GSL_IEEE_MASK_DENORMALIZED) mode |= _EM_DENORMAL; if(exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO) mode |= _EM_ZERODIVIDE; if(exception_mask & GSL_IEEE_MASK_OVERFLOW) mode |= _EM_OVERFLOW; if(exception_mask & GSL_IEEE_MASK_UNDERFLOW) mode |= _EM_UNDERFLOW; if(exception_mask & GSL_IEEE_TRAP_INEXACT) mode &= ~_EM_INEXACT; else mode |= _EM_INEXACT; _clearfp(); _controlfp_s(&old, mode, mask); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.7253275109, "avg_line_length": 30.1315789474, "ext": "c", "hexsha": "a4a522df2922830b94e47a07c3277ae423a1e550", "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/build.vc/fp-win.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/build.vc/fp-win.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/build.vc/fp-win.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": 626, "size": 2290 }
#pragma once #include "halley/plugin/iasset_importer.h" #include <gsl/gsl> #include "halley/file_formats/config_file.h" #include <yaml-cpp/node/node.h> namespace Halley { class ConfigFile; class ConfigImporter : public IAssetImporter { public: ImportAssetType getType() const override { return ImportAssetType::Config; } void import(const ImportingAsset& asset, IAssetCollector& collector) override; static ConfigNode parseYAMLNode(const YAML::Node& node); static void parseConfig(ConfigFile& config, gsl::span<const gsl::byte> data); }; }
{ "alphanum_fraction": 0.7666068223, "avg_line_length": 25.3181818182, "ext": "h", "hexsha": "49ff2dc35c4219fb706b754e2d4fcb5309100912", "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": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "sunhay/halley", "max_forks_repo_path": "src/tools/tools/src/assets/importers/config_importer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "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": "sunhay/halley", "max_issues_repo_path": "src/tools/tools/src/assets/importers/config_importer.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sunhay/halley", "max_stars_repo_path": "src/tools/tools/src/assets/importers/config_importer.h", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "num_tokens": 136, "size": 557 }
/** *\file utils.h *\author weckyy702 (weckyy702@gmail.com) *\brief Utility and core Header file *\date 2021-03-25 * *MIT License *Copyright (c) [2021] [Weckyy702 (weckyy702@gmail.com | https://github.com/Weckyy702)] *Permission is hereby granted, free of charge, to any person obtaining a copy *of this software and associated documentation files (the "Software"), to deal *in the Software without restriction, including without limitation the rights *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *copies of the Software, and to permit persons to whom the Software is *furnished to do so, subject to the following conditions: * *The above copyright notice and this permission notice shall be included in all *copies or substantial portions of the Software. * *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE *SOFTWARE. * */ #ifndef RAYCHEL_CORE_H #define RAYCHEL_CORE_H #include <cstdint> #include <limits> #if !((defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)) #error "C++(17) compilation is required!" #endif #include <cassert> #include <cmath> #include <cstddef> #include <gsl/gsl> #include <type_traits> //convenience headers #include <memory> #include <optional> #include <utility> #include <vector> #include "CMakeSettings.h" #include "Logger.h" #include "RaychelMath/constants.h" #include "RaychelMath/equivalent.h" #if defined(__clang__) || defined(__GNUC__) #define RAYCHEL_FUNC_NAME __PRETTY_FUNCTION__ #elif defined(_MSC_VER) #define RAYCHEL_FUNC_NAME __FUNCSIG__ #else #error "Unknown compiler detected!" #endif #ifdef RAYCHEL_DEBUG #define RAYCHEL_LOG(...) Logger::debug(RAYCHEL_FUNC_NAME, ": ", __VA_ARGS__, '\n'); #else #define RAYCHEL_LOG(...) #endif //terminate the application with the provided message #ifndef RAYCHEL_NO_LOGGER #define RAYCHEL_TERMINATE(...) \ Logger::fatal(RAYCHEL_FUNC_NAME, " at (", __FILE__, ":", __LINE__, "): ", __VA_ARGS__, '\n'); \ std::exit(0x41); #else #define RAYCHEL_TERMINATE(...) std::exit(0x41); #endif #if defined(RAYCHEL_DEBUG) || !defined(NDEBUG) #define RAYCHEL_ASSERT(exp) \ if (!(exp)) { \ RAYCHEL_TERMINATE("Assertion '", GSL_STRINGIFY(exp), "' failed!"); \ } #else #define RAYCHEL_ASSERT(exp) Expects(exp) #endif #define RAYCHEL_ASSERT_NOT_REACHED RAYCHEL_TERMINATE("Assertion failed! Expected to not execute ", __FILE__, ":", __LINE__) //#define RAYCHEL_LOGICALLY_EQUAL //<-- activates logical equivalency for vector-like types #define RAYCHEL_THROW_EXCEPTION(msg, fatal) throw ::Raychel::exception_context{msg, RAYCHEL_FUNC_NAME, fatal}; #define RAYCHEL_ASSERT_NORMALIZED(vec) RAYCHEL_ASSERT(equivalent(magSq(vec), 1.0f)); namespace Raychel { using gsl::byte, gsl::not_null; using std::size_t; template <typename _num> struct vec2Imp; template <typename _num> struct vec3Imp; template <typename _num> struct colorImp; /*TODO: implement template<typename _num> class colorAlphaImp; */ template <typename _num> class QuaternionImp; template <typename _num> struct TransformImp; template <typename _number> constexpr _number sq(_number x) { static_assert(std::is_arithmetic_v<_number>, "Raychel::sq<T> requires T to be of arithmetic type!"); return x * x; } /** *\brief Linearly interpolate between two numbers * *\tparam _number Type of number to interpolate. Must be arithmetic *\param a first number (x=0.0) *\param b second number (x=1.0) *\param x value of interpolation *\return _number the interpolated number */ template <typename _number> constexpr _number lerp(_number a, _number b, long double x) { return (x * b) + ((1.0 - x) * a); } template <typename _integral> constexpr _integral bit(size_t shift) { static_assert(std::is_integral_v<_integral>, "Raychel::bit<T> requires T to be of integral type!"); RAYCHEL_ASSERT(shift < (sizeof(_integral) * 8)); return static_cast<_integral>(1U << shift); } /** *\brief Get number of digits in a number * *\param num The number with its digits *\return constexpr int */ constexpr int numDigits(unsigned long long num, unsigned int base = 10U) { int digits = 0; do { digits++; num /= base; } while (num != 0); return digits; } } // namespace Raychel #endif // !RAYCHEL_CORE_H
{ "alphanum_fraction": 0.6406076325, "avg_line_length": 32.7151515152, "ext": "h", "hexsha": "60e3805333892f708cb7b0e8a63be7d5afc45dcf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-06T09:23:32.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-08T12:05:03.000Z", "max_forks_repo_head_hexsha": "a372ac0dfa3339cac19b06b11ec916ae275b67c0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Weckyy702/RaychelCPU", "max_forks_repo_path": "RaychelEngine/include/Raychel/Core/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a372ac0dfa3339cac19b06b11ec916ae275b67c0", "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": "Weckyy702/RaychelCPU", "max_issues_repo_path": "RaychelEngine/include/Raychel/Core/utils.h", "max_line_length": 150, "max_stars_count": 4, "max_stars_repo_head_hexsha": "a372ac0dfa3339cac19b06b11ec916ae275b67c0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Weckyy702/RaychelCPU", "max_stars_repo_path": "RaychelEngine/include/Raychel/Core/utils.h", "max_stars_repo_stars_event_max_datetime": "2021-12-06T10:39:18.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-07T21:57:14.000Z", "num_tokens": 1295, "size": 5398 }
/** * * @file testing_spemv.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Dulceneia Becker * @date 2011-10-06 * @generated s Tue Jan 7 11:45:19 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_smain.h" #define REAL #undef COMPLEX /*-------------------------------------------------------------- * Check the pemv */ static int check_solution(PLASMA_enum trans, PLASMA_enum storev, int M, int N, int L, float alpha, float *A, int LDA, float *X, int INCX, float beta, float *Y0, int INCY0, float *Y, int INCY, float *W, float *Rnorm) { int k; float eps = LAPACKE_slamch_work('e'); float *work; float mzone = -1.0; /* Copy x to w */ if ( trans == PlasmaNoTrans ) { k = N; } else { k = M; } work = (float *)malloc(k * sizeof(float)); cblas_scopy(k, Y0, INCY0, W, 1); /* w = a A x + b w */ cblas_sgemv(CblasColMajor, (CBLAS_TRANSPOSE)trans, M, N, (alpha), A, LDA, X, INCX, (beta), W, 1); /* y - w */ cblas_saxpy(k, (mzone), Y, INCY, W, 1); /* Max Norm */ *Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'm', 1, k, W, 1, work); if ( (*Rnorm / (M*N)) > eps) { return 1; } else { return 0; } } /*-------------------------------------------------------------- * Testing SPEMV */ int testing_spemv(int argc, char **argv) { /* Check for number of arguments*/ if ( argc != 1) { USAGE("PEMV", "N", " - N : number of columns\n"); return -1; } /* Args */ int arg_n = atoi(argv[0]); /* Local variables */ float *A, *X, *Y, *A0, *Y0, *work; float alpha, beta, alpha0, beta0; int n = arg_n; int lda = arg_n; int info_solution = 0; int i, j, k, t; int nbtests = 0; int nfails = 0; int storev; int l = 0; int m = n; int incx = 1; int incy = 1; char *cstorev; float rnorm; float eps = LAPACKE_slamch_work('e'); /* Allocate Data */ A = (float *)malloc(lda*n*sizeof(float)); A0 = (float *)malloc(lda*n*sizeof(float)); X = (float *)malloc(lda*n*sizeof(float)); Y = (float *)malloc(lda*n*sizeof(float)); Y0 = (float *)malloc( n*sizeof(float)); work = (float *)malloc( 2*n*sizeof(float)); LAPACKE_slarnv_work(1, ISEED, 1, &alpha0); LAPACKE_slarnv_work(1, ISEED, 1, &beta0 ); /* Check if unable to allocate memory */ if ( (!A) || (!X) || (!Y0) || (!work) ) { printf("Out of Memory \n "); exit(0); } /* Initialize Data */ PLASMA_splrnt(n, n, A, lda, 479 ); PLASMA_splrnt(n, n, X, lda, 320 ); PLASMA_splrnt(n, 1, Y0, n, 573 ); printf("\n"); printf("------ TESTS FOR PLASMA SPEMV ROUTINE ------- \n"); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf(" The relative machine precision (eps) is %e \n",eps); printf(" Computational tests pass if scaled residual is less than eps.\n"); printf("\n"); nfails = 0; for (i=0; i<6; i++) { /* m and n cannot be greater than lda (arg_n) */ switch (i) { case 0: l = 0; m = arg_n; n = m; break; case 1: l = 0; m = arg_n; n = arg_n/2; break; /**/ case 2: l = arg_n; m = l; n = l; break; case 3: l = arg_n/2; m = l; n = arg_n; break; case 4: l = arg_n/2; m = arg_n-l; n = l; break; case 5: l = arg_n/3; m = arg_n-l; n = arg_n/2; break; /**/ } /* Colwise ConjTrans & Rowwise NoTrans */ #ifdef COMPLEX for (t=0; t<3; t++) { #else for (t=0; t<2; t++) { #endif /* Swap m and n for transpose cases */ if ( t == 1 ) { k = m; m = n; n = k; } LAPACKE_slacpy_work( LAPACK_COL_MAJOR, 'A', m, n, A, lda, A0, lda); if ( trans[t] == PlasmaNoTrans ) { storev = PlasmaRowwise; cstorev = storevstr[0]; /* zeroed the upper right triangle */ int64_t i, j; for (j=(n-l); j<n; j++) { for (i=0; i<(j-(n-l)); i++) { A0[i+j*lda] = 0.0; } } } else { storev = PlasmaColumnwise; cstorev = storevstr[1]; /* zeroed the lower left triangle */ int64_t i, j; for (j=0; j<(l-1); j++) { for (i=(m-l+1+j); i<m; i++) { A0[i+j*lda] = 0.0; } } } for (j=0; j<3; j++) { /* Choose alpha and beta */ alpha = ( j==1 ) ? 0.0 : alpha0; beta = ( j==2 ) ? 0.0 : beta0; /* incx and incy: 1 or lda */ for (k=0; k<4; k++) { switch (k) { case 0: incx = 1; incy = 1; break; case 1: incx = 1; incy = lda; break; case 2: incx = lda; incy = 1; break; case 3: incx = lda; incy = lda; break; } /* initialize Y with incy */ cblas_scopy(n, Y0, 1, Y, incy); /* SPEMV */ CORE_spemv( trans[t], storev, m, n, l, alpha, A, lda, X, incx, beta, Y, incy, work); /* Check the solution */ info_solution = check_solution(trans[t], storev, m, n, l, alpha, A0, lda, X, incx, beta, Y0, 1, Y, incy, work, &rnorm); if ( info_solution != 0 ) { nfails++; printf("Failed: t=%s, s=%s, M=%3d, N=%3d, L=%3d, alpha=%e, incx=%3d, beta=%e, incy=%3d, rnorm=%e\n", transstr[t], cstorev, m, n, l, (alpha), incx, (beta), incy, rnorm ); } nbtests++; } } } } if ( nfails ) printf("%d / %d tests failed\n", nfails, nbtests); printf("***************************************************\n"); if (nfails == 0) { printf(" ---- TESTING SPEMV ...... PASSED !\n"); } else { printf(" ---- TESTING SPEMV ... FAILED !\n"); } printf("***************************************************\n"); free( A0 ); free( A ); free( X ); free( Y0 ); free( Y ); return 0; }
{ "alphanum_fraction": 0.3865992742, "avg_line_length": 29.9069767442, "ext": "c", "hexsha": "ca4807bc72262ea536e464eec7dc6b3872eb57dc", "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": "testing/testing_spemv.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": "testing/testing_spemv.c", "max_line_length": 125, "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": "testing/testing_spemv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2141, "size": 7716 }
/* im_invfft * * Copyright: 1990, N. Dessipris. * * Author: Nicos Dessipris * Written on: 12/04/1990 * Modified on : * 28/6/95 JC * - rewritten, based on new im_fwfft() code * 10/9/98 JC * - frees memory more quickly * 2/4/02 JC * - fftw code added * 13/7/02 JC * - Type reset * 27/2/03 JC * - tiny speed-up ... save 1 copy on write * 22/1/04 JC * - oops, fix for segv on wider than high fftw transforms * 3/11/04 * - added fftw3 support * 7/2/10 * - gtkdoc */ /* This file is part of VIPS. VIPS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <stdio.h> #include <math.h> #ifdef HAVE_FFTW #include <fftw.h> #endif /*HAVE_FFTW*/ #ifdef HAVE_FFTW3 #include <fftw3.h> #endif /*HAVE_FFTW3*/ #include <vips/vips.h> #include <vips/internal.h> #ifdef WITH_DMALLOC #include <dmalloc.h> #endif /*WITH_DMALLOC*/ #ifdef HAVE_FFTW /* Call fftw for a 1 band image. */ static int invfft1( IMAGE *dummy, IMAGE *in, IMAGE *out ) { fftwnd_plan plan; IMAGE *cmplx = im_open_local( out, "invfft1:1", "t" ); /* Make dp complex image. */ if( !cmplx || im_pincheck( in ) || im_poutcheck( out ) ) return( -1 ); if( in->Coding != IM_CODING_NONE || in->Bands != 1 ) { im_error( "im_invfft", "%s", _( "one band uncoded only" ) ); return( -1 ); } if( im_clip2fmt( in, cmplx, IM_BANDFMT_DPCOMPLEX ) ) return( -1 ); /* Make the plan for the transform. Yes, they really do use nx for * height and ny for width. */ if( !(plan = fftw2d_create_plan( in->Ysize, in->Xsize, FFTW_BACKWARD, FFTW_MEASURE | FFTW_USE_WISDOM | FFTW_IN_PLACE )) ) { im_error( "im_invfft", "%s", _( "unable to create transform plan" ) ); return( -1 ); } fftwnd_one( plan, (fftw_complex *) cmplx->data, NULL ); fftwnd_destroy_plan( plan ); /* Copy to out. */ if( im_copy( cmplx, out ) ) return( -1 ); return( 0 ); } #else /*!HAVE_FFTW*/ #ifdef HAVE_FFTW3 /* Complex to complex inverse transform. */ static int invfft1( IMAGE *dummy, IMAGE *in, IMAGE *out ) { fftw_plan plan; IMAGE *cmplx = im_open_local( out, "invfft1:1", "t" ); /* We have to have a separate buffer for the planner to work on. */ double *planner_scratch = IM_ARRAY( dummy, in->Xsize * in->Ysize * 2, double ); /* Make dp complex image. */ if( !cmplx || im_pincheck( in ) || im_poutcheck( out ) ) return( -1 ); if( in->Coding != IM_CODING_NONE || in->Bands != 1 ) { im_error( "im_invfft", "%s", _( "one band uncoded only" ) ); return( -1 ); } if( im_clip2fmt( in, cmplx, IM_BANDFMT_DPCOMPLEX ) ) return( -1 ); /* Make the plan for the transform. Yes, they really do use nx for * height and ny for width. */ if( !(plan = fftw_plan_dft_2d( in->Ysize, in->Xsize, (fftw_complex *) planner_scratch, (fftw_complex *) planner_scratch, FFTW_BACKWARD, 0 )) ) { im_error( "im_invfft", "%s", _( "unable to create transform plan" ) ); return( -1 ); } fftw_execute_dft( plan, (fftw_complex *) cmplx->data, (fftw_complex *) cmplx->data ); fftw_destroy_plan( plan ); /* Copy to out. */ if( im_copy( cmplx, out ) ) return( -1 ); return( 0 ); } #else /*!HAVE_FFTW3*/ /* Fall back to VIPS's built-in fft */ static int invfft1( IMAGE *dummy, IMAGE *in, IMAGE *out ) { int bpx = im_ispoweroftwo( in->Xsize ); int bpy = im_ispoweroftwo( in->Ysize ); float *buf, *q, *p1, *p2; int x, y; /* Buffers for real and imaginary parts. */ IMAGE *real = im_open_local( dummy, "invfft1:1", "t" ); IMAGE *imag = im_open_local( dummy, "invfft1:2", "t" ); /* Temps. */ IMAGE *t1 = im_open_local( dummy, "invfft1:3", "p" ); IMAGE *t2 = im_open_local( dummy, "invfft1:4", "p" ); if( !real || !imag || !t1 ) return( -1 ); if( im_pincheck( in ) || im_outcheck( out ) ) return( -1 ); if( in->Coding != IM_CODING_NONE || in->Bands != 1 || !im_iscomplex( in ) ) { im_error( "im_invfft", "%s", _( "one band complex uncoded only" ) ); return( -1 ); } if( !bpx || !bpy ) { im_error( "im_invfft", "%s", _( "sides must be power of 2" ) ); return( -1 ); } /* Make sure we have a single-precision complex input image. */ if( im_clip2fmt( in, t1, IM_BANDFMT_COMPLEX ) ) return( -1 ); /* Extract real and imag parts. We have to complement the imaginary. */ if( im_c2real( t1, real ) ) return( -1 ); if( im_c2imag( t1, t2 ) || im_lintra( -1.0, t2, 0.0, imag ) ) return( -1 ); /* Transform! */ if( im__fft_sp( (float *) real->data, (float *) imag->data, bpx - 1, bpy - 1 ) ) { im_error( "im_invfft", "%s", _( "fft_sp failed" ) ); return( -1 ); } /* WIO to out. */ if( im_cp_desc( out, in ) ) return( -1 ); out->BandFmt = IM_BANDFMT_COMPLEX; if( im_setupout( out ) ) return( -1 ); if( !(buf = (float *) IM_ARRAY( dummy, IM_IMAGE_SIZEOF_LINE( out ), PEL )) ) return( -1 ); /* Gather together real and imag parts. */ for( p1 = (float *) real->data, p2 = (float *) imag->data, y = 0; y < out->Ysize; y++ ) { q = buf; for( x = 0; x < out->Xsize; x++ ) { q[0] = *p1++; q[1] = *p2++; q += 2; } if( im_writeline( y, out, (PEL *) buf ) ) return( -1 ); } return( 0 ); } #endif /*HAVE_FFTW3*/ #endif /*HAVE_FFTW*/ /** * im_invfft: * @in: input image * @out: output image * * Transform an image from Fourier space to real space. The result is complex. * If you are OK with a real result, use im_invfftr() instead, it's quicker. * * VIPS uses the fftw3 or fftw2 Fourier transform libraries if possible. If * they were not available when VIPS was built, it falls back to it's own * FFT functions which are slow and only work for square images whose sides * are a power of two. * * See also: im_invfftr(), im_fwfft(), im_disp_ps(). * * Returns: 0 on success, -1 on error. */ int im_invfft( IMAGE *in, IMAGE *out ) { IMAGE *dummy = im_open( "im_invfft:1", "p" ); if( !dummy ) return( -1 ); if( im__fftproc( dummy, in, out, invfft1 ) ) { im_close( dummy ); return( -1 ); } im_close( dummy ); if( out->Bands == 1 ) out->Type = IM_TYPE_B_W; else out->Type = IM_TYPE_MULTIBAND; return( 0 ); }
{ "alphanum_fraction": 0.5992799778, "avg_line_length": 24.2348993289, "ext": "c", "hexsha": "444495d79c8c2bde1a553d39047d640f480bd0a8", "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/apps/vips/src/libvips/freq_filt/im_invfft.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/apps/vips/src/libvips/freq_filt/im_invfft.c", "max_line_length": 79, "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/apps/vips/src/libvips/freq_filt/im_invfft.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": 2338, "size": 7222 }
#ifndef __GSL_SORT_VECTOR_H__ #define __GSL_SORT_VECTOR_H__ #include <gsl/gsl_sort_vector_long_double.h> #include <gsl/gsl_sort_vector_double.h> #include <gsl/gsl_sort_vector_float.h> #include <gsl/gsl_sort_vector_ulong.h> #include <gsl/gsl_sort_vector_long.h> #include <gsl/gsl_sort_vector_uint.h> #include <gsl/gsl_sort_vector_int.h> #include <gsl/gsl_sort_vector_ushort.h> #include <gsl/gsl_sort_vector_short.h> #include <gsl/gsl_sort_vector_uchar.h> #include <gsl/gsl_sort_vector_char.h> #endif /* __GSL_SORT_VECTOR_H__ */
{ "alphanum_fraction": 0.8161350844, "avg_line_length": 25.380952381, "ext": "h", "hexsha": "d65a9ee9bb97679e47bd3ebd5f85f187f240d593", "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/sort/gsl_sort_vector.h", "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/sort/gsl_sort_vector.h", "max_line_length": 44, "max_stars_count": 77, "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/sort/gsl_sort_vector.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "num_tokens": 150, "size": 533 }
#pragma once // std #include <optional> // GSL #include <gsl/gsl_assert> // EnTT #include <entt/entt.hpp> // Qt #include <QtWidgets>
{ "alphanum_fraction": 0.6691176471, "avg_line_length": 10.4615384615, "ext": "h", "hexsha": "884d94e5d48a1680b1d6fdf282df072c9bf1e996", "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": "f32def214753ca0f6bab9968bc2bb5e451cb6e4f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Qt-Widgets/PolyDock", "max_forks_repo_path": "PolyDock/PolyDock/src/pd/pch/PCH.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f32def214753ca0f6bab9968bc2bb5e451cb6e4f", "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": "Qt-Widgets/PolyDock", "max_issues_repo_path": "PolyDock/PolyDock/src/pd/pch/PCH.h", "max_line_length": 25, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f32def214753ca0f6bab9968bc2bb5e451cb6e4f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Qt-Widgets/PolyDock", "max_stars_repo_path": "PolyDock/PolyDock/src/pd/pch/PCH.h", "max_stars_repo_stars_event_max_datetime": "2021-01-10T06:43:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-10T06:43:03.000Z", "num_tokens": 42, "size": 136 }
/* * Copyright 2021-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #define MEMCACHED_ENGINE_H #include <sys/types.h> #include <functional> #include <memory> #include <string_view> #include <unordered_set> #include <utility> #include <gsl/gsl> #include <optional> #include <memcached/visibility.h> #include "memcached/collections.h" #include "memcached/engine_common.h" #include "memcached/thread_pool_config.h" #include "memcached/types.h" #include "memcached/vbucket.h" namespace cb::durability { class Requirements; } // namespace cb::durability namespace cb::mcbp { class Request; } // namespace cb::mcbp namespace cb::prometheus { enum class Cardinality; } // namespace cb::prometheus class BucketStatCollector; class StatCollector; /*! \mainpage memcached public API * * \section intro_sec Introduction * * The memcached project provides an API for providing engines as well * as data definitions for those implementing the protocol in C. This * documentation will explain both to you. * * \section docs_sec API Documentation * * Jump right into <a href="modules.html">the modules docs</a> to get started. * * \example default_engine.cc */ /** * \defgroup Engine Storage Engine API * \defgroup Protex Protocol Extension API * \defgroup Protocol Binary Protocol Structures * * \addtogroup Engine * @{ * * Most interesting here is to implement engine_interface_v1 for your * engine. */ struct DocKey; struct ServerBucketIface; struct ServerCoreIface; struct ServerCallbackIface; struct ServerLogIface; struct ServerCookieIface; struct ServerDocumentIface; union protocol_binary_request_header; struct ServerApi { ServerCoreIface* core = nullptr; ServerCallbackIface* callback = nullptr; ServerLogIface* log = nullptr; ServerCookieIface* cookie = nullptr; ServerDocumentIface* document = nullptr; ServerBucketIface* bucket = nullptr; }; using GET_SERVER_API = ServerApi* (*)(); namespace cb { using EngineErrorItemPair = std::pair<cb::engine_errc, cb::unique_item_ptr>; using EngineErrorMetadataPair = std::pair<engine_errc, item_info>; enum class StoreIfStatus { Continue, Fail, GetItemInfo // please get me the item_info }; using StoreIfPredicate = std::function<StoreIfStatus( const std::optional<item_info>&, cb::vbucket_info)>; struct EngineErrorCasPair { engine_errc status; uint64_t cas; }; /// Result of getVBucketHlcNow() struct HlcTime { enum class Mode { Real, Logical }; /// Seconds since Unix epoch. std::chrono::seconds now; Mode mode; }; } // namespace cb /** * The different compression modes that a bucket supports */ enum class BucketCompressionMode : uint8_t { Off, //Data will be stored as uncompressed Passive, //Data will be stored as provided by the client Active //Bucket will actively try to compress stored //data }; /* The default minimum compression ratio */ static const float default_min_compression_ratio = 1.2f; /* The default maximum size for a value */ static const size_t default_max_item_size = 20 * 1024 * 1024; namespace cb::engine { /** * Definition of the features that an engine can support */ enum class Feature : uint16_t { Collections = 1, }; using FeatureSet = std::unordered_set<Feature>; } // namespace cb::engine namespace std { template <> struct hash<cb::engine::Feature> { public: size_t operator()(const cb::engine::Feature& f) const { return static_cast<size_t>(f); } }; } // namespace std /** * Definition of the first version of the engine interface */ struct MEMCACHED_PUBLIC_CLASS EngineIface { virtual ~EngineIface() = default; /** * Initialize an engine instance. * This is called *after* creation, but before the engine may be used. * * @param handle the engine handle * @param config_str configuration this engine needs to initialize itself. */ virtual cb::engine_errc initialize(const char* config_str) = 0; /** * Tear down this engine. * * @param force the flag indicating the force shutdown or not. */ virtual void destroy(bool force) = 0; /// Callback that a cookie will be disconnected virtual void disconnect(gsl::not_null<const void*> cookie){}; /** * Initiate the bucket shutdown logic (disconnect clients etc) */ virtual void initiate_shutdown() { // empty } // Set the number or reader threads virtual void set_num_reader_threads(ThreadPoolConfig::ThreadCount num) { // ignored } // Set the number or writer threads virtual void set_num_writer_threads(ThreadPoolConfig::ThreadCount num) { // ignored } // Set the number of storage threads virtual void set_num_storage_threads( ThreadPoolConfig::StorageThreadCount num) { // ignored } /** * Request the engine to cancel all of the ongoing requests which * may have cookies in an ewouldblock state. * * This method is to removed in CC when we'll tighten the logic for * bucket deletion to use the following logic: * * 1) Stop any new requests into the engine. * 2) Tell the engine to complete (cancel) anything currently in-flight * (this notification holds a write lock to the engine so it won't * race with any front end threads) * 3) wait for in-flight ops (i.e. step B) to finish then delete bucket. * * In Mad-Hatter initiate_shutdown may race with all of the frontend * worker threads, and could lead to operations being added after we've * inspected the vbucket. To work around that problem this new method * was introduced and will be called multiple times during bucket * deletion to work around potential race situations. */ virtual void cancel_all_operations_in_ewb_state() { // empty } /* * Item operations. */ /** * Allocate an item (extended API) * * @param cookie The cookie provided by the frontend * @param key the item's key * @param nbytes the number of bytes that will make up the * value of this item. * @param priv_nbytes The number of bytes in nbytes containing * system data (and may exceed the item limit). * @param flags the item's flags * @param exptime the maximum lifetime of this item * @param vbucket virtual bucket to request allocation from * @return pair containing the item and the items information * @thows cb::engine_error with: * * * `cb::engine_errc::no_bucket` The client is bound to the dummy * `no bucket` which don't allow * allocations. * * * `cb::engine_errc::no_memory` The bucket is full * * * `cb::engine_errc::too_big` The requested memory exceeds the * limit set for items in the bucket. * * * `cb::engine_errc::disconnect` The client should be disconnected * * * `cb::engine_errc::not_my_vbucket` The requested vbucket belongs * to someone else * * * `cb::engine_errc::temporary_failure` Temporary failure, the * _client_ should try again * * * `cb::engine_errc::too_busy` Too busy to serve the request, * back off and try again. */ virtual std::pair<cb::unique_item_ptr, item_info> allocateItem( gsl::not_null<const void*> cookie, const DocKey& key, size_t nbytes, size_t priv_nbytes, int flags, rel_time_t exptime, uint8_t datatype, Vbid vbucket) = 0; /** * Remove an item. * * @param cookie The cookie provided by the frontend * @param key the key identifying the item to be removed * @param cas The cas to value to use for delete (or 0 as wildcard) * @param vbucket the virtual bucket id * @param durability the durability specifier for the command * @param mut_info On a successful remove write the mutation details to * this address. * * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc remove( gsl::not_null<const void*> cookie, const DocKey& key, uint64_t& cas, Vbid vbucket, const std::optional<cb::durability::Requirements>& durability, mutation_descr_t& mut_info) = 0; /** * Indicate that a caller who received an item no longer needs * it. * * @param item the item to be released */ virtual void release(gsl::not_null<ItemIface*> item) = 0; /** * Retrieve an item. * * @param cookie The cookie provided by the frontend * @param item output variable that will receive the located item * @param key the key to look up * @param vbucket the virtual bucket id * @param documentStateFilter The document to return must be in any of * of these states. (If `Alive` is set, return * KEY_ENOENT if the document in the engine * is in another state) * * @return cb::engine_errc::success if all goes well */ virtual cb::EngineErrorItemPair get(gsl::not_null<const void*> cookie, const DocKey& key, Vbid vbucket, DocStateFilter documentStateFilter) = 0; /** * Optionally retrieve an item. Only non-deleted items may be fetched * through this interface (Documents in deleted state may be evicted * from memory and we don't want to go to disk in order to fetch these) * * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param filter callback filter to see if the item should be returned * or not. If filter returns false the item should be * skipped. * Note: the filter is applied only to the *metadata* of the * item_info - i.e. the `value` should not be expected to be * present when filter is invoked. * @return A pair of the error code and (optionally) the item */ virtual cb::EngineErrorItemPair get_if( gsl::not_null<const void*> cookie, const DocKey& key, Vbid vbucket, std::function<bool(const item_info&)> filter) = 0; /** * Retrieve metadata for a given item. * * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * * @return Pair (cb::engine_errc::success, Metadata) if all goes well */ virtual cb::EngineErrorMetadataPair get_meta( gsl::not_null<const void*> cookie, const DocKey& key, Vbid vbucket) = 0; /** * Lock and Retrieve an item. * * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param lock_timeout the number of seconds to hold the lock * (0 == use the engines default lock time) * * @return A pair of the error code and (optionally) the item */ virtual cb::EngineErrorItemPair get_locked( gsl::not_null<const void*> cookie, const DocKey& key, Vbid vbucket, uint32_t lock_timeout) = 0; /** * Unlock an item. * * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param cas the cas value for the locked item * * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc unlock(gsl::not_null<const void*> cookie, const DocKey& key, Vbid vbucket, uint64_t cas) = 0; /** * Get and update the expiry time for the document * * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param expirytime the new expiry time for the object * @param durability An optional durability requirement * @return A pair of the error code and (optionally) the item */ virtual cb::EngineErrorItemPair get_and_touch( gsl::not_null<const void*> cookie, const DocKey& key, Vbid vbucket, uint32_t expirytime, const std::optional<cb::durability::Requirements>& durability) = 0; /** * Store an item into the underlying engine with the given * state. If the DocumentState is set to DocumentState::Deleted * the document shall not be returned unless explicitly asked for * documents in that state, and the underlying engine may choose to * purge it whenever it please. * * @param cookie The cookie provided by the frontend * @param item the item to store * @param cas the CAS value for conditional sets * @param semantics the semantics of the store operation * @param durability An optional durability requirement * @param document_state The state the document should have after * the update * @param preserveTtl if set to true the existing documents TTL should * be used. * * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc store( gsl::not_null<const void*> cookie, gsl::not_null<ItemIface*> item, uint64_t& cas, StoreSemantics semantics, const std::optional<cb::durability::Requirements>& durability, DocumentState document_state, bool preserveTtl) = 0; /** * Store an item into the underlying engine with the given * state only if the predicate argument returns true when called against an * existing item. * * Optional interface; not supported by all engines. * * @param cookie The cookie provided by the frontend * @param item the item to store * @param cas the CAS value for conditional sets * @param semantics the semantics of the store operation * @param predicate a function that will be called from the engine the * result of which determines how the store behaves. * The function is given any existing item's item_info (as * a std::optional) and a cb::vbucket_info object. In the * case that the optional item_info is not initialised the * function can return cb::StoreIfStatus::GetInfo to * request that the engine tries to get the item_info, the * engine may ignore this return code if it knows better * i.e. a memory only engine and no item_info can be * fetched. The function can also return ::Fail if it * wishes to fail the store_if (returning predicate_failed) * or the predicate can return ::Continue and the rest of * the store_if will execute (and possibly fail for other * reasons). * @param durability An optional durability requirement * @param document_state The state the document should have after * the update * @param preserveTtl if set to true the existing documents TTL should * be used. * * @return a std::pair containing the engine_error code and new CAS */ virtual cb::EngineErrorCasPair store_if( gsl::not_null<const void*> cookie, gsl::not_null<ItemIface*> item, uint64_t cas, StoreSemantics semantics, const cb::StoreIfPredicate& predicate, const std::optional<cb::durability::Requirements>& durability, DocumentState document_state, bool preserveTtl) { return {cb::engine_errc::not_supported, 0}; } /** * Flush the cache. * * Optional interface; not supported by all engines. * * @param cookie The cookie provided by the frontend * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc flush(gsl::not_null<const void*> cookie) { return cb::engine_errc::not_supported; } /* * Statistics */ /** * Get statistics from the engine. * * @param cookie The cookie provided by the frontend * @param key optional argument to stats * @param value optional value for the given stat group * @param add_stat callback to feed results to the output * * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc get_stats(gsl::not_null<const void*> cookie, std::string_view key, std::string_view value, const AddStatFn& add_stat) = 0; /** * Get statistics for Prometheus exposition from the engine. * Some engines may not support this. * * @param collector where the bucket may register stats * * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc get_prometheus_stats( const BucketStatCollector& collector, cb::prometheus::Cardinality cardinality) { return cb::engine_errc::not_supported; } /** * Reset the stats. * * @param cookie The cookie provided by the frontend */ virtual void reset_stats(gsl::not_null<const void*> cookie) = 0; /** * Any unknown command will be considered engine specific. * * @param cookie The cookie provided by the frontend * @param request The request from the client * @param response function to transmit data * * @return cb::engine_errc::success if all goes well */ virtual cb::engine_errc unknown_command(const void* cookie, const cb::mcbp::Request& request, const AddResponseFn& response) { return cb::engine_errc::not_supported; } /** * Set the CAS id on an item. */ virtual void item_set_cas(gsl::not_null<ItemIface*> item, uint64_t cas) = 0; /** * Set the data type on an item. */ virtual void item_set_datatype(gsl::not_null<ItemIface*> item, protocol_binary_datatype_t datatype) = 0; /** * Get information about an item. * * The loader of the module may need the pointers to the actual data within * an item. Instead of having to create multiple functions to get each * individual item, this function will get all of them. * * @param item the item to request information about * @param item_info * @return true if successful */ virtual bool get_item_info(gsl::not_null<const ItemIface*> item, gsl::not_null<item_info*> item_info) = 0; /** * The set of collections related functions. May be defined optionally by * the engine(s) that support them. */ virtual cb::engine_errc set_collection_manifest( gsl::not_null<const void*> cookie, std::string_view json) { return cb::engine_errc::not_supported; } /** * Retrieve the last manifest set using set_manifest (a JSON document) */ virtual cb::engine_errc get_collection_manifest( gsl::not_null<const void*> cookie, const AddResponseFn& response) { return cb::engine_errc::not_supported; } virtual cb::EngineErrorGetCollectionIDResult get_collection_id( gsl::not_null<const void*> cookie, std::string_view path) { return cb::EngineErrorGetCollectionIDResult{ cb::engine_errc::not_supported}; } virtual cb::EngineErrorGetScopeIDResult get_scope_id( gsl::not_null<const void*> cookie, std::string_view path) { return cb::EngineErrorGetScopeIDResult{cb::engine_errc::not_supported}; } /** * Get the scope for the provided key * * @param cookie cookie object used to identify the request * @param key the key to look up * @return pair with the manifest UID and if found the scope where the key * belongs. */ virtual cb::EngineErrorGetScopeIDResult get_scope_id( gsl::not_null<const void*> cookie, const DocKey& key, std::optional<Vbid> vbid = std::nullopt) const { return cb::EngineErrorGetScopeIDResult(cb::engine_errc::not_supported); } /** * Ask the engine what features it supports. */ virtual cb::engine::FeatureSet getFeatures() = 0; /** * @returns if XATTRs are enabled for this bucket */ virtual bool isXattrEnabled() { return false; } /** * Get the "current" time and mode of the Hybrid Logical Clock for the * specified vBucket. * @returns seconds since unix epoch of the HLC, along with the current * HLC Mode (Real / Logical). */ virtual cb::HlcTime getVBucketHlcNow(Vbid vbucket) = 0; /** * @returns the compression mode of the bucket */ virtual BucketCompressionMode getCompressionMode() { return BucketCompressionMode::Off; } /** * @returns the maximum item size supported by the bucket */ virtual size_t getMaxItemSize() { return default_max_item_size; }; /** * @returns the minimum compression ratio defined in the bucket */ virtual float getMinCompressionRatio() { return default_min_compression_ratio; } /** * Set a configuration parameter in the engine * * @param cookie The cookie identifying the request * @param category The parameter category * @param key The name of the parameter * @param value The value for the parameter * @param vbucket The vbucket specified in the request (only used for * the vbucket sub group) * @return The standard engine codes */ virtual cb::engine_errc setParameter(gsl::not_null<const void*> cookie, EngineParamCategory category, std::string_view key, std::string_view value, Vbid vbucket) { return cb::engine_errc::not_supported; } /** * Compact a database * * @param cookie The cookie identifying the request * @param vbid The vbucket to compact * @param purge_before_ts The timestamp to purge items before * @param purge_before_seq The sequence number to purge items before * @param drop_deletes Set to true if deletes should be dropped * @return The standard engine codes */ virtual cb::engine_errc compactDatabase(gsl::not_null<const void*> cookie, Vbid vbid, uint64_t purge_before_ts, uint64_t purge_before_seq, bool drop_deletes) { return cb::engine_errc::not_supported; } /** * Get the state of a vbucket * * @param cookie The cookie identifying the request * @param vbid The vbucket to look up * @return A pair where the first entry is one of the standard engine codes * and the second is the state when the status is success. */ virtual std::pair<cb::engine_errc, vbucket_state_t> getVBucket( gsl::not_null<const void*> cookie, Vbid vbid) { return {cb::engine_errc::not_supported, vbucket_state_dead}; } /** * Set the state of a vbucket * * @param cookie The cookie identifying the request * @param vbid The vbucket to update * @param cas The current value used for CAS swap * @param state The new vbucket state * @param meta The optional meta information for the state (nullptr if * none is provided) * @return The standard engine codes */ virtual cb::engine_errc setVBucket(gsl::not_null<const void*> cookie, Vbid vbid, uint64_t cas, vbucket_state_t state, nlohmann::json* meta) { return cb::engine_errc::not_supported; } /** * Delete a vbucket * * @param cookie The cookie identifying the request * @param vbid The vbucket to delete * @param sync If the operation should block (return EWB and be signalled * when the operation is done) or delete in "fire and forget" * mode. * @return The standard engine codes */ virtual cb::engine_errc deleteVBucket(gsl::not_null<const void*> cookie, Vbid vbid, bool sync) { return cb::engine_errc::not_supported; } }; namespace cb { class ItemDeleter { public: ItemDeleter() : handle(nullptr) {} /** * Create a new instance of the item deleter. * * @param handle_ the handle to the the engine who owns the item */ explicit ItemDeleter(EngineIface* handle_) : handle(handle_) { if (handle == nullptr) { throw std::invalid_argument( "cb::ItemDeleter: engine handle cannot be nil"); } } /** * Create a copy constructor to allow us to use std::move of the item */ ItemDeleter(const ItemDeleter& other) = default; void operator()(ItemIface* item) { if (handle) { handle->release(item); } else { throw std::invalid_argument("cb::ItemDeleter: item attempted to be " "freed by null engine handle"); } } private: EngineIface* handle; }; inline EngineErrorItemPair makeEngineErrorItemPair(cb::engine_errc err) { return {err, unique_item_ptr{nullptr, ItemDeleter{}}}; } inline EngineErrorItemPair makeEngineErrorItemPair(cb::engine_errc err, ItemIface* it, EngineIface* handle) { return {err, unique_item_ptr{it, ItemDeleter{handle}}}; } } struct EngineDeletor { void operator()(EngineIface* engine) { engine->destroy(force); } bool force = false; }; using unique_engine_ptr = std::unique_ptr<EngineIface, EngineDeletor>; /** * @} */
{ "alphanum_fraction": 0.6113013082, "avg_line_length": 34.385377943, "ext": "h", "hexsha": "a263c61ae81223aab6c49dbead144df9e936eff9", "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": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_path": "include/memcached/engine.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_path": "include/memcached/engine.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_path": "include/memcached/engine.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6193, "size": 27749 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics_double.h> #include <math.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_voxel_graphics.h" #include "tz_neurotrace.h" #include "tz_stack_math.h" #include "tz_stack_utils.h" #include "tz_objdetect.h" #include "tz_voxeltrans.h" #include "tz_stack_stat.h" #include "tz_stack_draw.h" #include "tz_geo3d_vector.h" #include "tz_stack_bwmorph.h" #include "tz_stack_bwdist.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { #if 1 Stack *stack = Read_Stack("../data/lobster_neuron_seed.tif"); Voxel_List *list = Stack_To_Voxel_List(stack); //Print_Voxel_List(list); Pixel_Array *pa = Pixel_Array_Read("../data/lobster_neuron_seeds.pa"); //Print_Pixel_Array(pa); Voxel *seed; int i; double *pa_array = (double *) pa->array; printf("mean: %g, std: %g\n", gsl_stats_mean(pa_array, 1, pa->size), sqrt(gsl_stats_variance(pa_array, 1, pa->size))); double threshold = gsl_stats_mean(pa_array, 1, pa->size) + 3.0 * sqrt(gsl_stats_variance(pa_array, 1, pa->size)); double max_r = gsl_stats_max(pa_array, 1, pa->size); printf("%g, %g\n", threshold, max_r); max_r = 30.0; Set_Neuroseg_Max_Radius(max_r); dim_type dim[3]; dim[0] = stack->width; dim[1] = stack->height; dim[2] = stack->depth; IMatrix *chord = Make_IMatrix(dim, 3); Stack *code = Make_Stack(GREY16, stack->width, stack->height, stack->depth); Kill_Stack(stack); stack = Read_Stack("../data/lobster_neuron_single.tif"); Rgb_Color color; Set_Color(&color, 255, 0, 0); Stack *signal = Read_Stack("../data/lobster_neuron.tif"); Stack *canvas = Translate_Stack(signal, COLOR, 0); /************** soma detection *************/ #if 0 Struct_Element *se = Make_Ball_Se(((int) threshold)); Stack *stack1 = Stack_Erode_Fast(stack, NULL, se); Stack *soma = Stack_Dilate(stack1, NULL, se); Kill_Stack(stack1); Stack_And(stack, soma, soma); Stack_Label_Bwc(canvas, soma, color); Kill_Stack(soma); Write_Stack("../data/test.tif", canvas); return 0; #endif /*******************************************/ Object_3d *obj = NULL; int seed_offset = -1; Neurochain *chain = NULL; double z_scale = 0.488 / 0.588; Set_Zscale(z_scale); Stack *traced = Make_Stack(GREY, signal->width, signal->height, signal->depth); One_Stack(traced); for (i = 0; i < pa->size; i++) { seed = Voxel_Queue_De(&list); printf("------------------------------------------> seed: %d\n", i); if (*STACK_PIXEL_8(traced, seed->x, seed->y, seed->z, 0) == 0) { continue; } double width = pa_array[i]; if (width > max_r) { continue; } chain = New_Neurochain(); Print_Voxel(seed); printf("%g\n", width); int max_level = (int) (width + 0.5); if (max_level < 6) { max_level = 6; } seed_offset = Stack_Util_Offset(seed->x, seed->y, seed->z, stack->width, stack->height, stack->depth); Stack_Level_Code_Constraint(stack, code, chord->array, &seed_offset, 1, max_level + 1); Voxel_t v; Voxel_To_Tvoxel(seed, v); Print_Tvoxel(v); Stack *tmp_stack = Copy_Stack(stack); obj = Stack_Grow_Object_Constraint(tmp_stack, 1, v, chord, code, max_level); Free_Stack(tmp_stack); Print_Object_3d_Info(obj); double vec[3]; Object_3d_Orientation_Zscale(obj, vec, MAJOR_AXIS, z_scale); double theta, psi; Geo3d_Vector obj_vec; Set_Geo3d_Vector(&obj_vec, vec[0], vec[1], vec[2]); Geo3d_Vector_Orientation(&obj_vec, &theta, &psi); Set_Neuroseg(&(chain->seg), width, width, 10.0, theta, psi); double cpos[3]; cpos[0] = seed->x; cpos[1] = seed->y; cpos[2] = seed->z; cpos[2] *= z_scale; double bpos[3]; Neuroseg_Pos_Center_To_Bottom(&(chain->seg), cpos, bpos); Set_Position(chain->position, bpos[0], bpos[1], bpos[2]); if (Initialize_Tracing(signal, chain, NULL, NULL) >= MIN_SCORE) { if ((chain->seg.r1 < max_r) && (chain->seg.r2 < max_r)) { chain = Trace_Neuron(signal, chain, BOTH, traced); Print_Neurochain(chain); //Stack_Draw_Object_Bwc(canvas, obj, color); Neurochain_Erase(traced, Neurochain_Head(chain)); Neurochain_Label(canvas, Neurochain_Head(chain)); } } Free_Neurochain(chain); free(seed); Kill_Object_3d(obj); } Write_Stack("../data/lobster_neuron_traced.tif", canvas); #endif return 0; }
{ "alphanum_fraction": 0.6385857704, "avg_line_length": 23.2588832487, "ext": "c", "hexsha": "4145af91ae99428183e3711e216913e4bc7cfe93", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_lobster_neuron2.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_lobster_neuron2.c", "max_line_length": 78, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_lobster_neuron2.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 1414, "size": 4582 }
#include <petscksp.h> #include "AFS.h" #include "AFS_ctmc_petsc.h" #include "im_clam.h" #include "sparseExp.h" #include "cs.h" #include "AFS_ctmc.h" #include "nlopt.h" #include "adkGSL.h" #include <gsl/gsl_linalg.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> //Functions for jointly computing CTMC transitions and embedded chain //this function fills two petsc matrices: 1) embedded Discrete MC trans Mat, 2) CTMC trans mat // also fills the rates vector void fillPetscTransMats(afsStateSpace *S, double *topol, int *moveType, int *nzCount, int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2, Mat *DTMC, Mat *CTMC, gsl_vector *rates){ int i, j,k, newnz, abcount=0; int N = S->nstates,abFlag; double c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;; gsl_vector_set_zero(rates); //set rates vector for(i=0;i<N;i++){ c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ; if(theta2 == 0) c1r[i] = 0.0; else c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2; m0r[i] = S->states[i]->aCounts[0] * mig1 ; m1r[i] = S->states[i]->aCounts[1] * mig2 ; totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i]; rowSums[i] = 0.0; if(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0) gsl_vector_set(rates,i,1.0/totR[i]); else gsl_vector_set(rates,i,0); } newnz=0; for(k=0;k<*nzCount;k++){ i = dim1[k]; j= dim2[k]; // printf("i: %d, j:%d, movetype: %d\n",i,j,moveType[k]); if(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1; // if(S->states[i]->nalleles ==1 )abFlag=1; else abFlag = 0; switch(moveType[k]){ case 0: //coal pop0 if(totR[i]==0)tmp=0; else tmp = c0r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES); break; case 1: //coal pop1 if(totR[i]==0)tmp=0; else tmp = c1r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES); break; case 2: //mig pop0 if(totR[i]==0)tmp=0; else tmp = m0r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES); break; case 3: //mig pop1 if(totR[i]==0)tmp=0; else tmp = m1r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)MatSetValue(*DTMC,i,j,tmp,INSERT_VALUES); break; case -1: abcount+=1; break; } } newnz=*nzCount ; //now add diagonal elements; topol pre-set to -1 for(k=0;k<N;k++){ if((rowSums[k]) != 0.0){ MatSetValue(*CTMC,k,k,0.0-rowSums[k],INSERT_VALUES); newnz++; } MatSetValue(*DTMC,k,k,0.0,INSERT_VALUES); } *nzCount = newnz; /* Assemble the matrix */ MatAssemblyBegin(*CTMC,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(*CTMC,MAT_FINAL_ASSEMBLY); MatAssemblyBegin(*DTMC,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(*DTMC,MAT_FINAL_ASSEMBLY); } //fillPetscCsparseTransMats--this function fills one petsc matrix with CTMC transmat and returns pointer to CSparse matrix for DTMC trans mat // also fills the rates vector //note that the DTMC matrix needs to be cleared before entry to this function and compressed afterward. struct cs_di_sparse * fillPetscCsparseTransMats(afsStateSpace *S, double *topol, int *moveType, int *nzCount, int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2, Mat *CTMC, gsl_vector *rates){ int i, j,k, newnz, abcount=0; int N = S->nstates,abFlag; double c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;; struct cs_di_sparse *triplet, *tmat; //allocate new cs_sparse obj triplet = cs_spalloc(N, N, *nzCount + N , 1, 1); //alloc sparse mat with extra space for nonzero identity mats gsl_vector_set_zero(rates); //set rates vector for(i=0;i<N;i++){ c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ; if(theta2 == 0) c1r[i] = 0.0; else c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2; m0r[i] = S->states[i]->aCounts[0] * mig1 ; m1r[i] = S->states[i]->aCounts[1] * mig2 ; totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i]; rowSums[i] = 0.0; if(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0) gsl_vector_set(rates,i,1.0/totR[i]); else gsl_vector_set(rates,i,0); } newnz=0; for(k=0;k<*nzCount;k++){ i = dim1[k]; j= dim2[k]; // printf("i: %d, j:%d, movetype: %d\n",i,j,moveType[k]); if(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1; // if(S->states[i]->nalleles ==1 )abFlag=1; else abFlag = 0; switch(moveType[k]){ case 0: //coal pop0 if(totR[i]==0)tmp=0; else tmp = c0r[i] / totR[i] * topol[k]; // printf("here--- i:%d j:%d tmp*totR[i]:%f",i,j,tmp*totR[i]); MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case 1: //coal pop1 if(totR[i]==0)tmp=0; else tmp = c1r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case 2: //mig pop0 if(totR[i]==0)tmp=0; else tmp = m0r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case 3: //mig pop1 if(totR[i]==0)tmp=0; else tmp = m1r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case -1: abcount+=1; break; } } newnz=*nzCount ; //now add diagonal elements; topol pre-set to -1 for(k=0;k<N;k++){ if((rowSums[k]) != 0.0){ MatSetValue(*CTMC,k,k,0.0-rowSums[k],INSERT_VALUES); newnz++; } } *nzCount = newnz; /* Assemble the matrix */ MatAssemblyBegin(*CTMC,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(*CTMC,MAT_FINAL_ASSEMBLY); tmat = cs_compress(triplet); cs_spfree(triplet); return(tmat); } //fillPetscCsparseTransMats_prealloc--this function fills one petsc matrix with CTMC transmat and returns pointer to CSparse matrix for DTMC trans mat // also fills the rates vector struct cs_di_sparse * fillPetscCsparseTransMats_prealloc(afsStateSpace *S, double *topol, int *moveType, int *nzCount, int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2, Mat *CTMC, gsl_vector *rates, struct cs_di_sparse *triplet){ int i, j,k, newnz, abcount=0; int N = S->nstates,abFlag; double *c0r,*c1r,*m0r,*m1r,*totR,*rowSums, tmp; struct cs_di_sparse *tmat; c0r = malloc(sizeof(double)*N); c1r = malloc(sizeof(double)*N); m0r = malloc(sizeof(double)*N); m1r = malloc(sizeof(double)*N); totR = malloc(sizeof(double)*N); rowSums = malloc(sizeof(double)*N); gsl_vector_set_zero(rates); //set rates vector for(i=0;i<N;i++){ c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ; if(theta2 == 0) c1r[i] = 0.0; else c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2; m0r[i] = S->states[i]->aCounts[0] * mig1 ; m1r[i] = S->states[i]->aCounts[1] * mig2 ; totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i]; rowSums[i] = 0.0; if(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0) gsl_vector_set(rates,i,1.0/totR[i]); else gsl_vector_set(rates,i,0); } newnz=0; for(k=0;k<*nzCount;k++){ i = dim1[k]; j= dim2[k]; // printf("i: %d, j:%d, movetype: %d\n",i,j,moveType[k]); if(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1; // if(S->states[i]->nalleles ==1 )abFlag=1; else abFlag = 0; switch(moveType[k]){ case 0: //coal pop0 if(totR[i]==0)tmp=0; else tmp = c0r[i] / totR[i] * topol[k]; // printf("here--- i:%d j:%d tmp*totR[i]:%f",i,j,tmp*totR[i]); MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case 1: //coal pop1 if(totR[i]==0)tmp=0; else tmp = c1r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case 2: //mig pop0 if(totR[i]==0)tmp=0; else tmp = m0r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case 3: //mig pop1 if(totR[i]==0)tmp=0; else tmp = m1r[i] / totR[i] * topol[k]; MatSetValue(*CTMC,i,j,tmp*totR[i],INSERT_VALUES); rowSums[i] += tmp* totR[i]; if(abFlag==0)cs_entry(triplet,i,j,tmp); break; case -1: abcount+=1; break; } } newnz=*nzCount ; //now add diagonal elements; topol pre-set to -1 for(k=0;k<N;k++){ if((rowSums[k]) != 0.0){ MatSetValue(*CTMC,k,k,0.0-rowSums[k],INSERT_VALUES); newnz++; } } *nzCount = newnz; /* Assemble the matrix */ MatAssemblyBegin(*CTMC,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(*CTMC,MAT_FINAL_ASSEMBLY); tmat = cs_compress(triplet); free(c0r); free(c1r); free(m0r); free(m1r); free(totR); free(rowSums); return(tmat); } //calcLogAFS_IM -- returns the expects log AFS from an IM model void calcLogAFS_IM(void * p){ struct clam_lik_params * params = (struct clam_lik_params *) p; PetscInt i,j, N = params->stateSpace->nstates; cs *spMat, *mt, *tmpMat ; double timeV, sum, thetaA, theta2, mig1, mig2; PetscInt Na; gsl_vector *tmpStates; css *S ; csn *NN ; PetscInt n,Ntmp ; double *xx; PetscInt iStart,iEnd, *idx; const PetscInt *idx2; PetscScalar *tmpArray; const PetscScalar *tmpArrayC; PetscErrorCode ierr; MFNConvergedReason reason; //initialize some vectors gsl_vector_set_zero(params->rates); MatZeroEntries(params->C); MatZeroEntries(params->C2); tmpStates = gsl_vector_alloc(N); Ntmp=N; Na=params->Na; //For straight MLE the paramVector takes the form [N2,NA,m1,m2,t] theta2 = gsl_vector_get(params->paramVector,0); thetaA = gsl_vector_get(params->paramVector,1); mig1 = gsl_vector_get(params->paramVector,2); mig2 = gsl_vector_get(params->paramVector,3); timeV = gsl_vector_get(params->paramVector,4); // printf("params-> %f %f %f %f %f\n",theta2,thetaA,mig1,mig2,timeV); // printf("nnz %d nnzA%d \n",params->nnz,params->nnzA); //fill transMat // tmpMat = fillPetscCsparseTransMats_prealloc(params->stateSpace, params->top, params->move, &params->nnz, // params->dim1, params->dim2, 1, theta2, mig1, mig2, &params->C, params->rates,params->triplet); tmpMat = fillPetscCsparseTransMats(params->stateSpace, params->top, params->move, &params->nnz, params->dim1, params->dim2, 1, theta2, mig1, mig2, &params->C, params->rates); //using CSparse // S = (I-P)^-1 //add negative ident // ident = cs_spalloc(N,N,N,1,1); // for(i=0;i<N;i++) cs_entry(ident,i,i,1); // eye = cs_compress(ident); spMat = cs_add(params->eye,tmpMat,1.0,-1.0); //cs_print_adk(spMat); mt = cs_transpose(spMat,1); //cs_print_adk(mt); n = mt->n ; S = cs_sqr (0, mt, 0) ; /* ordering and symbolic analysis */ NN = cs_lu (mt, S, 1e-12) ; /* numeric LU factorization */ xx = cs_malloc (n, sizeof (double)) ; /* get workspace */ MatGetOwnershipRange(params->denseMat1,&iStart,&iEnd); PetscMalloc1(N,&idx); for(j=0;j<N;j++) idx[j]=j; ////Compute Entire Inverse Mat for(j=iStart;j<iEnd;j++){ //create unit array for solve for(i=0; i<N; i++)params->b[i] = 0.0; params->b[j]=1.0; //factor outside loop leads to ~40x speedup cs_ipvec (NN->pinv, params->b, xx, n) ; /* x = b(p) */ cs_lsolve (NN->L, xx) ; /* x = L\x */ cs_usolve (NN->U, xx) ; /* x = U\x */ cs_ipvec (S->q, xx, params->b, n) ; /* b(q) = x */ // if(!rank)printf("row %d\n",j); MatSetValues(params->denseMat1,1,&j,N,idx,params->b,INSERT_VALUES); } MatAssemblyBegin(params->denseMat1,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(params->denseMat1,MAT_FINAL_ASSEMBLY); //temporary clean up free(xx); cs_spfree(spMat); cs_spfree(mt); // cs_spfree(ident); // cs_spfree(eye); cs_spfree(tmpMat); cs_nfree(NN); cs_sfree(S); PetscFree(idx); // MatView(params->denseMat1,PETSC_VIEWER_STDOUT_WORLD); //broadcast the invMat[0,] as vector to each processor if(params->rank==0){ MatGetRow(params->denseMat1,0,&N,&idx2,&tmpArrayC); for (j = 0; j < N; j++) params->b[j] = tmpArrayC[j]; MatRestoreRow(params->denseMat1,0,&Ntmp,&idx2,&tmpArrayC); //have to use Ntmp here as MatRestoreRow does something funky } MPI_Bcast(params->b,N,MPI_DOUBLE,0,PETSC_COMM_WORLD); //Get Island Time 0-INF Unnormal gsl_matrix_set_zero(params->expAFS); fillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS); // printf("////////////////////Island Time 0 - INF unnormalized\n"); // for(i=0;i< (params->n1+1) ;i++){ // for(j=0;j< (params->n2+1);j++){ // printf("%.5f ",gsl_matrix_get(params->expAFS,i,j)); // } // printf("\n"); // } //Matrix Exponentiation to get state vector at time t //SLEPC Stuff ahead! /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the solver and set various options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Set operator matrix, the function to compute, and other options */ //transpose MatTranspose(params->C,MAT_REUSE_MATRIX,&params->C); ierr = MFNSetOperator(params->mfn,params->C);CHKERRV(ierr); /* Set solver parameters at runtime */ ierr = MFNSetScaleFactor(params->mfn,timeV); CHKERRV(ierr); ierr = MFNSetFromOptions(params->mfn);CHKERRV(ierr); /* set v = e_1 */ ierr = MatGetVecs(params->C,PETSC_NULL,&params->y);CHKERRV(ierr); ierr = MatGetVecs(params->C,&params->v, PETSC_NULL);CHKERRV(ierr); ierr = VecSetValue(params->v,0,1.0,INSERT_VALUES);CHKERRV(ierr); ierr = VecAssemblyBegin(params->v);CHKERRV(ierr); ierr = VecAssemblyEnd(params->v);CHKERRV(ierr); ierr = MFNSolve(params->mfn,params->v,params->y);CHKERRV(ierr); ierr = MFNGetConvergedReason(params->mfn,&reason);CHKERRV(ierr); if (reason!=MFN_CONVERGED_TOL) ierr = 1; CHKERRV(ierr); //retranspose for later use MatTranspose(params->C,MAT_REUSE_MATRIX,&params->C); //state vector at time t stored in y //scatter y and store in expoArray VecScatterCreateToAll(params->y,&params->ctx,&params->v_seq); VecScatterBegin(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecGetArray(params->v_seq,&tmpArray); for (j = 0; j < N; j++){ params->expoArray[j] = tmpArray[j]; //printf("%.5f\n",expoArray[j]); } VecRestoreArray(params->v_seq,&tmpArray); VecScatterDestroy(&params->ctx); VecDestroy(&params->v_seq); VecDuplicate(params->y,&params->x); //VecView(y, PETSC_VIEWER_STDOUT_WORLD); MatMultTranspose(params->denseMat1,params->y,params->x); VecScatterCreateToAll(params->x,&params->ctx,&params->v_seq); VecScatterBegin(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecGetArray(params->v_seq,&tmpArray); for (j = 0; j < N; j++){ params->b[j] = tmpArray[j]; //printf("rank %d expoArray[%d]:%.5f\n",rank,j,expoArray[j]); //printf("rank %d b[%d]:%.5f\n",rank,j,b[j]); } VecRestoreArray(params->v_seq,&tmpArray); VecScatterDestroy(&params->ctx); VecDestroy(&params->v_seq); fillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS2); //now subtract older AFS (t_t - t_INF) from total AFS (t_0 - t_INF) ///////////////// /////// gsl_matrix_sub(params->expAFS,params->expAFS2); ////////////////////// //Final phase, collapse popns, reset rates //now collapse populations //state vector at time t stored in st[] for largerStateSpace; use reverseMap for(i=0;i<N;i++)params->st[i]=0.0; for(i=0;i<N;i++){params->st[params->map[i]]+=params->expoArray[i]; // printf("expoArray[%d]:%f\n",i,expoArray[i]); } for(i=0; i<params->reducedStateSpace->nstates; i++){ VecSetValue(params->ancStateVec,i,params->st[params->reverseMap[i]],INSERT_VALUES ); } //Re-Fill trans mats for Ancestral Params params->nnzA = coalMarkovChainTopologyMatrix_sparse(params->reducedStateSpace,params->topA,params->moveA, params->dim1A, params->dim2A); tmpMat=fillPetscCsparseTransMats(params->reducedStateSpace, params->topA, params->moveA, &params->nnzA, params->dim1A, params->dim2A, thetaA, 0, 0, 0, &params->C2, params->rates); ////////////////////// // // S = (I-P)^-1 // ///////// ////// //add negative ident // ident = cs_spalloc(Na,Na,Na,1,1); // for(i=0;i<Na;i++) cs_entry(ident,i,i,1); // eye = cs_compress(ident); spMat = cs_add(params->eyeAnc,tmpMat,1.0,-1.0); //cs_print_adk(spMat); mt = cs_transpose(spMat,1); //VecView(y,PETSC_VIEWER_STDOUT_WORLD); n = mt->n ; S = cs_sqr (0, mt, 0) ; /* ordering and symbolic analysis */ NN = cs_lu (mt, S, 1e-12) ; /* numeric LU factorization */ xx = cs_malloc (n, sizeof (double)) ; /* get workspace */ MatGetOwnershipRange(params->denseMat2,&iStart,&iEnd); // printf("here\n"); PetscFree(idx); PetscMalloc1(Na,&idx); for(j=0;j<Na;j++) idx[j]=j; ////Compute Entire Inverse Mat for(j=iStart;j<iEnd;j++){ //create unit array for solve for(i=0; i<Na; i++)params->b[i] = 0.0; params->b[j]=1.0; //factor outside loop leads to ~40x speedup cs_ipvec (NN->pinv, params->b, xx, n) ; /* x = b(p) */ cs_lsolve (NN->L, xx) ; /* x = L\x */ cs_usolve (NN->U, xx) ; /* x = U\x */ cs_ipvec (S->q, xx, params->b, n) ; /* b(q) = x */ // if(!rank)printf("row %d\n",j); MatSetValues(params->denseMat2,1,&j,Na,idx,params->b,INSERT_VALUES); } MatAssemblyBegin(params->denseMat2,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(params->denseMat2,MAT_FINAL_ASSEMBLY); free(xx); MatMultTranspose(params->denseMat2,params->ancStateVec,params->ancResVec); VecScatterCreateToAll(params->ancResVec,&params->ctx,&params->v_seq); VecScatterBegin(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecGetArray(params->v_seq,&tmpArray); for (j = 0; j < Na; j++){ params->expoArray[j] = tmpArray[j]; //printf("%.5f\n",expoArray[j]); } VecRestoreArray(params->v_seq,&tmpArray); VecScatterDestroy(&params->ctx); VecDestroy(&params->v_seq); //get contribution starting at st gsl_matrix_set_zero(params->expAFS2); fillExpectedAFS_unnorm(params->reducedStateSpace, params->expoArray,params->rates,params->expAFS2); // printf("////////////////////--Ancestral bit\n"); // for(i=0;i< (n1+1) ;i++){ // for(j=0;j< (n2+1);j++){ // printf("%.5f ",gsl_matrix_get(expAFS2,i,j)); // } // printf("\n"); // } //if(params->rank==0)printf("////////////////////normalized IM:\n"); gsl_matrix_add(params->expAFS,params->expAFS2); sum = matrixSumDouble(params->expAFS); gsl_matrix_scale(params->expAFS, 1.0 / sum); params->meanTreeLength = sum; // for(i=0;i< (params->n1+1) ;i++){ // for(j=0;j< (params->n2+1);j++){ // if(params->rank==0)printf("%.5f ",gsl_matrix_get(params->expAFS,i,j)); // } // if(params->rank==0)printf("\n"); // } // //clean up PetscFree(idx); VecDestroy(&params->y); VecDestroy(&params->x); VecDestroy(&params->v); PetscFree(tmpArray); cs_spfree(spMat); cs_spfree(mt); // cs_spfree(ident); // cs_spfree(eye); cs_spfree(tmpMat); gsl_vector_free(tmpStates); cs_nfree(NN); cs_sfree(S); } //calcLogAFS_IM_allPETSC -- returns the expects log AFS from an IM model; only uses PETSC void calcLogAFS_IM_allPETSC(void * p){ struct clam_lik_params * params = (struct clam_lik_params *) p; PetscInt i,j, N = params->stateSpace->nstates; cs *spMat, *mt, *ident, *eye, *tmpMat ; double timeV, sum, thetaA, theta2, mig1, mig2; PetscInt Na; gsl_vector *tmpStates; css *S ; csn *NN ; PetscInt n,Ntmp ; double *xx; PetscInt iStart,iEnd, *idx; const PetscInt *idx2; PetscScalar *tmpArray; PetscScalar negOne = -1.0; // PetscScalar one = 1.0; const PetscScalar *tmpArrayC; PetscErrorCode ierr; IS perm,iperm; MatFactorInfo info; MFNConvergedReason reason; //initialize some vectors gsl_vector_set_zero(params->rates); MatZeroEntries(params->C); MatZeroEntries(params->C2); MatZeroEntries(params->D); tmpStates = gsl_vector_alloc(N); Ntmp=N; Na=params->Na; //For straight MLE the paramVector takes the form [N2,NA,m1,m2,t] theta2 = gsl_vector_get(params->paramVector,0); thetaA = gsl_vector_get(params->paramVector,1); mig1 = gsl_vector_get(params->paramVector,2); mig2 = gsl_vector_get(params->paramVector,3); timeV = gsl_vector_get(params->paramVector,4); // printf("params-> %f %f %f %f %f\n",theta2,thetaA,mig1,mig2,timeV); // printf("nnz %d nnzA%d \n",params->nnz,params->nnzA); //fill transMat fillPetscTransMats(params->stateSpace, params->top, params->move, &params->nnz, params->dim1, params->dim2, 1, theta2, mig1, mig2, &params->D, &params->C, params->rates); //using CSparse // S = (I-P)^-1 //subtract DTMC mat from identity MatZeroEntries(params->D_copy); MatCopy(params->ident,params->D_copy,DIFFERENT_NONZERO_PATTERN); MatAXPY(params->D_copy,negOne,params->D,DIFFERENT_NONZERO_PATTERN); // MatTranspose(params->D_copy,MAT_REUSE_MATRIX,&params->D); ierr = MatGetOrdering(params->D_copy, MATORDERINGNATURAL, &perm, &iperm); ierr = MatFactorInfoInitialize(&info); ierr = MatGetFactor(params->D_copy,MATSOLVERSUPERLU_DIST,MAT_FACTOR_LU,&params->F); PetscInt icntl_7 = 5; //ierr = MatMumpsSetIcntl(params->F,7,icntl_7); info.fill = 5.0; ierr = MatLUFactorSymbolic(params->F,params->D_copy,perm,iperm,&info); ierr = MatLUFactorNumeric(params->F,params->D_copy,&info); //ierr = MatLUFactor(params->D_copy, perm, iperm, &info); ////Compute Entire Inverse Mat ierr = MatMatSolve(params->F,params->denseIdent,params->denseMat1); //MatView(params->denseMat1,PETSC_VIEWER_STDOUT_SELF); // MatGetOwnershipRange(params->denseMat1,&iStart,&iEnd); // PetscMalloc1(N,&idx); // for(j=0;j<N;j++) idx[j]=j; // for(j=0;j<N;j++){ // //create unit array for solve // VecZeroEntries(params->bInv); // VecZeroEntries(params->xInv); // VecSetValue(params->bInv,j,one,INSERT_VALUES); // VecAssemblyBegin(params->bInv); // VecAssemblyEnd(params->bInv); // // KSPSolve(params->ksp,params->bInv,params->xInv); // VecGetValues(params->x,N,idx,hold); // MatSetValues(params->denseMat1,1,&j,N,idx,hold,INSERT_VALUES); // } // MatAssemblyBegin(params->denseMat1,MAT_FINAL_ASSEMBLY); // MatAssemblyEnd(params->denseMat1,MAT_FINAL_ASSEMBLY); // //temporary clean up // // free(xx); // // cs_spfree(spMat); // // cs_spfree(mt); // // cs_spfree(ident); // // cs_spfree(eye); // // cs_spfree(tmpMat); // // cs_nfree(NN); // // cs_sfree(S); // PetscFree(idx); // KSPDestroy(&params->ksp); // MatView(params->denseMat1,PETSC_VIEWER_STDOUT_WORLD); MatDestroy(&params->F); //broadcast the invMat[0,] as vector to each processor if(params->rank==0){ MatGetRow(params->denseMat1,0,&N,&idx2,&tmpArrayC); for (j = 0; j < N; j++) params->b[j] = tmpArrayC[j]; MatRestoreRow(params->denseMat1,0,&Ntmp,&idx2,&tmpArrayC); //have to use Ntmp here as MatRestoreRow does something funky } MPI_Bcast(params->b,N,MPI_DOUBLE,0,PETSC_COMM_WORLD); //Get Island Time 0-INF Unnormal gsl_matrix_set_zero(params->expAFS); fillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS); // printf("////////////////////Island Time 0 - INF unnormalized\n"); // for(i=0;i< (params->n1+1) ;i++){ // for(j=0;j< (params->n2+1);j++){ // printf("%.5f ",gsl_matrix_get(params->expAFS,i,j)); // } // printf("\n"); // } //Matrix Exponentiation to get state vector at time t //SLEPC Stuff ahead! /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the solver and set various options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Set operator matrix, the function to compute, and other options */ //transpose MatTranspose(params->C,MAT_REUSE_MATRIX,&params->C); ierr = MFNSetOperator(params->mfn,params->C);CHKERRV(ierr); /* Set solver parameters at runtime */ ierr = MFNSetScaleFactor(params->mfn,timeV); CHKERRV(ierr); ierr = MFNSetFromOptions(params->mfn);CHKERRV(ierr); /* set v = e_1 */ ierr = MatGetVecs(params->C,PETSC_NULL,&params->y);CHKERRV(ierr); ierr = MatGetVecs(params->C,&params->v, PETSC_NULL);CHKERRV(ierr); ierr = VecSetValue(params->v,0,1.0,INSERT_VALUES);CHKERRV(ierr); ierr = VecAssemblyBegin(params->v);CHKERRV(ierr); ierr = VecAssemblyEnd(params->v);CHKERRV(ierr); ierr = MFNSolve(params->mfn,params->v,params->y);CHKERRV(ierr); ierr = MFNGetConvergedReason(params->mfn,&reason);CHKERRV(ierr); if (reason!=MFN_CONVERGED_TOL) ierr = 1; CHKERRV(ierr); //retranspose for later use MatTranspose(params->C,MAT_REUSE_MATRIX,&params->C); //state vector at time t stored in y //scatter y and store in expoArray VecScatterCreateToAll(params->y,&params->ctx,&params->v_seq); VecScatterBegin(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(params->ctx,params->y,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecGetArray(params->v_seq,&tmpArray); for (j = 0; j < N; j++){ params->expoArray[j] = tmpArray[j]; //printf("%.5f\n",expoArray[j]); } VecRestoreArray(params->v_seq,&tmpArray); VecScatterDestroy(&params->ctx); VecDestroy(&params->v_seq); VecDuplicate(params->y,&params->x); //VecView(y, PETSC_VIEWER_STDOUT_WORLD); MatMultTranspose(params->denseMat1,params->y,params->x); VecScatterCreateToAll(params->x,&params->ctx,&params->v_seq); VecScatterBegin(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(params->ctx,params->x,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecGetArray(params->v_seq,&tmpArray); for (j = 0; j < N; j++){ params->b[j] = tmpArray[j]; //printf("rank %d expoArray[%d]:%.5f\n",rank,j,expoArray[j]); //printf("rank %d b[%d]:%.5f\n",rank,j,b[j]); } VecRestoreArray(params->v_seq,&tmpArray); VecScatterDestroy(&params->ctx); VecDestroy(&params->v_seq); fillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS2); //now subtract older AFS (t_t - t_INF) from total AFS (t_0 - t_INF) ///////////////// /////// gsl_matrix_sub(params->expAFS,params->expAFS2); ////////////////////// //Final phase, collapse popns, reset rates //now collapse populations //state vector at time t stored in st[] for largerStateSpace; use reverseMap for(i=0;i<N;i++)params->st[i]=0.0; for(i=0;i<N;i++){params->st[params->map[i]]+=params->expoArray[i]; // printf("expoArray[%d]:%f\n",i,expoArray[i]); } for(i=0; i<params->reducedStateSpace->nstates; i++){ VecSetValue(params->ancStateVec,i,params->st[params->reverseMap[i]],INSERT_VALUES ); } //Re-Fill trans mats for Ancestral Params params->nnzA = coalMarkovChainTopologyMatrix_sparse(params->reducedStateSpace,params->topA,params->moveA, params->dim1A, params->dim2A); tmpMat=fillPetscCsparseTransMats(params->reducedStateSpace, params->topA, params->moveA, &params->nnzA, params->dim1A, params->dim2A, thetaA, 0, 0, 0, &params->C2, params->rates); ////////////////////// // // S = (I-P)^-1 // ///////// ////// //add negative ident ident = cs_spalloc(Na,Na,Na,1,1); for(i=0;i<Na;i++) cs_entry(ident,i,i,1); eye = cs_compress(ident); spMat = cs_add(eye,tmpMat,1.0,-1.0); //cs_print_adk(spMat); mt = cs_transpose(spMat,1); //VecView(y,PETSC_VIEWER_STDOUT_WORLD); n = mt->n ; S = cs_sqr (0, mt, 0) ; /* ordering and symbolic analysis */ NN = cs_lu (mt, S, 1e-12) ; /* numeric LU factorization */ xx = cs_malloc (n, sizeof (double)) ; /* get workspace */ MatGetOwnershipRange(params->denseMat2,&iStart,&iEnd); // printf("here\n"); // PetscFree(idx); PetscMalloc1(Na,&idx); for(j=0;j<Na;j++) idx[j]=j; ////Compute Entire Inverse Mat for(j=iStart;j<iEnd;j++){ //create unit array for solve for(i=0; i<Na; i++)params->b[i] = 0.0; params->b[j]=1.0; //factor outside loop leads to ~40x speedup cs_ipvec (NN->pinv, params->b, xx, n) ; /* x = b(p) */ cs_lsolve (NN->L, xx) ; /* x = L\x */ cs_usolve (NN->U, xx) ; /* x = U\x */ cs_ipvec (S->q, xx, params->b, n) ; /* b(q) = x */ // if(!rank)printf("row %d\n",j); MatSetValues(params->denseMat2,1,&j,Na,idx,params->b,INSERT_VALUES); } MatAssemblyBegin(params->denseMat2,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(params->denseMat2,MAT_FINAL_ASSEMBLY); free(xx); MatMultTranspose(params->denseMat2,params->ancStateVec,params->ancResVec); VecScatterCreateToAll(params->ancResVec,&params->ctx,&params->v_seq); VecScatterBegin(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(params->ctx,params->ancResVec,params->v_seq,INSERT_VALUES,SCATTER_FORWARD); VecGetArray(params->v_seq,&tmpArray); for (j = 0; j < Na; j++){ params->expoArray[j] = tmpArray[j]; //printf("%.5f\n",expoArray[j]); } VecRestoreArray(params->v_seq,&tmpArray); VecScatterDestroy(&params->ctx); VecDestroy(&params->v_seq); //get contribution starting at st gsl_matrix_set_zero(params->expAFS2); fillExpectedAFS_unnorm(params->reducedStateSpace, params->expoArray,params->rates,params->expAFS2); // printf("////////////////////--Ancestral bit\n"); // for(i=0;i< (n1+1) ;i++){ // for(j=0;j< (n2+1);j++){ // printf("%.5f ",gsl_matrix_get(expAFS2,i,j)); // } // printf("\n"); // } //if(params->rank==0)printf("////////////////////normalized IM:\n"); gsl_matrix_add(params->expAFS,params->expAFS2); sum = matrixSumDouble(params->expAFS); gsl_matrix_scale(params->expAFS, 1.0 / sum); // for(i=0;i< (params->n1+1) ;i++){ // for(j=0;j< (params->n2+1);j++){ // if(params->rank==0)printf("%.5f ",gsl_matrix_get(params->expAFS,i,j)); // } // if(params->rank==0)printf("\n"); // } // //clean up PetscFree(idx); VecDestroy(&params->y); VecDestroy(&params->x); VecDestroy(&params->v); ierr = ISDestroy(&perm); ierr = ISDestroy(&iperm); PetscFree(tmpArray); cs_spfree(spMat); cs_spfree(mt); cs_spfree(ident); cs_spfree(eye); cs_spfree(tmpMat); gsl_vector_free(tmpStates); cs_nfree(NN); cs_sfree(S); } double calcLikNLOpt(unsigned n, const double *point, double *gradients, void *p){ int i,j; struct clam_lik_params * params = (struct clam_lik_params *) p; double localNNZ = params->nnz; double output = 666.0; double lik=0.0; double x[5]; for(i = 0;i<5;i++) x[i] = point[i]; MPI_Bcast(x,5,MPI_DOUBLE,0,PETSC_COMM_WORLD); for(i = 0;i<5;i++) gsl_vector_set(params->paramVector, i, x[i]); //fill in the expAFS table calcLogAFS_IM(p); params->nnz = localNNZ; //compute lik for(i=0;i<params->obsData->size1;i++){ for(j=0;j<params->obsData->size2;j++){ if (gsl_matrix_get(params->expAFS,i,j) > 0.0) //corners of AFS are zero prob lik += gsl_matrix_get(params->obsData,i,j) * (log(gsl_matrix_get(params->expAFS,i,j))); } } output = -1.0* lik; MPI_Bcast(&output,1,MPI_DOUBLE,0,PETSC_COMM_WORLD); if(params->rank == 0 && vbse){ for(i = 0;i<5;i++) printf("x[%d]: %lf\t",i,x[i]); printf("lik: %lf\n",lik); } params->fEvals += 1; // gsl_matrix_prettyPrint(params->expAFS); return(output); } double calcLikNLOpt_gradients(unsigned n, const double *point, double *gradients, void *p){ int i,j; //struct clam_lik_params * params = (struct clam_lik_params *) p; //double localNNZ = params->nnz; double output = 666.0; double lik=0.0; double newF; double x[5]; double temp[5]; double epsilon=1e-5; for(i = 0;i<5;i++) x[i] = point[i]; MPI_Bcast(x,5,MPI_DOUBLE,0,PETSC_COMM_WORLD); lik = calcLikNLOpt(n, point, NULL, p); if (gradients != NULL){ for(i=0; i<n ;i++){ for( j=0; j< n; j++) temp[j] = x[j]; temp[i] += epsilon; newF = calcLikNLOpt(n,temp,NULL,p); gradients[i] = (newF - lik)/epsilon; } } output = lik; MPI_Bcast(&output,1,MPI_DOUBLE,0,PETSC_COMM_WORLD); // gsl_matrix_prettyPrint(params->expAFS); return(output); } //maximizeLik-- maximizes the logLikFunction function using constraints via // nlOpt library void maximizeLikNLOpt(double *lik, void *p, double *mle){ //struct clam_lik_params * params = (struct clam_lik_params *) p; int np = 5; int err; //double x[5] = {1.0,1.0,1.0,1.0,1.5}; double minimum=666.6; nlopt_opt opt; opt = nlopt_create(NLOPT_LD_LBFGS, np); //define constraints nlopt_set_lower_bounds(opt, lowerBounds); nlopt_set_upper_bounds(opt, upperBounds); nlopt_set_min_objective(opt, calcLikNLOpt_gradients, (void *) p); nlopt_set_xtol_rel(opt, 1e-6); //set the seed for deterministic sequence in COBYLA alg //nlopt_srand(1232333); err = nlopt_optimize(opt, mle, &minimum); if (err < 0) { fprintf(stderr,"nlopt failed with code %d!\n",err); } // MPI_Barrier(MPI_COMM_WORLD); *lik=minimum; nlopt_destroy(opt); } //maximizeLikNLOpt_twoStage-- begins with coarse global, then goes local void maximizeLikNLOpt_twoStage(double *lik, void *p, double *mle){ //struct clam_lik_params * params = (struct clam_lik_params *) p; int np = 5; int err; //double x[5] = {1.0,1.0,1.0,1.0,1.5}; double minimum=666.6; nlopt_opt opt; opt = nlopt_create(NLOPT_GN_DIRECT_L_RAND, np); nlopt_set_lower_bounds(opt, lowerBounds); nlopt_set_upper_bounds(opt, upperBounds); nlopt_set_min_objective(opt, calcLikNLOpt_gradients, (void *) p); //nlopt_set_xtol_rel(opt, 0.25); //set the seed for deterministic sequence in COBYLA alg //nlopt_srand(1232333); err = nlopt_optimize(opt, mle, &minimum); if (err < 0) { fprintf(stderr,"nlopt failed with code %d!\n",err); } // MPI_Barrier(MPI_COMM_WORLD); *lik=minimum; nlopt_destroy(opt); } //maximizeLikNLOpt_MLSL-- multi-level restarts void maximizeLikNLOpt_MLSL(double *lik, void *p, double *mle){ int np = 5; int err; //double x[5] = {1.0,1.0,1.0,1.0,1.5}; double minimum=666.6; nlopt_opt opt, l_opt; opt = nlopt_create(NLOPT_G_MLSL, np); nlopt_set_lower_bounds(opt, lowerBounds); nlopt_set_upper_bounds(opt, upperBounds); nlopt_set_min_objective(opt, calcLikNLOpt_gradients, (void *) p); l_opt = nlopt_create(NLOPT_LD_LBFGS, np); nlopt_set_lower_bounds(l_opt, lowerBounds); nlopt_set_upper_bounds(l_opt, upperBounds); nlopt_set_min_objective(l_opt, calcLikNLOpt_gradients, (void *) p); //define constraints nlopt_set_local_optimizer(opt, l_opt); //nlopt_set_xtol_rel(opt, 0.25); //set the seed for deterministic sequence in COBYLA alg //nlopt_srand(1232333); err = nlopt_optimize(opt, mle, &minimum); if (err < 0) { fprintf(stderr,"nlopt failed with code %d!\n",err); } // MPI_Barrier(MPI_COMM_WORLD); *lik=minimum; nlopt_destroy(l_opt); nlopt_destroy(opt); } ///////////////// Hessian stuff /////////////////// double hessianMatrix_element(double lik, double *mle, int i, int j, double hi, double hj, void *p){ //struct clam_lik_params * params = (struct clam_lik_params *) p; double Pi0, Pj0,output,fpp,fpm,fmp,fmm; Pi0 = mle[i]; Pj0 = mle[j]; //printf("mle: %f\n",lik); if(i==j){ mle[i] = Pi0 + hi; fpp = calcLikNLOpt(5,mle,NULL,p); mle[i] = Pj0 - hi; fmm = calcLikNLOpt(5,mle,NULL,p); output = ((fpp - lik) + (fmm - lik))/(hi*hi); } else{ // f(xi + hi, xj + h) mle[i] = Pi0 + hi; mle[j] = Pj0 + hj; fpp = calcLikNLOpt(5,mle,NULL,p); // f(xi + hi, xj - hj) mle[i] = Pi0 + hi; mle[j] = Pj0 - hj; fpm = calcLikNLOpt(5,mle,NULL,p); // f(xi - hi, xj + hj) mle[i] = Pi0 - hi; mle[j] = Pj0 + hj; fmp = calcLikNLOpt(5,mle,NULL,p); // f(xi - hi, xj - hj) mle[i] = Pi0 - hi; mle[j] = Pj0 - hj; fmm = calcLikNLOpt(5,mle,NULL,p); output = (fpp - fpm - fmp + fmm)/(4 * hi * hj); } mle[i]=Pi0; mle[j]=Pj0; return output; } gsl_matrix *hessian(double *mle, double lik, void *p){ int i, j; double eps; gsl_matrix *H; H = gsl_matrix_alloc(5,5); eps = 0.01; for(i=0;i<5;i++){ for (j=i;j<5;j++){ gsl_matrix_set(H,i,j,hessianMatrix_element(lik, mle, i, j, eps, eps, p)); gsl_matrix_set(H,j,i,gsl_matrix_get(H,i,j)); } } return(H); } gsl_matrix *getFisherInfoMatrix(double *mle, double lik, void *p){ gsl_matrix *H; gsl_matrix *fi; gsl_permutation *perm = gsl_permutation_alloc(5); int s; H = hessian(mle,lik,p); //gsl_matrix_prettyPrint(H);printf("\n"); fi = gsl_matrix_alloc(5,5); gsl_matrix_scale(H,-1.0); gsl_linalg_LU_decomp (H, perm, &s); gsl_linalg_LU_invert (H, perm, fi); //gsl_matrix_prettyPrint(fi);printf("\n"); return(fi); } gsl_matrix *getGodambeInfoMatrix(double *mle, double lik, void *p){ gsl_matrix *H; gsl_matrix *J,*Jtemp, *Jinv, *origData, *boot; gsl_vector *cU, *grad_temp; struct clam_lik_params * params = (struct clam_lik_params *) p; gsl_permutation *perm = gsl_permutation_alloc(5); int s,i, nBoot; origData = params->obsData; nBoot = 100; H = hessian(mle,lik,p); gsl_matrix_scale(H,-1.0); //gsl_matrix_prettyPrint(H);printf("\n"); J = gsl_matrix_alloc(5,5); Jinv = gsl_matrix_alloc(5,5); Jtemp = gsl_matrix_alloc(5,5); boot = gsl_matrix_alloc(origData->size1,origData->size2); gsl_matrix_set_zero(J); gsl_matrix_set_zero(Jinv); gsl_matrix_set_zero(Jtemp); cU = gsl_vector_alloc(5); gsl_vector_set_zero(cU); //do bootstraps, estimate J for(i=0;i<nBoot;i++){ gsl_matrix_bootstrap(origData, boot, params->rng); params->obsData = boot; grad_temp = getGradient(mle,p); gsl_vector_outer_product(grad_temp,grad_temp,Jtemp); gsl_matrix_add(J,Jtemp); gsl_vector_add(cU,grad_temp); //gsl_matrix_prettyPrint(Jtemp); gsl_vector_free(grad_temp); } gsl_vector_scale(cU,1.0/(float)nBoot); gsl_matrix_scale(J,1.0/(float)nBoot); //printf("cU:\n"); //gsl_vector_fprintf(stdout,cU,"%f"); //printf("J:\n"); //gsl_matrix_prettyPrint(J);printf("\n"); //G = H*J^-1*H gsl_linalg_LU_decomp (J, perm, &s); gsl_linalg_LU_invert (J, perm, Jinv); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, H, Jinv, 0.0, Jtemp); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Jtemp, H, 0.0, J); //printf("godambe:\n"); //gsl_matrix_prettyPrint(J);printf("\n"); //need to invert this to get the Godambe information matrix gsl_linalg_LU_decomp (J, perm, &s); gsl_linalg_LU_invert (J, perm, Jinv); return(Jinv); } gsl_vector *getGradient(double *mle, void *p){ int i, j; double eps, epsVals[5], paramTemp[5], fp, fm; gsl_vector *gradient; gradient = gsl_vector_alloc(5); eps = 0.01; for(i=0;i<5;i++){ if( mle[i] != 0){ epsVals[i] = mle[i] * eps; //printf("eps[%d]=%f\n",i,epsVals[i]); } else{ epsVals[i] = eps; } paramTemp[i] = mle[i]; } for(i=0;i<5;i++){ for(j=0;j<5;j++) paramTemp[j] = mle[j]; if( mle[i] != 0){ paramTemp[i] = mle[i] + epsVals[i]; fp = calcLikNLOpt(5,paramTemp,NULL,p); paramTemp[i] = mle[i] - epsVals[i]; fm = calcLikNLOpt(5,paramTemp,NULL,p); gsl_vector_set(gradient,i,(fp-fm)/(2*epsVals[i])); } else{ paramTemp[i] = mle[i] + epsVals[i]; fp = calcLikNLOpt(5,paramTemp,NULL,p); paramTemp[i] = mle[i]; fm = calcLikNLOpt(5,paramTemp,NULL,p); gsl_vector_set(gradient,i,(fp-fm)/epsVals[i]); } } return(gradient); }
{ "alphanum_fraction": 0.6512323944, "avg_line_length": 31.086786552, "ext": "c", "hexsha": "3e3e61b526d4f215854e1fc5730e6621426051b1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_path": "AFS_ctmc_petsc.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_path": "AFS_ctmc_petsc.c", "max_line_length": 150, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_path": "AFS_ctmc_petsc.c", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "num_tokens": 13965, "size": 39760 }
#include <gsl/gsl_vector.h> #include <stdio.h> #include "vector.h" #include "api.h" static void ke_vector_alloc(sml_t* sml) { int n = sml_pop_int(sml); gsl_vector * v = gsl_vector_alloc(n); sml_mem_inc(sml); sml_push_vector(sml, v) } static void ke_vector_int_alloc(sml_t* sml) { int n = sml_pop_int(sml); gsl_vector_int * v = gsl_vector_int_alloc(n); sml_mem_inc(sml); sml_push_vector_int(sml, v); } static void ke_vector_free(sml_t* sml) { token_t * tokp = sml_pop_token(sml); void * v = sml_get_ptr(tokp); sml_free_ptr(sml, v); sml_set_ptr_null(sml,tokp); } static void ke_vector_int_free(sml_t* sml) { token_t * tokp = sml_pop_token(sml); void * v = sml_get_ptr(tokp); sml_free_ptr(sml, v); sml_set_ptr_null(sml,tokp); } void ke_vector_get(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); int i = sml_pop_int(sml); double r = gsl_vector_get(v, i); sml_push_real(sml, r); } void ke_vector_int_get(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int idx = sml_pop_int(sml); int i = gsl_vector_int_get(v, idx); sml_push_int(sml, i); } void ke_vector_prop_set(sml_t* sml) { double x = sml_pop_real(sml); gsl_vector * v = sml_pop_vector(sml); int i = sml_pop_int(sml); gsl_vector_set(v, i, x); } void ke_vector_int_set(sml_t* sml) { int x = sml_pop_int(sml); int i = sml_pop_int(sml); gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_set(v, i, x); } void ke_vector_prop_int_set(sml_t* sml) { int x = sml_pop_int(sml); gsl_vector_int * v = sml_pop_vector_int(sml); int i = sml_pop_int(sml); gsl_vector_int_set(v,i,x); } void ke_vector_set(sml_t* sml) { double x = sml_pop_real(sml); int i = sml_pop_int(sml); gsl_vector * v = sml_pop_vector(sml); gsl_vector_set(v,i,x); } void ke_vector_put(sml_t* sml) { int top = sml_get_top(sml); int n = sml_get_args(sml); gsl_vector * v = sml_peek_vector(sml, (top - n)); for (size_t i = 0; i < n - 1; ++i) { if (i == v->size) break; double x = sml_peek_real(sml, (top - n + i + 1)); gsl_vector_set(v, i, x); } top = top - n; sml_set_top(sml, top); } static void ke_vector_int_put(sml_t* sml) { int top = sml_get_top(sml); int n = sml_get_args(sml); gsl_vector_int * v = sml_peek_vector_int(sml, (top - n)); for (size_t i = 0; i < n - 1; ++i) { if (i == v->size) break; int x = sml_peek_int(sml, (top - n + i + 1)); gsl_vector_int_set(v, i, x); } top = top - n; sml_set_top(sml, top); } static void ke_vector_set_all(sml_t* sml) { double x = sml_pop_real(sml); gsl_vector * v = sml_pop_vector(sml); gsl_vector_set_all(v,x); } static void ke_vector_int_set_all(sml_t* sml) { int x = sml_pop_int(sml); gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_set_all(v, x); } static void ke_vector_set_zero(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); gsl_vector_set_zero(v); } static void ke_vector_int_set_zero(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_set_zero(v); } static void ke_vector_set_basis(sml_t* sml) { int i = sml_pop_int(sml); gsl_vector * v = sml_pop_vector(sml); gsl_vector_set_basis(v, i); } static void ke_vector_int_set_basis(sml_t* sml) { int i = sml_pop_int(sml); gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_set_basis(v, i); } static void ke_vector_add(sml_t* sml) { gsl_vector * b = sml_pop_vector(sml); gsl_vector * a = sml_pop_vector(sml); gsl_vector_add(a,b); } static void ke_vector_int_add(sml_t* sml) { gsl_vector_int * b = sml_pop_vector_int(sml); gsl_vector_int * a = sml_pop_vector_int(sml); gsl_vector_int_add(a, b); } static void ke_vector_sub(sml_t* sml) { gsl_vector * b = sml_pop_vector(sml); gsl_vector * a = sml_pop_vector(sml); gsl_vector_sub(a, b); } static void ke_vector_int_sub(sml_t* sml) { gsl_vector_int * b = sml_pop_vector_int(sml); gsl_vector_int * a = sml_pop_vector_int(sml); gsl_vector_int_sub(a, b); } static void ke_vector_mul(sml_t* sml) { gsl_vector * b = sml_pop_vector(sml); gsl_vector * a = sml_pop_vector(sml); gsl_vector_mul(a, b); } static void ke_vector_int_mul(sml_t* sml) { gsl_vector_int * b = sml_pop_vector_int(sml); gsl_vector_int * a = sml_pop_vector_int(sml); gsl_vector_int_mul(a, b); } static void ke_vector_div(sml_t* sml) { gsl_vector * b = sml_pop_vector(sml); gsl_vector * a = sml_pop_vector(sml); gsl_vector_div(a, b); } static void ke_vector_int_div(sml_t* sml) { gsl_vector_int * b = sml_pop_vector_int(sml); gsl_vector_int * a = sml_pop_vector_int(sml); gsl_vector_int_div(a, b); } static void ke_vector_scale(sml_t* sml) { double x = sml_pop_real(sml); gsl_vector * v = sml_pop_vector(sml); gsl_vector_scale(v,x); } static void ke_vector_int_scale(sml_t* sml) { double x = sml_pop_real(sml); gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_scale(v, x); } static void ke_vector_add_constant(sml_t* sml) { double x = sml_pop_real(sml); gsl_vector * a = sml_pop_vector(sml); gsl_vector_add_constant(a,x); } static void ke_vector_int_add_constant(sml_t* sml) { double x = sml_pop_real(sml); gsl_vector_int * a = sml_pop_vector_int(sml); gsl_vector_int_add_constant(a, x); } static void ke_vector_reverse(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); gsl_vector_reverse(v); } static void ke_vector_int_reverse(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_reverse(v); } static void ke_vector_swap_elements(sml_t* sml) { int j = sml_pop_int(sml); int i = sml_pop_int(sml); gsl_vector * v = sml_pop_vector(sml); gsl_vector_swap_elements(v,i,j); } static void ke_vector_int_swap_elements(sml_t* sml) { int j = sml_pop_int(sml); int i = sml_pop_int(sml); gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_swap_elements(v, i, j); } static void ke_vector_memcpy(sml_t* sml) { gsl_vector * src = sml_pop_vector(sml); gsl_vector * dest = sml_pop_vector(sml); gsl_vector_memcpy(dest, src); } static void ke_vector_int_memcpy(sml_t* sml) { gsl_vector_int * src = sml_pop_vector_int(sml); gsl_vector_int * dest = sml_pop_vector_int(sml); gsl_vector_int_memcpy(dest, src); } static void ke_vector_swap(sml_t* sml) { gsl_vector * w = sml_pop_vector(sml); gsl_vector * v = sml_pop_vector(sml); gsl_vector_swap(v,w); } static void ke_vector_int_swap(sml_t* sml) { gsl_vector_int * w = sml_pop_vector_int(sml); gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int_swap(v, w); } static void ke_vector_min(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); double r = gsl_vector_min(v); sml_push_real(sml,r); } static void ke_vector_int_min(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int i = gsl_vector_int_min(v); sml_push_int(sml, i); } static void ke_vector_max(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); double r = gsl_vector_max(v); sml_push_real(sml, r); } static void ke_vector_int_max(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int i = gsl_vector_int_max(v); sml_push_int(sml, i); } static void ke_vector_isnull(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); int i = gsl_vector_isnull(v); sml_push_int(sml, i); } static void ke_vector_int_isnull(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int i = gsl_vector_int_isnull(v); sml_push_int(sml, i); } static void ke_vector_ispos(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); int i = gsl_vector_ispos(v); sml_push_int(sml, i); } static void ke_vector_int_ispos(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int i = gsl_vector_int_ispos(v); sml_push_int(sml, i); } static void ke_vector_isneg(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); int i = gsl_vector_isneg(v); sml_push_int(sml, i); } static void ke_vector_int_isneg(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int i = gsl_vector_int_isneg(v); sml_push_int(sml, i); } static void ke_vector_isnonneg(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); int i = gsl_vector_isnonneg(v); sml_push_int(sml, i); } static void ke_vector_int_isnonneg(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); int i = gsl_vector_int_isnonneg(v); sml_push_int(sml, i); } static void ke_vector_equal(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); gsl_vector * u = sml_pop_vector(sml); int i = gsl_vector_equal(u,v); sml_push_int(sml, i); } static void ke_vector_int_equal(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); gsl_vector_int * u = sml_pop_vector_int(sml); int i = gsl_vector_int_equal(u, v); sml_push_int(sml, i); } static void ke_vector_fscanf(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "r"); gsl_vector_fscanf(f, v); fclose(f); } static void ke_vector_int_fscanf(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "r"); gsl_vector_int_fscanf(f, v); fclose(f); } static void ke_vector_fprintf(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "w"); gsl_vector_fprintf(f, v,"%5g"); fclose(f); } static void ke_vector_int_fprintf(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "w"); gsl_vector_int_fprintf(f, v, "%5g"); fclose(f); } static void ke_vector_fread(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "r"); gsl_vector_fread(f, v); fclose(f); } static void ke_vector_int_fread(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "r"); gsl_vector_int_fread(f, v); fclose(f); } static void ke_vector_fwrite(sml_t* sml) { gsl_vector * v = sml_pop_vector(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "w"); gsl_vector_fwrite(f, v); fclose(f); } static void ke_vector_int_fwrite(sml_t* sml) { gsl_vector_int * v = sml_pop_vector_int(sml); char * filename = sml_pop_str(sml); FILE * f = fopen(filename, "w"); gsl_vector_int_fwrite(f, v); fclose(f); } void ke_vector_hash(sml_t* sml) { ke_hash_add(sml, (fncp)&ke_vector_alloc, VECTOR); ke_hash_add(sml, (fncp)&ke_vector_alloc, VECTOR_ALLOC); ke_hash_add(sml, (fncp)&ke_vector_get, VECTOR_GET); ke_hash_add(sml, (fncp)&ke_vector_set, VECTOR_SET); ke_hash_add(sml, (fncp)&ke_vector_get, VECTOR_SGET); ke_hash_add(sml, (fncp)&ke_vector_set, VECTOR_SSET); ke_hash_add(sml, (fncp)&ke_vector_put, VECTOR_PUT); ke_hash_add(sml, (fncp)&ke_vector_free, VECTOR_FREE); ke_hash_add(sml, (fncp)&ke_vector_set_all, VECTOR_SET_ALL); ke_hash_add(sml, (fncp)&ke_vector_set_zero, VECTOR_SET_ZERO); ke_hash_add(sml, (fncp)&ke_vector_set_basis, VECTOR_SET_BASIS); ke_hash_add(sml, (fncp)&ke_vector_add, VECTOR_ADD); ke_hash_add(sml, (fncp)&ke_vector_sub, VECTOR_SUB); ke_hash_add(sml, (fncp)&ke_vector_mul, VECTOR_MUL); ke_hash_add(sml, (fncp)&ke_vector_div, VECTOR_DIV); ke_hash_add(sml, (fncp)&ke_vector_scale, VECTOR_SCALE); ke_hash_add(sml, (fncp)&ke_vector_add_constant, VECTOR_ADD_CONSTANT); ke_hash_add(sml, (fncp)&ke_vector_reverse, VECTOR_REVERSE); ke_hash_add(sml, (fncp)&ke_vector_swap_elements, VECTOR_SWAP_ELEMENTS); ke_hash_add(sml, (fncp)&ke_vector_memcpy, VECTOR_MEMCPY); ke_hash_add(sml, (fncp)&ke_vector_swap, VECTOR_SWAP); ke_hash_add(sml, (fncp)&ke_vector_min, VECTOR_MIN); ke_hash_add(sml, (fncp)&ke_vector_max, VECTOR_MAX); ke_hash_add(sml, (fncp)&ke_vector_isnull, VECTOR_ISNULL); ke_hash_add(sml, (fncp)&ke_vector_ispos, VECTOR_ISPOS); ke_hash_add(sml, (fncp)&ke_vector_isneg, VECTOR_ISNEG); ke_hash_add(sml, (fncp)&ke_vector_isnonneg, VECTOR_ISNONNEG); ke_hash_add(sml, (fncp)&ke_vector_equal, VECTOR_EQUAL); ke_hash_add(sml, (fncp)&ke_vector_fscanf, VECTOR_FSCANF); ke_hash_add(sml, (fncp)&ke_vector_fscanf, VECTOR_SCAN); ke_hash_add(sml, (fncp)&ke_vector_fprintf, VECTOR_FPRINTF); ke_hash_add(sml, (fncp)&ke_vector_fprintf, VECTOR_PRINT); ke_hash_add(sml, (fncp)&ke_vector_fread, VECTOR_FREAD); ke_hash_add(sml, (fncp)&ke_vector_fread, VECTOR_READ); ke_hash_add(sml, (fncp)&ke_vector_fwrite, VECTOR_FWRITE); ke_hash_add(sml, (fncp)&ke_vector_fwrite, VECTOR_WRITE); ke_hash_add(sml, (fncp)&ke_vector_int_alloc, VECTOR_INT); ke_hash_add(sml, (fncp)&ke_vector_int_alloc, VECTOR_INT_ALLOC); ke_hash_add(sml, (fncp)&ke_vector_int_get, VECTOR_INT_GET); ke_hash_add(sml, (fncp)&ke_vector_int_set, VECTOR_INT_SET); ke_hash_add(sml, (fncp)&ke_vector_int_put, VECTOR_INT_PUT); ke_hash_add(sml, (fncp)&ke_vector_int_free, VECTOR_INT_FREE); ke_hash_add(sml, (fncp)&ke_vector_int_set_all, VECTOR_INT_SET_ALL); ke_hash_add(sml, (fncp)&ke_vector_int_set_zero, VECTOR_INT_SET_ZERO); ke_hash_add(sml, (fncp)&ke_vector_int_set_basis, VECTOR_INT_SET_BASIS); ke_hash_add(sml, (fncp)&ke_vector_int_add, VECTOR_INT_ADD); ke_hash_add(sml, (fncp)&ke_vector_int_sub, VECTOR_INT_SUB); ke_hash_add(sml, (fncp)&ke_vector_int_mul, VECTOR_INT_MUL); ke_hash_add(sml, (fncp)&ke_vector_int_div, VECTOR_INT_DIV); ke_hash_add(sml, (fncp)&ke_vector_int_scale, VECTOR_INT_SCALE); ke_hash_add(sml, (fncp)&ke_vector_int_add_constant, VECTOR_INT_ADD_CONSTANT); ke_hash_add(sml, (fncp)&ke_vector_int_reverse, VECTOR_INT_REVERSE); ke_hash_add(sml, (fncp)&ke_vector_int_swap_elements, VECTOR_INT_SWAP_ELEMENTS); ke_hash_add(sml, (fncp)&ke_vector_int_memcpy, VECTOR_INT_MEMCPY); ke_hash_add(sml, (fncp)&ke_vector_int_swap, VECTOR_INT_SWAP); ke_hash_add(sml, (fncp)&ke_vector_int_min, VECTOR_INT_MIN); ke_hash_add(sml, (fncp)&ke_vector_int_max, VECTOR_INT_MAX); ke_hash_add(sml, (fncp)&ke_vector_int_isnull, VECTOR_INT_ISNULL); ke_hash_add(sml, (fncp)&ke_vector_int_ispos, VECTOR_INT_ISPOS); ke_hash_add(sml, (fncp)&ke_vector_int_isneg, VECTOR_INT_ISNEG); ke_hash_add(sml, (fncp)&ke_vector_int_isnonneg, VECTOR_INT_ISNONNEG); ke_hash_add(sml, (fncp)&ke_vector_int_equal, VECTOR_INT_EQUAL); ke_hash_add(sml, (fncp)&ke_vector_int_fscanf, VECTOR_INT_FSCANF); ke_hash_add(sml, (fncp)&ke_vector_int_fscanf, VECTOR_INT_SCAN); ke_hash_add(sml, (fncp)&ke_vector_int_fprintf, VECTOR_INT_FPRINTF); ke_hash_add(sml, (fncp)&ke_vector_int_fprintf, VECTOR_INT_PRINT); ke_hash_add(sml, (fncp)&ke_vector_int_fread, VECTOR_INT_FREAD); ke_hash_add(sml, (fncp)&ke_vector_int_fread, VECTOR_INT_READ); ke_hash_add(sml, (fncp)&ke_vector_int_fwrite, VECTOR_INT_FWRITE); ke_hash_add(sml, (fncp)&ke_vector_int_fwrite, VECTOR_INT_WRITE); } void ke_vector_print(sml_t* sml, token_t *k) { printf("Vector: %s\n", k->name); for(size_t i = 0; i < k->obj.vector->size; i++) { printf("%d : v:%g\n", (int)i, gsl_vector_get(k->obj.vector, i)); } } void ke_vector_freemem(sml_t* sml,token_t *e) { if (e->obj.vector && e->vtype == KEV_VEC) { gsl_vector_free(e->obj.vector); ke_dec_memory(sml); e->obj.vector = NULL; } } void ke_vector_int_print(sml_t* sml,token_t *k) { printf("Vector: %s\n", k->name); for (size_t i = 0; i < k->obj.vector_int->size; i++) { printf("%d : v:%d\n", (int)i, gsl_vector_int_get(k->obj.vector_int, i)); } } void ke_vector_int_freemem(sml_t* sml,token_t *e) { if (e->obj.vector_int && e->vtype == KEV_VEC_INT) { gsl_vector_int_free(e->obj.vector_int); ke_dec_memory(sml); e->obj.vector_int = NULL; } }
{ "alphanum_fraction": 0.7265905593, "avg_line_length": 30.6326129666, "ext": "c", "hexsha": "d800b64778fb64bf8d6fe69fa72c43f3088b27fc", "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": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vinej/sml", "max_forks_repo_path": "vector.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "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": "vinej/sml", "max_issues_repo_path": "vector.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vinej/sml", "max_stars_repo_path": "vector.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5165, "size": 15592 }
// Copyright 2018, Kevin Lang, Oath Research /* gcc -Wall -pedantic -Iinclude -Llib -o multi_reading_linsolve multi_reading_linsolve.c -lgsl -lgslcblas */ #include <stdio.h> #include <assert.h> #include <gsl/gsl_linalg.h> /*****************************************************************************/ #ifdef EXAMPLE_FOR_INTUITION #define NUMEQNS 5 #define NUMVARS 4 double a_data[] = { 0.18, 0.60, 0.57, 0.96, 0.41, 0.24, 0.99, 0.58, 0.14, 0.30, 0.97, 0.66, 0.51, 0.13, 0.19, 0.85, 0.65, 0.43, 1.16, 1.51 }; double b_data[] = { 1.0, 2.0, 3.0, 4.0, 7.0 }; #endif /*****************************************************************************/ void read_a_data (int num_eqns, int num_vars, double * a_data) { int i, j, nxt; double tmp; nxt = 0; for (i = 0; i < num_eqns; i++) { for (j = 0; j < num_vars; j++) { int got = scanf ("%lf", &tmp); assert (got == 1); a_data[nxt++] = tmp; } } assert (nxt == num_eqns * num_vars); } /*****************************************************************************/ void read_b_data (int num_eqns, double * b_data) { int i, nxt; double tmp; nxt = 0; for (i = 0; i < num_eqns; i++) { int got = scanf ("%lf", &tmp); assert (got == 1); b_data[nxt++] = tmp; } assert (nxt == num_eqns); } /*****************************************************************************/ int main (int argc, char ** argv) { if (argc != 3) { fprintf (stderr, "Usage: %s num_eqns num_vars < data_file\n", argv[0]); fprintf (stderr, " The data_file contains a matrix followed by a target vector.\n"); fprintf (stderr, " The matrix should be in equation major order.\n"); fprintf (stderr, " This version solves multiple problems with matching matrix dimensions.\n"); fprintf (stderr, " Each problem should be preceding by a '1'.\n"); fprintf (stderr, " The last problem should be followed by a '0'.\n"); return (-1); } int num_eqns = atoi(argv[1]); int num_vars = atoi(argv[2]); double * a_data = (double *) malloc (num_eqns * num_vars * sizeof(double)); assert (a_data != NULL); double * b_data = (double *) malloc (num_eqns * sizeof(double)); assert (b_data != NULL); while (1) { int keep_going = 0; int got = scanf ("%d", &keep_going); assert (got == 1); if (keep_going == 0) return 0; read_a_data (num_eqns, num_vars, a_data); read_b_data (num_eqns, b_data); gsl_matrix_view m = gsl_matrix_view_array (a_data, num_eqns, num_vars); gsl_vector *x = gsl_vector_alloc (num_vars); gsl_vector *tau = gsl_vector_alloc (num_vars); gsl_vector *residual = gsl_vector_alloc (num_eqns); gsl_vector_view b = gsl_vector_view_array (b_data, num_eqns); int s; s = gsl_linalg_QR_decomp (&m.matrix, tau); s = gsl_linalg_QR_lssolve (&m.matrix, tau, &b.vector, x, residual); gsl_vector_fprintf (stdout, x, "%.15g"); fflush (stdout); gsl_vector_free (x); gsl_vector_free (tau); gsl_vector_free (residual); } return 0; } // printf ("residual = \n"); gsl_vector_fprintf (stdout, residual, "%g"); // printf("solver got A: %d %d %.19g\n", i, j, tmp); // printf("solver got B: %d %.19g\n", i, tmp);
{ "alphanum_fraction": 0.5445424141, "avg_line_length": 28.3534482759, "ext": "c", "hexsha": "41e8ede97c4cbb876127e4ea988b820c6cedc502", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-05T09:23:02.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-06T19:57:10.000Z", "max_forks_repo_head_hexsha": "fda96c0ea51d0972a8ca081c24e04e036945ecbb", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "kevinjlang/cpc", "max_forks_repo_path": "precomputation/multi_reading_linsolve.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "fda96c0ea51d0972a8ca081c24e04e036945ecbb", "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": "kevinjlang/cpc", "max_issues_repo_path": "precomputation/multi_reading_linsolve.c", "max_line_length": 103, "max_stars_count": 10, "max_stars_repo_head_hexsha": "fda96c0ea51d0972a8ca081c24e04e036945ecbb", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "kevinjlang/cpc", "max_stars_repo_path": "precomputation/multi_reading_linsolve.c", "max_stars_repo_stars_event_max_datetime": "2018-10-16T21:42:20.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-21T08:55:11.000Z", "num_tokens": 1007, "size": 3289 }
//STARTWHOLE static char help[] = "Solve a 4x4 linear system using KSP.\n"; #include <petsc.h> int main(int argc,char **args) { PetscErrorCode ierr; Vec x, b; Mat A; KSP ksp; PetscInt i, j[4] = {0, 1, 2, 3}; // j = column index PetscReal ab[4] = {7.0, 1.0, 1.0, 3.0}, // vector entries aA[4][4] = {{ 1.0, 2.0, 3.0, 0.0}, // matrix entries { 2.0, 1.0, -2.0, -3.0}, {-1.0, 1.0, 1.0, 0.0}, { 0.0, 1.0, 1.0, -1.0}}; ierr = PetscInitialize(&argc,&args,NULL,help); if (ierr) return ierr; ierr = VecCreate(PETSC_COMM_WORLD,&b); CHKERRQ(ierr); ierr = VecSetSizes(b,PETSC_DECIDE,4); CHKERRQ(ierr); ierr = VecSetFromOptions(b); CHKERRQ(ierr); ierr = VecSetValues(b,4,j,ab,INSERT_VALUES); CHKERRQ(ierr); ierr = VecAssemblyBegin(b); CHKERRQ(ierr); ierr = VecAssemblyEnd(b); CHKERRQ(ierr); ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr); ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,4,4); CHKERRQ(ierr); ierr = MatSetFromOptions(A); CHKERRQ(ierr); ierr = MatSetUp(A); CHKERRQ(ierr); for (i=0; i<4; i++) { // set entries one row at a time ierr = MatSetValues(A,1,&i,4,j,aA[i],INSERT_VALUES); CHKERRQ(ierr); } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr); ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr); ierr = VecDuplicate(b,&x); CHKERRQ(ierr); ierr = KSPSolve(ksp,b,x); CHKERRQ(ierr); ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); KSPDestroy(&ksp); MatDestroy(&A); VecDestroy(&x); VecDestroy(&b); return PetscFinalize(); } //ENDWHOLE
{ "alphanum_fraction": 0.5859007833, "avg_line_length": 38.3, "ext": "c", "hexsha": "10d8f2d7455bf859fbf725bbd5348b64cf575c74", "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/ch2/vecmatksp.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/ch2/vecmatksp.c", "max_line_length": 75, "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/ch2/vecmatksp.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": 643, "size": 1915 }
#ifdef USE_MKL #include <mkl_lapacke.h> #else #include <lapacke.h> #endif // contains all calls to C-interface LAPACK functions (LAPACKE) // https://www.netlib.org/lapack/lapacke.html // returns the solution, x, to a real system of linear equations // A * x = b, // solution is returned in b, i.e. b --> x, for return value 0 int specex_posv(int n, const double *A, const double *b){ return LAPACKE_dposv(LAPACK_COL_MAJOR, 'L', n, 1, A, n, b, n); } // invert matrix A in place; A := inv(A) // http://www.netlib.org/lapack/explore-html/d8/d63/dpotri_8f_source.html int specex_potri(int n, const double *A){ return LAPACKE_dpotri(LAPACK_COL_MAJOR, 'L', n, A, n); }
{ "alphanum_fraction": 0.691740413, "avg_line_length": 28.25, "ext": "c", "hexsha": "fbbdc947561fcadb6e1ddc03f6be29af14ec9904", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-07-18T16:32:34.000Z", "max_forks_repo_forks_event_min_datetime": "2016-06-16T17:43:38.000Z", "max_forks_repo_head_hexsha": "c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "tskisner/specex", "max_forks_repo_path": "src/specex_lapack.c", "max_issues_count": 39, "max_issues_repo_head_hexsha": "c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2", "max_issues_repo_issues_event_max_datetime": "2022-01-07T00:11:25.000Z", "max_issues_repo_issues_event_min_datetime": "2016-06-17T19:58:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "tskisner/specex", "max_issues_repo_path": "src/specex_lapack.c", "max_line_length": 73, "max_stars_count": null, "max_stars_repo_head_hexsha": "c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tskisner/specex", "max_stars_repo_path": "src/specex_lapack.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 227, "size": 678 }
static char help[] = "Time-dependent advection equation, in flux-conservative form, in 2D.\n" "Option prefix -adv_. Domain is (-1,1) x (-1,1). Equation is\n" " u_t + div(a(x,y) u) = g(x,y,u).\n" "Boundary conditions are periodic in x and y. Cells are grid-point centered.\n" "Allows flux-limited (non-oscillatory) method-of-lines discretization:\n" " none O(h^1) first-order upwinding (limiter = 0)\n" " centered O(h^2) linear centered\n" " vanleer O(h^2) van Leer (1974) limiter\n" " koren O(h^3) Koren (1993) limiter [default].\n" "(There is separate control over the limiter in the residual and in the\n" "Jacobian. Only none and centered are implemented for the Jacobian.)\n" "Solves either of two problems with initial conditions:\n" " straight Figure 6.2, page 303, in Hundsdorfer & Verwer (2003) [default]\n" " rotation Figure 20.5, page 461, in LeVeque (2002).\n" "For straight, if final time is an integer and velocities are kept at default\n" "values, then exact solution is known and L1,L2 errors are reported.\n\n"; #include <petsc.h> //STARTCTX typedef enum {STUMP, SMOOTH, CONE, BOX} InitialType; static const char *InitialTypes[] = {"stump", "smooth", "cone", "box", "InitialType", "", NULL}; typedef enum {NONE, CENTERED, VANLEER, KOREN} LimiterType; static const char *LimiterTypes[] = {"none","centered","vanleer","koren", "LimiterType", "", NULL}; typedef enum {STRAIGHT, ROTATION} ProblemType; static const char *ProblemTypes[] = {"straight","rotation", "ProblemType", "", NULL}; typedef struct { ProblemType problem; double windx, windy, // x,y velocity in STRAIGHT (*initial_fcn)(double,double), // for STRAIGHT (*limiter_fcn)(double), // limiter used in RHS (*jac_limiter_fcn)(double); // used in Jacobian } AdvectCtx; //ENDCTX //STARTINITIAL // equal to 1 in a disc of radius 0.2 around (-0.6,-0.6) static double stump(double x, double y) { const double r = PetscSqrtReal((x+0.6)*(x+0.6) + (y+0.6)*(y+0.6)); return (r < 0.2) ? 1.0 : 0.0; } // smooth (C^6) version of stump static double smooth(double x, double y) { const double r = PetscSqrtReal((x+0.6)*(x+0.6) + (y+0.6)*(y+0.6)); if (r < 0.2) return PetscPowReal(1.0 - PetscPowReal(r / 0.2,6.0),6.0); else return 0.0; } // cone of height 1 of base radius 0.35 centered at (-0.45,0.0) static double cone(double x, double y) { const double r = PetscSqrtReal((x+0.45)*(x+0.45) + y*y); return (r < 0.35) ? 1.0 - r / 0.35 : 0.0; } // equal to 1 in square of side-length 0.5 (0.1,0.6) x (-0.25,0.25) static double box(double x, double y) { if ((0.1 < x) && (x < 0.6) && (-0.25 < y) && (y < 0.25)) return 1.0; else return 0.0; } static void* initialptr[] = {&stump, &smooth, &cone, &box}; //ENDINITIAL //STARTLIMITERS /* the centered-space method is linear */ static double centered(double theta) { return 0.5; } /* van Leer (1974) limiter is formula (1.11) in section III.1 of Hundsdorfer & Verwer (2003) */ static double vanleer(double theta) { const double abstheta = PetscAbsReal(theta); return 0.5 * (theta + abstheta) / (1.0 + abstheta); } /* Koren (1993) limiter is formula (1.7) in section III.1 of Hundsdorfer & Verwer (2003) */ static double koren(double theta) { const double z = (1.0/3.0) + (1.0/6.0) * theta; return PetscMax(0.0, PetscMin(1.0, PetscMin(z, theta))); } static void* limiterptr[] = {NULL, &centered, &vanleer, &koren}; //ENDLIMITERS // velocity a(x,y) = ( a^x(x,y), a^y(x,y) ) static double a_wind(double x, double y, int dir, AdvectCtx* user) { switch (user->problem) { case STRAIGHT: return (dir == 0) ? user->windx : user->windy; case ROTATION: return (dir == 0) ? y : - x; default: return 0.0; } } // source g(x,y,u) static double g_source(double x, double y, double u, AdvectCtx* user) { return 0.0; } // d g(x,y,u) / d u static double dg_source(double x, double y, double u, AdvectCtx* user) { return 0.0; } extern PetscErrorCode FormInitial(DMDALocalInfo*, Vec, AdvectCtx*); extern PetscErrorCode DumpBinary(const char*, const char*, Vec); extern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, double, double**, double**, AdvectCtx*); extern PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo*, double, double**, Mat, Mat, AdvectCtx*); int main(int argc,char **argv) { PetscErrorCode ierr; TS ts; DM da; Vec u; DMDALocalInfo info; double hx, hy, t0, c, dt, tf; char fileroot[PETSC_MAX_PATH_LEN] = ""; int steps; PetscBool oneline = PETSC_FALSE, snesfdset, snesfdcolorset; InitialType initial = STUMP; LimiterType limiter = KOREN, jac_limiter = NONE; AdvectCtx user; PetscInitialize(&argc,&argv,(char*)0,help); user.problem = STRAIGHT; user.windx = 2.0; user.windy = 2.0; ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "adv_", "options for advect.c", ""); CHKERRQ(ierr); ierr = PetscOptionsString("-dumpto","filename root for binary files with initial/final state", "advect.c",fileroot,fileroot,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr); ierr = PetscOptionsEnum("-initial", "shape of initial condition if problem==straight", "advect.c",InitialTypes, (PetscEnum)initial,(PetscEnum*)&initial,NULL); CHKERRQ(ierr); user.initial_fcn = initialptr[initial]; ierr = PetscOptionsEnum("-limiter", "flux-limiter type used in RHS evaluation", "advect.c",LimiterTypes, (PetscEnum)limiter,(PetscEnum*)&limiter,NULL); CHKERRQ(ierr); user.limiter_fcn = limiterptr[limiter]; ierr = PetscOptionsEnum("-jac_limiter", "flux-limiter type used in Jacobian (of RHS) evaluation", "advect.c",LimiterTypes, (PetscEnum)jac_limiter,(PetscEnum*)&jac_limiter,NULL); CHKERRQ(ierr); user.jac_limiter_fcn = limiterptr[jac_limiter]; ierr = PetscOptionsEnum("-problem", "problem type", "advect.c",ProblemTypes, (PetscEnum)user.problem,(PetscEnum*)&user.problem,NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-oneline", "in exact solution cases, show one-line output", "advect.c",oneline,&oneline,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-windx", "x component of wind for problem==straight", "advect.c",user.windx,&user.windx,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-windy", "y component of wind for problem==straight", "advect.c",user.windy,&user.windy,NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = PetscOptionsHasName(NULL,NULL,"-snes_fd",&snesfdset); CHKERRQ(ierr); ierr = PetscOptionsHasName(NULL,NULL,"-snes_fd_color",&snesfdcolorset); CHKERRQ(ierr); if (snesfdset || snesfdcolorset) { user.jac_limiter_fcn = NULL; jac_limiter = 5; // corresponds to empty string } ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC, DMDA_STENCIL_STAR, // no diagonal differencing 5,5,PETSC_DECIDE,PETSC_DECIDE, // default to hx=hx=0.2 grid // (mx=my=5 allows -snes_fd_color) 1, 2, // d.o.f & stencil width NULL,NULL,&da); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); hx = 2.0 / info.mx; hy = 2.0 / info.my; ierr = DMDASetUniformCoordinates(da, // grid is cell-centered -1.0+hx/2.0,1.0-hx/2.0,-1.0+hy/2.0,1.0-hy/2.0,0.0,1.0);CHKERRQ(ierr); ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); ierr = TSSetDM(ts,da); CHKERRQ(ierr); ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES, (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDATSSetRHSJacobianLocal(da, (DMDATSRHSJacobianLocal)FormRHSJacobianLocal,&user); CHKERRQ(ierr); ierr = TSSetType(ts,TSRK); CHKERRQ(ierr); // defaults to -ts_rk_type 3bs // time axis: use CFL number of 0.5 to set initial time step, but note // most methods adapt anyway if (user.problem == STRAIGHT) c = PetscMax(PetscAbsReal(user.windx)/hx, PetscAbsReal(user.windy)/hy); else c = PetscMax(1.0/hx, 1.0/hy); dt = 0.5 / c; ierr = TSSetTime(ts,0.0); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,0.6); CHKERRQ(ierr); ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSSetFromOptions(ts);CHKERRQ(ierr); ierr = DMCreateGlobalVector(da,&u); CHKERRQ(ierr); ierr = FormInitial(&info,u,&user); CHKERRQ(ierr); ierr = DumpBinary(fileroot,"_initial",u); CHKERRQ(ierr); ierr = TSGetTime(ts,&t0); CHKERRQ(ierr); ierr = TSGetTimeStep(ts,&dt); CHKERRQ(ierr); if (!oneline) { ierr = PetscPrintf(PETSC_COMM_WORLD, "solving problem %s with %s initial state on %d x %d grid,\n" " cells dx=%g x dy=%g, limiter = %s, and jac_limiter = %s ...\n", ProblemTypes[user.problem],InitialTypes[initial],info.mx,info.my, hx,hy,LimiterTypes[limiter],LimiterTypes[jac_limiter]); CHKERRQ(ierr); } ierr = TSSolve(ts,u); CHKERRQ(ierr); ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); ierr = TSGetTime(ts,&tf); CHKERRQ(ierr); ierr = DumpBinary(fileroot,"_final",u); CHKERRQ(ierr); if (!oneline) { ierr = PetscPrintf(PETSC_COMM_WORLD, "completed %d steps to time %g\n",steps,tf); CHKERRQ(ierr); } if ( (user.problem == STRAIGHT) && (PetscAbs(fmod(tf+0.5e-8,1.0)) <= 1.0e-8) && (fmod(user.windx,2.0) == 0.0) && (fmod(user.windy,2.0) == 0.0) ) { // exact solution is same as initial condition Vec uexact; double norms[2]; ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr); ierr = FormInitial(&info,uexact,&user); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact ierr = VecNorm(u,NORM_1_AND_2,norms); CHKERRQ(ierr); norms[0] *= hx * hy; norms[1] *= PetscSqrtReal(hx * hy); VecDestroy(&uexact); if (oneline) { ierr = PetscPrintf(PETSC_COMM_WORLD, "%s,%s,%s,%d,%d,%g,%g,%d,%g,%.4e,%.4e\n", ProblemTypes[user.problem],InitialTypes[initial], LimiterTypes[limiter],info.mx,info.my,hx,hy,steps,tf, norms[0],norms[1]); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, "errors |u-uexact|_{1,h} = %.4e, |u-uexact|_{2,h} = %.4e\n", norms[0],norms[1]); CHKERRQ(ierr); } } VecDestroy(&u); TSDestroy(&ts); DMDestroy(&da); return PetscFinalize(); } PetscErrorCode FormInitial(DMDALocalInfo *info, Vec u, AdvectCtx* user) { PetscErrorCode ierr; int i, j; double hx, hy, x, y, **au; ierr = VecSet(u,0.0); CHKERRQ(ierr); // clear it first ierr = DMDAVecGetArray(info->da, u, &au); CHKERRQ(ierr); hx = 2.0 / info->mx; hy = 2.0 / info->my; for (j=info->ys; j<info->ys+info->ym; j++) { y = -1.0 + (j+0.5) * hy; for (i=info->xs; i<info->xs+info->xm; i++) { x = -1.0 + (i+0.5) * hx; switch (user->problem) { case STRAIGHT: au[j][i] = (*user->initial_fcn)(x,y); break; case ROTATION: au[j][i] = cone(x,y) + box(x,y); break; default: SETERRQ(PETSC_COMM_WORLD,1,"invalid user->problem\n"); } } } ierr = DMDAVecRestoreArray(info->da, u, &au); CHKERRQ(ierr); return 0; } // dumps to file; does nothing if string root is empty or NULL PetscErrorCode DumpBinary(const char* root, const char* append, Vec u) { PetscErrorCode ierr; if ((root) && (strlen(root) > 0)) { PetscViewer viewer; char filename[PETSC_MAX_PATH_LEN] = ""; sprintf(filename,"%s%s.dat",root,append); ierr = PetscPrintf(PETSC_COMM_WORLD, "writing PETSC binary file %s ...\n",filename); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename, FILE_MODE_WRITE,&viewer); CHKERRQ(ierr); ierr = VecView(u,viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); } return 0; } /* method-of-lines discretization gives ODE system u' = G(t,u) so our finite volume scheme computes G_ij = - (fluxE - fluxW)/hx - (fluxN - fluxS)/hy + g(x,y,U_ij) but only east (E) and north (N) fluxes are computed */ //STARTFUNCTION PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info, double t, double **au, double **aG, AdvectCtx *user) { int i, j, q, dj, di; double hx, hy, halfx, halfy, x, y, a, u_up, u_dn, u_far, theta, flux; // clear G first for (j = info->ys; j < info->ys + info->ym; j++) for (i = info->xs; i < info->xs + info->xm; i++) aG[j][i] = 0.0; // fluxes on cell boundaries are traversed in E,N order with indices // q=0 for E and q=1 for N; cell center has coordinates (x,y) hx = 2.0 / info->mx; hy = 2.0 / info->my; halfx = hx / 2.0; halfy = hy / 2.0; for (j = info->ys-1; j < info->ys + info->ym; j++) { // note -1 start y = -1.0 + (j+0.5) * hy; for (i = info->xs-1; i < info->xs + info->xm; i++) { // -1 start x = -1.0 + (i+0.5) * hx; if ((i >= info->xs) && (j >= info->ys)) { aG[j][i] += g_source(x,y,au[j][i],user); } for (q = 0; q < 2; q++) { // E (q=0) and N (q=1) bdry fluxes if (q == 0 && j < info->ys) continue; if (q == 1 && i < info->xs) continue; di = 1 - q; dj = q; a = a_wind(x + halfx*di,y + halfy*dj,q,user); // first-order flux u_up = (a >= 0.0) ? au[j][i] : au[j+dj][i+di]; flux = a * u_up; // use flux-limiter if (user->limiter_fcn != NULL) { // formulas (1.2),(1.3),(1.6); H&V pp 216--217 u_dn = (a >= 0.0) ? au[j+dj][i+di] : au[j][i]; if (u_dn != u_up) { u_far = (a >= 0.0) ? au[j-dj][i-di] : au[j+2*dj][i+2*di]; theta = (u_up - u_far) / (u_dn - u_up); flux += a * (*user->limiter_fcn)(theta) * (u_dn-u_up); } } // update owned G_ij on both sides of computed flux if (q == 0) { if (i >= info->xs) aG[j][i] -= flux / hx; if (i+1 < info->xs + info->xm) aG[j][i+1] += flux / hx; } else { if (j >= info->ys) aG[j][i] -= flux / hy; if (j+1 < info->ys + info->ym) aG[j+1][i] += flux / hy; } } } } return 0; } //ENDFUNCTION PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo *info, double t, double **au, Mat J, Mat P, AdvectCtx *user) { PetscErrorCode ierr; const int dir[4] = { 0, 1, 0, 1}, // use x (0) or y (1) component xsh[4] = { 1, 0,-1, 0}, ysh[4] = { 0, 1, 0,-1}; int i, j, l, nc; double hx, hy, halfx, halfy, x, y, a, v[9]; MatStencil col[9],row; ierr = MatZeroEntries(P); CHKERRQ(ierr); hx = 2.0 / info->mx; hy = 2.0 / info->my; halfx = hx / 2.0; halfy = hy / 2.0; for (j = info->ys; j < info->ys+info->ym; j++) { y = -1.0 + (j+0.5) * hy; row.j = j; for (i = info->xs; i < info->xs+info->xm; i++) { x = -1.0 + (i+0.5) * hx; row.i = i; col[0].j = j; col[0].i = i; v[0] = dg_source(x,y,au[j][i],user); nc = 1; for (l = 0; l < 4; l++) { // loop over cell boundaries: E, N, W, S a = a_wind(x + halfx*xsh[l],y + halfy*ysh[l],dir[l],user); if (user->jac_limiter_fcn == NULL) { // Jacobian is from upwind fluxes switch (l) { case 0: col[nc].j = j; col[nc].i = (a >= 0.0) ? i : i+1; v[nc++] = - a / hx; break; case 1: col[nc].j = (a >= 0.0) ? j : j+1; col[nc].i = i; v[nc++] = - a / hy; break; case 2: col[nc].j = j; col[nc].i = (a >= 0.0) ? i-1 : i; v[nc++] = a / hx; break; case 3: col[nc].j = (a >= 0.0) ? j-1 : j; col[nc].i = i; v[nc++] = a / hy; break; } } else if (user->jac_limiter_fcn == &centered) { // Jacobian is from centered fluxes switch (l) { case 0: col[nc].j = j; col[nc].i = i; v[nc++] = - a / (2.0*hx); col[nc].j = j; col[nc].i = i+1; v[nc++] = - a / (2.0*hx); break; case 1: col[nc].j = j; col[nc].i = i; v[nc++] = - a / (2.0*hy); col[nc].j = j+1; col[nc].i = i; v[nc++] = - a / (2.0*hy); break; case 2: col[nc].j = j; col[nc].i = i-1; v[nc++] = a / (2.0*hx); col[nc].j = j; col[nc].i = i; v[nc++] = a / (2.0*hx); break; case 3: col[nc].j = j-1; col[nc].i = i; v[nc++] = a / (2.0*hy); col[nc].j = j; col[nc].i = i; v[nc++] = a / (2.0*hy); break; } } else { SETERRQ(PETSC_COMM_WORLD,1,"only Jacobian cases none|centered are implemented\n"); } } ierr = MatSetValuesStencil(P,1,&row,nc,col,v,ADD_VALUES); CHKERRQ(ierr); } } ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; }
{ "alphanum_fraction": 0.5177168348, "avg_line_length": 41.6181434599, "ext": "c", "hexsha": "640df925640adf44bfd709158c85bd8b68e8f885", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_path": "c/ch11/advect.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_path": "c/ch11/advect.c", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_path": "c/ch11/advect.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5981, "size": 19727 }
/* matrix/gsl_matrix_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_DOUBLE_H__ #define __GSL_MATRIX_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_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 * block; int owner; } gsl_matrix; typedef struct { gsl_matrix matrix; } _gsl_matrix_view; typedef _gsl_matrix_view gsl_matrix_view; typedef struct { gsl_matrix matrix; } _gsl_matrix_const_view; typedef const _gsl_matrix_const_view gsl_matrix_const_view; /* Allocation */ GSL_EXPORT gsl_matrix * gsl_matrix_alloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix * gsl_matrix_calloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix * gsl_matrix_alloc_from_block (gsl_block * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_EXPORT gsl_matrix * gsl_matrix_alloc_from_matrix (gsl_matrix * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_EXPORT gsl_vector * gsl_vector_alloc_row_from_matrix (gsl_matrix * m, const size_t i); GSL_EXPORT gsl_vector * gsl_vector_alloc_col_from_matrix (gsl_matrix * m, const size_t j); GSL_EXPORT void gsl_matrix_free (gsl_matrix * m); /* Views */ GSL_EXPORT _gsl_matrix_view gsl_matrix_submatrix (gsl_matrix * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_view gsl_matrix_row (gsl_matrix * m, const size_t i); GSL_EXPORT _gsl_vector_view gsl_matrix_column (gsl_matrix * m, const size_t j); GSL_EXPORT _gsl_vector_view gsl_matrix_diagonal (gsl_matrix * m); GSL_EXPORT _gsl_vector_view gsl_matrix_subdiagonal (gsl_matrix * m, const size_t k); GSL_EXPORT _gsl_vector_view gsl_matrix_superdiagonal (gsl_matrix * m, const size_t k); GSL_EXPORT _gsl_matrix_view gsl_matrix_view_array (double * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_view gsl_matrix_view_array_with_tda (double * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_view gsl_matrix_view_vector (gsl_vector * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_view gsl_matrix_view_vector_with_tda (gsl_vector * v, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_const_view gsl_matrix_const_submatrix (const gsl_matrix * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_const_view gsl_matrix_const_row (const gsl_matrix * m, const size_t i); GSL_EXPORT _gsl_vector_const_view gsl_matrix_const_column (const gsl_matrix * m, const size_t j); GSL_EXPORT _gsl_vector_const_view gsl_matrix_const_diagonal (const gsl_matrix * m); GSL_EXPORT _gsl_vector_const_view gsl_matrix_const_subdiagonal (const gsl_matrix * m, const size_t k); GSL_EXPORT _gsl_vector_const_view gsl_matrix_const_superdiagonal (const gsl_matrix * m, const size_t k); GSL_EXPORT _gsl_matrix_const_view gsl_matrix_const_view_array (const double * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_const_view gsl_matrix_const_view_array_with_tda (const double * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_const_view gsl_matrix_const_view_vector (const gsl_vector * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_const_view gsl_matrix_const_view_vector_with_tda (const gsl_vector * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_EXPORT double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x); GSL_EXPORT double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j); GSL_EXPORT const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_set_zero (gsl_matrix * m); GSL_EXPORT void gsl_matrix_set_identity (gsl_matrix * m); GSL_EXPORT void gsl_matrix_set_all (gsl_matrix * m, double x); GSL_EXPORT int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ; GSL_EXPORT int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ; GSL_EXPORT int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m); GSL_EXPORT int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format); GSL_EXPORT int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src); GSL_EXPORT int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2); GSL_EXPORT int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_transpose (gsl_matrix * m); GSL_EXPORT int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src); GSL_EXPORT double gsl_matrix_max (const gsl_matrix * m); GSL_EXPORT double gsl_matrix_min (const gsl_matrix * m); GSL_EXPORT void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out); GSL_EXPORT void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax); GSL_EXPORT void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin); GSL_EXPORT void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_EXPORT int gsl_matrix_isnull (const gsl_matrix * m); GSL_EXPORT int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b); GSL_EXPORT int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b); GSL_EXPORT int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b); GSL_EXPORT int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b); GSL_EXPORT int gsl_matrix_scale (gsl_matrix * a, const double x); GSL_EXPORT int gsl_matrix_add_constant (gsl_matrix * a, const double x); GSL_EXPORT int gsl_matrix_add_diagonal (gsl_matrix * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_EXPORT int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i); GSL_EXPORT int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j); GSL_EXPORT int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v); GSL_EXPORT int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v); /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } #endif return m->data[i * m->tda + j] ; } extern inline void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double 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 m->data[i * m->tda + j] = x ; } extern inline double * gsl_matrix_ptr(gsl_matrix * 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 (double *) (m->data + (i * m->tda + j)) ; } extern inline const double * gsl_matrix_const_ptr(const gsl_matrix * 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 double *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_DOUBLE_H__ */
{ "alphanum_fraction": 0.6479712475, "avg_line_length": 30.8250728863, "ext": "h", "hexsha": "dc063943d49efec5a35b4120c6162d3fe35ba0a9", "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_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_double.h", "max_line_length": 123, "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_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2616, "size": 10573 }
// cosmo.h // written by Suman Bhattacharya (https://github.com/bsuman79), modified by Samuel Flender // defines the cosmology and allows calculations of various cosmological params #ifndef cosmo_Header_included #define cosmo_Header_included #include <stdio.h> #include <math.h> #include <iostream> #include <stdlib.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> //double angdiam_func(double x, void * p); using namespace std; class cosmo { protected: float H0, Omega_M, rho_crit, a, Omega_k, Omega_L, wt; float PI, m_sun, G, mpc, gnewt; public: cosmo(float inp1, float inp2, float inp4, float inp5) { // cosmological params at z =0 H0 = inp1; Omega_M = inp2; Omega_k = inp4; Omega_L = 1.0- Omega_M- Omega_k; wt= inp5; PI = 4.*atan(1.); m_sun = 1.98892e30; G = 6.67e-11/1.0e9; // in km^3 kg^-1 s^-2 mpc = 3.0857e19; // in km gnewt = G*m_sun/mpc; //for cosm params (in km^2 Mpc msun^-1 s^-2) } float get_H0() { return H0; } float get_hubble70() { return H0/70.0; } float scale_fact(float redshift) { a = 1.0/(1.0+redshift); return a; } float hubblez(float redshift) { scale_fact(redshift); return H0 * Efact(redshift); } float calc_rho_crit(float redshift) { float Hz = hubblez(redshift); rho_crit = pow(Hz,2)*3./(8.*PI*gnewt); return rho_crit; } float Omega_Mz(float redshift) { scale_fact(redshift); float Hz = hubblez(redshift); return (Omega_M/pow(a,3))*pow(H0/Hz,2); } float Delta_vir(float redshift) { float x; x = Omega_Mz(redshift) - 1.0; return (18*pow(PI,2)) + (82*x) - (39*pow(x,2)); } float Efact(float redshift) { scale_fact(redshift); return sqrt(Omega_M/pow(a,3) + Omega_L/pow(a, 3*wt+3) + (1.0-Omega_M-Omega_L)/pow(a,2)); } float ang_diam(float redshift) { // note rcutoff is in units of Rvir int dummy; float result; double x[1000], y[1000]; float speed_of_light = 2.9979e5; //km/s double units = scale_fact(redshift)*speed_of_light/H0; for(dummy=0;dummy<1000;dummy++){ x[dummy]= 0.0+ redshift/999*dummy; y[dummy] = 1.0/(sqrt( Omega_M*pow(1+x[dummy],3) + Omega_L*pow(1+x[dummy], 3*wt+3) + (1.0-Omega_M-Omega_L)*pow(1+x[dummy],2))); } if (redshift==0.0) return 0.0; else { gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 1000); gsl_spline_init (spline, x, y, 1000); result=units*gsl_spline_eval_integ (spline, x[0], x[dummy-1], acc); gsl_spline_free (spline); gsl_interp_accel_free (acc); } return result; } float comov_dist(float redshift) { //comoving distance to redshift z in Mpc // note rcutoff is in units of Rvir int dummy; float result; double x[1000], y[1000]; float speed_of_light = 2.9979e5; //km/s double units = speed_of_light/H0; for(dummy=0;dummy<1000;dummy++){ x[dummy]= 0.0+ redshift/999*dummy; y[dummy] = 1.0/(sqrt( Omega_M*pow(1+x[dummy],3) + Omega_L*pow(1+x[dummy], 3*wt+3) + (1.0-Omega_M-Omega_L)*pow(1+x[dummy],2))); } if (redshift==0.0) return 0.0; else { gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 1000); gsl_spline_init (spline, x, y, 1000); result=units*gsl_spline_eval_integ (spline, x[0], x[dummy-1], acc); gsl_spline_free (spline); gsl_interp_accel_free (acc); } return result; } float cosmic_time(float redshift) { // function to calculate cosmic time to redshift given cosmological model //good to ~1% for z<10 // these are weight functions for solving the differential equation float x[16] = {0.0950,0.2816,0.4580,0.6179,0.7554,0.8656,0.9446,0.9894,-0.0950,-0.2816,-0.4580,-0.6179,-0.7554,-0.8656,-0.9446,-0.9894}; float w[16] = {0.1895,0.1826,0.1692,0.1496,0.1246,0.0952,0.0623,0.0272,0.1895,0.1826,0.1692,0.1496,0.1246,0.0952,0.0623,0.0272}; float a0 = 0.0, a1, Delta_a, h2, sum, cosm_h0, den0 = Omega_M, den1 = Omega_L, den2; float ss, ak, adot, cosm_t; float time_units, secperyr = 3.15569260e7, age_of_univ = 8.93120195E+17/2.0; // in seconds int Nsteps, i, k; Nsteps = 10000; a1 = 1.0/(1.0+redshift); Delta_a = (a1-a0)/Nsteps; h2 = Delta_a/2.0; sum = 0.0; cosm_h0 = sqrt(8.0*PI/3.0); time_units = (age_of_univ*2/secperyr/1.0E9)*(1.0E2/H0); // converts to Gyr // now solve friedman eqn. for (i=0;i<Nsteps;i++) { ss = 0.0; for (k=0;k<16;k++) { ak = a0+h2*(1.0+x[k]); den2 = den1*dynrho(ak,wt); adot = sqrt( den0/ak + den2*ak*ak + 1.0-den0-den1 ); ss = ss + w[k]/adot; } ss *= h2; a0 += Delta_a; sum += ss; } cosm_t = sum/cosm_h0; cosm_t = cosm_t*time_units; return cosm_t; } float dynrho(float a, float wdyn) { // CALDWELL: This function RETURNs the energy density // in the dynamical phi field, given the scale factor // such that at a=1, dynrho = 1 int n_dyn_q1,n_dyn_q2,n_dyn_q3; float drho; if (wdyn==-1.0) { n_dyn_q1 = 0; n_dyn_q2 = 0; n_dyn_q3 = 0; } else { n_dyn_q1 = 1; n_dyn_q2 = 1; n_dyn_q3 = 0; } // did I ask for dynamical field? Leave this as an option for later if (n_dyn_q1==1) { if(n_dyn_q2==1) drho = pow(a,(-3*(1.0 + wdyn))); } // otherwise, set the energy density to 1 else drho = 1.0; return drho; } friend class cluster; friend class growth; //friend double angdiam_func(double x, void * p); }; /*double angdiam_func(double x, void * p) { double *params = (double *) p; double OmegaM = params[0]; double OmegaL = params[1]; double wt= params[2]; double y, a = 1.0/(1.0+x); y = 1.0/(sqrt( OmegaM/pow(a,3) + OmegaL/pow(a, 3*wt+3) + (1.0-OmegaM-OmegaL)/pow(a,2))); return y; }*/ #endif
{ "alphanum_fraction": 0.6403340873, "avg_line_length": 25.3171806167, "ext": "h", "hexsha": "6a3992d927cdc28282686e4491ed682ed86a4d29", "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": "7f2b85a985fa80a388fa409393350689a6accaca", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sflender/pairwise", "max_forks_repo_path": "src/cosmo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7f2b85a985fa80a388fa409393350689a6accaca", "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": "sflender/pairwise", "max_issues_repo_path": "src/cosmo.h", "max_line_length": 138, "max_stars_count": null, "max_stars_repo_head_hexsha": "7f2b85a985fa80a388fa409393350689a6accaca", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sflender/pairwise", "max_stars_repo_path": "src/cosmo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2258, "size": 5747 }
/* * * Copyright 2011, 2012 by the CALATK development team * * 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 C_SOLVER_NLOPT_H #define C_SOLVER_NLOPT_H #include <string> #include <math.h> #include <nlopt.h> namespace CALATK { /** * Implements an LBFGS solver * */ template < class TState > class CSolverNLOpt : public CSolver< TState > { public: typedef typename TState::TFloat T; typedef CSolver< TState > Superclass; typedef typename Superclass::ObjectiveFunctionType ObjectiveFunctionType; typedef typename Superclass::CEnergyValues CEnergyValues; CSolverNLOpt(); ~CSolverNLOpt(); bool SolvePreInitialized(); // specializations bool SolvePreInitialized( double* ptr, long int liNumberOfStateVectorElements ); bool SolvePreInitialized( float* ptr, long int liNumberOfStateVectorElements ); virtual void SetAutoConfiguration( CJSONConfiguration * combined, CJSONConfiguration * cleaned ); SetMacro( initial_step1, T ); GetMacro( initial_step1, T ); SetMacro( maxeval, unsigned int ); GetMacro( maxeval, unsigned int ); SetMacro( xtol_rel, T ); GetMacro( xtol_rel, T ); SetMacro( ftol_rel, T ); GetMacro( ftol_rel, T ); SetMacro( vector_storage, unsigned int ); GetMacro( vector_storage, unsigned int ); protected: struct SUserData { CSolverNLOpt< TState > *pSolver; }; std::string GetStringForStatusCode( int ret ); T* m_x; // specialization for double static double _evaluate( unsigned n, const double *x, double *g, void *my_func_data ); // specialization for float static float _evaluate( unsigned n, const float *x, float *g, void *my_func_data ); // generic evaluate and progress methods T evaluate( unsigned n, const T *x, T *g, void *my_func_data ); T m_initial_step1; const T Defaultinitial_step1; bool m_ExternallySetinitial_step1; unsigned int m_maxeval; const unsigned int Defaultmaxeval; bool m_ExternallySetmaxeval; T m_xtol_rel; const T Defaultxtol_rel; bool m_ExternallySetxtol_rel; T m_ftol_rel; const T Defaultftol_rel; bool m_ExternallySetftol_rel; unsigned int m_vector_storage; const unsigned int Defaultvector_storage; bool m_ExternallySetvector_storage; }; #include "CSolverNLOpt.txx" } // end namespace #endif // C_SOLVER_NLOPT_H
{ "alphanum_fraction": 0.6999327957, "avg_line_length": 22.3759398496, "ext": "h", "hexsha": "c8fa9403754e3e643d60893da781788594d5df14", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-20T16:38:28.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-20T16:38:28.000Z", "max_forks_repo_head_hexsha": "849c17919ac5084b5b067c7631bc2aa1efd650df", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "cpatrick/calatk", "max_forks_repo_path": "Code/Libraries/Numerics/CSolverNLOpt.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "849c17919ac5084b5b067c7631bc2aa1efd650df", "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": "cpatrick/calatk", "max_issues_repo_path": "Code/Libraries/Numerics/CSolverNLOpt.h", "max_line_length": 99, "max_stars_count": 2, "max_stars_repo_head_hexsha": "3cee90488feab7e3ef2ade1f791106aa7f11e404", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "fbudin69500/calatk", "max_stars_repo_path": "Code/Libraries/Numerics/CSolverNLOpt.h", "max_stars_repo_stars_event_max_datetime": "2020-04-08T14:03:58.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-15T12:51:02.000Z", "num_tokens": 759, "size": 2976 }
#ifndef STK_Matrix_h #define STK_Matrix_h #include "common.h" #include "Error.h" #include "BasicVector.h" #include <stddef.h> #include <stdlib.h> #include <stdexcept> #include <iostream> #ifdef HAVE_ATLAS extern "C"{ #ifdef USE_MKL #include "mkl.h" #else #include <cblas.h> #include <atlas/clapack.h> #endif } #endif //#define TRACE_MATRIX_OPERATIONS #define CHECKSIZE namespace STK { // class matrix_error : public std::logic_error {};/ // class matrix_sizes_error : public matrix_error {}; /// defines a storage type typedef enum { STORAGE_UNDEFINED = 0, STORAGE_REGULAR, STORAGE_TRANSPOSED } StorageType; // declare the class so the header knows about it template<typename _ElemT> class Matrix; template<typename _ElemT> class MatrixRange; // we need to declare the friend << operator here template<typename _ElemT> std::ostream & operator << (std::ostream & out, Matrix<_ElemT> & m); /** ************************************************************************** ** ************************************************************************** * @brief Provides a matrix class * * This class provides a way to work with matrices in STK. * It encapsulates basic operations and memory optimizations. * */ template<typename _ElemT> class Matrix { public: // HTK parameter file header (see HTK manual) typedef struct { int nSamples; int sampPeriod; short sampSize; short paramKind; } HtkHeader; /// defines a type of this typedef Matrix<_ElemT> ThisType; // Constructors /// Empty constructor Matrix<_ElemT> (): mMRows(0), mMCols(0), mStride(0), mpData(NULL) #ifdef STK_MEMALIGN_MANUAL , mpFreeData(NULL) #endif {} /// Copy constructor Matrix<_ElemT> (const ThisType & t); /// Basic constructor Matrix<_ElemT> (const size_t r, const size_t c); /// Destructor virtual ~Matrix<_ElemT> (); /// Initializes matrix (if not done by constructor) void Init(const size_t r, const size_t c); /** * @brief Dealocates the matrix from memory and resets the dimensions to (0, 0) */ void Destroy(); /** * @brief Returns @c true if matrix is initialized */ const bool IsInitialized() const { return mpData != NULL; } /// Returns number of rows in the matrix const size_t Rows() const { return mMRows; } /// Returns number of columns in the matrix const size_t Cols() const { return mMCols; } /// Returns number of columns in the matrix memory const size_t Stride() const { return mStride; } /** * @brief Gives access to a specified matrix row without range check * @return Pointer to the const array */ const _ElemT* cpData () const { return mpData; } /** * @brief Gives access to a specified matrix row without range check * @return Pointer to the non-const data array */ _ElemT* __attribute__((aligned(16))) pData () const { return mpData; } /// Returns size of matrix in memory const size_t MSize() const { return mMRows * mStride * sizeof(_ElemT); } bool LoadHTK(const char* pFileName); //######################################################################## //######################################################################## // Math stuff /** * @brief Performs diagonal scaling * @param pDiagVector Array representing matrix diagonal * @return Refference to this */ ThisType& DiagScale(const _ElemT* pDiagVector); ThisType& DiagScale(const BasicVector<_ElemT>& rDiagVector); /** * @brief Performs vector multiplication on a and b and and adds the * result to this (elem by elem) */ ThisType & AddCMtMMul(const _ElemT& c, const ThisType& a, const ThisType& b); ThisType & AddMMMul(const ThisType& a, const ThisType& b); ThisType & AddMMtMul(const ThisType& a, const ThisType& b); ThisType & AddCMMtMul(const _ElemT& c, const ThisType& a, const ThisType& b); ThisType & AddCMMul(const _ElemT& c, const ThisType& a); ThisType & RepMMSub(const ThisType& a, const ThisType& b); ThisType & RepMMMul(const ThisType& a, const ThisType& b); ThisType & RepMtMMul(const ThisType& a, const ThisType& b); ThisType & AddCVVtMul(const _ElemT& c, const BasicVector<_ElemT>& rA, const BasicVector<_ElemT>& rB); ThisType & AddCVVtMul(const _ElemT& c, const _ElemT* pA, const _ElemT* pB); ThisType & AddCVVt(const _ElemT& c, const BasicVector<_ElemT>& rA, const _ElemT* pB); ThisType & DivC(const _ElemT& c); //######################################################################## //######################################################################## ThisType & DotMul(const ThisType& a); ThisType& NormalizeRows(); /** * @brief Returns sum of all elements */ const _ElemT& Sum() const; /** * @brief Performs log on all elements * result to this (elem by elem) */ ThisType& Log(); /** * @brief Performs fast sigmoid on row vectors * result to this (elem by elem) */ ThisType & FastRowSigmoid(); /** * @brief Performs fast softmax on row vectors * result to this (elem by elem) */ ThisType & FastRowSoftmax(); /** * @brief Performs sigmoid on row vectors * result to this (elem by elem) */ ThisType & RowSigmoid(); /** * @brief Performs softmax on row vectors * result to this (elem by elem) */ ThisType & RowSoftmax(); /** * @brief Performs matrix inversion */ ThisType & Invert(); ThisType & Clear(); /** * @brief Gives access to a specified matrix row without range check * @return pointer to the first field of the row */ inline _ElemT* operator [] (size_t i) const { return mpData + (i * mStride); } /** * @brief Gives access to a specified matrix row with range check * @return pointer to the first field of the row */ _ElemT* Row (const size_t r) { if (0 <= r && r < mMRows) { return this->operator[] (r); } else { throw std::out_of_range("Matrix row out of range"); } } /** * @brief Gives access to matrix elements (row, col) * @return pointer to the desired field */ _ElemT& operator () (const size_t r, const size_t c) { return *(mpData + r * mStride + c); } friend std::ostream & operator << <> (std::ostream & out, ThisType & m); void PrintOut(char *file); void ReadIn(char *file); /** * @brief Returns a matrix sub-range * @param ro Row offset * @param r Rows in range * @param co Column offset * @param c Coluns in range * See @c MatrixRange class for details */ MatrixRange<_ElemT> Range(const size_t ro, const size_t r, const size_t co, const size_t c) { return MatrixRange<_ElemT>(*this, ro, r, co, c); } protected: inline void swap4b(void *a); inline void swap2b(void *a); protected: /// these atributes store the real matrix size as it is stored in memory /// including memalignment size_t mMRows; ///< Number of rows size_t mMCols; ///< Number of columns size_t mStride; ///< true number of columns for the internal matrix. ///< This number may differ from M_cols as memory ///< alignment might be used /// data memory area _ElemT* mpData; #ifdef STK_MEMALIGN_MANUAL /// data to be freed (in case of manual memalignment use, see common.h) _ElemT* mpFreeData; #endif }; // class Matrix /** ************************************************************************** ** ************************************************************************** * @brief Provides a window matrix abstraction class * * This class provides a way to work with matrix cutouts in STK. * It encapsulates basic operations and memory optimizations. * */ template<typename _ElemT> class WindowMatrix : public Matrix<_ElemT> { protected: /// points to the original begining of the data array /// The data atribute points now to the begining of the window _ElemT * mpOrigData; //@{ /// these atributes store the real matrix size as it is stored in memory /// including memalignment size_t mOrigMRows; ///< Number of rows size_t mOrigMCols; ///< Number of columns size_t mOrigMRealCols; ///< true number of columns for the internal matrix. ///< This number may differ from M_cols as memory ///< alignment might be used size_t mTRowOff; ///< First row of the window size_t mTColOff; ///< First column of the window //@} public: /// defines a type of this typedef WindowMatrix<_ElemT> ThisType; /// Empty constructor WindowMatrix() : Matrix<_ElemT>() {}; /// Copy constructor WindowMatrix(const ThisType & rT); /// Basic constructor WindowMatrix(const size_t r, const size_t c): Matrix<_ElemT>(r, c), // create the base class mOrigMRows (Matrix<_ElemT>::mMRows), mOrigMCols (Matrix<_ElemT>::mMCols), mOrigMRealCols(Matrix<_ElemT>::mStride), mTRowOff(0), mTColOff(0) // set the offset { mpOrigData = Matrix<_ElemT>::mpData; } /// The destructor ~WindowMatrix<_ElemT>() { Matrix<_ElemT>::mpData = this->mpOrigData; } /// sets the size of the window (whole rows) void SetSize(const size_t ro, const size_t r); /// sets the size of the window void SetSize(const size_t ro, const size_t r, const size_t co, const size_t c); /** * @brief Resets the window to the default (full) size */ void Reset () { Matrix<_ElemT>::mpData = mpOrigData; Matrix<_ElemT>::mMRows = mOrigMRows; Matrix<_ElemT>::mMCols = mOrigMCols; Matrix<_ElemT>::mStride = mOrigMRealCols; mTRowOff = 0; mTColOff = 0; } }; /** ************************************************************************** ** ************************************************************************** * @brief Sub-matrix representation * * This class provides a way to work with matrix cutouts in STK. * * */ template<typename _ElemT> class MatrixRange : public Matrix<_ElemT> { public: /// Constructor MatrixRange(const Matrix<_ElemT>& rT, const size_t ro, const size_t r, const size_t co, const size_t c); /// The destructor virtual ~MatrixRange<_ElemT>() { #ifndef STK_MEMALIGN_MANUAL Matrix<_ElemT>::mpData = NULL; #else Matrix<_ElemT>::mpFreeData = NULL; #endif } }; } // namespace STK //***************************************************************************** //***************************************************************************** // we need to include the implementation #include "Matrix.tcc" //***************************************************************************** //***************************************************************************** /****************************************************************************** ****************************************************************************** * The following section contains specialized template definitions * whose implementation is in Matrix.cc */ namespace STK { template<> Matrix<float> & Matrix<float>:: FastRowSigmoid(); template<> Matrix<double> & Matrix<double>:: FastRowSigmoid(); template<> Matrix<float> & Matrix<float>:: RowSigmoid(); template<> Matrix<double> & Matrix<double>:: RowSigmoid(); template<> Matrix<float> & Matrix<float>:: DiagScale(const BasicVector<float>& rDiagVector); template<> Matrix<float> & Matrix<float>:: DiagScale(const float* pDiagVector); template<> Matrix<float> & Matrix<float>:: FastRowSoftmax(); template<> Matrix<double> & Matrix<double>:: FastRowSoftmax(); template<> Matrix<float> & Matrix<float>:: RowSoftmax(); template<> Matrix<double> & Matrix<double>:: RowSoftmax(); template<> Matrix<float> & Matrix<float>:: AddCMtMMul(const float& c, const Matrix<float>& a, const Matrix<float>& b); template<> Matrix<double> & Matrix<double>:: AddCMtMMul(const double& c, const Matrix<double>& a, const Matrix<double>& b); template<> Matrix<float> & Matrix<float>:: AddMMMul(const Matrix<float>& a, const Matrix<float>& b); template<> Matrix<double> & Matrix<double>:: AddMMMul(const Matrix<double> & a, const Matrix<double>& b); template<> Matrix<float> & Matrix<float>:: RepMMMul(const Matrix<float> & a, const Matrix<float>& b); template<> Matrix<float> & Matrix<float>:: AddCMMtMul(const float& c, const Matrix<float>& a, const Matrix<float>& b); template<> Matrix<double> & Matrix<double>:: AddCMMtMul(const double& c, const Matrix<double>& a, const Matrix<double>& b); template<> Matrix<float> & Matrix<float>:: AddCVVtMul(const float& c, const BasicVector<float>& rA, const BasicVector<float>& rB); template<> Matrix<double> & Matrix<double>:: AddCVVtMul(const double& c, const BasicVector<double>& rA, const BasicVector<double>& rB); } // namespace STK //#ifndef STK_Matrix_h #endif
{ "alphanum_fraction": 0.5020971801, "avg_line_length": 24.7555910543, "ext": "h", "hexsha": "86f6ef1164a2e00dfaa1c90fd14cfe00b1a6196e", "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": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "troylee/nnet-asr", "max_forks_repo_path": "src/STKLib/trunk/src/STKLib/Matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "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": "troylee/nnet-asr", "max_issues_repo_path": "src/STKLib/trunk/src/STKLib/Matrix.h", "max_line_length": 85, "max_stars_count": null, "max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "troylee/nnet-asr", "max_stars_repo_path": "src/STKLib/trunk/src/STKLib/Matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3549, "size": 15497 }
#include <mex.h> #include <matrix.h> #include <math.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <blas.h> // dgemv #include <lapack.h> // dstegr #define abs1(a) ((a) < 0.0 ? -(a) : (a)) #define sign1(a) ((a)==0) ? 0 : (((a)>0.0)?1:(-1)) #define max1(a,b) ((a) > (b) ? (a) : (b)) #define min1(a,b) ((a) < (b) ? (a) : (b)) double dot1(const double*a,const double*b,const ptrdiff_t n) { double ret = 0; ptrdiff_t i; for(i=0;i<n;i++) ret +=a[i]*b[i]; return ret; } void AxSym(const double*A, const double*x, double*result, const ptrdiff_t n) { /* * input: * A: n x n * x: n x 1 * output: * result = A*x: n x 1 * NOTE: A is a symmetric matrix, only the the lower triangular part of A is to be referenced * x and the result can not be the same space */ char *UPLO="L";ptrdiff_t N;double ALPHA; ptrdiff_t LDA; ptrdiff_t INCX; double BETA;ptrdiff_t INCY; N = n; ALPHA = 1; LDA = n; INCX=1; BETA=0; INCY=1; dsymv(UPLO,&N,&ALPHA,A,&LDA,x,&INCX,&BETA,result,&INCY); } double computeObj(double s, double u0, double u1, double u2,double d0,double d1,double d2) { return (u2*s*s + u1*s + u0) / (d2*s*s + d1*s + d0); } double quadfrac2(double u0, double u1, double u2,double d0,double d1,double d2) { double x1;double x2; double c2 = u2*d1 - d2*u1; double c1 = 2*u2*d0 - 2*d2*u0; double c0 = u1*d0 - d1*u0; double dd = sqrt(c1*c1 - 4*c2*c0); if(c2==0) { x1 = -c0/c1; x2 = x1; } else { x1 = (-c1+dd)/(2*c2); x2 = (-c1-dd)/(2*c2); } if(computeObj(x1,u0,u1,u2,d0,d1,d2)<computeObj(x2,u0,u1,u2,d0,d1,d2)) { return x1; } else { return x2; } } ptrdiff_t pos_max(const double*a,const ptrdiff_t n) { double val = abs1(a[0]); ptrdiff_t pos=0; ptrdiff_t i ; for (i=1;i<n;i++) { if(abs1(a[i]) > val) { val = abs1(a[i]); pos = i; } } return pos; } void pvec(const double*a,const ptrdiff_t n) { // print the vector a ptrdiff_t i; printf("[ "); for (i=0;i<n;i++) { printf("%f ",a[i]); } printf("]\n"); } void solve(double *x,const double *in_x, const double*A, const double*b, const double c, const double *Q, const double *r,const double s,const ptrdiff_t n,const ptrdiff_t max_iter) { double *Ax = (double*)malloc(n*sizeof(double)); double *Qx = (double*)malloc(n*sizeof(double)); double *up_g = (double*)malloc(n*sizeof(double)); double *down_g = (double*)malloc(n*sizeof(double)); double *grad = (double*)malloc(n*sizeof(double)); double xAx = 0;double bx = 0; double xQx = 0; double rx = 0; ptrdiff_t iter, i,j; memcpy(x,in_x,n*sizeof(double)); AxSym(A, x, Ax, n); xAx = dot1(x,Ax,n); bx = dot1(x,b,n); AxSym(Q,x,Qx,n); xQx = dot1(x,Qx,n); rx = dot1(r,x,n); for ( iter=1;iter<=max_iter;iter++) { double u0,u1,u2,d0,d1,d2,alpha; double up,down,fobj; up = 0.5*xAx + bx + c; down = 0.5*xQx + rx + s; fobj = up / down; for (j=0;j<n;j++) { up_g[j] = Ax[j]+b[j]; down_g[j] = Qx[j]+r[j]; grad[j] = up_g[j]/down - fobj * down_g[j]/down ; } i = pos_max(grad,n); u0 = 0.5*xAx + bx + c; u1 = Ax[i] + b[i]; u2 = 0.5*A[i*n+i]; d0 = 0.5*xQx + rx + s; d1 = Qx[i] + r[i]; d2 = 0.5*Q[i*n+i]; alpha = quadfrac2(u0,u1,u2,d0,d1,d2); x[i] = x[i] + alpha; xAx = xAx + 2*alpha*Ax[i] + alpha*alpha*A[i*n+i]; xQx = xQx + 2*alpha*Qx[i] + alpha*alpha*Q[i*n+i]; for (j=0;j<n;j++) { Ax[j] = Ax[j] + alpha*A[i*n+j]; Qx[j] = Qx[j] + alpha*Q[i*n+j]; } bx = bx + alpha*b[i]; rx = rx + alpha*r[i]; } for (ptrdiff_t i=0;i<n;i++)if(x[i]==0)x[i]=1e-100; free(Ax); free(Qx); free(up_g); free(down_g); free(grad); } void mexFunction (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { /*set up input arguments */ double* x = mxGetPr(prhs[0]); double* A = mxGetPr(prhs[1]); double* b = mxGetPr(prhs[2]); double c = mxGetScalar(prhs[3]); double* D = mxGetPr(prhs[4]); double* e = mxGetPr(prhs[5]); double f = mxGetScalar(prhs[6]); ptrdiff_t n = mxGetScalar(prhs[7]); ptrdiff_t max_iter = mxGetScalar(prhs[8]); double *out_x; plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL); out_x = mxGetPr(plhs[0]); solve(out_x,x,A,b,c,D,e,f,n,max_iter); }
{ "alphanum_fraction": 0.4836471754, "avg_line_length": 27.123655914, "ext": "c", "hexsha": "213592acd160ae587d0bc2d9bff38d8a0e7400a1", "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": "e0f71dcd683c8a4a5372d63d68a8e3a3375edefc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "RVreugdenhil/sparseQP", "max_forks_repo_path": "src/KDD/solver/QuadFractionalProgrammingCOO.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e0f71dcd683c8a4a5372d63d68a8e3a3375edefc", "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": "RVreugdenhil/sparseQP", "max_issues_repo_path": "src/KDD/solver/QuadFractionalProgrammingCOO.c", "max_line_length": 181, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e0f71dcd683c8a4a5372d63d68a8e3a3375edefc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "RVreugdenhil/sparseQP", "max_stars_repo_path": "src/KDD/solver/QuadFractionalProgrammingCOO.c", "max_stars_repo_stars_event_max_datetime": "2021-09-04T01:56:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-04T01:56:37.000Z", "num_tokens": 1702, "size": 5045 }
#pragma once // v1.4 By Ook // #include <gsl/gsl> #include "EnumConcepts.h" // this enum is here to simplify debugging enum class WindowMessages : DWORD { eWM_NULL, eWM_CREATE, // lParam = LPCREATESTRUCT eWM_DESTROY, eWM_MOVE, eWM_SIZEWAIT, eWM_SIZE, // lParam = width/height eWM_ACTIVATE, eWM_SETFOCUS, eWM_KILLFOCUS, eWM_SETVISIBLE, eWM_ENABLE, eWM_SETREDRAW, eWM_SETTEXT, eWM_GETTEXT, eWM_GETTEXTLENGTH, eWM_PAINT, eWM_CLOSE, eWM_QUERYENDSESSION, eWM_QUIT, eWM_QUERYOPEN, eWM_ERASEBKGND, // wParam = HDC eWM_SYSCOLORCHANGE, eWM_ENDSESSION, eWM_SYSTEMERROR, eWM_SHOWWINDOW, eWM_CTLCOLOR, eWM_WININICHANGE, eWM_DEVMODECHANGE, eWM_ACTIVATEAPP, eWM_FONTCHANGE, eWM_TIMECHANGE, eWM_CANCELMODE, eWM_SETCURSOR, eWM_MOUSEACTIVATE, eWM_CHILDACTIVATE, eWM_QUEUESYNC, eWM_GETMINMAXINFO, eWM_LOGOFF, eWM_PAINTICON, eWM_ICONERASEBKGND, eWM_NEXTDLGCTL, eWM_ALTTABACTIVE, eWM_SPOOLERSTATUS, eWM_DRAWITEM, eWM_MEASUREITEM, eWM_DELETEITEM, eWM_VKEYTOITEM, eWM_CHARTOITEM, eWM_SETFONT, eWM_GETFONT, eWM_SETHOTKEY, eWM_GETHOTKEY, eWM_SHELLNOTIFY, eWM_ISACTIVEICON, eWM_QUERYPARKICON, eWM_QUERYDRAGICON, eWM_WINHELP, eWM_COMPAREITEM, eWM_FULLSCREEN, eWM_CLIENTSHUTDOWN, eWM_DDEMLEVENT, eWM_GETOBJECT, eundefined_1, eundefined_2, eWM_TESTING, eWM_COMPACTING, eWM_OTHERWINDOWCREATED, eWM_OTHERWINDOWDESTROYED, eWM_COMMNOTIFY, eundefined_3, eWM_WINDOWPOSCHANGING, eWM_WINDOWPOSCHANGED, eWM_POWER, eWM_COPYGLOBALDATA, eWM_COPYDATA, eWM_CANCELJOURNAL, eundefined_4, eWM_KEYF1, eWM_NOTIFY, eWM_ACCESS_WINDOW, eWM_INPUTLANGCHANGEREQUEST, eWM_INPUTLANGCHANGE, eWM_TCARD, eWM_HELP, eWM_USERCHANGED, eWM_NOTIFYFORMAT, eundefined_5, eundefined_6, eundefined_7, eundefined_8, eundefined_9, eundefined_10, eundefined_11, eundefined_12, eundefined_13, eundefined_14, eundefined_15, eundefined_16, eundefined_17, eundefined_18, eundefined_19, eundefined_20, eundefined_21, eundefined_22, eundefined_23, eundefined_24, eundefined_25, eundefined_26, eundefined_27, eundefined_28, eundefined_29, eundefined_30, eWM_FINALDESTROY, eWM_MEASUREITEM_CLIENTDATA, eundefined_31, eundefined_32, eundefined_33, eundefined_34, eundefined_35, eundefined_36, eundefined_37, eundefined_38, eundefined_39, eWM_CONTEXTMENU, eWM_STYLECHANGING, eWM_STYLECHANGED, eWM_DISPLAYCHANGE, eWM_GETICON, eWM_SETICON, eWM_NCCREATE, // lParam = LPCREATESTRUCT eWM_NCDESTROY, eWM_NCCALCSIZE, eWM_NCHITTEST, eWM_NCPAINT, eWM_NCACTIVATE, eWM_GETDLGCODE, eWM_SYNCPAINT, eWM_SYNCTASK, eundefined_40, eWM_KLUDGEMINRECT, eWM_LPKDRAWSWITCHWND, eundefined_41, eundefined_42, eundefined_43, eWM_UAHDESTROYWINDOW, eWM_UAHDRAWMENU, eWM_UAHDRAWMENUITEM, eWM_UAHINITMENU, eWM_UAHMEASUREMENUITEM, eWM_UAHNCPAINTMENUPOPUP, eWM_UAHUPDATE, eundefined_44, eundefined_45, eundefined_46, eundefined_47, eundefined_48, eundefined_49, eundefined_50, eundefined_51, eundefined_52, eWM_NCMOUSEMOVE, eWM_NCLBUTTONDOWN, eWM_NCLBUTTONUP, eWM_NCLBUTTONDBLCLK, eWM_NCRBUTTONDOWN, eWM_NCRBUTTONUP, eWM_NCRBUTTONDBLCLK, eWM_NCMBUTTONDOWN, eWM_NCMBUTTONUP, eWM_NCMBUTTONDBLCLK, eundefined_53, eWM_NCXBUTTONDOWN, eWM_NCXBUTTONUP, eWM_NCXBUTTONDBLCLK, eWM_NCUAHDRAWCAPTION, eWM_NCUAHDRAWFRAME, // wParam = HDC eEM_GETSEL, eEM_SETSEL, eEM_GETRECT, eEM_SETRECT, eEM_SETRECTNP, eEM_SCROLL, eEM_LINESCROLL, eEM_SCROLLCARET, eEM_GETMODIFY, eEM_SETMODIFY, eEM_GETLINECOUNT, eEM_LINEINDEX, eEM_SETHANDLE, eEM_GETHANDLE, eEM_GETTHUMB, eundefined_54, eundefined_55, eEM_LINELENGTH, eEM_REPLACESEL, eEM_SETFONT, eEM_GETLINE, eEM_LIMITTEXT, eEM_CANUNDO, eEM_UNDO, eEM_FMTLINES, eEM_LINEFROMCHAR, eEM_SETWORDBREAK, eEM_SETTABSTOPS, eEM_SETPASSWORDCHAR, eEM_EMPTYUNDOBUFFER, eEM_GETFIRSTVISIBLELINE, eEM_SETREADONLY, eEM_SETWORDBREAKPROC, eEM_GETWORDBREAKPROC, eEM_GETPASSWORDCHAR, eEM_SETMARGINS, eEM_GETMARGINS, eEM_GETLIMITTEXT, eEM_POSFROMCHAR, eEM_CHARFROMPOS, eEM_SETIMESTATUS, eEM_GETIMESTATUS, eEM_MSGMAX, eundefined_56, eundefined_57, eundefined_58, eundefined_59, eundefined_60, eundefined_61, eundefined_62, eundefined_63, eundefined_64, eundefined_65, eundefined_66, eundefined_67, eundefined_68, eundefined_69, eundefined_70, eundefined_71, eundefined_72, eundefined_73, eundefined_74, eundefined_75, eundefined_76, eundefined_77, eundefined_78, eundefined_79, eundefined_80, eundefined_81, eundefined_82, eundefined_83, eundefined_84, eundefined_85, eundefined_86, eundefined_87, eundefined_88, eundefined_89, eundefined_90, eWM_INPUT_DEVICE_CHANGE, eWM_INPUT, eWM_KEYDOWN, eWM_KEYUP, eWM_CHAR, eWM_DEADCHAR, eWM_SYSKEYDOWN, eWM_SYSKEYUP, eWM_SYSCHAR, eWM_SYSDEADCHAR, eWM_YOMICHAR, eWM_UNICHAR, eWM_CONVERTREQUEST, eWM_CONVERTRESULT, eWM_INTERIM, eWM_IME_STARTCOMPOSITION, eWM_IME_ENDCOMPOSITION, eWM_IME_COMPOSITION, eWM_INITDIALOG, eWM_COMMAND, eWM_SYSCOMMAND, eWM_TIMER, eWM_HSCROLL, eWM_VSCROLL, eWM_INITMENU, eWM_INITMENUPOPUP, eWM_SYSTIMER, eWM_GESTURE, eWM_GESTURENOTIFY, eWM_GESTUREINPUT, eWM_GESTURENOTIFIED, eundefined_91, eundefined_92, eWM_MENUSELECT, eWM_MENUCHAR, eWM_ENTERIDLE, eWM_MENURBUTTONUP, eWM_MENUDRAG, eWM_MENUGETOBJECT, eWM_UNINITMENUPOPUP, eWM_MENUCOMMAND, eWM_CHANGEUISTATE, eWM_UPDATEUISTATE, eWM_QUERYUISTATE, eundefined_93, eundefined_94, eundefined_95, eundefined_96, eundefined_97, eundefined_98, eundefined_99, eWM_LBTRACKPOINT, eWM_CTLCOLORMSGBOX, eWM_CTLCOLOREDIT, eWM_CTLCOLORLISTBOX, eWM_CTLCOLORBTN, eWM_CTLCOLORDLG, eWM_CTLCOLORSCROLLBAR, eWM_CTLCOLORSTATIC, eundefined_100, eundefined_101, eundefined_102, eundefined_103, eundefined_104, eundefined_105, eundefined_106, eCB_GETEDITSEL, eCB_LIMITTEXT, eCB_SETEDITSEL, eCB_ADDSTRING, eCB_DELETESTRING, eCB_DIR, eCB_GETCOUNT, eCB_GETCURSEL, eCB_GETLBTEXT, eCB_GETLBTEXTLEN, eCB_INSERTSTRING, eCB_RESETCONTENT, eCB_FINDSTRING, eCB_SELECTSTRING, eCB_SETCURSEL, eCB_SHOWDROPDOWN, eCB_GETITEMDATA, eCB_SETITEMDATA, eCB_GETDROPPEDCONTROLRECT, eCB_SETITEMHEIGHT, eCB_GETITEMHEIGHT, eCB_SETEXTENDEDUI, eCB_GETEXTENDEDUI, eCB_GETDROPPEDSTATE, eCB_FINDSTRINGEXACT, eCB_SETLOCALE, eCB_GETLOCALE, eCB_GETTOPINDEX, eCB_SETTOPINDEX, eCB_GETHORIZONTALEXTENT, eCB_SETHORIZONTALEXTENT, eCB_GETDROPPEDWIDTH, eCB_SETDROPPEDWIDTH, eCB_INITSTORAGE, eCB_MSGMAX_OLD, eCB_MULTIPLEADDSTRING, eCB_GETCOMBOBOXINFO, eCB_MSGMAX, eCBEC_SETCOMBOFOCUS, eCBEC_KILLCOMBOFOCUS, eundefined_109, eundefined_110, eundefined_111, eundefined_112, eundefined_113, eundefined_114, eundefined_115, eundefined_116, eundefined_117, eundefined_118, eundefined_119, eundefined_120, eundefined_121, eundefined_122, eundefined_123, eundefined_124, eundefined_125, eundefined_126, eundefined_127, eundefined_128, eundefined_129, eundefined_130, eundefined_131, eundefined_132, eLB_ADDSTRING, eLB_INSERTSTRING, eLB_DELETESTRING, eLB_SELITEMRANGEEX, eLB_RESETCONTENT, eLB_SETSEL, eLB_SETCURSEL, eLB_GETSEL, eLB_GETCURSEL, eLB_GETTEXT, eLB_GETTEXTLEN, eLB_GETCOUNT, eLB_SELECTSTRING, eLB_DIR, eLB_GETTOPINDEX, eLB_FINDSTRING, eLB_GETSELCOUNT, eLB_GETSELITEMS, eLB_SETTABSTOPS, eLB_GETHORIZONTALEXTENT, eLB_SETHORIZONTALEXTENT, eLB_SETCOLUMNWIDTH, eLB_ADDFILE, eLB_SETTOPINDEX, eLB_GETITEMRECT, eLB_GETITEMDATA, eLB_SETITEMDATA, eLB_SELITEMRANGE, eLB_SETANCHORINDEX, eLB_GETANCHORINDEX, eLB_SETCARETINDEX, eLB_GETCARETINDEX, eLB_SETITEMHEIGHT, eLB_GETITEMHEIGHT, eLB_FINDSTRINGEXACT, eLBCB_CARETON, eLBCB_CARETOFF, eLB_SETLOCALE, eLB_GETLOCALE, eLB_SETCOUNT, eLB_INITSTORAGE, eLB_ITEMFROMPOINT, eLB_INSERTSTRINGUPPER, eLB_INSERTSTRINGLOWER, eLB_ADDSTRINGUPPER, eLB_ADDSTRINGLOWER, eLBCB_STARTTRACK, eLBCB_ENDTRACK, eLB_MSGMAX_OLD, eLB_MULTIPLEADDSTRING, eLB_GETLISTBOXINFO, eLB_MSGMAX, eundefined_133, eundefined_134, eundefined_135, eundefined_136, eundefined_137, eundefined_138, eundefined_139, eundefined_140, eundefined_141, eundefined_142, eundefined_143, eundefined_144, eundefined_145, eundefined_146, eundefined_147, eundefined_148, eundefined_149, eundefined_150, eundefined_151, eundefined_152, eundefined_153, eundefined_154, eundefined_155, eundefined_156, eundefined_157, eundefined_158, eundefined_159, eundefined_160, eundefined_161, eundefined_162, eundefined_163, eundefined_164, eundefined_165, eundefined_166, eundefined_167, eundefined_168, eundefined_169, eundefined_170, eundefined_171, eundefined_172, eundefined_173, eundefined_174, eundefined_175, eundefined_176, eMN_FIRST, eMN_GETHMENU, eMN_SIZEWINDOW, eMN_OPENHIERARCHY, eMN_CLOSEHIERARCHY, eMN_SELECTITEM, eMN_CANCELMENUS, eMN_SELECTFIRSTVALIDITEM, eundefined_183, eundefined_184, eMN_GETPPOPUPMENU, eMN_FINDMENUWINDOWFROMPOINT, // returns HWND or zero eMN_SHOWPOPUPWINDOW, eMN_BUTTONDOWN, eMN_MOUSEMOVE, eMN_BUTTONUP, eMN_SETTIMERTOOPENHIERARCHY, eMN_DBLCLK, eundefined_193, eundefined_194, eundefined_195, eundefined_196, eundefined_197, eundefined_198, eundefined_199, eundefined_200, eundefined_201, eundefined_202, eundefined_203, eundefined_204, eundefined_205, eundefined_206, eWM_MOUSEMOVE, eWM_LBUTTONDOWN, eWM_LBUTTONUP, eWM_LBUTTONDBLCLK, eWM_RBUTTONDOWN, eWM_RBUTTONUP, eWM_RBUTTONDBLCLK, eWM_MBUTTONDOWN, eWM_MBUTTONUP, eWM_MBUTTONDBLCLK, eWM_MOUSEWHEEL, eWM_XBUTTONDOWN, eWM_XBUTTONUP, eWM_XBUTTONDBLCLK, eWM_MOUSEHWHEEL, eundefined_207, eWM_PARENTNOTIFY, eWM_ENTERMENULOOP, eWM_EXITMENULOOP, eWM_NEXTMENU, eWM_SIZING, eWM_CAPTURECHANGED, eWM_MOVING, eundefined_208, eWM_POWERBROADCAST, eWM_DEVICECHANGE, eundefined_209, eundefined_210, eundefined_211, eundefined_212, eundefined_213, eundefined_214, eWM_MDICREATE, eWM_MDIDESTROY, eWM_MDIACTIVATE, eWM_MDIRESTORE, eWM_MDINEXT, eWM_MDIMAXIMIZE, eWM_MDITILE, eWM_MDICASCADE, eWM_MDIICONARRANGE, eWM_MDIGETACTIVE, eWM_DROPOBJECT, eWM_QUERYDROPOBJECT, eWM_BEGINDRAG, eWM_DRAGLOOP, eWM_DRAGSELECT, eWM_DRAGMOVE, eWM_MDISETMENU, eWM_ENTERSIZEMOVE, eWM_EXITSIZEMOVE, eWM_DROPFILES, eWM_MDIREFRESHMENU, eundefined_215, eundefined_216, eundefined_217, eWM_POINTERDEVICECHANGE, eWM_POINTERDEVICEINRANGE, eWM_POINTERDEVICEOUTOFRANGE, eWM_STOPINERTIA, eWM_ENDINERTIA, eWM_EDGYINERTIA, eundefined_218, eundefined_219, eWM_TOUCH, eWM_NCPOINTERUPDATE, eWM_NCPOINTERDOWN, eWM_NCPOINTERUP, eWM_NCPOINTERLAST, eWM_POINTERUPDATE, eWM_POINTERDOWN, eWM_POINTERUP, eWM_POINTER_reserved_248, eWM_POINTERENTER, eWM_POINTERLEAVE, eWM_POINTERACTIVATE, eWM_POINTERCAPTURECHANGED, eWM_TOUCHHITTESTING, eWM_POINTERWHEEL, eWM_POINTERHWHEEL, eWM_POINTER_reserved_250, eWM_POINTER_reserved_251, eWM_POINTER_reserved_252, eWM_POINTER_reserved_253, eWM_POINTER_reserved_254, eWM_POINTER_reserved_255, eWM_POINTER_reserved_256, eWM_POINTERLAST, eundefined_220, eundefined_221, eundefined_222, eundefined_223, eundefined_224, eundefined_225, eundefined_226, eundefined_227, eundefined_228, eundefined_229, eundefined_230, eundefined_231, eundefined_232, eundefined_233, eundefined_234, eundefined_235, eundefined_236, eundefined_237, eundefined_238, eundefined_239, eundefined_240, eundefined_241, eundefined_242, eundefined_243, eWM_VISIBILITYCHANGED, eWM_VIEWSTATECHANGED, eWM_UNREGISTER_WINDOW_SERVICES, eWM_CONSOLIDATED, eundefined_244, eundefined_245, eundefined_246, eundefined_247, eundefined_248, eundefined_249, eundefined_250, eundefined_251, eundefined_252, eundefined_253, eundefined_254, eundefined_255, eWM_IME_REPORT, eWM_IME_SETCONTEXT, eWM_IME_NOTIFY, eWM_IME_CONTROL, eWM_IME_COMPOSITIONFULL, eWM_IME_SELECT, eWM_IME_CHAR, eWM_IME_SYSTEM, eWM_IME_REQUEST, eWM_KANJI_reserved_289, eWM_KANJI_reserved_28a, eWM_KANJI_reserved_28b, eWM_KANJI_reserved_28c, eWM_KANJI_reserved_28d, eWM_KANJI_reserved_28e, eWM_KANJI_reserved_28f, eWM_IME_KEYDOWN, eWM_IME_KEYUP, eWM_KANJI_reserved_292, eWM_KANJI_reserved_293, eWM_KANJI_reserved_294, eWM_KANJI_reserved_295, eWM_KANJI_reserved_296, eWM_KANJI_reserved_297, eWM_KANJI_reserved_298, eWM_KANJI_reserved_299, eWM_KANJI_reserved_29a, eWM_KANJI_reserved_29b, eWM_KANJI_reserved_29c, eWM_KANJI_reserved_29d, eWM_KANJI_reserved_29e, eWM_KANJILAST, eWM_NCMOUSEHOVER, eWM_MOUSEHOVER, eWM_NCMOUSELEAVE, eWM_MOUSELEAVE, eWM_TRACKMOUSEEVENT__reserved_2a4, eWM_TRACKMOUSEEVENT__reserved_2a5, eWM_TRACKMOUSEEVENT__reserved_2a6, eWM_TRACKMOUSEEVENT__reserved_2a7, eWM_TRACKMOUSEEVENT__reserved_2a8, eWM_TRACKMOUSEEVENT__reserved_2a9, eWM_TRACKMOUSEEVENT__reserved_2aa, eWM_TRACKMOUSEEVENT__reserved_2ab, eWM_TRACKMOUSEEVENT__reserved_2ac, eWM_TRACKMOUSEEVENT__reserved_2ad, eWM_TRACKMOUSEEVENT__reserved_2ae, eWM_TRACKMOUSEEVENT_LAST, eundefined_256, eWM_WTSSESSION_CHANGE, eundefined_257, eundefined_258, eundefined_259, eundefined_260, eundefined_261, eundefined_262, eundefined_263, eundefined_264, eundefined_265, eundefined_266, eundefined_267, eundefined_268, eundefined_269, eundefined_270, eWM_TABLET_FIRST, eWM_TABLET__reserved_2c1, eWM_TABLET__reserved_2c2, eWM_TABLET__reserved_2c3, eWM_TABLET__reserved_2c4, eWM_TABLET__reserved_2c5, eWM_TABLET__reserved_2c6, eWM_TABLET__reserved_2c7, eWM_POINTERDEVICEADDED, eWM_POINTERDEVICEDELETED, eWM_TABLET__reserved_2ca, eWM_FLICK, eWM_TABLET__reserved_2cc, eWM_FLICKINTERNAL, eWM_BRIGHTNESSCHANGED, eWM_TABLET__reserved_2cf, eWM_TABLET__reserved_2d0, eWM_TABLET__reserved_2d1, eWM_TABLET__reserved_2d2, eWM_TABLET__reserved_2d3, eWM_TABLET__reserved_2d4, eWM_TABLET__reserved_2d5, eWM_TABLET__reserved_2d6, eWM_TABLET__reserved_2d7, eWM_TABLET__reserved_2d8, eWM_TABLET__reserved_2d9, eWM_TABLET__reserved_2da, eWM_TABLET__reserved_2db, eWM_TABLET__reserved_2dc, eWM_TABLET__reserved_2dd, eWM_TABLET__reserved_2de, eWM_TABLET_LAST, eWM_DPICHANGED, eundefined_271, eundefined_272, eundefined_273, eundefined_274, eundefined_275, eundefined_276, eundefined_277, eundefined_278, eundefined_279, eundefined_280, eundefined_281, eundefined_282, eundefined_283, eundefined_284, eundefined_285, eundefined_286, eundefined_287, eundefined_288, eundefined_289, eundefined_290, eundefined_291, eundefined_292, eundefined_293, eundefined_294, eundefined_295, eundefined_296, eundefined_297, eundefined_298, eundefined_299, eundefined_300, eundefined_301, eWM_CUT, eWM_COPY, eWM_PASTE, eWM_CLEAR, eWM_UNDO, eWM_RENDERFORMAT, eWM_RENDERALLFORMATS, eWM_DESTROYCLIPBOARD, eWM_DRAWCLIPBOARD, eWM_PAINTCLIPBOARD, eWM_VSCROLLCLIPBOARD, eWM_SIZECLIPBOARD, eWM_ASKCBFORMATNAME, eWM_CHANGECBCHAIN, eWM_HSCROLLCLIPBOARD, eWM_QUERYNEWPALETTE, eWM_PALETTEISCHANGING, eWM_PALETTECHANGED, eWM_HOTKEY, eWM_SYSMENU, eWM_HOOKMSG, eWM_EXITPROCESS, eWM_WAKETHREAD, eWM_PRINT, eWM_PRINTCLIENT, eWM_APPCOMMAND, eWM_THEMECHANGED, eWM_UAHINIT, eWM_DESKTOPNOTIFY, eWM_CLIPBOARDUPDATE, eWM_DWMCOMPOSITIONCHANGED, eWM_DWMNCRENDERINGCHANGED, eWM_DWMCOLORIZATIONCOLORCHANGED, eWM_DWMWINDOWMAXIMIZEDCHANGE, eWM_DWMEXILEFRAME, eWM_DWMSENDICONICTHUMBNAIL, eWM_MAGNIFICATION_STARTED, eWM_MAGNIFICATION_ENDED, eWM_DWMSENDICONICLIVEPREVIEWBITMAP, eWM_DWMTHUMBNAILSIZECHANGED, eWM_MAGNIFICATION_OUTPUT, eWM_BSDRDATA, eWM_DWMTRANSITIONSTATECHANGED, eundefined_302, eWM_KEYBOARDCORRECTIONCALLOUT, eWM_KEYBOARDCORRECTIONACTION, eWM_UIACTION, eWM_ROUTED_UI_EVENT, eWM_MEASURECONTROL, eWM_GETACTIONTEXT, eWM_CE_ONLY__reserved_332, eWM_FORWARDKEYDOWN, eWM_FORWARDKEYUP, eWM_CE_ONLY__reserved_335, eWM_CE_ONLY__reserved_336, eWM_CE_ONLY__reserved_337, eWM_CE_ONLY__reserved_338, eWM_CE_ONLY__reserved_339, eWM_CE_ONLY__reserved_33a, eWM_CE_ONLY__reserved_33b, eWM_CE_ONLY__reserved_33c, eWM_CE_ONLY__reserved_33d, eWM_CE_ONLY_LAST, eWM_GETTITLEBARINFOEX, eWM_NOTIFYWOW, eundefined_303, eundefined_304, eundefined_305, eundefined_306, eundefined_307, eundefined_308, eundefined_309, eundefined_310, eundefined_311, eundefined_312, eundefined_313, eundefined_314, eundefined_315, eundefined_316, eundefined_317, eundefined_318, eundefined_319, eundefined_320, eundefined_321, eundefined_322, eundefined_323, eundefined_324, eundefined_325, eWM_HANDHELDFIRST, eWM_HANDHELD_reserved_359, eWM_HANDHELD_reserved_35a, eWM_HANDHELD_reserved_35b, eWM_HANDHELD_reserved_35c, eWM_HANDHELD_reserved_35d, eWM_HANDHELD_reserved_35e, eWM_HANDHELDLAST, eWM_AFXFIRST, eWM_AFX_reserved_361, eWM_AFX_reserved_362, eWM_AFX_reserved_363, eWM_AFX_reserved_364, eWM_AFX_reserved_365, eWM_AFX_reserved_366, eWM_AFX_reserved_367, eWM_AFX_reserved_368, eWM_AFX_reserved_369, eWM_AFX_reserved_36a, eWM_AFX_reserved_36b, eWM_AFX_reserved_36c, eWM_AFX_reserved_36d, eWM_AFX_reserved_36e, eWM_AFX_reserved_36f, eWM_AFX_reserved_370, eWM_AFX_reserved_371, eWM_AFX_reserved_372, eWM_AFX_reserved_373, eWM_AFX_reserved_374, eWM_AFX_reserved_375, eWM_AFX_reserved_376, eWM_AFX_reserved_377, eWM_AFX_reserved_378, eWM_AFX_reserved_379, eWM_AFX_reserved_37a, eWM_AFX_reserved_37b, eWM_AFX_reserved_37c, eWM_AFX_reserved_37d, eWM_AFX_reserved_37e, eWM_AFXLAST, eWM_PENWINFIRST, eWM_PENWIN_reserved_381, eWM_PENWIN_reserved_382, eWM_PENWIN_reserved_383, eWM_PENWIN_reserved_384, eWM_PENWIN_reserved_385, eWM_PENWIN_reserved_386, eWM_PENWIN_reserved_387, eWM_PENWIN_reserved_388, eWM_PENWIN_reserved_389, eWM_PENWIN_reserved_38a, eWM_PENWIN_reserved_38b, eWM_PENWIN_reserved_38c, eWM_PENWIN_reserved_38d, eWM_PENWIN_reserved_38e, eWM_PENWINLAST, eWM_COALESCE_FIRST, eWM_COALESCE__reserved_391, eWM_COALESCE__reserved_392, eWM_COALESCE__reserved_393, eWM_COALESCE__reserved_394, eWM_COALESCE__reserved_395, eWM_COALESCE__reserved_396, eWM_COALESCE__reserved_397, eWM_COALESCE__reserved_398, eWM_COALESCE__reserved_399, eWM_COALESCE__reserved_39a, eWM_COALESCE__reserved_39b, eWM_COALESCE__reserved_39c, eWM_COALESCE__reserved_39d, eWM_COALESCE__reserved_39e, eWM_COALESCE_LAST, eWM_MM_RESERVED_FIRST, eWM_MM_RESERVED__reserved_3a1, eWM_MM_RESERVED__reserved_3a2, eWM_MM_RESERVED__reserved_3a3, eWM_MM_RESERVED__reserved_3a4, eWM_MM_RESERVED__reserved_3a5, eWM_MM_RESERVED__reserved_3a6, eWM_MM_RESERVED__reserved_3a7, eWM_MM_RESERVED__reserved_3a8, eWM_MM_RESERVED__reserved_3a9, eWM_MM_RESERVED__reserved_3aa, eWM_MM_RESERVED__reserved_3ab, eWM_MM_RESERVED__reserved_3ac, eWM_MM_RESERVED__reserved_3ad, eWM_MM_RESERVED__reserved_3ae, eWM_MM_RESERVED__reserved_3af, eWM_MM_RESERVED__reserved_3b0, eWM_MM_RESERVED__reserved_3b1, eWM_MM_RESERVED__reserved_3b2, eWM_MM_RESERVED__reserved_3b3, eWM_MM_RESERVED__reserved_3b4, eWM_MM_RESERVED__reserved_3b5, eWM_MM_RESERVED__reserved_3b6, eWM_MM_RESERVED__reserved_3b7, eWM_MM_RESERVED__reserved_3b8, eWM_MM_RESERVED__reserved_3b9, eWM_MM_RESERVED__reserved_3ba, eWM_MM_RESERVED__reserved_3bb, eWM_MM_RESERVED__reserved_3bc, eWM_MM_RESERVED__reserved_3bd, eWM_MM_RESERVED__reserved_3be, eWM_MM_RESERVED__reserved_3bf, eWM_MM_RESERVED__reserved_3c0, eWM_MM_RESERVED__reserved_3c1, eWM_MM_RESERVED__reserved_3c2, eWM_MM_RESERVED__reserved_3c3, eWM_MM_RESERVED__reserved_3c4, eWM_MM_RESERVED__reserved_3c5, eWM_MM_RESERVED__reserved_3c6, eWM_MM_RESERVED__reserved_3c7, eWM_MM_RESERVED__reserved_3c8, eWM_MM_RESERVED__reserved_3c9, eWM_MM_RESERVED__reserved_3ca, eWM_MM_RESERVED__reserved_3cb, eWM_MM_RESERVED__reserved_3cc, eWM_MM_RESERVED__reserved_3cd, eWM_MM_RESERVED__reserved_3ce, eWM_MM_RESERVED__reserved_3cf, eWM_MM_RESERVED__reserved_3d0, eWM_MM_RESERVED__reserved_3d1, eWM_MM_RESERVED__reserved_3d2, eWM_MM_RESERVED__reserved_3d3, eWM_MM_RESERVED__reserved_3d4, eWM_MM_RESERVED__reserved_3d5, eWM_MM_RESERVED__reserved_3d6, eWM_MM_RESERVED__reserved_3d7, eWM_MM_RESERVED__reserved_3d8, eWM_MM_RESERVED__reserved_3d9, eWM_MM_RESERVED__reserved_3da, eWM_MM_RESERVED__reserved_3db, eWM_MM_RESERVED__reserved_3dc, eWM_MM_RESERVED__reserved_3dd, eWM_MM_RESERVED__reserved_3de, eWM_MM_RESERVED_LAST, eWM_INTERNAL_DDE_FIRST, eWM_INTERNAL_DDE__reserved_3e1, eWM_INTERNAL_DDE__reserved_3e2, eWM_INTERNAL_DDE__reserved_3e3, eWM_INTERNAL_DDE__reserved_3e4, eWM_INTERNAL_DDE__reserved_3e5, eWM_INTERNAL_DDE__reserved_3e6, eWM_INTERNAL_DDE__reserved_3e7, eWM_INTERNAL_DDE__reserved_3e8, eWM_INTERNAL_DDE__reserved_3e9, eWM_INTERNAL_DDE__reserved_3ea, eWM_INTERNAL_DDE__reserved_3eb, eWM_INTERNAL_DDE__reserved_3ec, eWM_INTERNAL_DDE__reserved_3ed, eWM_INTERNAL_DDE__reserved_3ee, eWM_INTERNAL_DDE_LAST, eWM_CBT_RESERVED_FIRST, eWM_CBT_RESERVED__reserved_3f1, eWM_CBT_RESERVED__reserved_3f2, eWM_CBT_RESERVED__reserved_3f3, eWM_CBT_RESERVED__reserved_3f4, eWM_CBT_RESERVED__reserved_3f5, eWM_CBT_RESERVED__reserved_3f6, eWM_CBT_RESERVED__reserved_3f7, eWM_CBT_RESERVED__reserved_3f8, eWM_CBT_RESERVED__reserved_3f9, eWM_CBT_RESERVED__reserved_3fa, eWM_CBT_RESERVED__reserved_3fb, eWM_CBT_RESERVED__reserved_3fc, eWM_CBT_RESERVED__reserved_3fd, eWM_CBT_RESERVED__reserved_3fe, eWM_CBT_RESERVED_LAST, }; // Window Styles Helper enums. enum class WindowStyle : DWORD { None, Child = WS_CHILD, Border = WS_BORDER, Caption = WS_CAPTION, ClipChildren = WS_CLIPCHILDREN, TabStop = WS_TABSTOP, LBS_MultiSel = LBS_MULTIPLESEL, LBS_ExtendedSel = LBS_EXTENDEDSEL, LBS_UseTabStops = LBS_USETABSTOPS, BS_Bitmap = BS_BITMAP, BS_OwnerDraw = BS_OWNERDRAW, SS_EndEllipsis = SS_ENDELLIPSIS, SS_PathEllipsis = SS_PATHELLIPSIS, SS_NoPrefix = SS_NOPREFIX, SS_LeftNoWordWrap = SS_LEFTNOWORDWRAP, SS_Center = SS_CENTER, SS_Right = SS_RIGHT, ES_MultiLine = ES_MULTILINE, ES_Password = ES_PASSWORD, ES_ReadOnly = ES_READONLY, TVS_CheckBoxes = TVS_CHECKBOXES, CCS_NoParentAlign = CCS_NOPARENTALIGN, CCS_NoResize = CCS_NORESIZE, TCS_ForceLeftAlign = TCS_FORCELABELLEFT, PBS_Vertical = PBS_VERTICAL, MCS_MultiSelect = MCS_MULTISELECT, LVS_SingleSelect = LVS_SINGLESEL, LVS_ShowSelAlways = LVS_SHOWSELALWAYS, CBS_DropDown = CBS_DROPDOWN, CBS_Simple = CBS_SIMPLE, DTS_ShowNone = DTS_SHOWNONE }; enum class WindowExStyle : DWORD { None, DialogModalFrame = WS_EX_DLGMODALFRAME, ParentNotify = WS_EX_NOPARENTNOTIFY, TopMost = WS_EX_TOPMOST, AcceptFiles = WS_EX_ACCEPTFILES, Transparent = WS_EX_TRANSPARENT, MDIChild = WS_EX_MDICHILD, ToolWindow = WS_EX_TOOLWINDOW, WindowEdge = WS_EX_WINDOWEDGE, ControlParent = WS_EX_CONTROLPARENT, ClientEdge = WS_EX_CLIENTEDGE, Composited = WS_EX_COMPOSITED, Layered = WS_EX_LAYERED }; enum class WindowAnimStyle : DWORD { None }; template <EnumConcepts::IsNumeric T> constexpr WindowStyle to_WindowStyle(T other) noexcept { return gsl::narrow_cast<WindowStyle>(other); } template <EnumConcepts::IsNumeric T> constexpr WindowExStyle to_WindowExStyle(T other) noexcept { return gsl::narrow_cast<WindowExStyle>(other); } inline WindowStyle dcxGetWindowStyle(HWND Hwnd) noexcept { return to_WindowStyle(GetWindowLong(Hwnd, GWL_STYLE)); } inline WindowExStyle dcxGetWindowExStyle(HWND Hwnd) noexcept { return to_WindowExStyle(GetWindowLong(Hwnd, GWL_EXSTYLE)); } inline WindowStyle dcxSetWindowStyle(HWND Hwnd, WindowStyle style) noexcept { return to_WindowStyle(SetWindowLongPtr(Hwnd, GWL_STYLE, gsl::narrow_cast<LONG>(style))); } inline WindowExStyle dcxSetWindowExStyle(HWND Hwnd, WindowExStyle style) noexcept { return to_WindowExStyle(SetWindowLongPtr(Hwnd, GWL_EXSTYLE, gsl::narrow_cast<LONG>(style))); } inline HWND dcxCreateWindow(const WindowExStyle ExStyles, const TCHAR* const szClass, const WindowStyle Styles, const RECT* const rc, HWND hParent, const UINT uID, const void* const pthis = nullptr) noexcept { return CreateWindowEx( gsl::narrow_cast<DWORD>(ExStyles), szClass, nullptr, gsl::narrow_cast<DWORD>(Styles), rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top, hParent, (HMENU)uID, GetModuleHandle(nullptr), (LPVOID)pthis); } inline UINT dcxSetWindowID(HWND Hwnd, const UINT uID) noexcept { return gsl::narrow_cast<UINT>(SetWindowLongPtr(Hwnd, GWLP_ID, gsl::narrow_cast<LONG>(uID))); }
{ "alphanum_fraction": 0.8039099292, "avg_line_length": 21.9539530843, "ext": "h", "hexsha": "8a2459930ef480c27c7746c66169811319f7d35a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2018-08-04T23:53:29.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-01T09:39:33.000Z", "max_forks_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "twig/dcxdll", "max_forks_repo_path": "Classes/WindowStyles.h", "max_issues_count": 68, "max_issues_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:33:50.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-06T16:23:35.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "twig/dcxdll", "max_issues_repo_path": "Classes/WindowStyles.h", "max_line_length": 208, "max_stars_count": 18, "max_stars_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "twig/dcxdll", "max_stars_repo_path": "Classes/WindowStyles.h", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:48:31.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-21T05:41:19.000Z", "num_tokens": 8001, "size": 25269 }
#ifndef _MATH_UTIL_EULER_H_ #define _MATH_UTIL_EULER_H_ /* space group numbers for structures known by this program */ /* these are from the International Tables, allowed values are [1-230] */ /* * #define FCC 225 * #define BCC 229 * #define DIA 227 * #define SIMPLE_CUBIC 221 * #define HEX 194 * #define SAPPHIRE 167 * #define TRICLINIC 1 */ #ifndef CHECK_FREE #define CHECK_FREE(A) { if(A) free(A); (A)=NULL;} #endif #ifdef _MSC_VER /* identifies this as a Microsoft compiler */ #include <gsl/gsl_math.h> /* added RX2011 for NaN handling */ #define round(A) ceil(A-0.5) /* added RX2011 for round() function */ #define NAN gsl_nan() /* added RX2011 */ #define isNAN(A) gsl_isnan(A) /* added RX2011 */ #endif #ifndef NAN /* probably only needed for pcs */ #define NAN nan("") /* probably only needed for cygwin on pc */ #endif #ifndef isNAN /* a good test for NAN */ #define isNAN(A) ( (A) != (A) ) #endif #define VECTOR_COPY3(A,B) {A[0]=B[0]; A[1]=B[1]; A[2]=B[2];} void DeletePoints(size_t len, void *ptr, size_t pntLen, size_t numDel); void EulerMatrix(double alpha,double beta,double gamma,double M_Euler[3][3]); void rot2EulerAngles(double A[3][3], double *alpha, double *beta, double *gamma); void MatrixRz(double Rz[3][3],double angle); void MatrixRy(double Ry[3][3],double angle); /* void lowestOrderHKL(int hkl[3]); */ /* void lowestAllowedHKL(int hkl[3], int structure); */ /* long allowedHKL(long h, long k, long l, int structure); */ int gcf(int n1, int n2, int n3); double normalize3(double a[3]); void cross(double a[3], double b[3], double c[3]); void vector3cons(double a[3], double x); double dot3(double a[3],double b[3]); double determinant33(double a[3][3]); void MatrixMultiply31(double a[3][3], double v[3], double c[3]); void MatrixMultiply33(double a[3][3], double b[3][3], double c[3][3]); void MatrixTranspose33(double A[3][3]); /* transpose the 3x3 matrix A */ void MatrixCopy33(double dest[3][3], double source[3][3]); double diff3(double a[3], double b[3]); double matsDelta(double a[3][3], double b[3][3]); char *num2sexigesmal(char str[40], double seconds, long places); #endif
{ "alphanum_fraction": 0.6815874481, "avg_line_length": 31.8676470588, "ext": "h", "hexsha": "55549a6f6fcf40456aa88b437145e6a4ee48be76", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-21T17:48:28.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-21T17:48:28.000Z", "max_forks_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carterbox/cold", "max_forks_repo_path": "legacy/Euler3/include/mathUtil.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:34:20.000Z", "max_issues_repo_issues_event_min_datetime": "2022-01-21T17:14:55.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "carterbox/cold", "max_issues_repo_path": "legacy/Euler3/include/mathUtil.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carterbox/cold", "max_stars_repo_path": "legacy/Euler3/include/mathUtil.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 668, "size": 2167 }
#ifndef __QBLAS_EXTEND__CD #define __QBLAS_EXTEND__CD #ifdef HAVE_CBLAS_H #include <cblas.h> #elif (defined HAVE_MKL_CBLAS_H) #include <mkl_cblas.h> #elif (defined HAVE_GSL_CBLAS_H) #include <gsl_cblas.h> #endif /* some convenience functions for the case where all vectors are continguous in memory */ inline void cblas_daxpy(const int N, const double alpha, const double *X, double *Y) { cblas_daxpy(N,alpha,X,1,Y,1); } inline double cblas_dnrm2(const int N, const double *X) { return cblas_dnrm2(N,X,1); } inline void cblas_dcopy(const int N, const double *X, double *Y ) { cblas_dcopy(N,X,1,Y,1); } inline void cblas_dscal(const int N, const double alpha, double *X) { cblas_dscal(N,alpha,X,1); } inline double cblas_ddot(const int N, const double *X, const double *Y ) { return cblas_ddot(N,X,1,Y,1); } inline double cblas_ddot(const int N, const double *X) { return cblas_ddot(N,X,1,X,1); } inline void cblas_zdotc_sub(const int N, const double *X, const double *Y, double* dot) { return cblas_zdotc_sub(N,X,1,Y,1, dot); } //inline void cblas_cdotc_sub(const int N, const float *X, const float *Y, // float* dot) //{ return cblas_cdotc_sub(N,X,Y,dot); } #endif
{ "alphanum_fraction": 0.6123755334, "avg_line_length": 25.1071428571, "ext": "h", "hexsha": "75b83e51976eb063ca39b9a0c9e7f4e27c16f971", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-12-02T20:41:09.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-16T05:55:57.000Z", "max_forks_repo_head_hexsha": "329cd411d01dce8e3409335f55e478dac3c3bca4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "RBC-UKQCD/CPS", "max_forks_repo_path": "cps_pp/include/util/qblas_extend.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "329cd411d01dce8e3409335f55e478dac3c3bca4", "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": "RBC-UKQCD/CPS", "max_issues_repo_path": "cps_pp/include/util/qblas_extend.h", "max_line_length": 74, "max_stars_count": 7, "max_stars_repo_head_hexsha": "329cd411d01dce8e3409335f55e478dac3c3bca4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "RBC-UKQCD/CPS", "max_stars_repo_path": "cps_pp/include/util/qblas_extend.h", "max_stars_repo_stars_event_max_datetime": "2021-12-02T20:41:00.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-24T02:20:36.000Z", "num_tokens": 404, "size": 1406 }
#pragma once #include <ntdll.h> #include <gsl/span> #include <gsl/span_ext> #include "module.h" namespace pe { class module; class segment : public IMAGE_SECTION_HEADER { public: segment() = delete; const class module *module() const; class module *module(); std::string_view name() const; gsl::span<uint8_t> as_bytes(); gsl::span<const uint8_t> as_bytes() const; bool contains_code() const; bool contains_initialized_data() const; bool contains_uninitialized_data() const; uint32_t relocation_count() const; bool discardable() const; bool not_cached() const; bool not_paged() const; bool shared() const; bool executable() const; bool readable() const; bool writable() const; }; } #include "segment.inl"
{ "alphanum_fraction": 0.6768447837, "avg_line_length": 21.8333333333, "ext": "h", "hexsha": "183e1c83ff5727f20044694505e3942a549371ab", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-18T18:03:36.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-18T18:03:36.000Z", "max_forks_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bnsmodpolice/loginhelper", "max_forks_repo_path": "include/pe/segment.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "bnsmodpolice/loginhelper", "max_issues_repo_path": "include/pe/segment.h", "max_line_length": 46, "max_stars_count": 3, "max_stars_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bnsmodpolice/loginhelper", "max_stars_repo_path": "include/pe/segment.h", "max_stars_repo_stars_event_max_datetime": "2021-02-22T20:48:03.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-18T04:53:41.000Z", "num_tokens": 192, "size": 786 }
/* The VCL screen capture library is released under the MIT license. * * Copyright(c) 2018 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 // Abseil #include <absl/strings/string_view.h> // C++ standard library #include <array> #include <utility> // GSL #include <gsl/gsl> #ifdef VCL_GRAPHICS_RECORDER_EXPORTS # define VCL_GRAPHICS_RECORDER_API __declspec(dllexport) #else # define VCL_GRAPHICS_RECORDER_API __declspec(dllimport) #endif extern "C" { struct AVCodec; struct AVCodecContext; struct AVCodecParameters; struct AVFormatContext; struct AVFrame; struct AVStream; } namespace Vcl { namespace Graphics { namespace Recorder { enum class OutputFormat { Avi, Mkv, Mp4 }; enum class CodecType { H264 }; class VCL_GRAPHICS_RECORDER_API Recorder { public: Recorder(OutputFormat out_fmt, CodecType codec); ~Recorder(); public: void open(absl::string_view sink_name, unsigned int width, unsigned int height, unsigned int frame_rate); void close(); bool write(gsl::span<const uint8_t> Y, gsl::span<const uint8_t> U, gsl::span<const uint8_t> V); bool write(gsl::span<const uint8_t> Y, gsl::span<const std::array<uint8_t, 2>> UV); bool write(gsl::span<const std::array<uint8_t, 3>> rgb, unsigned int w, unsigned int h); private: //! Create the output format //! \param fmt Format to create //! \param ctx Context to assign the output format to void createOutputFormat(OutputFormat fmt, gsl::not_null<AVFormatContext*> ctx) const; //! Prepare codec //! \param codec Codec to create std::pair<AVCodec*, AVCodecContext*> createCodec(CodecType codec_cfg) const; //! Configure specific H264 parameters void configureH264(); //! Write a single frame to the output //! \param frame Frame to write out. Use 'nullptr' to flush the codec. //! \note Notes about internal API used: //! * https://blogs.gentoo.org/lu_zero/2016/03/29/new-avcodec-api/ //! * https://www.ffmpeg.org/doxygen/3.4/group__lavc__encdec.html bool write(AVFrame* frame); //! Hold the formating of the IO container AVFormatContext* _fmtCtx{nullptr}; //! Recording stream AVStream* _videoStream{nullptr}; //! Actual codec AVCodec* _codec{nullptr}; //! Codec context AVCodecContext* _codecCtx{nullptr}; //! Is the output open bool _isOpen{false}; //! Temporary frames for data processing AVFrame* _processing_frame{nullptr}; //! Current frame count int64_t _frames{0}; }; }}}
{ "alphanum_fraction": 0.7328027288, "avg_line_length": 29.0743801653, "ext": "h", "hexsha": "ac315c9de64ecea793b8feaea01b3d962e9b3030", "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": "b5b69ddfbe0da1f3cecc74a5e99167511fb53b26", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bfierz/vcl.graphics.recorder", "max_forks_repo_path": "src/vcl/graphics/recorder/recorder.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b5b69ddfbe0da1f3cecc74a5e99167511fb53b26", "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.graphics.recorder", "max_issues_repo_path": "src/vcl/graphics/recorder/recorder.h", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "b5b69ddfbe0da1f3cecc74a5e99167511fb53b26", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bfierz/vcl.graphics.recorder", "max_stars_repo_path": "src/vcl/graphics/recorder/recorder.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 910, "size": 3518 }
// MILOS v2.0 (2020) // Milne-Eddington inversion code (based on IDL MILOS code by D. Orozco) // Manuel Cabrera, Juan P. Cobos, Luis Bellot (IAA-CSIC) // For questions, please contact lbellot@iaa.es // /* ; eta0 = line-to-continuum absorption coefficient ratio ; B = magnetic field strength [Gauss] ; vlos = line-of-sight velocity [km/s] ; dopp = Doppler width [Angstroms] ; aa = damping parameter ; gm = magnetic field inclination [deg] ; az = magnetic field azimuth [deg] ; S0 = source function constant ; S1 = source function gradient ; mac = macroturbulent velocity [km/s] ; alpha = filling factor of the magnetic component [0->1] */ #include <time.h> #include "defines.h" #include <string.h> #include <stdio.h> #include "/opt/local/cfitsio/cfitsio-3.350/include/fitsio.h" ///opt/local/cfitsio/cfitsio-3.350/include/ #include "utilsFits.h" #include "milosUtils.h" #include "lib.h" #include "readConfig.h" #include <unistd.h> #include <complex.h> #include <fftw3.h> //siempre a continuacion de complex.h #include <gsl/gsl_spline.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <libgen.h> int NTERMS = 11; Cuantic *cuantic; // Variable global, está hecho así, de momento,para parecerse al original PRECISION **PUNTEROS_CALCULOS_COMPARTIDOS; int POSW_PUNTERO_CALCULOS_COMPARTIDOS; int POSR_PUNTERO_CALCULOS_COMPARTIDOS; REAL *dtaux, *etai_gp3, *ext1, *ext2, *ext3, *ext4; REAL *gp1, *gp2, *dt, *dti, *gp3, *gp4, *gp5, *gp6, *etai_2; REAL *gp4_gp2_rhoq, *gp5_gp2_rhou, *gp6_gp2_rhov; REAL *dgp1, *dgp2, *dgp3, *dgp4, *dgp5, *dgp6, *d_dt; REAL *d_ei, *d_eq, *d_eu, *d_ev, *d_rq, *d_ru, *d_rv; REAL *dfi, *dshi; REAL CC, CC_2, sin_gm, azi_2, sinis, cosis, cosis_2, cosi, sina, cosa, sinda, cosda, sindi, cosdi, sinis_cosa, sinis_sina; REAL *fi_p, *fi_b, *fi_r, *shi_p, *shi_b, *shi_r; REAL *etain, *etaqn, *etaun, *etavn, *rhoqn, *rhoun, *rhovn; REAL *etai, *etaq, *etau, *etav, *rhoq, *rhou, *rhov; REAL *parcial1, *parcial2, *parcial3; REAL *nubB, *nupB, *nurB; REAL **uuGlobalInicial; REAL **HGlobalInicial; REAL **FGlobalInicial; PRECISION *GMAC,* GMAC_DERIV; PRECISION * dirConvPar; REAL *resultConv; PRECISION * G = NULL; REAL * opa; int FGlobal, HGlobal, uuGlobal; REAL *d_spectra, *spectra, *spectra_mac, *spectra_slight; // GLOBAL variables to use for FFT calculation fftw_complex * inSpectraFwPSF, *inSpectraBwPSF, *outSpectraFwPSF, *outSpectraBwPSF; fftw_complex * inSpectraFwMAC, *inSpectraBwMAC, *outSpectraFwMAC, *outSpectraBwMAC; fftw_plan planForwardPSF, planBackwardPSF; fftw_plan planForwardMAC, planBackwardMAC; fftw_complex * inFilterMAC, * inFilterMAC_DERIV, * outFilterMAC, * outFilterMAC_DERIV; fftw_plan planFilterMAC, planFilterMAC_DERIV; fftw_complex * fftw_G_PSF, * fftw_G_MAC_PSF, * fftw_G_MAC_DERIV_PSF; fftw_complex * inPSF_MAC, * inMulMacPSF, * inPSF_MAC_DERIV, *inMulMacPSFDeriv, *outConvFilters, * outConvFiltersDeriv; fftw_plan planForwardPSF_MAC, planForwardPSF_MAC_DERIV,planBackwardPSF_MAC, planBackwardPSF_MAC_DERIV; //Convolutions values int sizeG = 0; PRECISION FWHM = 0; ConfigControl configCrontrolFile; // fvoigt memory consuption _Complex double *z,* zden, * zdiv; gsl_vector *eval; gsl_matrix *evec; gsl_eigen_symmv_workspace * workspace; int main(int argc, char **argv) { int i; // for indexes PRECISION *wlines; int nlambda; Init_Model *vModels; float chisqrf, * vChisqrf; int * vNumIter; // to store the number of iterations used to converge for each pixel int indexLine, free_params; // index to identify central line to read it //***** Init_Model INITIAL_MODEL; PRECISION * deltaLambda, * PSF; PRECISION initialLambda, step, finalLambda; int N_SAMPLES_PSF; int posWL=0; //---------------------------------------------- float * slight = NULL; int nl_straylight, ns_straylight, nx_straylight=0,ny_straylight=0; const char * nameInputFileSpectra ; char nameOutputFilePerfiles [4096]; const char * nameInputFileLines; const char * nameInputFilePSF ; FitsImage * fitsImage; PRECISION dat[7]; /********************* Read data input from file ******************************/ /* Read data input from file */ loadInitialValues(&configCrontrolFile); readTrolFile(argv[1],&configCrontrolFile,1); nameInputFileSpectra = configCrontrolFile.ObservedProfiles; nameInputFileLines = configCrontrolFile.AtomicParametersFile; nameInputFilePSF = configCrontrolFile.PSFFile; FWHM = configCrontrolFile.FWHM; /***************** READ INIT MODEL ********************************/ if(configCrontrolFile.InitialGuessModel[0]!='\0' && !readInitialModel(&INITIAL_MODEL,configCrontrolFile.InitialGuessModel)){ printf("\nERROR READING GUESS MODEL 1 FILE\n"); exit(EXIT_FAILURE); } checkInitialModel(&INITIAL_MODEL); if(INITIAL_MODEL.alfa<1 && access(configCrontrolFile.StrayLightFile,F_OK)){ printf("\nERROR. Filling factor in Initial model is less than 1 and Stray Light file %s can not be accessed\n",configCrontrolFile.StrayLightFile); exit(EXIT_FAILURE); } if(configCrontrolFile.fix[10]==0) NTERMS--; if(INITIAL_MODEL.mac ==0 && configCrontrolFile.fix[9]==0){ NTERMS--; } // allocate memory for eigen values eval = gsl_vector_alloc (NTERMS); evec = gsl_matrix_alloc (NTERMS, NTERMS); workspace = gsl_eigen_symmv_alloc (NTERMS); /***************** READ WAVELENGHT FROM GRID OR FITS ********************************/ PRECISION * vLambda, *vOffsetsLambda; if(configCrontrolFile.useMallaGrid){ // read lambda from grid file printf("\n--------------------------------------------------------------------------------"); printf("\nMALLA GRID FILE READ: %s",configCrontrolFile.MallaGrid); printf("\n--------------------------------------------------------------------------------"); indexLine = readMallaGrid(configCrontrolFile.MallaGrid, &initialLambda, &step, &finalLambda, 1); printf("--------------------------------------------------------------------------------\n"); nlambda = ((finalLambda-initialLambda)/step)+1; vOffsetsLambda = calloc(nlambda,sizeof(PRECISION)); vOffsetsLambda[0] = initialLambda; for(i=1;i<nlambda;i++){ vOffsetsLambda[i] = vOffsetsLambda[i-1]+step; } // pass to armstrong initialLambda = initialLambda/1000.0; step = step/1000.0; finalLambda = finalLambda/1000.0; vLambda = calloc(nlambda,sizeof(PRECISION)); printf("Number of wavelengths in the wavelength grid: %d",nlambda); printf("\n--------------------------------------------------------------------------------\n"); printf("\n--------------------------------------------------------------------------------"); printf("\nATMOSPHERE LINES FILE READ: %s",nameInputFileLines); configCrontrolFile.CentralWaveLenght = readFileCuanticLines(nameInputFileLines,dat,indexLine,1); if(configCrontrolFile.CentralWaveLenght==0){ printf("\n QUANTUM LINE NOT FOUND, REVIEW IT. INPUT CENTRAL WAVE LENGHT: %f",configCrontrolFile.CentralWaveLenght); exit(1); } vLambda[0]=configCrontrolFile.CentralWaveLenght+(initialLambda); for(i=1;i<nlambda;i++){ vLambda[i]=vLambda[i-1]+step; } /******************* CREATE CUANTINC AND INITIALIZE DINAMYC MEMORY*******************/ cuantic = create_cuantic(dat,1); } else{ // read lambda from fits file printf("\n--------------------------------------------------------------------------------"); printf("\nWAVELENGTH FILE READ: %s",configCrontrolFile.WavelengthFile); vLambda = readFitsLambdaToArray(configCrontrolFile.WavelengthFile,&indexLine,&nlambda); if(vLambda==NULL){ printf("\n FILE WITH WAVELENGHT HAS NOT BEEN READ PROPERLY, please check it.\n"); free(vLambda); exit(EXIT_FAILURE); } printf("--------------------------------------------------------------------------------\n"); printf("Number of wavelengths in the wavelength file: %d",nlambda); printf("\n--------------------------------------------------------------------------------\n"); printf("\n--------------------------------------------------------------------------------"); printf("\nATMOSPHERE LINES FILE READ: %s",nameInputFileLines); configCrontrolFile.CentralWaveLenght = readFileCuanticLines(nameInputFileLines,dat,indexLine,1); if(configCrontrolFile.CentralWaveLenght==0){ printf("\n QUANTUM LINE NOT FOUND, REVIEW IT. INPUT CENTRAL WAVE LENGHT: %f",configCrontrolFile.CentralWaveLenght); exit(1); } /******************* CREATE CUANTINC AND INITIALIZE DINAMYC MEMORY*******************/ cuantic = create_cuantic(dat,1); } /*********************************************** INITIALIZE VARIABLES *********************************/ REAL * vSigma = malloc((nlambda*NPARMS)*sizeof(REAL)); for(i=0;i<nlambda*NPARMS;i++){ vSigma[i] = configCrontrolFile.noise; } CC = PI / 180.0; CC_2 = CC * 2; wlines = (PRECISION *)calloc(2, sizeof(PRECISION)); wlines[0] = 1; wlines[1] = configCrontrolFile.CentralWaveLenght; // count how many free param we have free_params=0; for(i=0;i<11;i++){ if(configCrontrolFile.fix[i]) free_params++; } /****************************************************************************************************/ int numln=nlambda; // MACROTURBULENCE PLANS inFilterMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outFilterMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planFilterMAC = fftw_plan_dft_1d(numln, inFilterMAC, outFilterMAC, FFT_FORWARD, FFTW_MEASURE ); inFilterMAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outFilterMAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planFilterMAC_DERIV = fftw_plan_dft_1d(numln, inFilterMAC_DERIV, outFilterMAC_DERIV, FFT_FORWARD, FFTW_MEASURE ); inSpectraFwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outSpectraFwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planForwardMAC = fftw_plan_dft_1d(numln, inSpectraFwMAC, outSpectraFwMAC, FFT_FORWARD, FFTW_MEASURE ); inSpectraBwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outSpectraBwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planBackwardMAC = fftw_plan_dft_1d(numln, inSpectraBwMAC, outSpectraBwMAC, FFT_BACKWARD, FFTW_MEASURE ); // ********************************************* IF PSF HAS BEEN SELECTED IN TROL READ PSF FILE OR CREATE GAUSSIAN FILTER ***********// if(configCrontrolFile.ConvolveWithPSF){ if(configCrontrolFile.FWHM > 0){ G = fgauss_WL(FWHM,vLambda[1]-vLambda[0],vLambda[0],vLambda[nlambda/2],nlambda,&sizeG); //char nameAux [4096]; //char obsAux [4096]; //if(configCrontrolFile.ObservedProfiles[0]!='\0'){ // strcpy(obsAux,configCrontrolFile.ObservedProfiles); // strcpy(nameAux,dirname(obsAux)); //} //else{ // strcpy(obsAux,configCrontrolFile.InitialGuessModel); // strcpy(nameAux,dirname(obsAux)); //} //strcat(nameAux,"/gaussian.psf"); //FILE *fptr = fopen(nameAux, "w"); FILE *fptr = fopen("gaussian.psf", "w"); if(fptr!=NULL){ printf("\n Gaussian PSF will be saved to file gaussian.psf"); int kk; for (kk = 0; kk < nlambda; kk++) { fprintf(fptr,"\t%f\t%e\n", (vLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, G[kk]); } fclose(fptr); } else{ // printf("\n ERROR !!! The output file cannot be opened: %s",nameAux); printf("\n ERROR !!! The output file cannot be opened: gaussian.psf"); } }else{ // read the number of lines FILE *fp; char ch; N_SAMPLES_PSF=0; //open file in read more fp=fopen(nameInputFilePSF,"r"); if(fp==NULL) { printf("File \"%s\" does not exist!!!\n",nameInputFilePSF); return 0; } //read character by character and check for new line while((ch=fgetc(fp))!=EOF) { if(ch=='\n') N_SAMPLES_PSF++; } //close the file fclose(fp); if(N_SAMPLES_PSF>0){ deltaLambda = calloc(N_SAMPLES_PSF,sizeof(PRECISION)); PSF = calloc(N_SAMPLES_PSF,sizeof(PRECISION)); readPSFFile(deltaLambda,PSF,nameInputFilePSF,configCrontrolFile.CentralWaveLenght); // CHECK if values of deltaLambda are in the same range of vLambda. For do that we truncate to 4 decimal places if( (trunc(vOffsetsLambda[0])) < (trunc(deltaLambda[0])) || (trunc(vOffsetsLambda[nlambda-1])) > (trunc(deltaLambda[N_SAMPLES_PSF-1])) ){ printf("\n\n ERROR: The wavelength range given in the PSF file is smaller than the range in the mesh file [%lf,%lf] [%lf,%lf] \n\n",deltaLambda[0],vOffsetsLambda[0],deltaLambda[N_SAMPLES_PSF-1],vOffsetsLambda[nlambda-1]); exit(EXIT_FAILURE); } G = malloc(nlambda * sizeof(PRECISION)); double offset=0; for(i=0;i<nlambda && !posWL;i++){ if( fabs(trunc(vOffsetsLambda[i]))==0) posWL = i; } if(posWL!= (nlambda/2) ){ // move center to the middle of samples offset = (( ((nlambda)/2) - posWL)*step)*1000; } interpolationLinearPSF(deltaLambda, PSF, vOffsetsLambda ,N_SAMPLES_PSF, G, nlambda,offset); sizeG = nlambda; } else{ printf("\n****************** ERROR THE PSF FILE is empty or damaged.******************\n"); exit(EXIT_FAILURE); } printf("\n--------------------------------------------------------------------------------"); printf("\nPSF FILE READ: %s", nameInputFilePSF); printf("\n--------------------------------------------------------------------------------\n"); } //PSF FILTER PLANS inSpectraFwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outSpectraFwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planForwardPSF = fftw_plan_dft_1d(numln, inSpectraFwPSF, outSpectraFwPSF, FFT_FORWARD, FFTW_MEASURE ); inSpectraBwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outSpectraBwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planBackwardPSF = fftw_plan_dft_1d(numln, inSpectraBwPSF, outSpectraBwPSF, FFT_BACKWARD, FFTW_MEASURE ); fftw_complex * in = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * numln); int i; for (i = 0; i < numln; i++) { in[i] = G[i] + 0 * _Complex_I; } fftw_G_PSF = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * numln); fftw_plan p = fftw_plan_dft_1d(numln, in, fftw_G_PSF, FFT_FORWARD, FFTW_MEASURE ); fftw_execute(p); for (i = 0; i < numln; i++) { fftw_G_PSF[i] = fftw_G_PSF[i] / numln; } fftw_destroy_plan(p); fftw_free(in); inPSF_MAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); fftw_G_MAC_PSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planForwardPSF_MAC = fftw_plan_dft_1d(numln, inPSF_MAC, fftw_G_MAC_PSF, FFT_FORWARD, FFTW_MEASURE ); inMulMacPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outConvFilters = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planBackwardPSF_MAC = fftw_plan_dft_1d(numln, inMulMacPSF, outConvFilters, FFT_BACKWARD, FFTW_MEASURE ); inPSF_MAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); fftw_G_MAC_DERIV_PSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planForwardPSF_MAC_DERIV = fftw_plan_dft_1d(numln, inPSF_MAC_DERIV, fftw_G_MAC_DERIV_PSF, FFT_FORWARD, FFTW_MEASURE ); inMulMacPSFDeriv = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); outConvFiltersDeriv = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * numln); planBackwardPSF_MAC_DERIV = fftw_plan_dft_1d(numln, inMulMacPSFDeriv, outConvFiltersDeriv, FFT_BACKWARD, FFTW_MEASURE ); } /****************************************************************************************************/ // IF NUMBER OF CYCLES IS LES THAN 0 THEN --> WE USE CLASSICAL ESTIMATES // IF NUMBER OF CYCLES IS 0 THEN --> DO SYNTHESIS FROM THE INIT MODEL // IF NUMBER OF CYCLES IS GREATER THAN 0 --> READ FITS FILE OR PER FILE AND PROCESS DO INVERSION WITH N CYCLES if(configCrontrolFile.NumberOfCycles<0){ // read fits or per AllocateMemoryDerivedSynthesis(nlambda); if(strcmp(file_ext(configCrontrolFile.ObservedProfiles),PER_FILE)==0){ // invert only per file float * spectroPER = calloc(nlambda*NPARMS,sizeof(float)); FILE * fReadSpectro; char * line = NULL; size_t len = 0; ssize_t read; fReadSpectro = fopen(configCrontrolFile.ObservedProfiles, "r"); int contLine=0; if (fReadSpectro == NULL) { printf("Error opening the file of parameters, it's possible that the file doesn't exist. Please verify it. \n"); printf("\n ******* THIS IS THE NAME OF THE FILE RECEVIED : %s \n", configCrontrolFile.ObservedProfiles); fclose(fReadSpectro); exit(EXIT_FAILURE); } float aux1, aux2,aux3,aux4,aux5,aux6; while ((read = getline(&line, &len, fReadSpectro)) != -1 && contLine<nlambda) { sscanf(line,"%e %e %e %e %e %e",&aux1,&aux2,&aux3,&aux4,&aux5,&aux6); spectroPER[contLine] = aux3; spectroPER[contLine + nlambda] = aux4; spectroPER[contLine + nlambda * 2] = aux5; spectroPER[contLine + nlambda * 3] = aux6; contLine++; } fclose(fReadSpectro); printf("\n--------------------------------------------------------------------------------"); printf("\nOBSERVED PROFILES FILE READ: %s ", configCrontrolFile.ObservedProfiles); printf("\n--------------------------------------------------------------------------------\n"); Init_Model initModel; initModel.eta0 = 0; initModel.mac = 0; initModel.dopp = 0; initModel.aa = 0; initModel.alfa = 0; //0.38; //stray light factor initModel.S1 = 0; //invert with classical estimates estimacionesClasicas(wlines[1], vLambda, nlambda, spectroPER, &initModel,0); // save model to file char nameAuxOutputModel [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAuxOutputModel,"_model_ce"); strcat(nameAuxOutputModel,MOD_FILE); FILE * fptr = fopen(nameAuxOutputModel, "w"); if(fptr!=NULL){ fprintf(fptr,"eta_0 :%lf\n",initModel.eta0); fprintf(fptr,"magnetic field [G] :%lf\n",initModel.B); fprintf(fptr,"LOS velocity[km/s] :%lf\n",initModel.vlos); fprintf(fptr,"Doppler width [A] :%lf\n",initModel.dopp); fprintf(fptr,"damping :%lf\n",initModel.aa); fprintf(fptr,"gamma [deg] :%lf\n",initModel.gm); fprintf(fptr,"phi [deg] :%lf\n",initModel.az); fprintf(fptr,"S_0 :%lf\n",initModel.S0); fprintf(fptr,"S_1 :%lf\n",initModel.S1); fprintf(fptr,"v_mac :%lf\n",initModel.mac); fprintf(fptr,"filling factor :%lf\n",initModel.alfa); fprintf(fptr,"# Iterations :%d\n",0); fprintf(fptr,"chisqr :%le\n",0.0); fprintf(fptr,"\n\n"); fclose(fptr); } else{ printf("\n ¡¡¡¡¡ ERROR: OUTPUT MODEL FILE CAN NOT BE OPENED: %s \n !!!!!",nameAuxOutputModel); } free(spectroPER); } else if(strcmp(file_ext(configCrontrolFile.ObservedProfiles),FITS_FILE)==0){ // invert image from fits file fitsImage = readFitsSpectroImage(configCrontrolFile.ObservedProfiles,0,nlambda); printf("\n--------------------------------------------------------------------------------"); printf("\nOBSERVED PROFILES FILE READ: %s", configCrontrolFile.ObservedProfiles); printf("\n--------------------------------------------------------------------------------\n"); // ALLOCATE MEMORY FOR STORE THE RESULTS int indexPixel = 0; vModels = calloc (fitsImage->numPixels , sizeof(Init_Model)); vChisqrf = calloc (fitsImage->numPixels , sizeof(float)); vNumIter = calloc (fitsImage->numPixels , sizeof(int)); for(indexPixel = 0; indexPixel < fitsImage->numPixels; indexPixel++){ //Initial Model Init_Model initModel; initModel.eta0 = INITIAL_MODEL.eta0; initModel.B = INITIAL_MODEL.B; //200 700 initModel.gm = INITIAL_MODEL.gm; initModel.az = INITIAL_MODEL.az; initModel.vlos = INITIAL_MODEL.vlos; //km/s 0 initModel.mac = INITIAL_MODEL.mac; initModel.dopp = INITIAL_MODEL.dopp; initModel.aa = INITIAL_MODEL.aa; initModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor initModel.S0 = INITIAL_MODEL.S0; initModel.S1 = INITIAL_MODEL.S1; estimacionesClasicas(wlines[1],vLambda, nlambda, fitsImage->pixels[indexPixel].spectro, &initModel,0); vModels[indexPixel] = initModel; } char nameAuxOutputModel [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAuxOutputModel,"_model_ce"); strcat(nameAuxOutputModel,FITS_FILE); if(!writeFitsImageModels(nameAuxOutputModel,fitsImage->rows,fitsImage->cols,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){ printf("\n ERROR WRITING FILE OF MODELS: %s",nameAuxOutputModel); } free(vModels); free(vChisqrf); free(vNumIter); } else{ printf("\n OBSERVED PROFILES DOESN'T HAVE CORRECT EXTENSION .PER or .FITS "); exit(EXIT_FAILURE); } } else if(configCrontrolFile.NumberOfCycles==0){ // synthesis if(access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ // IF NOT EMPTY READ stray light file if(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){ slight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda); printf("\n--------------------------------------------------------------------------------"); printf("\nSTRAY LIGHT FILE READ: %s ", configCrontrolFile.StrayLightFile); printf("\n--------------------------------------------------------------------------------\n"); } else if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){ slight= readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight); if(nx_straylight!=0 || ny_straylight!=0){ printf("\n Stray light file has 4 dimensions and for Synthesis only 2 dimensiones file is accepted, henceforth, stray light will not used for synthesis. \n"); free(slight); slight= NULL; } if(nl_straylight!=nlambda){ printf("\n The number of wavelengths is different in the stray light file: %d and malla grid file %d. \n. Stray light will not used for synthesis.", nl_straylight,nlambda); free(slight); slight= NULL; } printf("\n--------------------------------------------------------------------------------"); printf("\nSTRAY LIGHT FILE READ: %s ", configCrontrolFile.StrayLightFile); printf("\n--------------------------------------------------------------------------------\n"); } else{ printf("\n Stray light file hasn't extension .PER or .FITS, review it. \n. Stray light will not used for synthesis.\n"); free(slight); slight= NULL; } } Init_Model initModel; initModel.eta0 = INITIAL_MODEL.eta0; initModel.B = INITIAL_MODEL.B; //200 700 initModel.gm = INITIAL_MODEL.gm; initModel.az = INITIAL_MODEL.az; initModel.vlos = INITIAL_MODEL.vlos; //km/s 0 initModel.mac = INITIAL_MODEL.mac; initModel.dopp = INITIAL_MODEL.dopp; initModel.aa = INITIAL_MODEL.aa; initModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor initModel.S0 = INITIAL_MODEL.S0; initModel.S1 = INITIAL_MODEL.S1; printf("\n--------------------------------------------------------------------------------"); printf("\nATMOSPHERE MODEL FILE READ: %s ",configCrontrolFile.InitialGuessModel); printf("\n--------------------------------------------------------------------------------"); printf("\nINITAL MODEL ATMOSPHERE: \n\n"); printf("eta_0 :%lf\n",initModel.eta0); printf("magnetic field [G] :%lf\n",initModel.B); printf("LOS velocity[km/s] :%lf\n",initModel.vlos); printf("Doppler width [A] :%lf\n",initModel.dopp); printf("damping :%lf\n",initModel.aa); printf("gamma [deg] :%lf\n",initModel.gm); printf("phi [deg] :%lf\n",initModel.az); printf("S_0 :%lf\n",initModel.S0); printf("S_1 :%lf\n",initModel.S1); printf("v_mac [km/s] :%lf\n",initModel.mac); printf("filling factor :%lf\n",initModel.alfa); printf("--------------------------------------------------------------------------------\n"); AllocateMemoryDerivedSynthesis(nlambda); if(configCrontrolFile.ConvolveWithPSF && initModel.mac>0){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Filter PSF activated and macroturbulence greater than zero. "); printf("\n--------------------------------------------------------------------------------\n"); } else if(configCrontrolFile.ConvolveWithPSF){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Filter PSF activated. "); printf("\n--------------------------------------------------------------------------------\n"); } else if(initModel.mac>0){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Macroturbulence in initial atmosphere model greater than zero."); printf("\n--------------------------------------------------------------------------------\n"); } // synthesis mil_sinrf(cuantic, &initModel, wlines, vLambda, nlambda, spectra, configCrontrolFile.mu, slight,spectra_mac,spectra_slight, configCrontrolFile.ConvolveWithPSF); me_der(cuantic, &initModel, wlines, vLambda, nlambda, d_spectra, spectra_mac, spectra_slight, configCrontrolFile.mu, slight, configCrontrolFile.ConvolveWithPSF,configCrontrolFile.fix); // in this case basenamefile is from initmodel char nameAux [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAux,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAux,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAux,PER_FILE); FILE *fptr = fopen(nameAux, "w"); if(fptr!=NULL){ int kk; for (kk = 0; kk < nlambda; kk++) { fprintf(fptr,"%d\t%f\t%e\t%e\t%e\t%e\n", indexLine, (vLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, spectra[kk], spectra[kk + nlambda], spectra[kk + nlambda * 2], spectra[kk + nlambda * 3]); } fclose(fptr); printf("\n--------------------------------------------------------------------------------"); printf("\n------------------SYNTHESIS DONE: %s",nameAux); printf("\n--------------------------------------------------------------------------------\n"); } else{ printf("\n ERROR !!! The output file can not be open: %s",nameAux); } /*int number_parametros = 0; for (number_parametros = 0; number_parametros < NTERMS; number_parametros++) { strcpy(nameAux,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAux,"_C_"); char extension[10]; sprintf(extension, "%d%s", number_parametros,".per"); strcat(nameAux,extension); FILE *fptr = fopen(nameAux, "w"); //printf("\n FUNCION RESPUESTA: %d \n",number_parametros); int kk; for (kk = 0; kk < nlambda; kk++) { fprintf(fptr,"1\t%lf\t%le\t%le\t%le\t%le\n", vLambda[kk], d_spectra[kk + nlambda * number_parametros], d_spectra[kk + nlambda * number_parametros + nlambda * NTERMS], d_spectra[kk + nlambda * number_parametros + nlambda * NTERMS * 2], d_spectra[kk + nlambda * number_parametros + nlambda * NTERMS * 3]); } fclose(fptr); } printf("\n");*/ } else{ // INVERT PIXEL FROM PER FILE OR IMAGE FROM FITS FILE if(strcmp(file_ext(configCrontrolFile.ObservedProfiles),PER_FILE)==0){ // invert only per file float * spectroPER = calloc(nlambda*NPARMS,sizeof(float)); FILE * fReadSpectro; char * line = NULL; size_t len = 0; ssize_t read; fReadSpectro = fopen(configCrontrolFile.ObservedProfiles, "r"); int contLine=0; if (fReadSpectro == NULL) { printf("Error opening the file of parameters, it's possible that the file doesn't exist. Please verify it. \n"); printf("\n ******* THIS IS THE NAME OF THE FILE RECEVIED : %s \n", configCrontrolFile.ObservedProfiles); fclose(fReadSpectro); exit(EXIT_FAILURE); } float aux1, aux2, aux3, aux4, aux5, aux6; while ((read = getline(&line, &len, fReadSpectro)) != -1) { sscanf(line,"%e %e %e %e %e %e",&aux1,&aux2,&aux3,&aux4,&aux5,&aux6); if(contLine<nlambda){ spectroPER[contLine] = aux3; spectroPER[contLine + nlambda] = aux4; spectroPER[contLine + nlambda * 2] = aux5; spectroPER[contLine + nlambda * 3] = aux6; } contLine++; } fclose(fReadSpectro); printf("\n--------------------------------------------------------------------------------"); printf("\nOBSERVED PROFILES FILE READ: %s ", configCrontrolFile.ObservedProfiles); printf("\n--------------------------------------------------------------------------------"); printf("\nNumber of wavelengths in the observed profiles: %d",contLine); printf("\n--------------------------------------------------------------------------------\n"); if(nlambda!=contLine){ printf("\n--------------------------------------------------------------------------------\n"); printf("\nERROR: The number of wavelenghts in observed profiles file %d is different to number of wavelengths in malla grid %d\n",contLine,nlambda); exit(EXIT_FAILURE); } if(configCrontrolFile.fix[10] && access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ // IF NOT EMPTY READ stray light file if(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){ slight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda); printf("\n--------------------------------------------------------------------------------"); printf("\nSTRAY LIGHT FILE READ: %s ", configCrontrolFile.StrayLightFile); printf("\n--------------------------------------------------------------------------------\n"); } else if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){ slight= readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight); if(nx_straylight!=0 || ny_straylight!=0){ printf("\n Stray light file has 4 dimensions and for Inversion pixel only 2 dimensiones file is accepted, henceforth, stray light will not used for inversion pixel. \n"); free(slight); slight= NULL; } if(nl_straylight!=nlambda){ printf("\n The number of wavelengths is different in the stray light file: %d and malla grid file %d. \n. Stray light will not used for inversion pixel.", nl_straylight,nlambda); free(slight); slight= NULL; } printf("\n--------------------------------------------------------------------------------"); printf("\nSTRAY LIGHT FILE READ: %s ", configCrontrolFile.StrayLightFile); printf("\n--------------------------------------------------------------------------------\n"); } else{ printf("\n Stray light file hasn't extension .PER or .FITS, review it. \n. Stray light will not used for inversion pixel.\n"); free(slight); slight= NULL; } } AllocateMemoryDerivedSynthesis(nlambda); Init_Model initModel; initModel.eta0 = INITIAL_MODEL.eta0; initModel.B = INITIAL_MODEL.B; //200 700 initModel.gm = INITIAL_MODEL.gm; initModel.az = INITIAL_MODEL.az; initModel.vlos = INITIAL_MODEL.vlos; //km/s 0 initModel.mac = INITIAL_MODEL.mac; initModel.dopp = INITIAL_MODEL.dopp; initModel.aa = INITIAL_MODEL.aa; initModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor initModel.S0 = INITIAL_MODEL.S0; initModel.S1 = INITIAL_MODEL.S1; printf("\n--------------------------------------------------------------------------------"); printf("\nATMOSPHERE MODEL FILE READ: %s ",configCrontrolFile.InitialGuessModel); printf("\n--------------------------------------------------------------------------------"); printf("\nINITAL MODEL ATMOSPHERE: \n\n"); printf("eta_0 :%lf\n",initModel.eta0); printf("magnetic field [G] :%lf\n",initModel.B); printf("LOS velocity[km/s] :%lf\n",initModel.vlos); printf("Doppler width [A] :%lf\n",initModel.dopp); printf("damping :%lf\n",initModel.aa); printf("gamma [deg] :%lf\n",initModel.gm); printf("phi [deg] :%lf\n",initModel.az); printf("S_0 :%lf\n",initModel.S0); printf("S_1 :%lf\n",initModel.S1); printf("v_mac [km/s] :%lf\n",initModel.mac); printf("filling factor :%lf\n",initModel.alfa); printf("--------------------------------------------------------------------------------\n"); if(configCrontrolFile.ConvolveWithPSF && initModel.mac>0){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Filter PSF activated and macroturbulence greater than zero. "); printf("\n--------------------------------------------------------------------------------\n"); } else if(configCrontrolFile.ConvolveWithPSF){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Filter PSF activated. "); printf("\n--------------------------------------------------------------------------------\n"); } else if(initModel.mac>0){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Macroturbulence in initial atmosphere model greater than zero."); printf("\n--------------------------------------------------------------------------------\n"); } int numIter =0; printf("\n--------------------------------------------------------------------------------"); printf("\nNumber of free parameters for inversion: %d", free_params); printf("\n--------------------------------------------------------------------------------\n"); lm_mils(cuantic, wlines, vLambda, nlambda, spectroPER, nlambda, &initModel, spectra, &chisqrf, slight, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles, configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&numIter,configCrontrolFile.mu, configCrontrolFile.logclambda); // SAVE OUTPUT MODEL char nameAuxOutputModel [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAuxOutputModel,"_model"); strcat(nameAuxOutputModel,MOD_FILE); FILE *fptr = fopen(nameAuxOutputModel, "w"); if(fptr!=NULL){ fprintf(fptr,"eta_0 :%lf\n",initModel.eta0); fprintf(fptr,"magnetic field [G] :%lf\n",initModel.B); fprintf(fptr,"LOS velocity[km/s] :%lf\n",initModel.vlos); fprintf(fptr,"Doppler width [A] :%lf\n",initModel.dopp); fprintf(fptr,"damping :%lf\n",initModel.aa); fprintf(fptr,"gamma [deg] :%lf\n",initModel.gm); fprintf(fptr,"phi [deg] :%lf\n",initModel.az); fprintf(fptr,"S_0 :%lf\n",initModel.S0); fprintf(fptr,"S_1 :%lf\n",initModel.S1); fprintf(fptr,"v_mac [km/s] :%lf\n",initModel.mac); fprintf(fptr,"filling factor :%lf\n",initModel.alfa); fprintf(fptr,"# Iterations :%d\n",numIter); fprintf(fptr,"chisqr :%le\n",chisqrf); fprintf(fptr,"\n\n"); fclose(fptr); printf("\n\n--------------------------------------------------------------------------------"); printf("\nINVERTED MODEL SAVED IN FILE: %s",nameAuxOutputModel); printf("\n--------------------------------------------------------------------------------\n"); } else{ printf("\n ¡¡¡¡¡ ERROR: OUTPUT MODEL FILE CAN NOT BE OPENED\n !!!!! "); } // SAVE OUTPUT ADJUST SYNTHESIS PROFILES if(configCrontrolFile.SaveSynthesisAdjusted){ char nameAuxOutputStokes [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAuxOutputStokes,STOKES_PER_EXT); FILE *fptr = fopen(nameAuxOutputStokes, "w"); if(fptr!=NULL){ //printf("\n valores de spectro sintetizado\n"); int kk; for (kk = 0; kk < nlambda; kk++) { fprintf(fptr,"%d\t%f\t%e\t%e\t%e\t%e\n", indexLine, (vLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, spectra[kk], spectra[kk + nlambda], spectra[kk + nlambda * 2], spectra[kk + nlambda * 3]); } //printf("\nVALORES DE LAS FUNCIONES RESPUESTA \n"); fclose(fptr); printf("\n--------------------------------------------------------------------------------"); printf("\nOutput profiles: %s",nameAuxOutputStokes); printf("\n--------------------------------------------------------------------------------\n"); } else{ printf("\n ¡¡¡¡¡ ERROR: OUTPUT SYNTHESIS PROFILE ADJUSTED FILE CAN NOT BE OPENED\n !!!!! "); } } free(spectroPER); } else if(strcmp(file_ext(configCrontrolFile.ObservedProfiles),FITS_FILE)==0){ // invert image from fits file // check if read stray light if(configCrontrolFile.fix[10] && access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ // IF NOT EMPTY READ stray light file if(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){ slight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda); printf("\n--------------------------------------------------------------------------------"); printf("\nSTRAY LIGHT FILE READ: %s ", configCrontrolFile.StrayLightFile); printf("\n--------------------------------------------------------------------------------\n"); } else if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){ slight = readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight); if(nl_straylight!=nlambda){ printf("\n The number of wavelengths is different in the stray light file: %d and malla grid file %d. \n. Stray light will not used for inversion.", nl_straylight,nlambda); free(slight); slight= NULL; exit(EXIT_FAILURE); } printf("\n--------------------------------------------------------------------------------"); printf("\nSTRAY LIGHT FILE READ: %s", configCrontrolFile.StrayLightFile); printf("\n--------------------------------------------------------------------------------\n"); } else{ printf("\n Stray light file hasn't extension .PER or .FITS, review it. \n. Stray light will not used for inversion.\n"); free(slight); slight= NULL; exit(EXIT_FAILURE); } } // READ PIXELS FROM IMAGE PRECISION timeReadImage; clock_t t; t = clock(); fitsImage = readFitsSpectroImage(nameInputFileSpectra,0,nlambda); t = clock() - t; timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds printf("\n--------------------------------------------------------------------------------"); printf("\nOBSERVED PROFILES FILE READ: %s", nameInputFileSpectra); printf("\n--------------------------------------------------------------------------------"); printf("\nTIME TO READ FITS IMAGE: %f seconds to execute ", timeReadImage); printf("\n--------------------------------------------------------------------------------\n"); if(fitsImage!=NULL){ FitsImage * imageStokesAdjust = NULL; if(configCrontrolFile.SaveSynthesisAdjusted){ imageStokesAdjust = malloc(sizeof(FitsImage)); imageStokesAdjust->rows = fitsImage->rows; imageStokesAdjust->cols = fitsImage->cols; imageStokesAdjust->nLambdas = fitsImage->nLambdas; imageStokesAdjust->numStokes = fitsImage->numStokes; imageStokesAdjust->pos_col = fitsImage->pos_col; imageStokesAdjust->pos_row = fitsImage->pos_row; imageStokesAdjust->pos_lambda = fitsImage->pos_lambda; imageStokesAdjust->pos_stokes_parameters = fitsImage->pos_stokes_parameters; imageStokesAdjust->numPixels = fitsImage->numPixels; imageStokesAdjust->pixels = calloc(imageStokesAdjust->numPixels, sizeof(vpixels)); imageStokesAdjust->naxes = fitsImage->naxes; imageStokesAdjust->vCard = fitsImage->vCard; imageStokesAdjust->vKeyname = fitsImage->vKeyname; imageStokesAdjust->nkeys = fitsImage->nkeys; imageStokesAdjust->naxis = fitsImage->naxis; imageStokesAdjust->bitpix = fitsImage->bitpix; for( i=0;i<imageStokesAdjust->numPixels;i++){ imageStokesAdjust->pixels[i].spectro = calloc ((imageStokesAdjust->numStokes*imageStokesAdjust->nLambdas),sizeof(float)); } } printf("\n--------------------------------------------------------------------------------"); printf("\nATMOSPHERE MODEL FILE READ: %s ",configCrontrolFile.InitialGuessModel); printf("\n--------------------------------------------------------------------------------"); printf("\nINITAL MODEL ATMOSPHERE: \n\n"); printf("eta_0 :%lf\n",INITIAL_MODEL.eta0); printf("magnetic field [G] :%lf\n",INITIAL_MODEL.B); printf("LOS velocity[km/s] :%lf\n",INITIAL_MODEL.vlos); printf("Doppler width [A] :%lf\n",INITIAL_MODEL.dopp); printf("damping :%lf\n",INITIAL_MODEL.aa); printf("gamma [deg] :%lf\n",INITIAL_MODEL.gm); printf("phi [deg] :%lf\n",INITIAL_MODEL.az); printf("S_0 :%lf\n",INITIAL_MODEL.S0); printf("S_1 :%lf\n",INITIAL_MODEL.S1); printf("v_mac [km/s] :%lf\n",INITIAL_MODEL.mac); printf("filling factor :%lf\n",INITIAL_MODEL.alfa); printf("--------------------------------------------------------------------------------\n"); if(configCrontrolFile.ConvolveWithPSF && INITIAL_MODEL.mac>0){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Filter PSF activated and macroturbulence greater than zero. "); printf("\n--------------------------------------------------------------------------------\n"); } else if(configCrontrolFile.ConvolveWithPSF){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Filter PSF activated. "); printf("\n--------------------------------------------------------------------------------\n"); } else if(INITIAL_MODEL.mac>0){ printf("\n--------------------------------------------------------------------------------"); printf("\nThe program needs to use convolution. Macroturbulence in initial atmosphere model greater than zero."); printf("\n--------------------------------------------------------------------------------\n"); } printf("\n--------------------------------------------------------------------------------"); printf("\nNumber of free parameters for inversion: %d", free_params); printf("\n--------------------------------------------------------------------------------\n"); //***************************************** INIT MEMORY WITH SIZE OF LAMBDA ****************************************************// AllocateMemoryDerivedSynthesis(nlambda); int indexPixel = 0; // ALLOCATE MEMORY FOR STORE THE RESULTS vModels = calloc (fitsImage->numPixels , sizeof(Init_Model)); vChisqrf = calloc (fitsImage->numPixels , sizeof(float)); vNumIter = calloc (fitsImage->numPixels , sizeof(int)); t = clock(); printf("\n--------------------------------------------------------------------------------"); printf("\n----------------------- IMAGE INVERSION IN PROGRESS ----------------------------"); printf("\n--------------------------------------------------------------------------------\n"); for(indexPixel = 0; indexPixel < fitsImage->numPixels; indexPixel++){ //Initial Model Init_Model initModel; initModel.eta0 = INITIAL_MODEL.eta0; initModel.B = INITIAL_MODEL.B; //200 700 initModel.gm = INITIAL_MODEL.gm; initModel.az = INITIAL_MODEL.az; initModel.vlos = INITIAL_MODEL.vlos; //km/s 0 initModel.mac = INITIAL_MODEL.mac; initModel.dopp = INITIAL_MODEL.dopp; initModel.aa = INITIAL_MODEL.aa; initModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor initModel.S0 = INITIAL_MODEL.S0; initModel.S1 = INITIAL_MODEL.S1; // CLASSICAL ESTIMATES TO GET B, GAMMA estimacionesClasicas(wlines[1], vLambda, nlambda, fitsImage->pixels[indexPixel].spectro, &initModel,1); if (isnan(initModel.B)) initModel.B = 1; if (isnan(initModel.vlos)) initModel.vlos = 1e-3; if (isnan(initModel.gm)) initModel.gm = 1; if (isnan(initModel.az)) initModel.az = 1; // INVERSION RTE float * slightPixel; if(slight==NULL) slightPixel = NULL; else{ if(nx_straylight && ny_straylight){ slightPixel = slight+ (nlambda*NPARMS*indexPixel); } else { slightPixel = slight; } } vNumIter[indexPixel] = indexPixel; lm_mils(cuantic, wlines, vLambda, nlambda, fitsImage->pixels[indexPixel].spectro, nlambda, &initModel, spectra, &vChisqrf[indexPixel], slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles, configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise,configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&vNumIter[indexPixel],configCrontrolFile.mu,configCrontrolFile.logclambda); vModels[indexPixel] = initModel; if(configCrontrolFile.SaveSynthesisAdjusted){ int kk; for (kk = 0; kk < (nlambda * NPARMS); kk++) { imageStokesAdjust->pixels[indexPixel].spectro[kk] = spectra[kk] ; } } } t = clock() - t; timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds printf("\n\n--------------------------------------------------------------------------------"); printf("\nFINISH EXECUTION OF INVERSION: %f seconds to execute ", timeReadImage); printf("\n--------------------------------------------------------------------------------"); char nameAuxOutputModel [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAuxOutputModel,MOD_FITS); if(!writeFitsImageModels(nameAuxOutputModel,fitsImage->rows,fitsImage->cols,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){ printf("\n ERROR WRITING FILE OF MODELS: %s",nameAuxOutputModel); } // PROCESS FILE OF SYNTETIC PROFILES if(configCrontrolFile.SaveSynthesisAdjusted){ // WRITE SINTHETIC PROFILES TO FITS FILE char nameAuxOutputStokes [4096]; if(configCrontrolFile.ObservedProfiles[0]!='\0') strcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.ObservedProfiles)); else strcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.InitialGuessModel)); strcat(nameAuxOutputStokes,STOKES_FIT_EXT); if(!writeFitsImageProfiles(nameAuxOutputStokes,nameInputFileSpectra,imageStokesAdjust)){ printf("\n ERROR WRITING FILE OF SINTHETIC PROFILES: %s",nameOutputFilePerfiles); } } if(configCrontrolFile.SaveSynthesisAdjusted) free(imageStokesAdjust); free(vModels); free(vChisqrf); free(vNumIter); } else{ printf("\n\n ***************************** FITS FILE WITH THE SPECTRO IMAGE CAN NOT BE READ IT ******************************\n"); } freeFitsImage(fitsImage); } else{ printf("\n OBSERVED PROFILES DOESN'T HAVE CORRECT EXTENSION .PER or .FITS "); exit(EXIT_FAILURE); } } fftw_free(inFilterMAC); fftw_free(outFilterMAC); fftw_destroy_plan(planFilterMAC); fftw_free(inFilterMAC_DERIV); fftw_free(outFilterMAC_DERIV); fftw_destroy_plan(planFilterMAC_DERIV); fftw_free(inSpectraFwMAC); fftw_free(outSpectraFwMAC); fftw_destroy_plan(planForwardMAC); fftw_free(inSpectraBwMAC); fftw_free(outSpectraBwMAC); fftw_destroy_plan(planBackwardMAC); if(configCrontrolFile.ConvolveWithPSF){ fftw_free(inSpectraFwPSF); fftw_free(outSpectraFwPSF); fftw_destroy_plan(planForwardPSF); fftw_free(inSpectraBwPSF); fftw_free(outSpectraBwPSF); fftw_destroy_plan(planBackwardPSF); fftw_free(fftw_G_PSF); fftw_free(fftw_G_MAC_PSF); fftw_free(fftw_G_MAC_DERIV_PSF); fftw_free(inPSF_MAC); fftw_free(inMulMacPSF); fftw_free(inPSF_MAC_DERIV); fftw_free(inMulMacPSFDeriv); fftw_free(outConvFilters); fftw_free(outConvFiltersDeriv); fftw_destroy_plan(planForwardPSF_MAC); fftw_destroy_plan(planForwardPSF_MAC_DERIV); fftw_destroy_plan(planBackwardPSF_MAC); fftw_destroy_plan(planBackwardPSF_MAC_DERIV); } free(cuantic); free(wlines); free(vSigma); FreeMemoryDerivedSynthesis(); if(G!=NULL) free(G); gsl_eigen_symmv_free (workspace); gsl_vector_free(eval); gsl_matrix_free(evec); return 0; }
{ "alphanum_fraction": 0.5961538462, "avg_line_length": 45.2888086643, "ext": "c", "hexsha": "0bae2d261a2dd53ef00669b83dc2ffd3a231143a", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z", "max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dcalc/hrt_pipeline", "max_forks_repo_path": "p-milos/src/milos.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dcalc/hrt_pipeline", "max_issues_repo_path": "p-milos/src/milos.c", "max_line_length": 260, "max_stars_count": null, "max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dcalc/hrt_pipeline", "max_stars_repo_path": "p-milos/src/milos.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 13495, "size": 50180 }
#pragma GCC diagnostic ignored "-Wdeclaration-after-statement" /* * ocl_model_maintenance.c * * Created on: 09.02.2014 * Author: mheimel */ #include "ocl_model_maintenance.h" #include <math.h> #include <stdlib.h> #include <sys/time.h> #include "ocl_adaptive_bandwidth.h" #include "ocl_error_metrics.h" #include "ocl_estimator.h" #include "ocl_sample_maintenance.h" #include "ocl_utilities.h" // Optimization routines. #include <nlopt.h> #include "lbfgs/lbfgs.h" #include "catalog/pg_kdefeedback.h" #include "executor/spi.h" #include "optimizer/path/gpukde/ocl_estimator_api.h" #include "storage/lock.h" // Global GUC variables bool kde_enable_bandwidth_optimization; int kde_bandwidth_optimization_feedback_window; extern int kde_bandwidth_representation; const double learning_rate = 0.01f; // ############################################################ // # Code for adaptive bandwidth optimization (online learning). // ############################################################ void ocl_notifyModelMaintenanceOfSelectivity( Oid relation, double selected, double allrows) { CREATE_TIMER(); // Check if we have an estimator for this relation. ocl_estimator_t* estimator = ocl_getEstimator(relation); if (estimator == NULL) return; if (!estimator->open_estimation) return; // No registered estimation. double selectivity = selected / allrows; estimator->rows_in_table = allrows; // Notify the sample maintenance of this observation so it can track the sample quality. ocl_notifySampleMaintenanceOfSelectivity(estimator, selectivity); // Update the bandwidth using online learning. ocl_runOnlineLearningStep(estimator, selectivity); // Write the error to the log file. ocl_reportErrorToLogFile( relation, estimator->last_selectivity, selectivity, estimator->rows_in_table); // We are done. estimator->open_estimation = false; LOG_TIMER("Model Maintenance"); } // ############################################################ // # Code for offline bandwidth optimization (batch learning). // ############################################################ // Helper function to extract the n latest feedback records for the given // estimator from the catalogue. The function will only return tuples that // have feedback that matches the estimator's attributes. // // Returns the actual number of valid feedback records in the catalog. static unsigned int ocl_extractLatestFeedbackRecordsFromCatalog( ocl_estimator_t* estimator, unsigned int requested_records, kde_float_t* range_buffer, kde_float_t* selectivity_buffer) { unsigned int current_tuple = 0; // Open a new scan over the feedback table. unsigned int i, j; if (SPI_connect() != SPI_OK_CONNECT) { fprintf(stderr, "> Error connecting to Postgres Backend.\n"); return current_tuple; } char query_buffer[1024]; snprintf(query_buffer, 1024, "SELECT columns, ranges, alltuples, qualifiedtuples FROM " "pg_kdefeedback WHERE \"table\" = %i ORDER BY \"timestamp\" DESC " "LIMIT %i;", estimator->table, requested_records); if (SPI_execute(query_buffer, true, 0) != SPI_OK_SELECT) { fprintf(stderr, "> Error querying system table.\n"); return current_tuple; } SPITupleTable *spi_tuptable = SPI_tuptable; unsigned int result_tuples = SPI_processed; TupleDesc spi_tupdesc = spi_tuptable->tupdesc; for (i = 0; i < result_tuples; ++i) { bool isnull; HeapTuple record_tuple = spi_tuptable->vals[i]; // First, check whether this record only covers columns that are part of the estimator. unsigned int columns_in_record = DatumGetInt32( SPI_getbinval(record_tuple, spi_tupdesc, 1, &isnull)); if ((columns_in_record | estimator->columns) != estimator->columns) continue; // This is a valid record, initialize the range buffer. unsigned int pos = current_tuple * 2 * estimator->nr_of_dimensions; for (j=0; j<estimator->nr_of_dimensions; ++j) { range_buffer[pos + 2*j] = -1.0 * INFINITY; range_buffer[pos + 2*j + 1] = INFINITY; } // Now extract all clauses and isert them into the range buffer. RQClause* clauses; unsigned int nr_of_clauses = extract_clauses_from_buffer(DatumGetByteaP( SPI_getbinval(record_tuple, spi_tupdesc, 2, &isnull)), &clauses); for (j=0; j<nr_of_clauses; ++j) { // First, locate the correct column position in the estimator. int column_in_estimator = estimator->column_order[clauses[j].var]; // Re-Scale the bounds, add potential padding and write them to their position. float8 lo = clauses[j].lobound; if (clauses[j].loinclusive != EX) lo -= 0.001; float8 hi = clauses[j].hibound; if (clauses[j].hiinclusive != EX) hi += 0.001; range_buffer[pos + 2*column_in_estimator] = lo; range_buffer[pos + 2*column_in_estimator + 1] = hi; } // Finally, extract the selectivity and increase the tuple count. double all_rows = DatumGetFloat8( SPI_getbinval(record_tuple, spi_tupdesc, 3, &isnull)); double qualified_rows = DatumGetFloat8( SPI_getbinval(record_tuple, spi_tupdesc, 4, &isnull)); selectivity_buffer[current_tuple++] = qualified_rows / all_rows; } // We are done :) SPI_finish(); return current_tuple; } // Helper function that extracts feedback for the given estimator and // pushes it to the device. static unsigned int ocl_prepareFeedback( ocl_estimator_t* estimator, cl_mem* device_ranges, cl_mem* device_selectivities) { cl_int err = CL_SUCCESS; // First, we have to count how many matching feedback records are available // for this estimator in the query feedback table. if (SPI_connect() != SPI_OK_CONNECT) { fprintf(stderr, "> Error connecting to Postgres Backend.\n"); return 0; } char query_buffer[1024]; snprintf(query_buffer, 1024, "SELECT COUNT(*) FROM pg_kdefeedback WHERE \"table\" = %i;", estimator->table); if (SPI_execute(query_buffer, true, 0) != SPI_OK_SELECT) { fprintf(stderr, "> Error querying system table.\n"); return 0; } SPITupleTable *tuptable = SPI_tuptable; bool isnull; unsigned int available_records = DatumGetInt32( SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &isnull)); SPI_finish(); if (available_records == 0) { fprintf(stderr, "> No feedback available for table %i\n", estimator->table); return 0; } // Adjust the number of records according to the specified window size. int used_records; if (kde_bandwidth_optimization_feedback_window == -1) used_records = available_records; else used_records = Min(available_records, kde_bandwidth_optimization_feedback_window); fprintf(stderr, "> Checking the %i latest feedback records.\n", used_records); // Allocate arrays and fetch the actual feedback data. kde_float_t* range_buffer = palloc( sizeof(kde_float_t) * 2 * estimator->nr_of_dimensions * used_records); kde_float_t* selectivity_buffer = palloc(sizeof(kde_float_t) * used_records); unsigned int actual_records = ocl_extractLatestFeedbackRecordsFromCatalog( estimator, used_records, range_buffer, selectivity_buffer); // Now push the records to the device to prepare the actual optimization. if (actual_records == 0) { fprintf(stderr, "> No valid feedback records found.\n"); return 0; } fprintf(stderr, "> Found %i valid records, pushing to device.\n", actual_records); ocl_context_t* context = ocl_getContext(); *device_ranges = clCreateBuffer( context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t) * 2 * actual_records * estimator->nr_of_dimensions, NULL, &err); Assert(err == CL_SUCCESS); err = clEnqueueWriteBuffer( context->queue, *device_ranges, CL_FALSE, 0, sizeof(kde_float_t) * 2 * actual_records * estimator->nr_of_dimensions, range_buffer, 0, NULL, NULL); estimator->stats->optimization_transfer_to_device++; Assert(err == CL_SUCCESS); *device_selectivities = clCreateBuffer( context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t) * actual_records, NULL, &err); Assert(err == CL_SUCCESS); err = clEnqueueWriteBuffer( context->queue, *device_selectivities, CL_FALSE, 0, sizeof(kde_float_t) * actual_records, selectivity_buffer, 0, NULL, NULL); estimator->stats->optimization_transfer_to_device++; Assert(err == CL_SUCCESS); err = clFinish(context->queue); Assert(err == CL_SUCCESS); pfree(range_buffer); pfree(selectivity_buffer); return actual_records; } typedef struct { ocl_estimator_t* estimator; unsigned int nr_of_observations; cl_mem observed_ranges; cl_mem observed_selectivities; // Temporary buffers. size_t stride_size; cl_mem gradient_accumulator_buffer; cl_mem error_accumulator_buffer; cl_mem gradient_buffer; cl_mem error_buffer; // Required event and accumulation buffers. ocl_aggregation_descriptor_t** summation_descriptors; cl_mem* summation_buffers; } optimization_config_t; /** * Counters for evaluations. */ int evaluations; double start_error; struct timeval opt_start; /* * Function to compute the gradient for a penalized objective function that will * add a strong penalty factor to negative bandwidth values. This function is * passed to nlopt to compute the gradient and evaluate the function. */ /* * Callback function that computes the gradient and value for the objective * function at the current bandwidth. */ static double computeGradient( unsigned n, const double* bandwidth, double* gradient, void* params) { unsigned int i; cl_int err = CL_SUCCESS; optimization_config_t* conf = (optimization_config_t*)params; ocl_estimator_t* estimator = conf->estimator; ocl_context_t* context = ocl_getContext(); evaluations++; if (ocl_isDebug()) { fprintf(stderr, ">>> Evaluation %i:\n\tCurrent bandwidth:", evaluations); for (i=0; i<n; ++i) fprintf(stderr, " %e", bandwidth[i]); fprintf(stderr, "\n"); } // First, transfer the current bandwidth to the device. Note that we might // need to cast the bandwidth to float first. kde_float_t* fbandwidth = NULL; cl_event input_transfer_event; if (sizeof(kde_float_t) != sizeof(double)) { fbandwidth = palloc(sizeof(kde_float_t) * estimator->nr_of_dimensions); for (i = 0; i<estimator->nr_of_dimensions; ++i) { fbandwidth[i] = bandwidth[i]; } err = clEnqueueWriteBuffer( context->queue, estimator->bandwidth_buffer, CL_FALSE, 0, sizeof(kde_float_t) * estimator->nr_of_dimensions, fbandwidth, 0, NULL, &input_transfer_event); estimator->stats->optimization_transfer_to_device++; Assert(err == CL_SUCCESS); } else { err = clEnqueueWriteBuffer( context->queue, estimator->bandwidth_buffer, CL_FALSE, 0, sizeof(kde_float_t) * estimator->nr_of_dimensions, bandwidth, 0, NULL, &input_transfer_event); estimator->stats->optimization_transfer_to_device++; Assert(err == CL_SUCCESS); } // Prepare the kernel that computes a gradient for each observation. cl_kernel gradient_kernel = ocl_getKernel( ocl_getSelectedErrorMetric()->batch_kernel_name, estimator->nr_of_dimensions); // First, fix the local and global size. We identify the optimal local size // by looking at available and required local memory and by ensuring that // the local size is evenly divisible by the preferred workgroup multiple.. size_t local_size; err = clGetKernelWorkGroupInfo( gradient_kernel, context->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &local_size, NULL); Assert(err == CL_SUCCESS); size_t available_local_memory; err = clGetKernelWorkGroupInfo( gradient_kernel, context->device, CL_KERNEL_LOCAL_MEM_SIZE, sizeof(size_t), &available_local_memory, NULL); Assert(err == CL_SUCCESS); available_local_memory = context->local_mem_size - available_local_memory; local_size = Min( local_size, available_local_memory / (3 * sizeof(kde_float_t) * estimator->nr_of_dimensions)); size_t preferred_local_size_multiple; err = clGetKernelWorkGroupInfo( gradient_kernel, context->device, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), &preferred_local_size_multiple, NULL); Assert(err == CL_SUCCESS); local_size = preferred_local_size_multiple * (local_size / preferred_local_size_multiple); size_t global_size = local_size * (conf->nr_of_observations / local_size); if (global_size < conf->nr_of_observations) global_size += local_size; // Configure the kernel by setting all required parameters. err |= clSetKernelArg( gradient_kernel, 0, sizeof(cl_mem), &(estimator->sample_buffer)); err |= clSetKernelArg( gradient_kernel, 1, sizeof(unsigned int), &(estimator->rows_in_sample)); err |= clSetKernelArg( gradient_kernel, 2, sizeof(cl_mem), &(conf->observed_ranges)); err |= clSetKernelArg( gradient_kernel, 3, sizeof(cl_mem), &(conf->observed_selectivities)); err |= clSetKernelArg( gradient_kernel, 4, sizeof(unsigned int), &(conf->nr_of_observations)); err |= clSetKernelArg( gradient_kernel, 5, sizeof(cl_mem), &(estimator->bandwidth_buffer)); err |= clSetKernelArg( gradient_kernel, 6, local_size * sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL); err |= clSetKernelArg( gradient_kernel, 7, local_size * sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL); err |= clSetKernelArg( gradient_kernel, 8, local_size * sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL); err |= clSetKernelArg( gradient_kernel, 9, sizeof(cl_mem), &(conf->error_accumulator_buffer)); err |= clSetKernelArg( gradient_kernel, 10, sizeof(cl_mem), &(conf->gradient_accumulator_buffer)); unsigned int stride_elements = conf->stride_size / sizeof(kde_float_t); err |= clSetKernelArg( gradient_kernel, 11, sizeof(unsigned int), &stride_elements); err |= clSetKernelArg( gradient_kernel, 12, sizeof(unsigned int), &(estimator->rows_in_table)); err |= clSetKernelArg( gradient_kernel, 13, sizeof(cl_mem), &(estimator->mean_buffer)); err |= clSetKernelArg( gradient_kernel, 14, sizeof(cl_mem), &(estimator->sdev_buffer)); Assert(err == CL_SUCCESS); // Compute the gradient for each observation. cl_event partial_gradient_event; err = clEnqueueNDRangeKernel( context->queue, gradient_kernel, 1, NULL, &global_size, &local_size, 1, &input_transfer_event, &partial_gradient_event); Assert(err == CL_SUCCESS); // Sum up the individual error contributions ... cl_event* summation_events = palloc( sizeof(cl_event) * (1 + estimator->nr_of_dimensions)); summation_events[0] = predefinedSumOfArray( conf->summation_descriptors[0], partial_gradient_event); // .. and the individual gradients. for (i=0; i<estimator->nr_of_dimensions; ++i) { summation_events[i + 1] = predefinedSumOfArray( conf->summation_descriptors[i + 1], partial_gradient_event); } // Now transfer the gradient back to the device. cl_event result_events[2]; kde_float_t* tmp_gradient = palloc( sizeof(kde_float_t) * estimator->nr_of_dimensions); err = clEnqueueReadBuffer( context->queue, conf->gradient_buffer, CL_FALSE, 0, sizeof(kde_float_t) * estimator->nr_of_dimensions, tmp_gradient, estimator->nr_of_dimensions + 1, summation_events, &(result_events[0])); estimator->stats->optimization_transfer_to_host++; Assert(err == CL_SUCCESS); // As well as the error. kde_float_t error; err = clEnqueueReadBuffer( context->queue, conf->error_buffer, CL_FALSE, 0, sizeof(kde_float_t), &error, 1, &(summation_events[0]), &(result_events[1])); estimator->stats->optimization_transfer_to_host++; Assert(err == CL_SUCCESS); err = clWaitForEvents(2, result_events); Assert(err == CL_SUCCESS); if (err != 0) { fprintf(stderr, "OpenCL functions failed to compute gradient.\n"); } error /= conf->nr_of_observations; if (evaluations == 1) start_error = error; struct timeval now; gettimeofday(&now, NULL); long seconds = now.tv_sec - opt_start.tv_sec; long useconds = now.tv_usec - opt_start.tv_usec; long mtime = ((seconds) * 1000 + useconds / 1000.0) + 0.5; // Ok, cool. Transfer the bandwidth back. if (ocl_isDebug()) { fprintf( stderr, "\r\tOptimization round %i. Current error: %f " "(started at %f), took: %ld ms.", evaluations, error, start_error, mtime); } // Finally, cast back to double. if (gradient) { for (i = 0; i<estimator->nr_of_dimensions; ++i) { // Apply the gradient normalization. double h = bandwidth[i]; if(kde_bandwidth_representation == PLAIN_BW){ gradient[i] = tmp_gradient[i] * M_SQRT2 / ( sqrt(M_PI) * h * h * pow(2.0, estimator->nr_of_dimensions) * conf->nr_of_observations * estimator->rows_in_sample); } else { gradient[i] = tmp_gradient[i] * M_SQRT2 / ( sqrt(M_PI) * exp(h) * pow(2.0, estimator->nr_of_dimensions) * conf->nr_of_observations * estimator->rows_in_sample); } } if (ocl_isDebug()) { fprintf(stderr, "\n\tGradient:"); for (i=0; i<n; ++i) fprintf(stderr, " %e", gradient[i]); fprintf(stderr, "\n"); } } // Ok, clean everything up. for (i=0; i<estimator->nr_of_dimensions; ++i) { err = clReleaseEvent(summation_events[i]); Assert(err == CL_SUCCESS); } pfree(summation_events); pfree(tmp_gradient); if (fbandwidth) pfree(fbandwidth); err |= clReleaseEvent(input_transfer_event); err |= clReleaseEvent(partial_gradient_event); err |= clReleaseEvent(result_events[0]); err |= clReleaseEvent(result_events[1]); err |= clReleaseKernel(gradient_kernel); Assert(err == CL_SUCCESS); return error; } static void ocl_setScottsBandwidth(ocl_estimator_t* estimator) { ocl_context_t* context = ocl_getContext(); cl_int err = CL_SUCCESS; // First, we need to compute the variance for each dimension. unsigned int i; kde_float_t* variances = malloc( sizeof(kde_float_t) * estimator->nr_of_dimensions); cl_mem* buffers = malloc(sizeof(cl_mem) * estimator->nr_of_dimensions); cl_mem averages = clCreateBuffer( context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t) * estimator->nr_of_dimensions, NULL, &err); Assert(err == CL_SUCCESS); cl_event* events = malloc(sizeof(cl_event) * estimator->nr_of_dimensions); size_t sample_size = estimator->rows_in_sample; size_t dimensions = estimator->nr_of_dimensions; for (i=0; i<estimator->nr_of_dimensions; ++i) { // Allocate all required buffers. buffers[i] = clCreateBuffer( context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t) * estimator->rows_in_sample, NULL, &err); Assert(err == CL_SUCCESS); // First we extract all sample components for this dimension. cl_kernel extractComponents = ocl_getKernel("extract_dimension", 0); err |= clSetKernelArg( extractComponents, 0, sizeof(cl_mem), &(estimator->sample_buffer)); err |= clSetKernelArg(extractComponents, 1, sizeof(cl_mem), &(buffers[i])); err |= clSetKernelArg(extractComponents, 2, sizeof(unsigned int), &i); err |= clSetKernelArg(extractComponents, 3, sizeof(unsigned int), &(estimator->nr_of_dimensions)); Assert(err == CL_SUCCESS); cl_event extraction_event; err = clEnqueueNDRangeKernel( context->queue, extractComponents, 1, NULL, &sample_size, NULL, 0, NULL, &extraction_event); Assert(err == CL_SUCCESS); // Now we sum them up, so we can compute the average. cl_event average_summation_event = sumOfArray( buffers[i], estimator->rows_in_sample, averages, i, extraction_event); // Alright, we can compute the variance contributions from each point. cl_kernel precomputeVariance = ocl_getKernel("precompute_variance", 0); err |= clSetKernelArg(precomputeVariance, 0, sizeof(cl_mem), &(buffers[i])); err |= clSetKernelArg(precomputeVariance, 1, sizeof(cl_mem), &averages); err |= clSetKernelArg(precomputeVariance, 2, sizeof(unsigned int), &i); err |= clSetKernelArg(precomputeVariance, 3, sizeof(unsigned int), &(estimator->rows_in_sample)); cl_event variance_event; err = clEnqueueNDRangeKernel( context->queue, precomputeVariance, 1, NULL, &sample_size, NULL, 1, &average_summation_event, &variance_event); Assert(err == CL_SUCCESS); // We now sum up the single contributions to compute the variance. cl_event variance_summation_event = sumOfArray( buffers[i], estimator->rows_in_sample, averages, i, variance_event); // Finally, we can compute and store the bandwidth for this value. cl_kernel finalizeBandwidth = ocl_getKernel("set_scotts_bandwidth", 0); err |= clSetKernelArg(finalizeBandwidth, 0, sizeof(cl_mem), &averages); err |= clSetKernelArg(finalizeBandwidth, 1, sizeof(cl_mem), &(estimator->bandwidth_buffer)); err |= clSetKernelArg(finalizeBandwidth, 2, sizeof(unsigned int), &i); err |= clSetKernelArg(finalizeBandwidth, 3, sizeof(unsigned int), &(estimator->nr_of_dimensions)); err |= clSetKernelArg(finalizeBandwidth, 4, sizeof(unsigned int), &(estimator->rows_in_sample)); Assert(err == CL_SUCCESS); err = clEnqueueNDRangeKernel( context->queue, finalizeBandwidth, 1, NULL, &dimensions, NULL, 1, &variance_summation_event, &events[i]); Assert(err == CL_SUCCESS); // Clean up. err = clReleaseMemObject(buffers[i]); Assert(err == CL_SUCCESS); err |= clReleaseEvent(extraction_event); err |= clReleaseEvent(average_summation_event); err |= clReleaseEvent(variance_event); err |= clReleaseEvent(variance_summation_event); Assert(err == CL_SUCCESS); } err = clReleaseMemObject(averages); Assert(err == CL_SUCCESS); // Wait for the events to finalize: err = clWaitForEvents(estimator->nr_of_dimensions, events); Assert(err == CL_SUCCESS); for (i=0; i<estimator->nr_of_dimensions; ++i) { err = clReleaseEvent(events[i]); Assert(err == CL_SUCCESS); } // Clean up. free(variances); free(events); } void ocl_runModelOptimization(ocl_estimator_t* estimator) { if (estimator == NULL) return; cl_int err = CL_SUCCESS; // Set the rule-of-thumb bandwidth to initialize the estimator. ocl_setScottsBandwidth(estimator); // Now check if we do a full bandwidth optimization. if (!kde_enable_bandwidth_optimization) return; if (ocl_isDebug()) { fprintf( stderr, "Beginning model optimization for estimator on table %i\n", estimator->table); } // First, we need to fetch the feedback records for this table and push them // to the device. cl_mem device_ranges, device_selectivites; unsigned int feedback_records = ocl_prepareFeedback( estimator, &device_ranges, &device_selectivites); if (feedback_records == 0) return; // We need to transfer the bandwidth to the host. kde_float_t* fbandwidth = palloc( sizeof(kde_float_t) * estimator->nr_of_dimensions); ocl_context_t* context = ocl_getContext(); err = clEnqueueReadBuffer( context->queue, estimator->bandwidth_buffer, CL_TRUE, 0, sizeof(kde_float_t) * estimator->nr_of_dimensions, fbandwidth, 0, NULL, NULL); estimator->stats->optimization_transfer_to_host++; Assert(err == CL_SUCCESS); // Cast to double (nlopt operates on double). double* bandwidth = lbfgs_malloc(estimator->nr_of_dimensions); unsigned int i; for (i=0; i<estimator->nr_of_dimensions; ++i) { bandwidth[i] = fbandwidth[i]; } // Package all required buffers. optimization_config_t params; params.estimator = estimator; params.nr_of_observations = feedback_records; params.observed_ranges = device_ranges; params.observed_selectivities = device_selectivites; params.error_accumulator_buffer = clCreateBuffer( context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t) * feedback_records, NULL, &err); Assert(err == CL_SUCCESS); // Allocate a buffer to hold temporary gradient contributions. This buffer // will keep D contributions per observation. We store all contributions // consecutively (i.e. 111222333444). For optimal performance, we therefore // have to make sure that the consecutive regions (strides) have a size that // is aligned to the required machine alignment. params.stride_size = sizeof(kde_float_t) * feedback_records; if ((params.stride_size * 8) % context->required_mem_alignment) { // The stride size is misaligned, add some padding. params.stride_size *= 8; params.stride_size = (1 + params.stride_size / context->required_mem_alignment) * context->required_mem_alignment; params.stride_size /= 8; } params.gradient_accumulator_buffer = clCreateBuffer( context->context, CL_MEM_READ_WRITE, estimator->nr_of_dimensions * params.stride_size, NULL, &err); Assert(err == CL_SUCCESS); params.gradient_buffer = clCreateBuffer( context->context, CL_MEM_READ_WRITE, estimator->nr_of_dimensions * sizeof(kde_float_t), NULL, &err); Assert(err == CL_SUCCESS); params.error_buffer = clCreateBuffer( context->context, CL_MEM_READ_WRITE, sizeof(kde_float_t), NULL, &err); Assert(err == CL_SUCCESS); // Prepare the summation buffers. params.summation_descriptors = palloc( sizeof(ocl_aggregation_descriptor_t) * (1 + estimator->nr_of_dimensions)); // Prepare the partial aggregations for the error. params.summation_descriptors[0] = prepareSumDescriptor( params.error_accumulator_buffer, params.nr_of_observations, params.error_buffer, 0); // .. and for each dimension. params.summation_buffers = palloc( sizeof(cl_mem) * estimator->nr_of_dimensions); for (i=0; i<estimator->nr_of_dimensions; ++i) { cl_buffer_region region; region.size = params.stride_size; region.origin = i * params.stride_size; params.summation_buffers[i] = clCreateSubBuffer( params.gradient_accumulator_buffer, CL_MEM_READ_ONLY, CL_BUFFER_CREATE_TYPE_REGION, &region, &err); Assert(err == CL_SUCCESS); params.summation_descriptors[i + 1] = prepareSumDescriptor( params.summation_buffers[i], params.nr_of_observations, params.gradient_buffer, i); } // Ok, we are prepared. Call the optimization routine. gettimeofday(&opt_start, NULL); evaluations = 0; fprintf(stderr, "> Starting numerical optimization of the model.\n"); // Prepare the bound constraints. double* lower_bounds = palloc(sizeof(double) * estimator->nr_of_dimensions); double* upper_bounds = palloc(sizeof(double) * estimator->nr_of_dimensions); if(kde_bandwidth_representation == LOG_BW){ for (i=0; i<estimator->nr_of_dimensions; ++i) { lower_bounds[i] = log(1e-20); // We never want to be negative. } for (i=0; i<estimator->nr_of_dimensions; ++i) { upper_bounds[i] = log(4) + bandwidth[i]; // We never want to be negative. } } else { for (i=0; i<estimator->nr_of_dimensions; ++i) { lower_bounds[i] = 1e-20; // We never want to be negative. } for (i=0; i<estimator->nr_of_dimensions; ++i) { upper_bounds[i] = 4 * bandwidth[i]; } } double tmp; int nl_err; // We start with a global optimization step. nlopt_opt global_optimizer = nlopt_create( NLOPT_GD_MLSL, estimator->nr_of_dimensions); Assert(global_optimizer); nl_err = nlopt_set_lower_bounds(global_optimizer, lower_bounds); Assert(nl_err > 0 ); nl_err = nlopt_set_upper_bounds(global_optimizer, upper_bounds); Assert(nl_err > 0 ); nl_err = nlopt_set_maxeval(global_optimizer, 120); Assert(nl_err > 0 ); nl_err = nlopt_set_min_objective(global_optimizer, computeGradient, &params); Assert(nl_err > 0 ); // Register a local LBFGS instance for the global optimizer. nlopt_opt global_local_optimizer = nlopt_create( NLOPT_LD_LBFGS, estimator->nr_of_dimensions); nl_err = nlopt_set_maxeval(global_local_optimizer, 40); Assert(nl_err > 0 ); nl_err = nlopt_set_local_optimizer(global_optimizer, global_local_optimizer); Assert(nl_err > 0 ); fprintf(stderr, "> Running global pre-optimization: "); nl_err = nlopt_optimize(global_optimizer, bandwidth, &tmp); Assert(nl_err > 0 ); fprintf(stderr, " done (%i, %f)\n", nl_err, tmp); // Prepare the local refinement. nlopt_opt local_optimizer = nlopt_create( NLOPT_LD_LBFGS, estimator->nr_of_dimensions); nlopt_set_lower_bounds(local_optimizer, lower_bounds); nlopt_set_min_objective(local_optimizer, computeGradient, &params); nlopt_set_ftol_abs(local_optimizer, 1e-20); nlopt_set_maxeval(local_optimizer, 100); fprintf(stderr, "> Running local refinement: "); err = nlopt_optimize(local_optimizer, bandwidth, &tmp); fprintf(stderr, " done (%i, %f)\n", err, tmp); if (ocl_isDebug()) { if (err < 0) { fprintf(stderr, "\nOptimization failed: %i!", err); } else { fprintf(stderr, "\nNew bandwidth:"); for ( i = 0; i < estimator->nr_of_dimensions ; ++i) fprintf(stderr, " %e", bandwidth[i]); fprintf(stderr, "\n"); } } nlopt_destroy(local_optimizer); // Transfer the bandwidth to the device. for (i=0; i<estimator->nr_of_dimensions; ++i) { fbandwidth[i] = bandwidth[i]; } err = clEnqueueWriteBuffer( context->queue, estimator->bandwidth_buffer, CL_TRUE, 0, sizeof(kde_float_t) * estimator->nr_of_dimensions, fbandwidth, 0, NULL, NULL); estimator->stats->optimization_transfer_to_device++; Assert(err == CL_SUCCESS); // Clean up. pfree(fbandwidth); lbfgs_free(bandwidth); for (i=0; i<estimator->nr_of_dimensions; ++i) { err = clReleaseMemObject(params.summation_buffers[i]); Assert(err == CL_SUCCESS); releaseAggregationDescriptor(params.summation_descriptors[i + 1]); } releaseAggregationDescriptor(params.summation_descriptors[0]); pfree(params.summation_descriptors); pfree(params.summation_buffers); err |= clReleaseMemObject(params.error_buffer); err |= clReleaseMemObject(params.gradient_buffer); err |= clReleaseMemObject(params.error_accumulator_buffer); err |= clReleaseMemObject(params.gradient_accumulator_buffer); err |= clReleaseMemObject(device_ranges); err |= clReleaseMemObject(device_selectivites); Assert(err == CL_SUCCESS); }
{ "alphanum_fraction": 0.7051532942, "avg_line_length": 40.4485488127, "ext": "c", "hexsha": "219fcefe57f852bd7be448f7cb57b8dc2f37279c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-18T12:42:07.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-17T16:06:33.000Z", "max_forks_repo_head_hexsha": "96e2a861dbb285b268d712e9076b89d0da104e01", "max_forks_repo_licenses": [ "PostgreSQL" ], "max_forks_repo_name": "sfu-db/feedback-kde", "max_forks_repo_path": "src/backend/optimizer/path/gpukde/ocl_model_maintenance.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "96e2a861dbb285b268d712e9076b89d0da104e01", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "PostgreSQL" ], "max_issues_repo_name": "sfu-db/feedback-kde", "max_issues_repo_path": "src/backend/optimizer/path/gpukde/ocl_model_maintenance.c", "max_line_length": 91, "max_stars_count": 1, "max_stars_repo_head_hexsha": "96e2a861dbb285b268d712e9076b89d0da104e01", "max_stars_repo_licenses": [ "PostgreSQL" ], "max_stars_repo_name": "sfu-db/feedback-kde", "max_stars_repo_path": "src/backend/optimizer/path/gpukde/ocl_model_maintenance.c", "max_stars_repo_stars_event_max_datetime": "2021-05-13T05:39:12.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-13T05:39:12.000Z", "num_tokens": 7751, "size": 30660 }
#ifndef SOURCE_ROBANALYT_H_ #define SOURCE_ROBANALYT_H_ // *** source/rob_analyt.h *** // Author: Kevin Wolz, date: 08/2018 // // Class RobAnalyt: analytical algorithm to calculate distribution in the WPL. #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <stdlib.h> #include <sys/stat.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_integration.h> #include "utils.h" #include "print_to_file.h" class RobAnalyt { public: gsl_matrix* gaussian_quadratic_matrix_; // quadratic contraction with data unsigned int num_steps_; // number of PDF evaluation points double lower_limit_; // lower limit of PDF calculation double upper_limit_; // upper limit of PDF calculation RobAnalyt(int num_steps, double upper_limit, double lower_limit, unsigned int datdim, // number of data points unsigned int pardim, // number of models parameters gsl_matrix* g_matrix, // model design matrix gsl_matrix* inv_covar_matrix, // inverse data covariance matrix gsl_matrix* fisher_matrix_tot, // Fisher matrix of total data gsl_matrix* fisher_matrix_1, // Fisher matrix of first subset gsl_matrix* fisher_matrix_2, // Fisher matrix of second subset gsl_matrix* prior_matrix, gsl_vector* prior_param_values, // prior fiducial parameter values gsl_vector* data_mean_values); // mean of data vector int CalculateAnalytWeakPrior(std::string& filepath); private: unsigned int datdim_; unsigned int pardim_; gsl_matrix* g_matrix_tot_; gsl_matrix* g_matrix_1_; gsl_matrix* g_matrix_2_; gsl_matrix* inv_covar_matrix_tot_; gsl_matrix* inv_covar_matrix_1_; gsl_matrix* inv_covar_matrix_2_; gsl_matrix* fisher_matrix_tot_; gsl_matrix* fisher_matrix_1_; gsl_matrix* fisher_matrix_2_; gsl_matrix* prior_matrix_; gsl_vector* prior_param_values_; gsl_vector* data_mean_values_; double delta_y_; // constant shift of Robustness (1) double delta_y_wpl_; // constant shift of Robustness (WPL, 1) double rob_constant_; // constant shift of Robustness (2) gsl_vector* linear_gaussian_vector_; // linear contraction with data gsl_matrix* covar_matrix_tot_; // covariance matrix of total data }; #endif // SOURCE_ROBANALYT_H_
{ "alphanum_fraction": 0.7120921305, "avg_line_length": 32.9746835443, "ext": "h", "hexsha": "2066804bf1fe918d02a2c32f2b38d51d95f32d81", "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/rob_analyt.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/rob_analyt.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/rob_analyt.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 691, "size": 2605 }
#include "lah.h" #ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */ #include <lapacke.h> lah_Return lah_chol(lah_mat *P, lah_index setZero) { lah_index i, j; lapack_int res; if (P == NULL || !LAH_ISTYPE(P, lahTypeSquare)) return lahReturnParameterError; res = POTRF(LAH_LAPACK_LAYOUT, 'L' , P->nR, P->data, P->nR); /* Set rest of matrix to zero, if setZero == 1 */ if (setZero) { for (i = 0; i < P->nR; i++) { for(j = i + 1; j < P->nC; ++j) { LAH_ENTRY(P, i, j) = 0.0; } } } return (res == 0) ? lahReturnOk : lahReturnExternError; } #else /* fallback to primitive linear algebra subroutines */ #include <math.h> lah_Return lah_chol(lah_mat *P, lah_index setZero) { lah_index i, j, k, N; lah_value *diag, *value; if (P == NULL) { return lahReturnParameterError; } N = P->nR; /* see https://de.wikipedia.org/wiki/Cholesky-Zerlegung#Pseudocode */ for (i = 0; i < N; i++) { /* Pointer to diagonal element */ diag = P->data + i * (P->incRow + P->incCol); /* check if positive */ if (*diag < 0.00001 ) { return lahReturnMathError; } /* square root of diagonal element in place */ *diag = sqrt(*diag); /* divide elements below diagonal by diagonal element */ for (k = 1; k < N - i; k++) { *(diag + k * P->incRow) /= *diag; } /* compute upper right submatrix */ for (j = i + 1; j < N; j++) { value = P->data + j * P->incRow + j * P->incCol; for (k = j; k < N; k++) { *value -= LAH_ENTRY(P, k, i) * LAH_ENTRY(P, j, i); value += P->incRow; } } } /* Set rest of matrix to zero, if setZero == 1 */ if (setZero) { for (i = 0; i < N; i++) { for(j = i + 1; j < N; ++j) { LAH_ENTRY(P, i, j) = 0.0; } } } return lahReturnOk; } #endif /* endif primitive implementation */
{ "alphanum_fraction": 0.4708029197, "avg_line_length": 25.1954022989, "ext": "c", "hexsha": "0e01cb15c7605ec5c64e174b300b34d41d5408a3", "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_chol.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_chol.c", "max_line_length": 73, "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_chol.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 650, "size": 2192 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_drotg (double *a, double *b, double *c, double *s) { #define BASE double #include "source_rotg.h" #undef BASE }
{ "alphanum_fraction": 0.7083333333, "avg_line_length": 16, "ext": "c", "hexsha": "f7103bf0e6259780d693a1d4c5e5b4c6a9a355d9", "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/drotg.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/drotg.c", "max_line_length": 56, "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/drotg.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": 63, "size": 192 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <assert.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include "core_allvars.h" #include "model_dust.h" #include "model_misc.h" double integrate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const double lower_limit, const double upper_limit); double interpolate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const int xi); double compute_imf (const double m); double compute_taum (const double m); void produce_metals_dust(const double metallicity, const double dt, const int p, const int centralgal, const int step, struct GALAXY *galaxies) { double A = run_params.BinaryFraction; double yield; double yCr_snia, yFe_snia, yNi_snia; double yC_agb, yN_agb, yO_agb; double yC_sn, yO_sn, yMg_sn, ySi_sn, yS_sn, yCa_sn, yFe_sn; double Cr_snia, Fe_snia, Ni_snia; double C_agb, N_agb, O_agb; double C_sn, O_sn, Mg_sn, Si_sn, S_sn, Ca_sn, Fe_sn; double yCagb[run_params.countagb], yNagb[run_params.countagb], yOagb[run_params.countagb]; double m_agb[run_params.countagb]; double yCsn[run_params.countsn], yOsn[run_params.countsn], yMgsn[run_params.countsn], ySisn[run_params.countsn], ySsn[run_params.countsn], yCasn[run_params.countsn], yFesn[run_params.countsn]; double m_sn[run_params.countsn]; int i, j; double phi, taum, time, sfr; double gamma = 2.0; //to compute binary mass function for SN Ia double low_agb = 1; //lower limit for stars that ends up as AGB, Msun double low_binary = 3; //lower limit for binary star, Msun double up_agb = 6; //upper limit for stars that ends up as AGB, Msun double low_sn = run_params.msn[0]; //lower limit for stars that ends up as SN II, Msun double up_binary = 16; //upper limit for binary stars, Msun double up_sn = 40; //upper limit for stars that ends up as SN II, Msun double age[SNAPLEN], sfh[SNAPLEN]; for (i=0; i<SNAPLEN; i++) { age[i] = run_params.lbtime[i]; //change the variable name to represent the age of universe instead of lbtime sfh[i] = galaxies[p].Sfr[i]; } /* the following computation is from eq. 9 Arrigoni et al. 2010 */ // SN Ia // int count = 20; //any nymber will do double mu[count]; // M2/Mbinary double mbin[count]; //total mass of binary double fmu, yCrmu[count], yFemu[count], yNimu[count]; //to integrate over mu double yCrphi[count], yFephi[count], yNiphi[count]; double max_mu = 0.5; //maximum value of mu for (i=0; i<count; i++){ mbin[i] = low_binary + ((up_binary - low_binary) / (count-i)); mu[i] = max_mu/(count-i); fmu = pow(2, 1+gamma) * (1+gamma) * pow(mu[i], gamma); //eq. 10 Arrigoni et al. 2010 taum = compute_taum(mu[i] * mbin[i]); time = age[galaxies[p].SnapNum] - taum; if(time < run_params.lbtime[0]){ sfr=0; } else { sfr = interpolate_arr(age, sfh, SNAPLEN, time); } yCrmu[i] = fmu * sfr * run_params.qCrsnia; yFemu[i] = fmu * sfr * run_params.qFesnia; yNimu[i] = fmu * sfr * run_params.qNisnia; } double yCr = integrate_arr(mu, yCrmu, count, max_mu/count, max_mu); double yFe = integrate_arr(mu, yFemu, count, max_mu/count, max_mu); double yNi = integrate_arr(mu, yNimu, count, max_mu/count, max_mu); for (i=0; i<count; i++){ yCrphi[i] = yCr * compute_imf(mbin[i]); yFephi[i] = yFe * compute_imf(mbin[i]); yNiphi[i] = yNi * compute_imf(mbin[i]); //printf("SNIa done \n"); } // AGB // if(run_params.AGBYields == 0) { i = j = 0; double Z_std[METALGRID] = {0.0, 1e-4, 4e-4, 4e-3, 8e-3, 0.02, 0.05}; double sfrz = metallicity; if (sfrz < Z_std[0]){ sfrz = Z_std[0];} else if (sfrz > Z_std[6]){ sfrz = Z_std[6];} for (i=0; i<METALGRID; i++) { if(Z_std[i] <= sfrz && Z_std[i] > sfrz) { j = i; } } //double yCagb[run_params.countagb], yNagb[run_params.countagb], yOagb[run_params.countagb]; //double m_agb[run_params.countagb]; for(i=0; i<run_params.countagb; i++){ if(run_params.magb[i] != 0) { m_agb[i] = run_params.magb[i]; phi = compute_imf(run_params.magb[i]); taum = compute_taum(run_params.magb[i]); time = age[galaxies[p].SnapNum] - taum; if(time < run_params.lbtime[0]){ sfr=0; } else { sfr = interpolate_arr(age, sfh, SNAPLEN, time); } yCagb[i] = run_params.qCagb[i][j] * phi * sfr; yNagb[i] = run_params.qNagb[i][j] * phi * sfr; yOagb[i] = run_params.qOagb[i][j] * phi * sfr; } else { yCagb[i] = 0; yNagb[i] = 0; yOagb[i] = 0; } } //printf("AGB done \n"); } // SN II // if(run_params.SNIIYields == 0) //Woosley & Weaver 1995 { i = j = 0; double Z_std[METALGRID] = {0.0, 1e-4, 4e-4, 4e-3, 8e-3, 0.02, 0.05}; double sfrz = metallicity; if (sfrz < Z_std[0]){ sfrz = Z_std[0];} else if (sfrz > Z_std[6]){ sfrz = Z_std[6];} for (i=0; i<METALGRID; i++) { if(Z_std[i] <= sfrz && Z_std[i] > sfrz) { j = i; } } for(i=0; i<run_params.countsn; i++){ if(run_params.msn[i] != 0) { m_sn[i] = run_params.msn[i]; phi = compute_imf(run_params.msn[i]); taum = compute_taum(run_params.msn[i]); time = age[galaxies[p].SnapNum] - taum; if(time < run_params.lbtime[0]){ sfr=0; } else { sfr = interpolate_arr(age, sfh, SNAPLEN, time); } yCsn[i] = run_params.qCsn[i][j] * phi * sfr; yOsn[i] = run_params.qOsn[i][j] * phi * sfr; yMgsn[i] = run_params.qMgsn[i][j] * phi * sfr; ySisn[i] = run_params.qSisn[i][j] * phi * sfr; ySsn[i] = run_params.qSsn[i][j] * phi * sfr; yCasn[i] = run_params.qCasn[i][j] * phi * sfr; yFesn[i] = run_params.qFesn[i][j] * phi * sfr; } else { yCsn[i] = 0; yOsn[i] = 0; yMgsn[i] = 0; ySisn[i] = 0; ySsn[i] = 0; yCasn[i] = 0; yFesn[i] = 0; } } //printf("SNII done \n"); } else if(run_params.SNIIYields == 1) //Nomoto et al. 2006 { i = j = 0; double Z_std[METALGRID] = {0.0, 0.001, 0004, 0.02}; double sfrz = metallicity; if (sfrz < Z_std[0]){ sfrz = Z_std[0];} else if (sfrz > Z_std[3]){ sfrz = Z_std[3];} for (i=0; i<METALGRID; i++) { if(Z_std[i] <= sfrz && Z_std[i] > sfrz) { j = i; } } for(i=0; i<run_params.countsn; i++){ if(run_params.msn[i] != 0) { m_sn[i] = run_params.msn[i]; phi = compute_imf(run_params.msn[i]); taum = compute_taum(run_params.msn[i]); time = age[galaxies[p].SnapNum] - taum; if(time < run_params.lbtime[0]){ sfr=0; } else { sfr = interpolate_arr(age, sfh, SNAPLEN, time); } yCsn[i] = run_params.qCsn[i][j] * phi * sfr; yOsn[i] = run_params.qOsn[i][j] * phi * sfr; yMgsn[i] = run_params.qMgsn[i][j] * phi * sfr; ySisn[i] = run_params.qSisn[i][j] * phi * sfr; ySsn[i] = run_params.qSsn[i][j] * phi * sfr; yCasn[i] = run_params.qCasn[i][j] * phi * sfr; yFesn[i] = run_params.qFesn[i][j] * phi * sfr; } else { yCsn[i] = 0; yOsn[i] = 0; yMgsn[i] = 0; ySisn[i] = 0; ySsn[i] = 0; yCasn[i] = 0; yFesn[i] = 0; } } //printf("SNII done \n"); } //printf("start integration"); yCr_snia = A * integrate_arr(mbin, yCrphi, count, mbin[0], up_binary); yNi_snia = A * integrate_arr(mbin, yNiphi, count, mbin[0], up_binary); yFe_snia = A * integrate_arr(mbin, yFephi, count, mbin[0], up_binary); yC_agb = (1-A) * integrate_arr(m_agb, yCagb, run_params.countagb, low_binary, up_agb) + integrate_arr(m_agb, yCagb, run_params.countagb, low_agb, low_binary); yN_agb = (1-A) * integrate_arr(m_agb, yNagb, run_params.countagb, low_binary, up_agb) + integrate_arr(m_agb, yNagb, run_params.countagb, low_agb, low_binary); yO_agb = (1-A) * integrate_arr(m_agb, yOagb, run_params.countagb, low_binary, up_agb) + integrate_arr(m_agb, yOagb, run_params.countagb, low_agb, low_binary); yC_sn = (1-A) * integrate_arr(m_sn, yCsn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, yCsn, run_params.countsn, up_binary, up_sn); yO_sn = (1-A) * integrate_arr(m_sn, yOsn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, yOsn, run_params.countsn, up_binary, up_sn); yMg_sn = (1-A) * integrate_arr(m_sn, yMgsn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, yMgsn, run_params.countsn, up_binary, up_sn); ySi_sn = (1-A) * integrate_arr(m_sn, ySisn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, ySisn, run_params.countsn, up_binary, up_sn); yS_sn = (1-A) * integrate_arr(m_sn, ySsn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, ySsn, run_params.countsn, up_binary, up_sn); yCa_sn = (1-A) * integrate_arr(m_sn, yCasn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, yCasn, run_params.countsn, up_binary, up_sn); yFe_sn = (1-A) * integrate_arr(m_sn, yFesn, run_params.countsn, low_sn, up_binary) + integrate_arr(m_sn, yFesn, run_params.countsn, up_binary, up_sn); //printf("end integration"); double yield_agb = yC_agb + yN_agb + yO_agb; double yield_snia = yCr_snia + yNi_snia + yFe_snia; double yield_sn = yC_sn + yO_sn + yMg_sn + ySi_sn + yS_sn + yCa_sn + yFe_sn; yield = (yield_agb + yield_snia + yield_sn); //overall metallicity if(galaxies[p].ColdGas > 5.0e-2) { galaxies[p].MetalsColdGas += yield * dt; } else { galaxies[centralgal].MetalsHotGas += yield * dt; } XPRINT(galaxies[p].MetalsColdGas <= galaxies[p].ColdGas, "metallicity = %.3f, cold gas mass = %.3e, galaxy ID = %i \n", galaxies[p].MetalsColdGas / galaxies[p].ColdGas, galaxies[p].ColdGas, galaxies[p].GalaxyNr); //mass of each element formed in each production channel, should satisfy same condition with overall metallicity if(galaxies[p].ColdGas > 1.0e-2) { Cr_snia = yCr_snia * dt; Fe_snia = yFe_snia * dt; Ni_snia = yNi_snia * dt; C_agb = yC_agb * dt; N_agb = yN_agb * dt; O_agb = yO_agb * dt; C_sn = yC_sn * dt; O_sn = yO_sn * dt; Mg_sn = yMg_sn * dt; Si_sn = ySi_sn * dt; S_sn = yS_sn * dt; Ca_sn = yCa_sn * dt; Fe_sn = yFe_sn * dt; double dustdot = 0; //produce dust //double dust_agb, dust_sn, dust_snia; double delta_agb = 0.2; //should be free parameter!! (value based on Popping et al. 2017) double delta_sn = 0.2; //should be free parameter!! (value based on Popping et al. 2017) double delta_snia = 0.15; //should be free parameter!! (value based on Popping et al. 2017) assert(dt > 0 && "dt must be greater than 0"); /* eq 4 and eq 5 Popping et al. 2017 */ //from AGB if (C_agb/O_agb > 1) { dustdot += delta_agb * (C_agb - 0.75*O_agb) / dt; } else { dustdot += delta_agb * (C_agb + N_agb + O_agb) / dt; } /* eq 6 Popping et al. 2017 */ //from SN dustdot += delta_sn * C_sn / dt; dustdot += delta_sn * O_sn / dt; dustdot += 16 * delta_sn * (Mg_sn/24 + Si_sn/28 + S_sn/32 + Ca_sn/40 + Fe_sn/56) / dt; /* eq 6 Popping et al. 2017 */ //from SNIa //printf("dustdot before = %f \n", dustdot); //dustdot += 16 * delta_snia * (Fe_snia/56) / dt; //dustdot += delta_snia * (Cr_snia + Ni_snia) / dt; //printf("dustdot after = %f \n", dustdot); galaxies[p].ColdDust += dustdot * dt; galaxies[p].MetalsColdGas -= dustdot * dt; galaxies[p].dustdotform[step] += dustdot; XPRINT(dustdot * dt >= 0, "dust mass = %.3e, delta dust = %.3e, galaxy id = %i \n", galaxies[p].ColdDust, dustdot*dt, galaxies[p].GalaxyNr); } } void accrete_dust(const double metallicity, const double dt, const int p, const int step, struct GALAXY *galaxies) { //dust accretion in ISM : eq 20 Asano13 double dustdot = 0; double tacc_zero = 20 * SEC_PER_MEGAYEAR / run_params.UnitTime_in_s; //should be free parameter! yr if (galaxies[p].MetalsColdGas > galaxies[p].ColdDust && metallicity > 0 ) { double tacc = tacc_zero * 0.02 / metallicity; dustdot += (1 - galaxies[p].ColdDust/galaxies[p].MetalsColdGas) * (galaxies[p].f_H2 * galaxies[p].ColdDust / tacc); galaxies[p].dustdotgrowth[step] += dustdot; galaxies[p].ColdDust += dustdot * dt; galaxies[p].MetalsColdGas -= dustdot * dt; XPRINT(galaxies[p].ColdDust >= 0, "dust mass = %.3e, delta dust = %.3e, galaxy id = %i \n", galaxies[p].ColdDust, dustdot*dt, galaxies[p].GalaxyNr); } } void destruct_dust(const double metallicity, const double stars, const double dt, const int p, const int step, struct GALAXY *galaxies) { //dust destruction : Asano et al. 13 int i; double sfr; double dustdot = 0; double age[SNAPLEN], sfh[SNAPLEN]; double m_low = 8; //lower limit of stellar mass that end up as SN double up_binary = 16; //upper limit for binary stars, Msun double m_up = 40; //upper limit of stellar mass that end up as SN double t_low = compute_taum(m_up); //the shortest stellar lifetime that end up as SN double eta = 0.1; //should be free parameter, we used value adopted by Asano et al. 13 double m_swept = 1535 * pow((metallicity/0.02 + 0.039), -0.289) * run_params.Hubble_h / 1.e10; //eq. 14 Asano et al. 13 int count = 20; double mass[count], phi[count], mphi[count]; double A = run_params.BinaryFraction; // double m_swept = 600 * run_params.Hubble_h / 1.e10; for (i=0; i<SNAPLEN; i++) { age[i] = run_params.lbtime[i]; //change the variable name to represent the age of universe instead of lbtime sfh[i] = galaxies[p].Sfr[i]; } //Dwek & Cherchneff 2011 if (age[galaxies[p].SnapNum] > t_low) { for(i=0; i<count; i++) { mass[i] = 1 + ((m_up - 1) / (count-i)); phi[i] = compute_imf(mass[i]); mphi[i] = mass[i]*phi[i]; } /* for (i=0; i<count; i++){ mass[i] = m_low + ((m_up - m_low) / (count-i)); phi[i] = compute_imf(mass[i]); double taum = compute_taum(mass[i]); double time = age[galaxies[p].SnapNum] - taum; if(time < run_params.lbtime[0]){ sfr=0; } else { sfr = interpolate_arr(age, sfh, SNAPLEN, time); } mphi[i] = sfr*phi[i]; } */ double mstar = integrate_arr(mass, mphi, count, mass[0], m_up) / integrate_arr(mass, phi, count, m_low, m_up); double mstar_ia = integrate_arr(mass, mphi, count, mass[0], m_up) / integrate_arr(mass, phi, count, m_low, up_binary); double mstar_ii = integrate_arr(mass, mphi, count, mass[0], m_up) / integrate_arr(mass, phi, count, up_binary, m_up); double Rsn_ia = A*stars / dt / mstar_ia; double Rsn_ii = (1-A) * stars / dt / mstar_ia + stars/dt/mstar_ii; //printf("%f \n", Rsn_ii/Rsn_ia); double Rsn = stars / dt / mstar; assert(m_swept > 0 && "mass of ISM swept by SN must be greater than 0"); // if (Rsn > 0 && galaxies[p].ColdGas > 0 && galaxies[p].f_HI >0) { if (Rsn > 0 && galaxies[p].ColdGas > 0) { Rsn *= run_params.UnitMass_in_g / run_params.UnitTime_in_s * SEC_PER_YEAR / SOLAR_MASS; //convert to Msun/yr // double tsn = galaxies[p].ColdGas * galaxies[p].f_HI/ (eta * m_swept * Rsn); //eq.12 Asano et al 13 [yr] double tsn = galaxies[p].ColdGas / (eta * m_swept * Rsn); //eq.12 Asano et al 13 [yr] tsn /= run_params.UnitTime_in_s / SEC_PER_YEAR; //back to internal unit // printf("coldgas = %.3e, dust = %.3e, m_swept = %.3e, Rsn = %.3e, tsn = %.3e, dt = %.3e Myr \n", galaxies[p].ColdGas, galaxies[p].ColdDust, m_swept, Rsn, tsn * run_params.UnitTime_in_s / SEC_PER_MEGAYEAR, dt * run_params.UnitTime_in_s / SEC_PER_MEGAYEAR); // assert(tsn > 0 && "tsn must be greater than 0"); dustdot += galaxies[p].ColdDust / tsn; } if (galaxies[p].ColdDust - dustdot * dt > 0) { galaxies[p].dustdotdestruct[step] += dustdot; galaxies[p].ColdDust -= dustdot * dt; galaxies[p].MetalsColdGas += dustdot * dt; } else { galaxies[p].dustdotdestruct[step] += dustdot; galaxies[p].MetalsColdGas += galaxies[p].ColdDust; galaxies[p].ColdDust = 0; } } } void dust_thermal_sputtering(const int gal, const double dt, struct GALAXY *galaxies) //section 3.5 Popping 2017 { double adot; double a = 1e-5 / run_params.UnitLength_in_cm; //a = 0.1 micrometer double mdot = 0.0; // thermal sputtering in hot dust if(galaxies[gal].HotDust > 0.0 && galaxies[gal].Vvir > 0.0) { const double temp0 = 2e6; //in Kelvin const double temp = 35.9 * galaxies[gal].Vvir * galaxies[gal].Vvir; //in Kelvin const double gamma = 2.5; double x = -3.2e-18 / PROTONMASS / (pow(temp0/temp, gamma) + 1); //in cm^4 / g /s x /= run_params.UnitLength_in_cm / run_params.UnitDensity_in_cgs / run_params.UnitTime_in_s; //in internal unit double rho = galaxies[gal].HotGas / (4 / 3 * M_PI * galaxies[gal].Rvir * galaxies[gal].Rvir * galaxies[gal].Rvir); adot = rho / x; a -= adot * dt; assert(a > 0); a /= 1e-5 / run_params.UnitLength_in_cm; //in 0.1 micrometer unit rho *= run_params.UnitDensity_in_cgs; const double tau0 = 170 * SEC_PER_MEGAYEAR / run_params.UnitTime_in_s; // 0.17Gyr to internal unit const double tau = tau0 * (a/rho) * (pow(temp0/temp, gamma) + 1); mdot = galaxies[gal].HotDust / tau / 3; galaxies[gal].HotDust -= mdot * dt; galaxies[gal].MetalsHotGas += mdot * dt; } // thermal sputtering in ejected dust if(galaxies[gal].EjectedDust > 0.0 && galaxies[gal].Vvir > 0.0) { const double temp0 = 2e6; //in Kelvin const double temp = 35.9 * galaxies[gal].Vvir * galaxies[gal].Vvir; //in Kelvin const double gamma = 2.5; double x = -3.2e-18 / PROTONMASS / (pow(temp0/temp, gamma) + 1); //in cm^4 / g /s x /= run_params.UnitLength_in_cm / run_params.UnitDensity_in_cgs / run_params.UnitTime_in_s; //in internal unit double rho = galaxies[gal].EjectedMass / (4 / 3 * M_PI * galaxies[gal].Rvir * galaxies[gal].Rvir * galaxies[gal].Rvir); adot = rho / x; a -= adot * dt; assert(a > 0); a /= 1e-5 / run_params.UnitLength_in_cm; //in 0.1 micrometer unit rho *= run_params.UnitDensity_in_cgs; const double tau0 = 170 * SEC_PER_MEGAYEAR / run_params.UnitTime_in_s; // 0.17Gyr to internal unit const double tau = tau0 * (a/rho) * (pow(temp0/temp, gamma) + 1); mdot = galaxies[gal].EjectedDust / tau / 3; galaxies[gal].EjectedDust -= mdot * dt; galaxies[gal].MetalsEjectedMass += mdot * dt; } } double integrate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const double lower_limit, const double upper_limit) { double Q; gsl_interp_accel *acc; gsl_spline *spl; acc = gsl_interp_accel_alloc (); spl = gsl_spline_alloc (gsl_interp_linear, npts); gsl_spline_init (spl, arr1, arr2, npts); Q = gsl_spline_eval_integ (spl, lower_limit, upper_limit, acc); gsl_spline_free (spl); gsl_interp_accel_free (acc); return Q; } double interpolate_arr(const double arr1[MAX_STRING_LEN], const double arr2[MAX_STRING_LEN], const int npts, const int xi) { double Q; gsl_interp_accel *acc; gsl_spline *spl; acc = gsl_interp_accel_alloc (); spl = gsl_spline_alloc (gsl_interp_linear, npts); gsl_spline_init (spl, arr1, arr2, npts); Q = gsl_spline_eval (spl, xi, acc); gsl_spline_free (spl); gsl_interp_accel_free (acc); return Q; } double compute_imf (const double m) { //eq 11 Arrigoni et al. 2010 double mass = m; double A = 0.9098, B = 0.2539, x = 1.3, sigma=0.69; double mc = 0.079; //Msun double phi; if (m < 1){ phi = A * exp( -(log10(mass) - log10(mc)) / (2*sigma*sigma)); } else { phi = B * pow(mass, -x); } return phi; } double compute_taum (const double m) { //eq 3 Raiteri et al. 1996 double mass = m; double Z = 0.02; double a0 = 10.13 + 0.07547*log10(Z) - 0.008084*log10(Z)*log10(Z); double a1 = -4.424 - 0.7939*log10(Z) - 0.1187*log10(Z)*log10(Z); double a2 = 1.262 + 0.3385*log10(Z) + 0.05417*log10(Z)*log10(Z); double logt = a0 + a1*log10(mass) + a2*log10(mass)*log10(mass); double t = pow(10, logt) / 1e6 ; //in Myr/h /* convert into Myrs/h */ return t; }
{ "alphanum_fraction": 0.5913998339, "avg_line_length": 40.137037037, "ext": "c", "hexsha": "dc131b623a368b12f7af320d97a8e8dc5eb52b7b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-04-09T11:12:02.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-14T05:45:47.000Z", "max_forks_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dptriani/sage", "max_forks_repo_path": "src/model_dust.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b", "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": "dptriani/sage", "max_issues_repo_path": "src/model_dust.c", "max_line_length": 265, "max_stars_count": 6, "max_stars_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dptriani/sage", "max_stars_repo_path": "src/model_dust.c", "max_stars_repo_stars_event_max_datetime": "2022-03-20T04:14:05.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-06T02:47:49.000Z", "num_tokens": 7271, "size": 21674 }
/* * Copyright (c) 2018-2021 Aleksas Mazeliauskas, Stefan Floerchinger, * Eduardo Grossi, and Derek Teaney * All rights reserved. * * FastReso is distributed under MIT license; * see the LICENSE file that should be present in the root * of the source distribution, or alternately available at: * https://github.com/amazeliauskas/FastReso/ */ #ifndef FASTRESO_TFastReso_formulas_h #define FASTRESO_TFastReso_formulas_h #include <gsl/gsl_integration.h> #include "TParticle.h" #include <vector> // List of parameters for GSL integration procedure. #include "qag_params.h" #include "grid_params.h" #include <gsl/gsl_errno.h> //using namespace std; //! Eabc -- energy of b in restframe of a in a->b+c decay double get_Eabc(double ma,double mb,double mc) { return (ma*ma+mb*mb-mc*mc)/(2*ma);} //! particle momenta double get_p(double E, double m) { return sqrt(E*E-m*m);} //! pabc -- momentum of b or c in restframe of a in a->b+c decay double get_pabc(double ma,double mb,double mc) { return get_p(get_Eabc(ma,mb,mc),mb);} //! returns thermal Bose-Einstein, Fermi-Dirac or Boltzmann distribution double get_thermal_F(double Ebar, double T, double QMu, EParticleType type); //! returns derivative of thermal Bose-Einstein, Fermi-Dirac or Boltzmann distribution double get_thermal_dF(double Ebar, double T, double QMu, EParticleType type); //! Initialize f_j on the freeze-out surface //! Here you can add additional fj's double get_initial_Fj(EFjIndex j, double Ebar, double T, double QMu, EParticleType type, double m, double Cs2) { double pbar = sqrt(Ebar*Ebar-m*m); switch(j){ case EFjIndex::kFeq1: //feq 1 return pbar*get_thermal_F(Ebar,T, QMu, type); break; case EFjIndex::kFeq2: //feq 2 return pbar*get_thermal_F(Ebar,T, QMu, type); break; case EFjIndex::kFshear1: //fshear 1 return pbar*pbar*pbar*get_thermal_dF(Ebar,T, QMu, type); break; case EFjIndex::kFshear2: //fshear 2 return pbar*pbar*pbar*get_thermal_dF(Ebar,T, QMu, type); break; case EFjIndex::kFshear3: //fshear 3 return pbar*pbar*pbar*get_thermal_dF(Ebar,T, QMu, type); break; case EFjIndex::kFbulk1: //fbulk 1 return pbar*get_thermal_dF(Ebar,T, QMu, type)*(1./3.*m*m/T/Ebar-Ebar/T*(1./3.-Cs2)); break; case EFjIndex::kFbulk2: //fbulk 2 return pbar*get_thermal_dF(Ebar,T, QMu, type)*(1./3.*m*m/T/Ebar-Ebar/T*(1./3.-Cs2)); break; case EFjIndex::kFtemp1: //ftemperature. 1 return pbar*get_thermal_dF(Ebar,T, QMu, type)*Ebar/T; break; case EFjIndex::kFtemp2: //ftemperature 2 return pbar*get_thermal_dF(Ebar,T, QMu, type)*Ebar/T; break; case EFjIndex::kFvel1: //fvelocity 1 return pbar*pbar*get_thermal_dF(Ebar,T, QMu, type); break; case EFjIndex::kFvel2: //fvelocity 2 return pbar*pbar*get_thermal_dF(Ebar,T, QMu, type); break; case EFjIndex::kFvel3: //fvelocity 3 return pbar*pbar*get_thermal_dF(Ebar,T, QMu, type); break; default: std::cerr << "\033[1mTFastReso.cpp::get_initial_Fj\033[0m : \033[1;31merror\033[0m : wrong index " << (int) j << std::endl; exit(EXIT_FAILURE); } } //! Transformation rule factor A for Fj in a 2-body decay //! Here you can add additional rules for fj's double get_factor_Aj(EFjIndex j, double Qw, double Ew, double Ebar, double pbar, double Ma, double pw) { // double A= (Ma*Eabc/Mb/Mb-w*Ma*pabc/Mb/Mb*Ebar/pbar); // double Ew= (Ma*Eabc*Ebar/Mb/Mb-w*Ma*pabc*pbar/Mb/Mb); switch( j){ case EFjIndex::kFeq1: // feq 1 return Qw/pw; break; case EFjIndex::kFeq2: // feq 2 return pbar/pw*Ew/Ebar; break; case EFjIndex::kFshear1: // fshear 1 return Qw/pw*(2.5*Qw/pw*Qw/pw-1.5); break; case EFjIndex::kFshear2: // fshear 2 return Qw/pw; break; case EFjIndex::kFshear3: // fshear 3 return (1.5*Qw/pw*Qw/pw-0.5)*Ew/Ebar*pbar/pw; break; case EFjIndex::kFbulk1: // fbulk 1 return Qw/pw; break; case EFjIndex::kFbulk2: // fbulk 2 return pbar/pw*Ew/Ebar; break; case EFjIndex::kFtemp1: // ftemperature 1 return Qw/pw; break; case EFjIndex::kFtemp2: // ftemperature 2 return pbar/pw*Ew/Ebar; break; case EFjIndex::kFvel1: // fvelocity 1 return 1.5*Qw/pw*Qw/pw-0.5; break; case EFjIndex::kFvel2: // fvelocity 2 return 1; break; case EFjIndex::kFvel3: // fvelocity 3 return pbar/pw*Qw/pw*Ew/Ebar; break; default: std::cerr << "\033[1mTFastReso.cpp::get_factor_Aj\033[0m : \033[1;31merror\033[0m : wrong index " << (int) j << std::endl; exit(EXIT_FAILURE); } } //! Parameters for integration of thermal distribution struct thermal_params{ double m; double Tfo; double QMu; EParticleType type; }; //! Thermal distribution function for integration over vbar=[0,1] double get_F_p_dvbar(double vbar, void * p) { double &m = ((struct thermal_params *) p)->m; double &Tfo = ((struct thermal_params *) p)->Tfo; double &QMu = ((struct thermal_params *) p)->QMu; EParticleType &type = ((struct thermal_params *) p)->type; double Ebar=m/sqrt(1-vbar*vbar); double pbar=vbar*Ebar; double F_p = get_thermal_F(Ebar,Tfo,QMu, type); return F_p*pbar*pbar*4*M_PI*m/pow(2*M_PI*sqrt(1-vbar*vbar),3); } //! Parameters for integration of two body decay function struct twobody_params{ double Ebar; double Ma; double Mb; double Mc; TParticle * Parent; EFjIndex index; }; //! Integrand of two body decay formula for f_j components double get_F_pu_dw(double w, void * p) { double &Ebar = ((struct twobody_params *) p)->Ebar; double &Ma = ((struct twobody_params *) p)->Ma; double &Mb = ((struct twobody_params *) p)->Mb; double &Mc = ((struct twobody_params *) p)->Mc; TParticle *Parent = ((struct twobody_params *) p)->Parent; EFjIndex &index = ((struct twobody_params *) p)->index; double Eabc = get_Eabc(Ma,Mb,Mc); double pabc = get_p(Eabc, Mb); //double pbar = GSL_MAX(get_p(Ebar, Mb),DBL_EPSILON); double pbar = get_p(Ebar, Mb);// ,DBL_EPSILON); double Ebar_old = Ebar*Eabc*Ma/Mb/Mb-w*pbar*pabc*Ma/Mb/Mb; //double Ebar_old = pbar*pabc*Ma/Mb/Mb*(1-w); //double Ebar_old = pbar*pabc/Ma*u; double F_old=Parent->get_Fj( (int) index, Ebar_old); double Qw= (Ma*Eabc*pbar/Mb/Mb-w*Ma*pabc/Mb/Mb*Ebar); //double Qw = pabc/Ma*u; // double Ew= (Ma*Eabc*Ebar/Mb/Mb-w*Ma*pabc*pbar/Mb/Mb); double A = get_factor_Aj(index, Qw, Ebar_old, Ebar, pbar, Ma,sqrt(Qw*Qw+(1-w*w)*Ma*Ma/Mb/Mb*pabc*pabc)); return F_old*A; } double get_F_pu_du(double u, void * p) { double &Ebar = ((struct twobody_params *) p)->Ebar; double &Ma = ((struct twobody_params *) p)->Ma; double &Mb = ((struct twobody_params *) p)->Mb; double &Mc = ((struct twobody_params *) p)->Mc; TParticle *Parent = ((struct twobody_params *) p)->Parent; EFjIndex &index = ((struct twobody_params *) p)->index; double Eabc = get_Eabc(Ma,Mb,Mc); double pabc = get_p(Eabc, Mb); //double pbar = GSL_MAX(get_p(Ebar, Mb),DBL_EPSILON); double pbar = get_p(Ebar, Mb);// ,DBL_EPSILON); //double Ebar_old = Ebar*Eabc*Ma/Mb/Mb-w*pbar*pabc*Ma/Mb/Mb; //double Ebar_old = pbar*pabc*Ma/Mb/Mb*(1-w); if (pbar==0) { return 0;}; double Ebar_old = Ma/2*(pbar/pabc+pabc/pbar)+u*Ma; double F_old=Parent->get_Fj((int) index, Ebar_old); //double Qw= (Ma*Eabc/Mb/Mb-w*Ma*pabc/Mb/Mb*Ebar/pbar); double Qw = Ma/2/pbar*(pbar*pbar/pabc-pabc)+Ma*u; // double Ew= (Ma*Eabc*Ebar/Mb/Mb-w*Ma*pabc*pbar/Mb/Mb); double A = get_factor_Aj(index, Qw, Ebar_old, Ebar, pbar, Ma,sqrt(Qw*Qw+2*u*pabc/pbar*Ma*Ma)); return F_old*A/(pbar*pabc/Ma/Ma); } //! Parameters for three body decay mass integral struct threebody_params{ gsl_function *twobody_function; double Mc; double Md; gsl_integration_workspace *twobody_workspace; }; //! Integrand for three body decay normalization double get_B_dm(double mct, void * p) { gsl_function *twobody_function = ((struct threebody_params *) p)->twobody_function; double &Ma = ((struct twobody_params *) twobody_function->params)->Ma; double &Mb = ((struct twobody_params *) twobody_function->params)->Mb; double &Mc = ((struct threebody_params *) p)->Mc; double &Md = ((struct threebody_params *) p)->Md; return get_pabc(Ma,Mb,mct)*get_pabc(mct, Mc, Md); } //! Integrand for three body decay function double get_F_pu_dm(double mct, void * p) { gsl_function *twobody_function = ((struct threebody_params *) p)->twobody_function; ((struct twobody_params *) twobody_function->params)->Mc = mct; gsl_integration_workspace *twobody_workspace = ((struct threebody_params *) p)->twobody_workspace; double &Ma = ((struct twobody_params *) twobody_function->params)->Ma; double &Mb = ((struct twobody_params *) twobody_function->params)->Mb; double &Mc = ((struct threebody_params *) p)->Mc; double &Md = ((struct threebody_params *) p)->Md; double result,error; using namespace qag_params; int status = gsl_integration_qag (twobody_function, -1, 1, fEpsAbs,fEpsRel, fLimit,fKey ,twobody_workspace, &result, &error); // Check status of integration and reduce accuracy if failing if (status) { status = gsl_integration_qag (twobody_function, -1, 1, fEpsAbs,1e-4, fLimit,GSL_INTEG_GAUSS15,twobody_workspace, &result, &error); if (status) { status = gsl_integration_qag (twobody_function, -1, 1, 1e-4,1e-4, fLimit,GSL_INTEG_GAUSS15,twobody_workspace, &result, &error); if (status) { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31merror\033[0m : integration failure! status = " <<gsl_strerror ( status )<< ". " << result << "+_" << error << std::endl; exit(EXIT_FAILURE); }else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative and absolute error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } return result*get_pabc(Ma,Mb,mct)*get_pabc(mct, Mc,Md); } double get_F_pu_dm_u(double mct, void * p) { gsl_function *twobody_function = ((struct threebody_params *) p)->twobody_function; ((struct twobody_params *) twobody_function->params)->Mc = mct; gsl_integration_workspace *twobody_workspace = ((struct threebody_params *) p)->twobody_workspace; double &Ma = ((struct twobody_params *) twobody_function->params)->Ma; double &Mb = ((struct twobody_params *) twobody_function->params)->Mb; double &Mc = ((struct threebody_params *) p)->Mc; double &Md = ((struct threebody_params *) p)->Md; double result,error; using namespace qag_params; int status = gsl_integration_qagiu (twobody_function, 0.0, fEpsAbs,fEpsRel, fLimit,twobody_workspace, &result, &error); // Check status of integration and reduce accuracy if failing if (status) { status = gsl_integration_qagiu (twobody_function, 0.0, fEpsAbs,1e-4, fLimit,twobody_workspace, &result, &error); if (status) { status = gsl_integration_qagiu (twobody_function, 0.0, 1e-4,1e-4, fLimit,twobody_workspace, &result, &error); if (status) { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31merror\033[0m : integration failure! status = " << gsl_strerror (status )<< ". " << result << "+_" << error << std::endl; exit(EXIT_FAILURE); }else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative and absolute error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } return result*get_pabc(Ma,Mb,mct)*get_pabc(mct, Mc,Md); } void do_2bodydecay(TParticle * Parent, TParticle * Child1, TParticle * Child2, double BranchingRatio); void do_3bodydecay(TParticle * Parent, TParticle * Child1, TParticle * Child2, TParticle * Child3, double BranchingRatio); //! Initialize thermal distribution double get_thermal_F(double Ebar, double T, double QMu, EParticleType type) { switch(type){ case EParticleType::kBoson: return 1.0/(exp((Ebar-QMu)/T)-1); break; case EParticleType::kFermion: return 1.0/(exp((Ebar-QMu)/T)+1); break; case EParticleType::kBoltzman: return exp(-(Ebar-QMu)/T); break; default: std::cerr << "\033[1mTFastReso.cpp::get_thermal_F\033[0m : \033[1;31merror\033[0m : unrecognined particle type!" <<std::endl; exit(EXIT_FAILURE);} } //! Initialize derivative of t hermal distribution (With a minus sign) double get_thermal_dF(double Ebar, double T, double QMu, EParticleType type) { switch(type){ case EParticleType::kBoson: return 1.0/(exp((Ebar-QMu)/T)-1)*(1+1.0/(exp((Ebar-QMu)/T)-1)); break; case EParticleType::kFermion: return 1.0/(exp((Ebar-QMu)/T)+1)*(1-1.0/(exp((Ebar-QMu)/T)+1)); break; case EParticleType::kBoltzman: return exp(-(Ebar-QMu)/T); break; default: std::cerr << "\033[1mTFastReso.cpp::get_thermal_F_pu\033[0m : \033[1;31merror\033[0m : unrecognined particle type!" <<std::endl; exit(EXIT_FAILURE);} } //! Perform two body decay integral: Parent->Child1 + Child2 void do_2bodydecay(TParticle * Parent, TParticle * Child1, TParticle * Child2, double BranchingRatio){ using namespace qag_params; gsl_integration_workspace * fWorkspace2body ; fWorkspace2body = gsl_integration_workspace_alloc (fLimit); Parent->lock(); double Ma = Parent->getM(); double Mb = Child1->getM(); double Mc = Child2->getM(); double nua = Parent->getNu(); double nub = Child1->getNu(); double Ebar=0.0; Child1->clean_buffer(); if (Ma < Mb+Mc) { std::cerr << "\033[1mTFastReso.cpp::do_2bodydecays\033[0m : \033[1;31merror\033[0m : father particle lighter than childern! " << Ma << " < " << Mb+Mc << std::endl; exit(EXIT_FAILURE); } gsl_function func2body; if (Mb==0) { func2body.function = get_F_pu_du; } else { func2body.function = get_F_pu_dw; } twobody_params params = {Ebar, Ma, Mb, Mc, Parent, EFjIndex::kFeq1}; func2body.params = &params; double error, result ; int sym=1 ; if (Child1==Child2 ){ sym=2; } else { sym=1; } double Nfather = Parent->getN(); //! add fraction of the total yield to child Child1->addN(BranchingRatio*Nfather*sym); for (int i=0; i < Child1->getNpbar(); i++){ double Ebar =Child1->getEbar(i); params.Ebar =Ebar; //for (int j=0; j < grid_params::fNf ; j++){ for(auto j: Parent->fComponents) { params.index =j; double fac = 0; if (Mb==0) { int status = gsl_integration_qagiu (&func2body, 0.0, fEpsAbs,fEpsRel, fLimit ,fWorkspace2body, &result, &error); // Check status of integration and reduce accuracy if failing if (status) { status = gsl_integration_qagiu (&func2body, 0.0, fEpsAbs,1e-4, fLimit ,fWorkspace2body, &result, &error); if (status) { status = gsl_integration_qagiu (&func2body, 0.0, 1e-4,1e-4, fLimit ,fWorkspace2body, &result, &error); if (status) { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31merror\033[0m : integration failure! status = " << gsl_strerror (status )<< ". " << result << "+_" << error << std::endl; exit(EXIT_FAILURE); }else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative and absolute error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } fac = sym*BranchingRatio*nua/nub/2; } else { int status = gsl_integration_qag (&func2body, -1, 1, fEpsAbs,fEpsRel, fLimit,fKey ,fWorkspace2body, &result, &error); // Check status of integration and reduce accuracy if failing if (status) { status = gsl_integration_qag (&func2body, -1, 1, fEpsAbs,1e-4, fLimit, GSL_INTEG_GAUSS15,fWorkspace2body, &result, &error); if (status) { status = gsl_integration_qag (&func2body, -1, 1, 1e-4,1e-4, fLimit, GSL_INTEG_GAUSS15 ,fWorkspace2body, &result, &error); if (status) { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31merror\033[0m : integration failure! status = " << gsl_strerror (status) << ". " << result << "+_" << error << std::endl; exit(EXIT_FAILURE); }else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative and absolute error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } fac = sym*BranchingRatio*nua/nub*pow(Ma/Mb,2)/2; } Child1->addFj((int) j,i, fac*result); } } //if (Child1=="pi0139plu" ) { getParticle(Child1)->print_buffer(Child1+"_"+Parent+"_"+Child2);} gsl_integration_workspace_free (fWorkspace2body); } //! Perform three body decay integral Parent->Child1 + Child2 + Child3 void do_3bodydecay(TParticle * Parent, TParticle * Child1, TParticle * Child2, TParticle * Child3, double BranchingRatio){ using namespace qag_params; gsl_integration_workspace * fWorkspace2body ; gsl_integration_workspace * fWorkspace3body ; fWorkspace2body = gsl_integration_workspace_alloc (fLimit); fWorkspace3body = gsl_integration_workspace_alloc (fLimit); Parent->lock(); double Ma = Parent->getM(); double Mb = Child1->getM(); double Mc = Child2->getM(); double Md = Child3->getM(); double nua = Parent->getNu(); double nub = Child1->getNu(); double Ebar=0.0; Child1->clean_buffer(); if (Ma < Mb+Mc+Md) { std::cerr << "\033[1mTFastReso.cpp::do_3bdoydecays\033[0m : \033[1;31merror\033[0m : father particle lighter than childern! " << Ma << " < " << Mb+Mc+Md << std::endl; exit(EXIT_FAILURE); } gsl_function func2body; gsl_function func3body; if (Mb==0) { func2body.function = get_F_pu_du; } else { func2body.function = get_F_pu_dw; } func3body.function = get_B_dm; twobody_params params2 = {Ebar, Ma, Mb, Mc+Md, Parent, EFjIndex::kFeq1}; func2body.params = &params2; threebody_params params3 = {&func2body, Mc,Md, fWorkspace2body}; func3body.params = &params3; double error, result ; int status =gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,fEpsRel, fLimit,fKey ,fWorkspace3body, &result, &error); // Check status of integration and reduce accuracy if failing if (status) { status =gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); if (status) { status =gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, 1e-4,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); if (status) { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31merror\033[0m : integration failure! status = " << gsl_strerror (status )<< ". " << result << "+_" << error << std::endl; exit(EXIT_FAILURE); }else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative and absolute error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } double B3body = result; if (Mb==0) { func3body.function = get_F_pu_dm_u; } else { func3body.function = get_F_pu_dm; } int sym = 1 ; if (Child1==Child2 and Child2==Child3 ){ sym=3; } else if (Child1==Child2 or Child1==Child3 ){ sym=2;} else { sym=1; } double Nfather = Parent->getN(); // add fraction of yield to child Child1->addN(BranchingRatio*Nfather*sym); for (int i=0; i < Child1->getNpbar(); i++){ double Ebar =Child1->getEbar(i); params2.Ebar =Ebar; //for (int j=0; j < grid_params::fNf ; j++){ for(auto j: Parent->fComponents) { params2.index =j; int status = gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,fEpsRel, fLimit,fKey ,fWorkspace3body, &result, &error); // Check status of integration and reduce accuracy if failing if (status) { status = gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); if (status) { status = gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, 1e-4,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); if (status) { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31merror\033[0m : integration failure! status = " << gsl_strerror (status )<< ". " << result << "+_" << error << std::endl; exit(EXIT_FAILURE); }else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative and absolute error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } else { std::cerr << "\033[1mTFastReso_formulas.h\033[0m : \033[1;31mwarning\033[0m : reduced relative error (1e-4) integration. Result = " << result << "+-" << error <<std::endl; } } double fac =0; if (Mb==0) { fac = sym*BranchingRatio*nua/nub/2/B3body; } else { fac = sym*BranchingRatio*nua/nub*pow(Ma/Mb,2)/2/B3body; } Child1->addFj((int) j,i, fac*result); } } //if (Child1=="pi0139plu" ) { getParticle(Child1)->print_buffer(Child1+"_"+Parent+"_"+Child2+"_"+Child3);} gsl_integration_workspace_free (fWorkspace2body); gsl_integration_workspace_free (fWorkspace3body); } #endif
{ "alphanum_fraction": 0.6540639351, "avg_line_length": 42.3188679245, "ext": "h", "hexsha": "a5f1d28467534230bb1a36879c57887bddd435fe", "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": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "amazeliauskas/FastReso", "max_forks_repo_path": "TFastReso_formulas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "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": "amazeliauskas/FastReso", "max_issues_repo_path": "TFastReso_formulas.h", "max_line_length": 206, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "amazeliauskas/FastReso", "max_stars_repo_path": "TFastReso_formulas.h", "max_stars_repo_stars_event_max_datetime": "2020-09-22T14:25:58.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-11T02:48:59.000Z", "num_tokens": 7450, "size": 22429 }
#pragma once #include "common.h" #include <gsl/gsl_rng.h> #define ALT_CNT 4 enum categorical_flags { TEST_TYPE_CODOMINANT = 1, TEST_TYPE_RECESSIVE = 2, TEST_TYPE_DOMINANT = 4, TEST_TYPE_ALLELIC = 8 }; struct categorical_supp { uint8_t *phen_bits; size_t *filter, *table, *phen_mar, *outer; }; struct categorical_res { double nlpv[ALT_CNT], qas[ALT_CNT]; }; struct maver_adj_supp { uint8_t *phen_bits; size_t *filter, *table, *phen_mar, *phen_perm, *outer; struct categorical_snp_data *snp_data; }; struct maver_adj_res { double nlpv[ALT_CNT]; size_t rpl[ALT_CNT]; }; double stat_exact(size_t *, size_t *, size_t *); double qas_exact(size_t *t); bool categorical_init(struct categorical_supp *, size_t, size_t); struct categorical_res categorical_impl(struct categorical_supp *, uint8_t *, size_t *, size_t, size_t, enum categorical_flags); void categorical_close(struct categorical_supp *); bool maver_adj_init(struct maver_adj_supp *, size_t, size_t, size_t); struct maver_adj_res maver_adj_impl(struct maver_adj_supp *, uint8_t *, size_t *, size_t, size_t, size_t, size_t, size_t, gsl_rng *, enum categorical_flags); void maver_adj_close(struct maver_adj_supp *);
{ "alphanum_fraction": 0.739625712, "avg_line_length": 26.7173913043, "ext": "h", "hexsha": "7b74ff12800836a07f09d29ef4d8acabd0853347", "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": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_forks_repo_path": "src/categorical.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "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": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_issues_repo_path": "src/categorical.h", "max_line_length": 157, "max_stars_count": null, "max_stars_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_stars_repo_path": "src/categorical.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 333, "size": 1229 }
/* multifit_nlinear/lm.c * * Copyright (C) 2014, 2015, 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> /* * This module contains an implementation of the Levenberg-Marquardt * algorithm for nonlinear optimization problems. This implementation * closely follows the following works: * * [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and * Data Fitting, Informatics and Mathematical Modeling, * Technical University of Denmark (DTU), 2010. * * [2] J. J. More, The Levenberg-Marquardt Algorithm: Implementation * and Theory, Lecture Notes in Mathematics, v630, 1978. */ typedef struct { size_t n; /* number of observations */ size_t p; /* number of parameters */ gsl_vector *fvv; /* D_v^2 f(x), size n */ gsl_vector *vel; /* geodesic velocity (standard LM step), size p */ gsl_vector *acc; /* geodesic acceleration, size p */ gsl_vector *workp; /* workspace, length p */ gsl_vector *workn; /* workspace, length n */ int accel; /* use geodesic acceleration? */ /* tunable parameters */ gsl_multifit_nlinear_parameters params; } lm_state_t; #include "common.c" static void *lm_alloc (const int accel, const void * params, const size_t n, const size_t p); static void *lm_alloc_noaccel (const void * params, const size_t n, const size_t p); static void *lm_alloc_accel (const void * params, const size_t n, const size_t p); static void lm_free(void *vstate); static int lm_init(const void *vtrust_state, void *vstate); static int lm_preloop(const void * vtrust_state, void * vstate); static int lm_step(const void * vtrust_state, const double delta, gsl_vector * dx, void * vstate); static int lm_preduction(const void * vtrust_state, const gsl_vector * dx, double * pred, void * vstate); static void * lm_alloc (const int accel, const void * params, const size_t n, const size_t p) { const gsl_multifit_nlinear_parameters *mparams = (const gsl_multifit_nlinear_parameters *) params; lm_state_t *state; state = calloc(1, sizeof(lm_state_t)); if (state == NULL) { GSL_ERROR_NULL ("failed to allocate lm state", GSL_ENOMEM); } state->workp = gsl_vector_alloc(p); if (state->workp == NULL) { GSL_ERROR_NULL ("failed to allocate space for workp", GSL_ENOMEM); } state->workn = gsl_vector_alloc(n); if (state->workn == NULL) { GSL_ERROR_NULL ("failed to allocate space for workn", GSL_ENOMEM); } state->fvv = gsl_vector_alloc(n); if (state->fvv == NULL) { GSL_ERROR_NULL ("failed to allocate space for fvv", GSL_ENOMEM); } state->vel = gsl_vector_alloc(p); if (state->vel == NULL) { GSL_ERROR_NULL ("failed to allocate space for vel", GSL_ENOMEM); } state->acc = gsl_vector_alloc(p); if (state->acc == NULL) { GSL_ERROR_NULL ("failed to allocate space for acc", GSL_ENOMEM); } state->n = n; state->p = p; state->params = *mparams; state->accel = accel; return state; } static void * lm_alloc_noaccel (const void * params, const size_t n, const size_t p) { return lm_alloc(0, params, n, p); } static void * lm_alloc_accel (const void * params, const size_t n, const size_t p) { return lm_alloc(1, params, n, p); } static void lm_free(void *vstate) { lm_state_t *state = (lm_state_t *) vstate; if (state->workp) gsl_vector_free(state->workp); if (state->workn) gsl_vector_free(state->workn); if (state->fvv) gsl_vector_free(state->fvv); if (state->vel) gsl_vector_free(state->vel); if (state->acc) gsl_vector_free(state->acc); free(state); } /* lm_init() Initialize LM solver Inputs: vtrust_state - trust state vstate - workspace Return: success/error */ static int lm_init(const void *vtrust_state, void *vstate) { const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; lm_state_t *state = (lm_state_t *) vstate; gsl_vector_set_zero(state->vel); gsl_vector_set_zero(state->acc); *(trust_state->avratio) = 0.0; return GSL_SUCCESS; } /* lm_preloop() Initialize LM method for new Jacobian matrix */ static int lm_preloop(const void * vtrust_state, void * vstate) { int status; const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; const gsl_multifit_nlinear_parameters *params = trust_state->params; (void)vstate; /* initialize linear least squares solver */ status = (params->solver->init)(trust_state, trust_state->solver_state); if (status) return status; return GSL_SUCCESS; } /* lm_step() Calculate a new step vector by solving the linear least squares system: [ J ] v = - [ f ] [ sqrt(mu) D ] [ 0 ] */ static int lm_step(const void * vtrust_state, const double delta, gsl_vector * dx, void * vstate) { int status; const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; lm_state_t *state = (lm_state_t *) vstate; const gsl_multifit_nlinear_parameters *params = trust_state->params; const double mu = *(trust_state->mu); (void)delta; /* prepare the linear solver with current LM parameter mu */ status = (params->solver->presolve)(mu, trust_state, trust_state->solver_state); if (status) return status; /* * solve: [ J ] v = - [ f ] * [ sqrt(mu)*D ] [ 0 ] */ status = (params->solver->solve)(trust_state->f, state->vel, trust_state, trust_state->solver_state); if (status) return status; if (state->accel) { double anorm, vnorm; /* compute geodesic acceleration */ status = gsl_multifit_nlinear_eval_fvv(params->h_fvv, trust_state->x, state->vel, trust_state->f, trust_state->J, trust_state->sqrt_wts, trust_state->fdf, state->fvv, state->workp); if (status) return status; /* * solve: [ J ] a = - [ fvv ] * [ sqrt(mu)*D ] [ 0 ] */ status = (params->solver->solve)(state->fvv, state->acc, trust_state, trust_state->solver_state); if (status) return status; anorm = gsl_blas_dnrm2(state->acc); vnorm = gsl_blas_dnrm2(state->vel); /* store |a| / |v| */ *(trust_state->avratio) = anorm / vnorm; } /* compute step dx = v + 1/2 a */ scaled_addition(1.0, state->vel, 0.5, state->acc, dx); return GSL_SUCCESS; } /* lm_preduction() Compute predicted reduction using Eq 4.4 of More 1978 */ static int lm_preduction(const void * vtrust_state, const gsl_vector * dx, double * pred, void * vstate) { const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; lm_state_t *state = (lm_state_t *) vstate; const gsl_vector *diag = trust_state->diag; const gsl_vector *p = state->vel; const double norm_Dp = scaled_enorm(diag, p); const double normf = gsl_blas_dnrm2(trust_state->f); const double mu = *(trust_state->mu); double norm_Jp; double u, v; (void)dx; /* compute work = J*p */ gsl_blas_dgemv(CblasNoTrans, 1.0, trust_state->J, p, 0.0, state->workn); /* compute ||J*p|| */ norm_Jp = gsl_blas_dnrm2(state->workn); u = norm_Jp / normf; v = norm_Dp / normf; *pred = u * u + 2.0 * mu * v * v; return GSL_SUCCESS; } static const gsl_multifit_nlinear_trs lm_type = { "levenberg-marquardt", lm_alloc_noaccel, lm_init, lm_preloop, lm_step, lm_preduction, lm_free }; const gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_lm = &lm_type; static const gsl_multifit_nlinear_trs lmaccel_type = { "levenberg-marquardt+accel", lm_alloc_accel, lm_init, lm_preloop, lm_step, lm_preduction, lm_free }; const gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_lmaccel = &lmaccel_type;
{ "alphanum_fraction": 0.6380186283, "avg_line_length": 27.3855072464, "ext": "c", "hexsha": "b76f0d9f6c9ae40d488ecce458039729268ad0b8", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/lm.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/multifit_nlinear/lm.c", "max_line_length": 100, "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/multifit_nlinear/lm.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": 2519, "size": 9448 }
/** * @file mcc_localizer.h * @brief grid search based localization * @author Kenichi Kumatani */ #ifndef MCC_LOCALIZER_H #define MCC_LOCALIZER_H #include <stdio.h> #include <assert.h> #include <float.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_complex.h> #include <common/refcount.h> #include "common/jexception.h" #include "stream/stream.h" #include "feature/feature.h" //#include "modulated/modulated.h" /** @brief construct a search grid for source localization and return the time delay corresponding to each position on the grid. @note In order to do efficient grid-search for the source position which provides the maximum/minimum objective function, each cell size of a search grid has to be "reasonable". @usage After you construct an instance, you have to 1. set the geometry of the microphone array with setRadius(), setDistanceBtwMicrophones() or setPositionsOfMicrophones(). 2. obtain the time delays at the source position with getTimeDelays(), and 3. go to the next search candidate on the grid with nextSearchGrid(). */ class SearchGridBuilder { public: SearchGridBuilder( int nChan, bool isFarField, unsigned int samplingFreq=16000); virtual ~SearchGridBuilder(); const gsl_vector *getSearchPosition(){return(const gsl_vector *)_hypopos;} float maxTimeDelay(){return _maxTimeDelay;} size_t chanN(){return(_mpos->size1);} unsigned int samplingFrequency(){return(_samplingFreq);} void reset(); virtual const gsl_vector *getTimeDelays(){return NULL;} virtual bool nextSearchGrid(){return false;} protected: virtual const gsl_vector *nextSearchGridFF(){return NULL;} const gsl_vector *nextSearchGridNF(); protected: const bool _isFarField; /* if _isFarField = true, the far-filed is assumed. Otherwise, the near-field is assumed. */ unsigned int _samplingFreq; float _maxTimeDelay; gsl_matrix* _mpos; gsl_vector *_hypopos; gsl_vector *_delays; float _constV; }; typedef refcount_ptr<SearchGridBuilder> SearchGridBuilderPtr; class SGB4LinearArray : public SearchGridBuilder{ public: SGB4LinearArray( int nChan, bool isFarField, unsigned int samplingFreq=16000); void setDistanceBtwMicrophones( float distance ); void setPositionsOfMicrophones( const gsl_matrix* mpos ); virtual const gsl_vector *getTimeDelays(); virtual bool nextSearchGrid(); protected: const gsl_vector *nextSearchGridFF(); }; typedef Inherit<SGB4LinearArray, SearchGridBuilderPtr> SGB4LinearArrayPtr; class SGB4CircularArray : public SearchGridBuilder { public: SGB4CircularArray( int nChan, bool isFarField, unsigned int samplingFreq=16000 ); void setRadius( float radius, float height=0.0 ); virtual const gsl_vector *getTimeDelays(); virtual bool nextSearchGrid(); protected: const gsl_vector *nextSearchGridFF(); }; typedef Inherit<SGB4CircularArray, SearchGridBuilderPtr> SGB4CircularArrayPtr; /** @brief keeps samples in the previous block. this object is used in order to fill the gap between previous and current block data. */ class SampleHolder { public: SampleHolder( size_t chanN, size_t maxSampleDelay ): _filledNum(0),_buffer(gsl_matrix_float_calloc(chanN,maxSampleDelay)) {} ~SampleHolder() { gsl_matrix_float_free(_buffer); } void setSamples( size_t chanX, gsl_vector_float *samples ) { size_t maxSampleDelay = _buffer->size2; if( samples->size >= maxSampleDelay ){ size_t frameY = samples->size - maxSampleDelay; for(size_t frameX=0;frameX<maxSampleDelay;frameX++,frameY++){ gsl_matrix_float_set( _buffer, chanX, frameX, gsl_vector_float_get( samples, frameY ) ); } _filledNum = maxSampleDelay; } else{ // shift the elements of the buffer size_t frameN = maxSampleDelay - samples->size; for(size_t frameX=0;frameX<frameN;frameX++){ gsl_matrix_float_set( _buffer, chanX, frameX, gsl_matrix_float_get( _buffer, chanX, frameX + samples->size ) ); } // hold the samples of the current block size_t frameY = 0; for(size_t frameX=frameN;frameX<maxSampleDelay;frameX++,frameY++){ gsl_matrix_float_set( _buffer, chanX, frameX, gsl_vector_float_get( samples, frameY ) ); } _filledNum += samples->size; if( _filledNum > maxSampleDelay ) _filledNum = maxSampleDelay; } } float getSample( int chanX, int minusFrameX ) { return gsl_matrix_float_get( _buffer, chanX, _buffer->size2 + minusFrameX ); } int nFilled(){ return _filledNum;} private: int _filledNum; gsl_matrix_float *_buffer; /* the number of channels X samples */ }; typedef refcount_ptr<SampleHolder> SampleHolderPtr; /** @brief hold information for a position estimate. */ class SourceCandidate { public: SourceCandidate(size_t chanN, double costV=100000): _costV(costV), _chanN(chanN){ _sampledelay = new int[chanN]; _position = gsl_vector_calloc( 3 ); _eigenvalues = gsl_vector_alloc( chanN ); } ~SourceCandidate(){ delete [] _sampledelay; gsl_vector_free(_position); gsl_vector_free( _eigenvalues ); } void setSourceInfo( int *tau, const gsl_vector *position, double costV, gsl_vector *eigenvalues ){ for(size_t i=0;i<_chanN;i++){_sampledelay[i]=tau[i];} gsl_vector_memcpy(_position, (gsl_vector *)position); _costV = costV; gsl_vector_memcpy(_eigenvalues, eigenvalues); } void setConstV( double costV=100000 ){ _costV = costV; } double _costV; /* value of the cost function */ int *_sampledelay; gsl_vector *_position; gsl_vector *_eigenvalues; private: size_t _chanN; }; /** @class estimate the source positions which provide the larger multi-channel cross correlation values. @usage 1. setChannel() 2. next() 3. @note The algorithm implemented here is described in: J. Chen, J. Benesty and Y. Huang, "Robust Time Delay Estimation Exploiting Redundancy Among Multiple Microphones", IEEE Trans. SAP, vol.11, Sep. 2003. */ class MCCLocalizer : public VectorFeatureStream { public: MCCLocalizer( SearchGridBuilderPtr &sgbPtr, size_t maxSource=1, const String& nm= "MCCSourceLocalizer" ); ~MCCLocalizer(); virtual const gsl_vector* next(int frameX = -5); virtual void reset(); //void setChannel(SampleFeaturePtr& chan); void setChannel(VectorFloatFeatureStreamPtr& chan); /*@brief obtain a relative delay at a microphone which corresponds to the best candidate */ int getDelayedSample( int chanX ){return _sourceCandidates[0]->_sampledelay[chanX];} /*@brief obtain the maximum MCCC value */ double getMaxMCCC(){/* mistake: it was getMinMCCC() */ #ifdef _NO_LOG_ return( 1 -_sourceCandidates[0]->_costV ); #else return( 1 -exp(_sourceCandidates[0]->_costV) ); #endif } /*@brief obtain the best candidate of the position estimates */ const gsl_vector* getPosition(){return((const gsl_vector* )_sourceCandidates[0]->_position);} /*@brief obtain a relative delay at a microphone which corresponds to the N-th best candidate */ int getNthBestDelayedSample( int nth, int chanX ){return _sourceCandidates[nth]->_sampledelay[chanX];} /*@brief obtain the N-th best MCCC value */ double getNthBestMCCC( int nth ){ #ifdef _NO_LOG_ return( 1 -_sourceCandidates[nth]->_costV ); #else return( 1 - exp(_sourceCandidates[nth]->_costV) ); #endif } /*@brief obtain theN-th best candidate of the position estimates */ const gsl_vector* getNthBestPosition( int nth ){return((const gsl_vector* )_sourceCandidates[nth]->_position);} const gsl_vector* getEigenValues(){return ((const gsl_vector*)_sourceCandidates[0]->_eigenvalues);} gsl_matrix *getR(){return _R;} protected: bool setIncomingData( int frameX ); void doEigenValueDecomposition(); double calcObjectiveFunction( bool normalizeVariance = true ); private: gsl_matrix *calcCovarianceMatrix(); private: gsl_vector* search( int frameX = -5 ); protected: typedef list<VectorFloatFeatureStreamPtr> _ChannelList; //typedef list<SampleFeaturePtr> _ChannelList; typedef _ChannelList::iterator _ChannelIterator; _ChannelList _channelList; SearchGridBuilderPtr _sgbPtr; vector<const gsl_vector_float *> _blockList; int *_tau; /* sample delays */ gsl_vector *_x; gsl_matrix *_R; /* covariance matrix */ gsl_matrix *_Rcopy; double _detR; void *_workspace; gsl_vector *_eigenvalues; SampleHolderPtr _shPtr; /* keep samples of the block processed at a prevous frame */ vector<SourceCandidate *> _sourceCandidates; /* _sourceCandidates[n] is the N-th best candidate */ }; typedef Inherit<MCCLocalizer, VectorFeatureStreamPtr> MCCLocalizerPtr; /** @class calculate multichannel cross correlation coefficient givin a position or time delays. */ class MCCCalculator : public MCCLocalizer { public: MCCCalculator( SearchGridBuilderPtr &sgbPtr, bool normalizeVariance=true, const String& nm= "MCCCalculator" ); ~MCCCalculator(); void setTimeDelays( gsl_vector *delays ); double getMCCC(); double getCostV(); virtual const gsl_vector* next(int frameX = -5); virtual void reset(); private: gsl_matrix *calcCovarianceMatrix( gsl_vector *delays ); private: gsl_vector *_delays; bool _normalizeVariance; }; typedef Inherit<MCCCalculator, MCCLocalizerPtr> MCCCalculatorPtr; /** @class recursively estimate the source position which provides the multi-channel cross correlation. @usage @note The algorithm implemented here is described in: J. Benesty, J. Chen and Y. Huang, "Time-Delay Estimation via Linear Interpolation and Cross Correlation", IEEE Trans. SAP, vol.12, Sep. 2004. */ class RMCCLocalizer : public MCCLocalizer { public: RMCCLocalizer( SearchGridBuilderPtr &sgbPtr, float lambda, size_t maxSource=1, const String& nm= "RMCCSourceLocalizer" ); ~RMCCLocalizer(); virtual const gsl_vector* next(int frameX = -5); virtual void reset(); private: void calcInverseMatrix(); void updateParameters(); gsl_matrix *_invR; /* an inverse matrix of the covariance matrix */ gsl_vector *_kd; /* a priori Kalman gain vector */ //gsl_vector *_old_x; gsl_matrix *_old_R; /* covariance matrix at a previous frame */ gsl_matrix *_old_invR; gsl_vector *_old_kd; /* a priori Kalman gain vector at a previous frame */ }; typedef Inherit<RMCCLocalizer, MCCLocalizerPtr> RMCCLocalizerPtr; #endif
{ "alphanum_fraction": 0.7377329783, "avg_line_length": 33.4904458599, "ext": "h", "hexsha": "9ab97bbf46c78338266f33917b940d9e5fb29b29", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/localization/mcc_localizer.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/localization/mcc_localizer.h", "max_line_length": 180, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/localization/mcc_localizer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 2755, "size": 10516 }
/* roots/gsl_roots.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_ROOTS_H__ #define __GSL_ROOTS_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_math.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 { const char *name; size_t size; int (*set) (void *state, gsl_function * f, double * root, double x_lower, double x_upper); int (*iterate) (void *state, gsl_function * f, double * root, double * x_lower, double * x_upper); } gsl_root_fsolver_type; typedef struct { const gsl_root_fsolver_type * type; gsl_function * function ; double root ; double x_lower; double x_upper; void *state; } gsl_root_fsolver; typedef struct { const char *name; size_t size; int (*set) (void *state, gsl_function_fdf * f, double * root); int (*iterate) (void *state, gsl_function_fdf * f, double * root); } gsl_root_fdfsolver_type; typedef struct { const gsl_root_fdfsolver_type * type; gsl_function_fdf * fdf ; double root ; void *state; } gsl_root_fdfsolver; GSL_FUN gsl_root_fsolver * gsl_root_fsolver_alloc (const gsl_root_fsolver_type * T); GSL_FUN void gsl_root_fsolver_free (gsl_root_fsolver * s); GSL_FUN int gsl_root_fsolver_set (gsl_root_fsolver * s, gsl_function * f, double x_lower, double x_upper); GSL_FUN int gsl_root_fsolver_iterate (gsl_root_fsolver * s); GSL_FUN const char * gsl_root_fsolver_name (const gsl_root_fsolver * s); GSL_FUN double gsl_root_fsolver_root (const gsl_root_fsolver * s); GSL_FUN double gsl_root_fsolver_x_lower (const gsl_root_fsolver * s); GSL_FUN double gsl_root_fsolver_x_upper (const gsl_root_fsolver * s); GSL_FUN gsl_root_fdfsolver * gsl_root_fdfsolver_alloc (const gsl_root_fdfsolver_type * T); GSL_FUN int gsl_root_fdfsolver_set (gsl_root_fdfsolver * s, gsl_function_fdf * fdf, double root); GSL_FUN int gsl_root_fdfsolver_iterate (gsl_root_fdfsolver * s); GSL_FUN void gsl_root_fdfsolver_free (gsl_root_fdfsolver * s); GSL_FUN const char * gsl_root_fdfsolver_name (const gsl_root_fdfsolver * s); GSL_FUN double gsl_root_fdfsolver_root (const gsl_root_fdfsolver * s); GSL_FUN int gsl_root_test_interval (double x_lower, double x_upper, double epsabs, double epsrel); GSL_FUN int gsl_root_test_residual (double f, double epsabs); GSL_FUN int gsl_root_test_delta (double x1, double x0, double epsabs, double epsrel); GSL_VAR const gsl_root_fsolver_type * gsl_root_fsolver_bisection; GSL_VAR const gsl_root_fsolver_type * gsl_root_fsolver_brent; GSL_VAR const gsl_root_fsolver_type * gsl_root_fsolver_falsepos; GSL_VAR const gsl_root_fdfsolver_type * gsl_root_fdfsolver_newton; GSL_VAR const gsl_root_fdfsolver_type * gsl_root_fdfsolver_secant; GSL_VAR const gsl_root_fdfsolver_type * gsl_root_fdfsolver_steffenson; __END_DECLS #endif /* __GSL_ROOTS_H__ */
{ "alphanum_fraction": 0.7246102976, "avg_line_length": 30.6811594203, "ext": "h", "hexsha": "b8e516b40d7360fa312d18b166833e53dd81a94d", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_roots.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_roots.h", "max_line_length": 103, "max_stars_count": 2, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_roots.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 1137, "size": 4234 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> void integral_recur ( int nmin, int nmax, double vals[]); void integral_recur (int nmin, int nmax, double vals[]) { double IN = 0; int i = nmax - 1; vals [nmax] = IN; while ( i >= nmin) { vals[i] = (IN + exp (-1.))/((double) i); i = i - 1; } }
{ "alphanum_fraction": 0.5434173669, "avg_line_length": 18.7894736842, "ext": "c", "hexsha": "e559e3267f0bf0779a78e50c9cf0fa8a409ef63a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Paulther/hw7", "max_forks_repo_path": "integral_recur.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Paulther/hw7", "max_issues_repo_path": "integral_recur.c", "max_line_length": 57, "max_stars_count": null, "max_stars_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Paulther/hw7", "max_stars_repo_path": "integral_recur.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 118, "size": 357 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include <mcbp/protocol/opcode.h> #include <mcbp/protocol/request.h> #include <mcbp/protocol/response.h> #include <mcbp/protocol/status.h> #include <gsl/gsl-lite.hpp> namespace cb::mcbp { /** * FrameBuilder allows you to build up a request / response frame in * a provided memory area. It provides helper methods which makes sure * that the fields is formatted in the correct byte order etc. * * The frame looks like: * * * Byte/ 0 | 1 | 2 | 3 | * / | | | | * |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| * +---------------+---------------+---------------+---------------+ * 0| Magic | | Framing extras| Key Length | * +---------------+---------------+---------------+---------------+ * 4| Extras length | | | * +---------------+---------------+---------------+---------------+ * 8| Total body length | * +---------------+---------------+---------------+---------------+ * 12| | * +---------------+---------------+---------------+---------------+ * 16| | * | | * +---------------+---------------+---------------+---------------+ * 24| Optional section containing framing extras Max 255 bytes | * +---------------------------------------------------------------+ * | Optional section containing command extras | * +---------------------------------------------------------------+ * | Optional section containing the key | * +---------------------------------------------------------------+ * | Optional section containing the value. | * | The size of the value is the total body length minus the | * | size of the optional framing extras, extras and key. | * +---------------------------------------------------------------+ * */ template <typename T> class FrameBuilder { public: explicit FrameBuilder(cb::char_buffer backing, bool initialized = false) : FrameBuilder( {reinterpret_cast<uint8_t*>(backing.data()), backing.size()}, initialized) { } explicit FrameBuilder(cb::byte_buffer backing, bool initialized = false) : buffer(backing) { checkSize(sizeof(T)); if (!initialized) { std::fill(backing.begin(), backing.begin() + sizeof(T), 0); } } T* getFrame() { return reinterpret_cast<T*>(buffer.data()); } void setMagic(Magic magic) { getFrame()->setMagic(magic); } void setOpcode(ClientOpcode opcode) { getFrame()->setOpcode(opcode); } void setOpcode(ServerOpcode opcode) { getFrame()->setOpcode(opcode); } void setDatatype(Datatype datatype) { getFrame()->setDatatype(datatype); } void setVBucket(Vbid value) { getFrame()->setVBucket(value); } void setOpaque(uint32_t opaque) { getFrame()->setOpaque(opaque); } void setCas(uint64_t val) { getFrame()->setCas(val); } /** * Insert/replace the Framing extras section and move the rest of the * sections to their new locations. */ void setFramingExtras(cb::const_byte_buffer val) { if (!is_alternative_encoding(getFrame()->getMagic())) { throw std::logic_error( R"(setFramingExtras: Magic needs to be one of the alternative packet encodings)"); } auto* req = getFrame(); auto existing = req->getFramingExtras(); // can we fit the data? checkSize(existing.size(), val.size()); moveAndInsert(existing, val, req->getBodylen() - existing.size()); req->setFramingExtraslen(gsl::narrow<uint8_t>(val.size())); } /** * Insert/replace the Extras section and move the rest of the sections * to their new locations. */ void setExtras(cb::const_byte_buffer val) { auto* req = getFrame(); auto existing = req->getExtdata(); checkSize(existing.size(), val.size()); auto move_size = req->getKey().size() + req->getValue().size(); moveAndInsert(existing, val, move_size); req->setExtlen(gsl::narrow<uint8_t>(val.size())); } void setExtras(std::string_view val) { setExtras({reinterpret_cast<const uint8_t*>(val.data()), val.size()}); } /** * Insert/replace the Key section and move the value section to the new * location. */ void setKey(cb::const_byte_buffer val) { auto* req = getFrame(); auto existing = req->getKey(); checkSize(existing.size(), val.size()); moveAndInsert(existing, val, req->getValue().size()); req->setKeylen(gsl::narrow<uint16_t>(val.size())); } void setKey(std::string_view val) { setKey({reinterpret_cast<const uint8_t*>(val.data()), val.size()}); } /** * Insert/replace the value section. */ void setValue(cb::const_byte_buffer val) { auto* req = getFrame(); auto existing = req->getValue(); checkSize(existing.size(), val.size()); moveAndInsert(existing, val, 0); } void setValue(std::string_view val) { setValue({reinterpret_cast<const uint8_t*>(val.data()), val.size()}); } /** * Try to validate the underlying packet */ void validate() { getFrame()->isValid(); } protected: /** * check that the requested size fits into the buffer * * @param size The total requested size (including header) */ void checkSize(size_t size) { if (size > buffer.size()) { throw std::logic_error( "FrameBuilder::checkSize: too big to fit in buffer"); } } /** * check if there is room in the buffer to replace the field with * one with a different size * * @param oldfield * @param newfield */ void checkSize(size_t oldfield, size_t newfield) { checkSize(sizeof(T) + getFrame()->getBodylen() - oldfield + newfield); } /** * Move the rest of the packet to the new location and insert the * new value */ void moveAndInsert(cb::byte_buffer existing, cb::const_byte_buffer value, size_t size) { auto* location = existing.data(); if (size > 0 && existing.size() != value.size()) { // we need to move the data following this entry to a different // location. memmove(location + value.size(), location + existing.size(), size); } std::copy(value.begin(), value.end(), location); auto* req = getFrame(); // Update the total length req->setBodylen(gsl::narrow<uint32_t>(req->getBodylen() - existing.size() + value.size())); } cb::byte_buffer buffer; }; /** * Specialized class to build a Request */ class RequestBuilder : public FrameBuilder<Request> { public: explicit RequestBuilder(cb::char_buffer backing, bool initialized = false) : RequestBuilder( {reinterpret_cast<uint8_t*>(backing.data()), backing.size()}, initialized) { } explicit RequestBuilder(cb::byte_buffer backing, bool initialized = false) : FrameBuilder<Request>(backing, initialized) { } void setVbucket(Vbid vbucket) { getFrame()->setVBucket(vbucket); } }; /** * Specialized class to build a response */ class ResponseBuilder : public FrameBuilder<Response> { public: explicit ResponseBuilder(cb::char_buffer backing, bool initialized = false) : ResponseBuilder( {reinterpret_cast<uint8_t*>(backing.data()), backing.size()}, initialized) { } explicit ResponseBuilder(cb::byte_buffer backing, bool initialized = false) : FrameBuilder<Response>(backing, initialized) { } void setStatus(Status status) { getFrame()->setStatus(status); } }; } // namespace cb::mcbp
{ "alphanum_fraction": 0.5169124986, "avg_line_length": 34.6807692308, "ext": "h", "hexsha": "089bc26994b5256b13ddae5c355145ed0f0e4c29", "lang": "C", "max_forks_count": 71, "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "nawazish-couchbase/kv_engine", "max_forks_repo_path": "include/mcbp/protocol/framebuilder.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "nawazish-couchbase/kv_engine", "max_issues_repo_path": "include/mcbp/protocol/framebuilder.h", "max_line_length": 102, "max_stars_count": 104, "max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "nawazish-couchbase/kv_engine", "max_stars_repo_path": "include/mcbp/protocol/framebuilder.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "num_tokens": 1964, "size": 9017 }
/** * * @file * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.7.1 * @author Mathieu Faverge * @date 2010-11-15 **/ /* * @precisions normal z -> c d s */ #include <cblas.h> #include "dplasma.h" #include "dplasma_cores.h" #include "dplasma_zcores.h" /** ****************************************************************************** * * @ingroup parsec_complex64 * * dplasma_core_ztradd adds to matrices together as in PBLAS pztradd. * * B <- alpha * op(A) + beta * B * ******************************************************************************* * * @param[in] uplo * Specifies the shape of A and B matrices: * = PlasmaUpperLower: A and B are general matrices. * = PlasmaUpper: op(A) and B are upper trapezoidal matrices. * = PlasmaLower: op(A) and B are lower trapezoidal matrices. * * @param[in] trans * Specifies whether the matrix A is non-transposed, transposed, or * conjugate transposed * = PlasmaNoTrans: op(A) = A * = PlasmaTrans: op(A) = A' * = PlasmaConjTrans: op(A) = conj(A') * * @param[in] M * Number of rows of the matrices A and B. * * @param[in] N * Number of columns of the matrices A and B. * * @param[in] alpha * Scalar factor of A. * * @param[in] A * Matrix of size LDA-by-N. * * @param[in] LDA * Leading dimension of the array A. LDA >= max(1,M) * * @param[in] beta * Scalar factor of B. * * @param[in,out] B * Matrix of size LDB-by-N. * On exit, B = alpha * op(A) + beta * B * * @param[in] LDB * Leading dimension of the array B. LDB >= max(1,M) * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ int dplasma_core_ztradd(PLASMA_enum uplo, PLASMA_enum trans, int M, int N, parsec_complex64_t alpha, const parsec_complex64_t *A, int LDA, parsec_complex64_t beta, parsec_complex64_t *B, int LDB) { static parsec_complex64_t zone = (parsec_complex64_t)1.; int j; if (uplo == PlasmaUpperLower){ return dplasma_core_zgeadd( trans, M, N, alpha, A, LDA, beta, B, LDB ); } if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { dplasma_error("dplasma_core_ztradd", "illegal value of trans"); return -1; } if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans) && (trans != PlasmaConjTrans)) { dplasma_error("dplasma_core_ztradd", "illegal value of trans"); return -2; } if (M < 0) { dplasma_error("dplasma_core_ztradd", "Illegal value of M"); return -3; } if (N < 0) { dplasma_error("dplasma_core_ztradd", "Illegal value of N"); return -4; } if ( ((trans == PlasmaNoTrans) && (LDA < dplasma_imax(1,M)) && (M > 0)) || ((trans != PlasmaNoTrans) && (LDA < dplasma_imax(1,N)) && (N > 0)) ) { dplasma_error("dplasma_core_ztradd", "Illegal value of LDA"); return -7; } if ( (LDB < dplasma_imax(1,M)) && (M > 0) ) { dplasma_error("dplasma_core_ztradd", "Illegal value of LDB"); return -9; } if (uplo == PlasmaLower) { switch( trans ) { #if defined(PRECISION_z) || defined(PRECISION_c) case PlasmaConjTrans: for (j=0; j<N; j++, M--, A+=LDA+1, B+=LDB+1) { for(int i=0; i<M; i++) { B[i] = beta * B[i] + alpha * conj(A[LDA*i]); } } break; #endif /* defined(PRECISION_z) || defined(PRECISION_c) */ case PlasmaTrans: for (j=0; j<N; j++, M--, A+=LDA+1, B+=LDB+1) { if (beta != zone) { cblas_zscal(M, CBLAS_SADDR(beta), B, 1); } cblas_zaxpy(M, CBLAS_SADDR(alpha), A, LDA, B, 1); } break; case PlasmaNoTrans: default: for (j=0; j<N; j++, M--, A+=LDA+1, B+=LDB+1) { if (beta != zone) { cblas_zscal(M, CBLAS_SADDR(beta), B, 1); } cblas_zaxpy(M, CBLAS_SADDR(alpha), A, 1, B, 1); } } } else { switch( trans ) { #if defined(PRECISION_z) || defined(PRECISION_c) case PlasmaConjTrans: for (j=0; j<N; j++, A++, B+=LDB) { for(int i=0; i<=j; i++) { B[i] = beta * B[i] + alpha * conj(A[LDA*i]); } } break; #endif /* defined(PRECISION_z) || defined(PRECISION_c) */ case PlasmaTrans: for (j=0; j<N; j++, A++, B+=LDB) { if (beta != zone) { cblas_zscal(j+1, CBLAS_SADDR(beta), B, 1); } cblas_zaxpy(j+1, CBLAS_SADDR(alpha), A, LDA, B, 1); } break; case PlasmaNoTrans: default: for (j=0; j<N; j++, A+=LDA, B+=LDB) { if (beta != zone) { cblas_zscal(j+1, CBLAS_SADDR(beta), B, 1); } cblas_zaxpy(j+1, CBLAS_SADDR(alpha), A, 1, B, 1); } } } return 0; }
{ "alphanum_fraction": 0.4677846425, "avg_line_length": 29.9735449735, "ext": "c", "hexsha": "fc5fe0518aac5d11d9092c7518a00980a3f5eb18", "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": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/cores/core_ztradd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/cores/core_ztradd.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/cores/core_ztradd.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 1604, "size": 5665 }
/* 生成sample for Regression */ /* theta12, m21 fixed */ /* theta23, theta13, m31 flat distribution in 3 sigma range */ /* deltacp flat distribution in 0~360 */ /* 使用方式(產100K組) : ./sample_regression <filename.h5> <num> */ /* Caution: `num` should not greater than 1000. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <globes/globes.h> /* GLoBES library */ #include <gsl/gsl_math.h> /* GNU Scientific library (required for root finding) */ #include <gsl/gsl_roots.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_spline.h> #include "hdf5.h" #define degree M_PI/180 /*************************************************************************** * M A I N P R O G R A M * ***************************************************************************/ float keithRandom() { // Random number function based on the GNU Scientific Library // Returns a random float between 0 and 1, exclusive; e.g., (0,1) const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); struct timeval tv; // Seed generation based on time gettimeofday(&tv,0); unsigned long mySeed = tv.tv_sec + tv.tv_usec; T = gsl_rng_default; // Generator setup r = gsl_rng_alloc (T); gsl_rng_set(r, mySeed); double u = gsl_rng_uniform(r); // Generate it! gsl_rng_free (r); return (float)u; } double randn (double mu, double sigma) { /*mu is the central value, sigma is the width of gaussian distribution. */ double U1, U2, W, mult; static double X1, X2; static int call = 0; if (call == 1) { call = !call; return (mu + sigma * (double) X2); } do{ U1 = -1 + ((double) rand () / RAND_MAX) * 2; U2 = -1 + ((double) rand () / RAND_MAX) * 2; W = pow (U1, 2) + pow (U2, 2); } while (W >= 1 || W == 0); mult = sqrt ((-2 * log (W)) / W); X1 = U1 * mult; X2 = U2 * mult; call = !call; return (mu + sigma * (double) X1); } double TCRandom(double mu, double sigma) { // Random number function based on the GNU Scientific Library // Returns a random float between 0 and 1, exclusive; e.g., (0,1) const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); struct timeval tv; // Seed generation based on time gettimeofday(&tv,0); unsigned long mySeed = tv.tv_sec + tv.tv_usec; T = gsl_rng_default; // Generator setup r = gsl_rng_alloc (T); gsl_rng_set(r, mySeed); double u = mu + gsl_ran_gaussian(r, sigma); // Generate it! gsl_rng_free (r); return u; } int case_judger (int mode, double value) { /* * mode 1: Octant; * mode 2: CPV; * mode 3: MO; */ int result; switch (mode){ case 1: if ((value == 0) || (value==180)){ result = 0; } else { result = 1; } break; case 2: if (value > 45) { result = 1; } else if (value == 45) { result = 0; } else { result = -1; } break; case 3: result = value > 0 ? 1 : -1; break; } return result; } int main(int argc, char *argv[]) { /* Initialize GLoBES and define chi^2 functions */ glbInit(argv[0]); /* * Read the prefix of file name and add suffix to two child string. */ char filename[32], Group_name[32], channel_info_dset_name[] = "/Spectrum/expr_0/channel_0\0", size_info_dset_name[] = "/Spectrum/expr_0/channel_0/Bin_ize\0", energy_info_dset_name[] = "/Spectrum/expr_0/channel_0/Bin_energy\0", expr_info_dset_name[] = "/Spectrum/expr_0\0"; strcpy(filename, argv[1]); int TOTALsample = atof(argv[2]); /* * Declare the variables for hdf5. */ hid_t file_id, space_id, dset_id, group_id, sub_group_id, sub2_group_id, sub3_group_id; herr_t status; hsize_t dims[2]; /* * Initialize experiment parameters. */ glbInitExperiment("./DUNE2021/DUNE_GLoBES.glb",&glb_experiment_list[0],&glb_num_of_exps); glbInitExperiment("./HK_globes/HK_combined_coarse.glb",&glb_experiment_list[0],&glb_num_of_exps); glb_params true_values = glbAllocParams(); /* Set standard oscillation parameters (cf. hep-ph/0405172v5) */ double theta12_c = 33.44; // double theta13_c = 8.57; // double theta23_c = 45; double sdm_c = 7.42; // double ldm_c = 2.514; double delta_12 = (35.86 - 31.27)/2; double delta_13 = (8.97 - 8.20)/2; double delta_23 = (51.80 - 39.60)/2; double delta_sdm = (8.04 - 6.82)/2; double delta_ldm = (2.598 - 2.431)/2; int num_simulatiom; int ew_low, ew_high; int i, j, num_expriment, channel; file_id = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); group_id = H5Gcreate(file_id, "/Spectrum", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); for ( num_expriment = 0; num_expriment < 2; num_expriment++){ double *bin_c_energy = glbGetBinCentersListPtr( num_expriment ); double *bin_size = glbGetBinSizeListPtr( num_expriment ); int channel_max = glbGetNumberOfRules( num_expriment ); expr_info_dset_name[15] = num_expriment+'0'; sub_group_id = H5Gcreate(file_id, expr_info_dset_name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); for(channel=0;channel<channel_max;channel++){ glbGetEnergyWindowBins( num_expriment, channel, &ew_low, &ew_high); int energy_window = ew_high - ew_low; hsize_t dims_s[1] = {energy_window}; double dset_channel_eng[energy_window]; double dset_channel_size[energy_window]; j = 0; for ( i = ew_low; i <= ew_high; i++) { dset_channel_eng[j] = bin_c_energy[i]; dset_channel_size[j] = bin_size[i]; j += 1; } channel_info_dset_name[15] = num_expriment+'0'; channel_info_dset_name[25] = channel+'0'; energy_info_dset_name[15] = num_expriment+'0'; energy_info_dset_name[25] = channel+'0'; size_info_dset_name[15] = num_expriment+'0'; size_info_dset_name[25] = channel+'0'; sub2_group_id = H5Gcreate(file_id, channel_info_dset_name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); space_id = H5Screate_simple(1, dims_s, NULL); dset_id = H5Dcreate(sub2_group_id, energy_info_dset_name, H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, dset_channel_eng); status = H5Dclose(dset_id); dset_id = H5Dcreate(sub2_group_id, size_info_dset_name, H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, dset_channel_size); status = H5Dclose(dset_id); status = H5Sclose(space_id); status = H5Gclose(sub2_group_id); } status = H5Gclose(sub_group_id); } status = H5Gclose(group_id); double dataset[TOTALsample][9], TRUE_RATE[TOTALsample][2][4][8], TRUE_RATE_PRIME[2][4][8][TOTALsample]; for (num_simulatiom=0;num_simulatiom<TOTALsample;num_simulatiom++){ // double theta12 = TCRandom (theta12_c, delta_12 ); // double theta13 = TCRandom (theta13_c, delta_13 ); // double theta23 = TCRandom (theta23_c, delta_23 ); // double sdm = TCRandom ( sdm_c, delta_sdm); //eV^2 // double ldm = TCRandom ( ldm_c, delta_ldm); //eV^2 // double theta12 = (35.86+31.27)/2 + (keithRandom()-0.5)*(35.86-31.27); double theta13 = ( 8.97+ 8.20)/2 + (keithRandom()-0.5)*( 8.97- 8.20); double theta23 = (45 + 45)/2 + (keithRandom()-0.5)*(51.80-39.60); // double sdm = ( 8.04 + 6.82)/2 + (keithRandom()-0.5)*( 8.04- 6.82); double ldm = (2.598 + 2.431)/2 + (keithRandom()-0.5)*(2.598-2.431); double sign_ldm = 1; if ( keithRandom() < 0.5) sign_ldm = -1; ldm = sign_ldm * ldm; // if(keithRandom()<0.33) {theta23 = 45;} double deltacp = keithRandom()*360.0*2.0-180.0; if (deltacp<0){ deltacp=0; } else if (deltacp>360){ deltacp=180; } //double deltacp = keithRandom() * 360.0; int octant = case_judger(1, theta23); int cpv = case_judger(2, deltacp); int mo = case_judger(3, ldm); glbDefineParams(true_values,theta12_c*degree,theta13*degree,theta23*degree,deltacp*degree,1e-5*sdm_c,1e-3*ldm); glbSetDensityParams(true_values,1.0,GLB_ALL); glbSetOscillationParameters(true_values); glbSetRates(); num_expriment = 0; channel = 0; for ( num_expriment = 0; num_expriment < 2; num_expriment++){ int channel_max = glbGetNumberOfRules( num_expriment ); for ( channel = 0; channel < channel_max ; channel++){ glbGetEnergyWindowBins( num_expriment, channel, &ew_low, &ew_high); double *true_rates = glbGetRuleRatePtr( num_expriment, channel ); int count = 0; for (i=ew_low; i <= ew_high; i++){ TRUE_RATE[num_simulatiom][num_expriment][channel][count] = true_rates[i]; count += 1; } } } double tmp_array[9] = {theta12_c, theta13, theta23, deltacp, sdm_c, ldm, octant, cpv, mo}; int count = 0; for ( count = 0; count < 9; count++){ dataset[num_simulatiom][count] = tmp_array[count]; } } int k, l; for ( i = 0; i < TOTALsample; i++){ for ( j = 0; j < 2; j++){ for ( k = 0; k < 4; k++){ for ( l = 0; l < 8; l++){ TRUE_RATE_PRIME[j][k][l][i] = TRUE_RATE[i][j][k][l]; } } } } char channel_spec_true_name[] = "/Parameter/true/expr_0/channel_0\0", expr_spec_true_name[] = "/Parameter/true/expr_0\0", expr_spec_sim_name[] = "/Parameter/simulation\0"; hsize_t dims_s[2] = {TOTALsample, 8}; group_id = H5Gcreate(file_id, "/Parameter", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); sub_group_id = H5Gcreate(file_id, "/Parameter/true/", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); for ( i = 0; i < 2; i ++){ expr_spec_true_name[21] = i+'0'; sub2_group_id = H5Gcreate(file_id, expr_spec_true_name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); for ( j = 0; j < 4; j++){ channel_spec_true_name[21] = i+'0'; channel_spec_true_name[31] = j+'0'; space_id = H5Screate_simple(2, dims_s, NULL); dset_id = H5Dcreate(sub2_group_id, channel_spec_true_name, H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, TRUE_RATE_PRIME[i][j]); status = H5Dclose(dset_id); status = H5Sclose(space_id); } status = H5Gclose(sub2_group_id); } status = H5Gclose(sub_group_id); hsize_t dims_d[2] = {TOTALsample, 9}; sub_group_id = H5Gcreate(file_id, "/Parameter/simulation/", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); space_id = H5Screate_simple(2, dims_d, NULL); dset_id = H5Dcreate(sub_group_id, "/Parameter/simulation/dataset", H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, dataset); status = H5Dclose(dset_id); status = H5Sclose(space_id); status = H5Gclose(sub_group_id); status = H5Gclose(group_id); /* Clean up */ glbFreeParams(true_values); status = H5Fclose(file_id); return 0; }
{ "alphanum_fraction": 0.6348389387, "avg_line_length": 32.382183908, "ext": "c", "hexsha": "220db0958479fe160b00cea89050cfc03d188791", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-16T16:25:35.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-16T16:25:35.000Z", "max_forks_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "davidho27941/ML4NO", "max_forks_repo_path": "script/simulation/sample_classification.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "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": "davidho27941/ML4NO", "max_issues_repo_path": "script/simulation/sample_classification.c", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "davidho27941/ML4NO", "max_stars_repo_path": "script/simulation/sample_classification.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3820, "size": 11269 }
/*! \file Fitting.h * \brief header file for fitting functions to data. */ #ifndef FITTING_H #define FITTING_H #include <cmath> #include <iostream> #include <limits> #include <gsl/gsl_math.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> #ifdef HAVE_GSL22 #include <gsl/gsl_multifit_nlinear.h> #endif #include <Precision.h> #include <Function.h> #include <Matrix.h> #include <GMatrix.h> #include <Interpolate.h> #include <ExtremaRootFinding.h> using namespace std; namespace Math { /*! \brief Nonlinear fitting using Levenberg–Marquardt algorithm. Least Squares fitting of function f(x) from x[lower] to x[upper] to data y[lower]-y[upper]. Returns chi2 and altered params (which must be passed with initial guess) one can also pass a weight matrix (which is inverse of covariance matrix of data points), error on the relative change in chi2, and also a pointer that indicates whether the parameters are held fixed. finally, if data binned dof reduced by 1 and can specify maximum number of iterations Note the function does not explicitly take into account errors on the x and y points save in the use of the weight matrix which is the inverse of the covariance matrix Furthermore, the covariance matrix for the parameters is determined using the confidence level assuming normaly distributed errors. If that is not the case, the returned covariance matrix will not be correct and the degree to which it is correct cannot be correct for. Instead a more rigours determination of the confidence region used to determine the covariance matrix, such as MC methods using the data as a sample of the underlying distribution and fitting resulting data numerous times must be done. The resulting distribution of parameters can then be fit itself using a function if necessary. */ Double_t FitNonLinLS(const math_function fitfunc, const math_function *difffuncs, const int nparams, Double_t *params, GMatrix &covar, const int npoints, const Double_t x[], const Double_t y[], GMatrix *Weight=NULL, Double_t error=1e-3, Double_t cl=0.95, int *fixparam=NULL, int binned=1, int maxiterations=1000, int iestimateerror=0, bool icallgsl=true); Double_t FitNonLinLSNoGSL(const math_function fitfunc, const math_function *difffuncs, const int nparams, Double_t *params, GMatrix &covar, const int npoints, const Double_t x[], const Double_t y[], GMatrix *Weight=NULL, Double_t error=1e-3, Double_t cl=0.95, int *fixparam=NULL, int binned=1, int maxiterations=1000, int iestimateerror=0); #ifdef HAVE_GSL22 Double_t FitNonLinLSWithGSL(const math_function fitfunc, const math_function *difffuncs, const int nparams, Double_t *params, GMatrix &covar, const int npoints, const Double_t x[], const Double_t y[], GMatrix *W, Double_t error, Double_t cl, int *fixparam, int binned, int maxiit, int iestimateerror); #endif /*! \brief Given n points of data, determine optimal bin size and return binned data and bin centers. This is done by dividing the data range into N bins of width Delta. Count the number of events k_i that enter the i'th bin. Calculate the mean and variance of the number of events as kmean=1/N *Sum k_i and kvar=1/N*Sum (k_i -kmean)^2 Then calculate C(Delta)= (2*kmean-kvar)/Delta^2, a cost function Repeat while changing Delta and find Delta' that minimizes C(Delta). Return Delta' Based on Shimazaki H. and Shinomoto S., A method for selecting the bin size of a time histogram Neural Computation (2007) Vol. 19(6), 1503-1527 \n Can also provide weights for the data points. */ Double_t OptimalBins(const int npoints, Double_t *points, Double_t xmin, Double_t xmax, Double_t *weights=NULL); } #endif
{ "alphanum_fraction": 0.7337468983, "avg_line_length": 51.6666666667, "ext": "h", "hexsha": "71df27100cfd473e0e9e3bddc8ad2197c90c1455", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z", "max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ICRAR/NBodylib", "max_forks_repo_path": "src/Math/Fitting.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ICRAR/NBodylib", "max_issues_repo_path": "src/Math/Fitting.h", "max_line_length": 177, "max_stars_count": null, "max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ICRAR/NBodylib", "max_stars_repo_path": "src/Math/Fitting.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1011, "size": 4030 }
#include <cblas.h> #include <assert.h> #include <unistd.h> #include "benchmark.hpp" void dot_cblas(const double *A, const size_t A_m, const size_t A_n, const double *B, const size_t B_m, const size_t B_n, double *C) { UNUSED(B_m); assert(A != NULL && B != NULL && C != NULL); assert(A_m > 0 && A_n > 0 && B_m > 0 && B_n > 0); assert(A_n == B_m); cblas_dgemm(CblasColMajor, /* Matrix data arrangement */ CblasNoTrans, /* Transpose A */ CblasNoTrans, /* Transpose B */ A_m, /* Number of rows in A and C */ B_n, /* Number of cols in B and C */ A_n, /* Number of cols in A */ 1.0, /* Scaling factor for the product of A and B */ A, /* Matrix A */ A_n, /* First dimension of A */ B, /* Matrix B */ B_n, /* First dimension of B */ 1.0, /* Scale factor for C */ C, /* Output */ A_m /* First dimension of C */ ); } int main() { // Array - Blas for (size_t k = 10; k < 1000; k += 10) { size_t m = k; double *A = create_random_sq_matrix(m); double *B = create_random_sq_matrix(m); double *C = (double *) malloc(sizeof(double) * m * m); /* CBLAS dot() */ /* sleep(1); */ struct timespec t = tic(); dot_cblas(A, m, m, B, m, m, C); printf("matrix_size: %ld\tdot_cblas(): %fs\n", m, toc(&t)); free(A); free(B); free(C); } return 0; }
{ "alphanum_fraction": 0.4483985765, "avg_line_length": 29.5789473684, "ext": "c", "hexsha": "49c73c0fe7f2a8d14900ee0c87f967c485d323c8", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:19:44.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-12T05:10:24.000Z", "max_forks_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "daoran/proto", "max_forks_repo_path": "proto/lib/benchmarks/bench_matmul-blas.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_issues_repo_issues_event_max_datetime": "2021-12-21T01:10:10.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:08:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "daoran/proto", "max_issues_repo_path": "proto/lib/benchmarks/bench_matmul-blas.c", "max_line_length": 76, "max_stars_count": 15, "max_stars_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "daoran/proto", "max_stars_repo_path": "proto/lib/benchmarks/bench_matmul-blas.c", "max_stars_repo_stars_event_max_datetime": "2021-12-20T12:25:04.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-27T21:37:47.000Z", "num_tokens": 455, "size": 1686 }
#ifndef __GSL_VECTOR_H__ #define __GSL_VECTOR_H__ #include <gsl/gsl_vector_complex_long_double.h> #include <gsl/gsl_vector_complex_double.h> #include <gsl/gsl_vector_complex_float.h> #include <gsl/gsl_vector_long_double.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_vector_float.h> #include <gsl/gsl_vector_ulong.h> #include <gsl/gsl_vector_long.h> #include <gsl/gsl_vector_uint.h> #include <gsl/gsl_vector_int.h> #include <gsl/gsl_vector_ushort.h> #include <gsl/gsl_vector_short.h> #include <gsl/gsl_vector_uchar.h> #include <gsl/gsl_vector_char.h> #endif /* __GSL_VECTOR_H__ */
{ "alphanum_fraction": 0.7976588629, "avg_line_length": 23, "ext": "h", "hexsha": "cf762e42fa949be09907f99b62ef90e9e2fede31", "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/gsl/gsl_vector.h", "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/gsl/gsl_vector.h", "max_line_length": 47, "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/gsl/gsl_vector.h", "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": 170, "size": 598 }
/*-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. File Name : leef.c Purpose: embedding learning on a weighted graph Creation Date : 15-01-2017 Last Modified : Wed 15 Mar 2017 03:07:53 PM CDT Created By : Huan Gui (huangui2@illinois.edu) _._._._._._._._._._._._._._._._._._._._._.*/ #include <assert.h> #include <gsl/gsl_rng.h> #include <math.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <set> #include "ransampl.h" #define MAX_STRING 100 #define MAX_SENTENCE 1000 #define MAX_SIGMOID 8.0 #define MAX_N_NODE_TYPE 10 #define MAX_N_EDGE_TYPE 10 // maximum number of edge types typedef double real; // Precision of float numbers const int mini_batch = 1; const int sigmoid_table_size = 2000; const long hash_size = 30000000; // For each type of nodes, there are 3M nodes const int node_count_inc = 1000, neighbor_initial_count = 10; const long neg_table_size = 1e8; const long edge_table_size = 1e9; const real sigmoid_coeff = sigmoid_table_size / MAX_SIGMOID / 2.0; real sample_power = 0.75; // defined for negative sampling as the power of frequency real prior_power = 1; // defined for negative sampling as the power of frequency real max_sim = 0.5; real max_iteration = 10; struct ClassNeighbor { long node_id; long edge_id; }; struct ClassNode { char * name; real degree; real weight; // for the authority of nodes int *n_neighbor; int * max_n_neighbor; ClassNeighbor **neighbors; }; struct ClassEdge { long src_id; long dst_id; real weight; real t_weight; }; int n_node_type, n_edge_type; // the node type for source node and dest node int edge_node_type[MAX_N_EDGE_TYPE][2]; char output_folder[MAX_SENTENCE], input_folder[MAX_SENTENCE]; char embed_folder[MAX_SENTENCE], weight_folder[MAX_SENTENCE]; char train_network_file[MAX_N_EDGE_TYPE][MAX_SENTENCE]; char input_fix_embedding_file[MAX_SENTENCE]; char input_node_weight_file[MAX_SENTENCE]; char output_embedding[MAX_N_NODE_TYPE][MAX_SENTENCE]; char query_file[MAX_SENTENCE]; struct ClassNode* nodes[MAX_N_NODE_TYPE]; struct ClassEdge* edges[MAX_N_EDGE_TYPE]; set::set<long> query; int author_type, term_type, paper_type, term_paper_edge_type; int num_threads = 20, dim = 200; int negative_k = 5; // create hash table and negative table for each type of nodes and edges, respectively long *node_hash_table[MAX_N_NODE_TYPE]; long *neg_table[MAX_N_NODE_TYPE]; ransampl_ws *edge_alias[MAX_N_EDGE_TYPE]; ransampl_ws *topic_edge_alias; // The maximum size of each types of nodes, and the current count long max_sz_node[MAX_N_NODE_TYPE], node_cnt[MAX_N_NODE_TYPE]; // total samples of edges to update parameters, and the current samples long total_samples = 15, current_sample, edge_cnt[MAX_N_EDGE_TYPE]; real init_alpha = 0.025, alpha; // the embedding of each type of nodes, relative to different types of nodes real *emb_node[MAX_N_NODE_TYPE]; real *sigmoid_table; //specify the types of nodes, and edge names char node_names[MAX_N_NODE_TYPE][MAX_STRING]; char edge_names[MAX_N_EDGE_TYPE][MAX_STRING]; bool output_types[MAX_N_NODE_TYPE]; bool load_types[MAX_N_NODE_TYPE]; bool node_weight[MAX_N_NODE_TYPE]; bool edge_weight[MAX_N_NODE_TYPE]; bool valid_edge[MAX_N_NODE_TYPE][MAX_N_NODE_TYPE]; real beta[MAX_N_NODE_TYPE]; real node_sample_power[MAX_N_NODE_TYPE]; const gsl_rng_type * gsl_T; gsl_rng * gsl_r; clock_t start; // the hash function is the same for all types of nodes inline unsigned long GetHash(char *input) { unsigned long hash = 5381; char c; while ((c = *input) != '\0') { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ ++input; } return hash % hash_size; } // initialize the hash table for all types of nodes void InitHashTable() { for (int node_type = 0; node_type < n_node_type; ++node_type) { node_hash_table[node_type] = (long *) malloc(hash_size * sizeof(long)); for (long k = 0; k < hash_size; ++k) node_hash_table[node_type][k] = -1; } } void InsertHashTable(char *key, int value, int type) { unsigned long loc = GetHash(key); while (node_hash_table[type][loc] != -1) loc = (loc + 1) % hash_size; node_hash_table[type][loc] = value; } // hashing based on the name string long SearchHashTable(char *key, int type) { unsigned long addr = GetHash(key); while (1) { if (node_hash_table[type][addr] == -1) return -1; if (!strcmp(key, nodes[type][node_hash_table[type][addr]].name)) return node_hash_table[type][addr]; addr = (addr + 1) % hash_size; } return -1; } void AddNeighbor(int src_type, int dst_type, long src_id, long dst_id, int edge_type, long edge_id) { assert(valid_edge[src_type][dst_type]); ClassNode &node = nodes[src_type][src_id]; int n_neighbor = node.n_neighbor[dst_type]; if (n_neighbor + 2 >= node.max_n_neighbor[dst_type]) { node.max_n_neighbor[dst_type] *= 2; ClassNeighbor *tmp = (struct ClassNeighbor*) realloc( node.neighbors[dst_type], node.max_n_neighbor[dst_type] * sizeof(struct ClassNeighbor)); if (tmp != NULL) { node.neighbors[dst_type] = tmp; } else { printf("Fail to reallocate\n"); exit(1); } } node.neighbors[dst_type][n_neighbor].node_id = dst_id; node.neighbors[dst_type][n_neighbor].edge_id = edge_id; node.n_neighbor[dst_type] += 1; } // Add a node to the vertex set int AddNode(char *name, int node_type) { int length = strlen(name) + 1; if (length > MAX_STRING) length = MAX_STRING; ClassNode & node = nodes[node_type][node_cnt[node_type]]; // insert the node, and initial the value of name, node_type, and degree; node.name = (char *) calloc(length, sizeof(char)); node.degree = 0; node.weight = 1; node.n_neighbor = (int *) calloc(n_node_type, sizeof(int)); node.max_n_neighbor = (int *) calloc(n_node_type, sizeof(int)); node.neighbors = (ClassNeighbor **) calloc(n_node_type, sizeof(ClassNeighbor *)); for (int i = 0; i < n_node_type; ++i) { if (valid_edge[node_type][i]) { node.max_n_neighbor[i] = neighbor_initial_count; node.neighbors[i] = (ClassNeighbor *) calloc(neighbor_initial_count, sizeof(ClassNeighbor)); } } if (length < MAX_STRING) { strcpy(node.name, name); } else { strncpy(node.name, name, MAX_STRING - 1); node.name[MAX_STRING - 1] = '\0'; } ++node_cnt[node_type]; if (node_cnt[node_type] + 2 >= max_sz_node[node_type]) { max_sz_node[node_type] += node_count_inc; struct ClassNode *tmp = (struct ClassNode *) realloc(nodes[node_type], max_sz_node[node_type] * sizeof(struct ClassNode)); if (tmp != NULL) { nodes[node_type] = tmp; } else { printf("fail to reallocate\n"); } } InsertHashTable(name, node_cnt[node_type] - 1, node_type); return node_cnt[node_type] - 1; } void UpdateEdgeWeight(int edge_type) { long src_id, dst_id; int src_type = edge_node_type[edge_type][0]; int dst_type = edge_node_type[edge_type][1]; for (long k = 0; k < edge_cnt[edge_type]; ++k) { src_id = edges[edge_type][k].src_id; dst_id = edges[edge_type][k].dst_id; nodes[src_type][src_id].degree -= edges[edge_type][k].weight; nodes[dst_type][dst_id].degree -= edges[edge_type][k].weight; edges[edge_type][k].weight *= nodes[src_type][src_id].weight * nodes[dst_type][dst_id].weight; nodes[src_type][src_id].degree += edges[edge_type][k].weight; nodes[dst_type][dst_id].degree += edges[edge_type][k].weight; } // printf("Finish updating edge weight of edge %s \n", edge_names[edge_type]); } void ReadNodeWeight(int node_type) { FILE *fin; char field[MAX_STRING], str[10000]; real weight; long node_id, n_lines = 0; sprintf(input_node_weight_file, "%s/%s.weights", weight_folder, node_names[node_type]); // printf("%s\n", input_node_weight_file); fin = fopen(input_node_weight_file, "rb"); while (fgets(str, sizeof(str), fin)) ++n_lines; fclose(fin); fin = fopen(input_node_weight_file, "rb"); for (long k = 0; k < n_lines; ++k) { fscanf(fin, "%s %lf", field, &weight); if (prior_power != 1) { weight = pow(weight, prior_power); } node_id = SearchHashTable(field, node_type); if (node_id == -1) { printf("Invalid node name %s of type %s \n", field, node_names[node_type]); exit(1); } nodes[node_type][node_id].weight = weight; } //printf("Finish updating the weight for nodes %s \n", node_names[node_type]); } /* Read edges of different types in the network */ void ReadEdgeData(int edge_type) { FILE *fin; real weight; long src_id, dst_id; int src_type = edge_node_type[edge_type][0]; int dst_type = edge_node_type[edge_type][1]; char str[MAX_SENTENCE], src_name[MAX_STRING], dst_name[MAX_STRING]; // Get how many number of edges we have fin = fopen(train_network_file[edge_type], "rb"); printf("input: %s \n", train_network_file[edge_type]); edge_cnt[edge_type] = 0; while (fgets(str, sizeof(str), fin)) ++edge_cnt[edge_type]; fclose(fin); printf("Number of edges (%s): %ld \n", edge_names[edge_type], edge_cnt[edge_type]); edges[edge_type] = (ClassEdge *) malloc( edge_cnt[edge_type] * sizeof(ClassEdge)); fin = fopen(train_network_file[edge_type], "rb"); for (long k = 0; k < edge_cnt[edge_type]; ++k) { fscanf(fin, "%s %s %f", src_name, dst_name, &weight); assert(weight > 0); src_id = SearchHashTable(src_name, src_type); if (src_id == -1) { src_id = AddNode(src_name, src_type); } dst_id = SearchHashTable(dst_name, dst_type); if (dst_id == -1) { dst_id = AddNode(dst_name, dst_type); } edges[edge_type][k].src_id = src_id; edges[edge_type][k].dst_id = dst_id; edges[edge_type][k].weight = weight; if (src_type == author_type || src_type == term_type) { AddNeighbor(src_type, dst_type, src_id, dst_id, edge_type, edge_id); AddNeighbor(dst_type, src_type, dst_id, src_id, edge_type, edge_id); } // update node degree nodes[src_type][src_id].degree += weight; nodes[dst_type][dst_id].degree += weight; if (k % 50000 == 0) { printf("Loading edges : %.3lf%%%c", k / (real)(edge_cnt[edge_type] + 1) * 100, 13); fflush(stdout); } } fclose(fin); } /* Read the fixed embedding of terms */ void ReadFixEmbedding(int node_type) { FILE *fin; char str[(dim + 1) * MAX_STRING + 1000]; long node_id; long fix_node_count = node_cnt[node_type], count = 0; char *token; sprintf(input_fix_embedding_file, "%s/%s.embeddings", embed_folder, node_names[node_type]); if (access(input_fix_embedding_file, F_OK) == -1) { printf("Can't read the file %s \n", input_fix_embedding_file); exit(1); } // Get how many number of edges we have fin = fopen(input_fix_embedding_file, "rb"); // printf("debug: finish init\n"); if (fgets(str, sizeof(str), fin) == NULL) { printf("Can't read the file %s \n", input_fix_embedding_file); exit(1); } while (fgets(str, sizeof(str), fin)) { // printf("debug: parse %s\n", str); if (count >= fix_node_count) break; ++count; token = strtok(str, " "); node_id = SearchHashTable(token, node_type); if (node_id == -1) { continue; } for (int k = 0; k < dim; ++k) { token = strtok(NULL, " "); if (token == NULL) { printf("Error: embedding length dismatch!\n"); exit(1); } emb_node[node_type][node_id * dim + k] = atof(token) / 20; } } fclose(fin); printf("Embedding of node %s imported!\n", node_names[node_type]); } void InitNodeVector(int node_type, real *emb_node) { long offset = 0; for (long i = 0; i < node_cnt[node_type]; ++i) { for (int k = 0; k < dim; ++k) { emb_node[offset++] = (gsl_rng_uniform(gsl_r) - 0.5) / dim; } } } /* Initialize the vertex embedding and the context embedding */ void InitVector(){ printf("Initializing node vector ... \n %c", 13); fflush(stdout); // initialize the target and context embedding of each type of node for (int node_type = 0; node_type < n_node_type; ++node_type) { posix_memalign((void **)& emb_node[node_type], 128, node_cnt[node_type] * dim * sizeof(real)); if (emb_node[node_type] == NULL) { printf("Error: memory allocation failed\n"); exit(1); } InitNodeVector(node_type, emb_node[node_type]); } } // Given a node type, sample a negative node void InitNegTable(int node_type) { real sum = 0, cur_sum = 0, por = 0; long vid = 0; printf("Initializing negative table for %s ... \t\t\t\t %c", node_names[node_type], 13); fflush(stdout); neg_table[node_type] = (long *)malloc(neg_table_size * sizeof(long)); for (long k = 0; k < node_cnt[node_type]; ++k) { sum += pow(nodes[node_type][k].degree, node_sample_power[node_type]); } for (long k = 0; k < neg_table_size; ++k) { if ((real)(k + 1) / neg_table_size > por) { cur_sum += pow(nodes[node_type][vid].degree, node_sample_power[node_type]); por = cur_sum / sum; ++vid; } neg_table[node_type][k] = vid - 1; } } void InitEdgeAlias(int edge_type) { printf("Initializing alias table for edge %s ... %c", edge_names[edge_type], 13); real *prob = (real *) calloc(edge_cnt[edge_type], sizeof(real)); real total_weight = 0; for (int i = 0; i < edge_cnt[edge_type]; ++i) { total_weight += edges[edge_type][i].weight; } for (int i = 0; i < edge_cnt[edge_type]; ++i) { prob[i] = edges[edge_type][i].weight / total_weight; } edge_alias[edge_type] = ransampl_alloc(edge_cnt[edge_type]); ransampl_set(edge_alias[edge_type], prob); } /* Fastly compute sigmoid function */ void InitSigmoidTable() { real x; printf("Initializing sigmoid table ... %c", 13); fflush(stdout); sigmoid_table = (real *)malloc((sigmoid_table_size + 1) * sizeof(real)); for (int k = 0; k < sigmoid_table_size; ++k) { x = 2 * (real)(MAX_SIGMOID * k) / sigmoid_table_size - MAX_SIGMOID; sigmoid_table[k] = 1 / (1 + exp(-x)); } } inline real FastSigmoid(real x) { if (x > MAX_SIGMOID) return 1; else if (x < -MAX_SIGMOID) return 0; return sigmoid_table[(int)((x + MAX_SIGMOID) * sigmoid_coeff)]; } inline long SampleNegativeNode(int node_type, gsl_rng * & gsl_r_local) { // return gsl_rng_uniform_int(gsl_r_local, node_cnt[node_type]); return neg_table[node_type][ gsl_rng_uniform_int(gsl_r_local, neg_table_size)]; } inline long SampleEdge(int edge_type, gsl_rng * & gsl_r_local) { return ransampl_draw(edge_alias[edge_type], gsl_rng_uniform(gsl_r_local), gsl_rng_uniform(gsl_r_local)); } inline void Update(int src_type, int dst_type, long src_id, long end_id, long *neg_node_ids, real *context_update) { long target_id, target_offset, context_offset; real f = 0, g = 0, label = 1; real decay_target = alpha * beta[dst_type]; real decay_context = alpha * beta[src_type]; memset(context_update, 0, dim * sizeof(real)); context_offset = src_id * dim; for (int i = 0; i <= negative_k; ++i) { if (i == negative_k) { target_id = end_id; label = 1; } else { target_id = neg_node_ids[i]; if (target_id == end_id) continue; label = 0; } target_offset = target_id * dim; f = 0; for (int j = 0; j < dim; j ++) { f += emb_node[dst_type][target_offset + j] * emb_node[src_type][context_offset + j]; } g = (label - FastSigmoid(f)) * alpha; for (int j = 0; j < dim; ++j) { context_update[j] += g * emb_node[dst_type][target_offset + j] - decay_context * emb_node[src_type][context_offset + j]; emb_node[dst_type][target_offset + j] += g * emb_node[src_type][context_offset + j] - decay_target * emb_node[dst_type][target_offset + j]; } } for (int j = 0; j < dim; ++j) { emb_node[src_type][context_offset + j] += context_update[j]; } } void *TrainThread(void *id) { long count = 0, last_count = 0; long limit = total_samples / num_threads + 2; int src_type, dst_type; long edge_id, src_id, dst_id; long *neg_node_ids; neg_node_ids = (long *) malloc(negative_k * sizeof(long)); gsl_rng * gsl_r_local = gsl_rng_alloc(gsl_T); gsl_rng_set(gsl_r_local, (unsigned long int) id); real *err_update = (real *) malloc(dim * sizeof(real)); real ratio; clock_t now; while (1) { // decide when to exist the learning if (count > limit) { current_sample += count - last_count; break ; } // update output information if (count - last_count == 10000) { current_sample += count - last_count; last_count = count; ratio = current_sample / (real)(total_samples + 1); if (count % 100000 == 0) { now=clock(); printf("%cAlpha: %f Progress: %.2lf%% Events/thread/sec: %.2fk", 13, alpha, ratio * 100, current_sample / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); fflush(stdout); } alpha = init_alpha * (1 - ratio); } ++count; for (int edge_type = 0; edge_type < n_edge_type; ++edge_type) { src_type = edge_node_type[edge_type][0]; dst_type = edge_node_type[edge_type][1]; edge_id = SampleEdge(edge_type, gsl_r_local); src_id = edges[edge_type][edge_id].src_id; dst_id = edges[edge_type][edge_id].dst_id; //printf("%d %d %d %s %s \n", edge_type, src_type, dst_type, nodes[src_type][src_id].name, nodes[dst_type][dst_id].name); for (int i = 0; i < negative_k; ++i) { neg_node_ids[i] = SampleNegativeNode(dst_type, gsl_r_local); } Update(src_type, dst_type, src_id, dst_id, neg_node_ids, err_update); } } free(neg_node_ids); free(err_update); pthread_exit(NULL); } // output the embeddings of nodes and the context embedding void Output() { // for each type of nodes, output the embeddings char file_name[MAX_STRING]; FILE *fo; long offset; // output the embeddings of nodes for (int node_type = 0; node_type < n_node_type; ++node_type) { if (!output_types[node_type]) continue; printf("storing the embedding of nodes %s\n", node_names[node_type]); sprintf(file_name, "%s/%s.embeddings", output_folder, node_names[node_type]); fo = fopen(file_name, "wb"); fprintf(fo, "%ld %d\n", node_cnt[node_type], dim); offset = 0; for (long i = 0; i < node_cnt[node_type]; ++i) { fprintf(fo, "%s ", nodes[node_type][i].name); for (int k = 0; k < dim; ++k) { fprintf(fo, "%lf ", emb_node[node_type][offset++]); } fprintf(fo, "\n"); } fclose(fo); } } // query string is delimited by # void readQuery(char *qString, set::set<long> query) { query.clear(); char delim[] = "#"; char *token = strtok(name, delim); long node_id; while (token != NULL) { node_id = SearchHashTable(token, term_type); if (node_id == -1) { node_id = AddNode(token, map_node_type); } query.insert(node_id); token = strtok(NULL, delim); } } void hitPapers(set::set<long> &query, set::set<long> &paper_set) { paper_set.clear(); for (set::set<long>::iterator it = query.begin(); it != query.end(); ++it) { long term_id = *it; ClassNode &node = nodes[term_type][term_id]; for (int j = 0; j < node.n_neighbor[paper_type]; ++j) { paper_set.insert(node.neighbors[paper_type][j]); } } } void nodeExpansion(int src_type, int dst_type, set::set<long> &src_set, set::set<long> &dst_set) { dst_set.clear(); for (set::set<long>::iterator it = src_set.begin(); it != src_set.end(); ++it) { long src_id = *it; ClassNode &node = nodes[src_type][src_id]; for (int j = 0; j < node.n_neighbor[dst_type]; ++j) { dst_set.insert(node.neighbors[dst_type][j]); } } } void queryExpansion(set::set<long> &paper_set, set::set<long> &query, set::set<long> &new_query) { new_query.clear(); long t_n_edges = 0; std::map<long, real> topic_edges; for (set::set<long>::iterator it = paper_set.begin(), it != paper_set.end(); ++it) { long paper_id = *it; class &node = *it; for (int j = 0; j < node.n_neighbor[term_type]; ++j) { long edge_id = node.neighbors[term_type][j].edge_id; real weight = edges[term_paper_edge_type][edge_id].weight; topic_edges[edge_id] = weight; } } long * sample_topic_edges = (long *) malloc(topic_edges.size() * sizeof(long)); real * sample_prob = (real *) malloc(topic_edges.size() * sizeof(real)); real sum_weight = 0; int k = 0; for (std::map<long, real>::iterator it = topic_edges.begin(); it != topic_edges.end(); ++it) { sample_topic_edges[k] = it->first; sample_prob[k] = it->second; sum_weight += sample_prob[k]; k ++; } topic_edge_alias = ransampl_alloc(topic_edges.size()); ransampl_set(topic_edge_alias, sample_prob); } set::set<long> expandDocument(set::set<long> query) { long * new_query; set::set<long> author_set, paper_set; set::set<long> new_query; while (true) { hitPapers(query, paper_set); nodeExpansion(paper_type, author_type, paper_set, author_set); nodeExpansion(author_type, paper_type, author_set, paper_set); queryExpansion(paper_set, query, new_query); } hitPapers(query, paper_set); return paper_set; } void TrainModel() { gsl_rng_env_setup(); gsl_T = gsl_rng_rand48; gsl_r = gsl_rng_alloc(gsl_T); gsl_rng_set(gsl_r, 314159265); InitHashTable(); printf("HashTable Initialized! \n"); for (int edge_type = 0; edge_type < n_edge_type; ++edge_type) { printf("Start to read edges of %s\n", edge_names[edge_type]); ReadEdgeData(edge_type); } printf("Node types: %d \n", n_node_type); for (int i = 0; i < n_node_type; i ++) { printf("%s ", node_names[i]); } printf("\n"); for (int node_type = 0; node_type < n_node_type; ++node_type) { if (node_weight[node_type]) { ReadNodeWeight(node_type); } } printf("Edge types: %d \n", n_edge_type); for (int i = 0; i < n_edge_type; i ++) { printf("%s ", edge_names[i]); } printf("\n"); printf("-------------------------------- \n"); for (int k = 0; k < n_node_type; ++k) { printf("Number of nodes (%s): %ld \n", node_names[k], node_cnt[k]); } // map each ege into corresponding total_samples = (long) (1000000 * total_samples); printf("--------------------------------\n"); printf("Dimension: %d\n", dim); printf("Initial alpha: %.3lf\n", alpha); printf("Thread : %d \n", num_threads); printf("--------------------------------\n"); printf("Load node weight : \n"); for (int node_type = 0; node_type < n_node_type; ++node_type) { printf("\t%s : %s \n", node_names[node_type], node_weight[node_type] ? "Yes":"No"); } printf("\n"); printf("Prior power : %f \n\n", prior_power); printf("Update edge weight : \n"); for (int edge_type = 0; edge_type < n_edge_type; ++edge_type) { if (edge_weight[edge_type] && (node_weight[edge_node_type[edge_type][0]] || node_weight[edge_node_type[edge_type][1]])) { printf("\t%s : %s \n", edge_names[edge_type], "Yes"); UpdateEdgeWeight(edge_type); } else { printf("\t%s : %s \n", edge_names[edge_type], "No"); } } printf("\n"); printf("Output node types:"); for (int m = 0; m < n_node_type; ++m){ if (output_types[m]) { printf(" %s", node_names[m]); } } printf("\n\n"); InitVector(); InitSigmoidTable(); printf("Finish initialization! \n"); FILE *fin = fopen(query_file, "rb"); char c; int nQuery = 0; while (fgets(str, sizeof(str), fin)) ++nQuery; fclose(); fin = fopen(query_file, "rb"); set::set<long> papers, query; char query_string[MAX_SENTENCE]; for (int q = 0; q < nQuery; q++) { int pos = 0; do { c = fgetc(fin); if (c == EOF || c == '\n') break; else if (pos < MAX_SENTENCE - 1) query_string[pos++] = (char) c; } query_string[pos] = 0; readQuery(query_string, query); papers.clear(); papers = expandDocument(query); } struct timeval t1, t2; gettimeofday(&t1, NULL); start = clock(); pthread_t *pt = (pthread_t *)malloc((num_threads) * sizeof(pthread_t)); for (long a = 0; a < num_threads; ++a) { pthread_create(&pt[a], NULL, TrainThread, (void *)a); } for (int a = 0; a < num_threads; ++a) { pthread_join(pt[a], NULL); } gettimeofday(&t2, NULL); printf("\nTotal optimization time: %.2lf minitues\n", (real)(t2.tv_sec - t1.tv_sec) / 60); Output(); } int ArgPos(char *str, int argc, char **argv) { for (int a = 0; a < argc; ++a) { if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } } return -1; } int main(int argc, char **argv) { int i, j, k; char str[MAX_SENTENCE], source[MAX_SENTENCE], dest[MAX_SENTENCE]; strcpy(output_folder, "output"); strcpy(input_folder, "data"); InitSigmoidTable(); if (argc == 1) { printf("\t leef: Local Embedding for Expert Finding\n"); printf("Options:"); printf("\tPlease specify the parameter file!\n"); printf("\t-para <file> \n"); printf("\t\tProvide the parameter file on edges\n"); printf("\t-size <int>\n"); printf("\t\tSet dimension of vertex embeddings; default is 200\n"); printf("\t-scoring <int>\n"); printf("\t\tScoring function, 0: complete element-wise product," "1: complete pairwise inner product, 2: pairwise inner product with central type\n"); printf("\t-iter <int>\n"); printf("\t\tSet the number of training samples as the number of iterations of number of edges\n"); printf("\t-tthread <int>\n"); printf("\t\tUse <int> threads for tensor updating(default 1)\n"); printf("\t-wthread <int>\n"); printf("\t\tUse <int> threads for word2vec updating(default 1)\n"); printf("\t-negative <int>\n"); printf("\t\tSample <int> negative samples for word2vec updating(default 1)\n"); printf("\t-alpha <float>\n"); printf("\t\tSet the starting learning rate; default is 0.025\n"); printf("\t-input input folder ...\n"); printf("\t\tSet the folder data which read data\n"); printf("\t-output output folder ...\n"); printf("\t\tSet the folder to which output data\n"); return 0; } // global parameters shared across all the edges if ((i = ArgPos((char *) "-size", argc, argv)) > 0) dim = atoi(argv[i + 1]); if ((i = ArgPos((char *) "-iter", argc, argv)) > 0) total_samples = atoi(argv[i + 1]); if ((i = ArgPos((char *) "-alpha", argc, argv)) > 0) init_alpha = atof(argv[i + 1]); if ((i = ArgPos((char *) "-thread", argc, argv)) > 0) { num_threads = atoi(argv[i + 1]); } if ((i = ArgPos((char *) "-negative", argc, argv)) > 0) { negative_k = atoi(argv[i + 1]); } for (i = 0; i < n_node_type; ++i) { for (j = 0; j < n_node_type; ++j) { valid_edge[i][j] = false; } } if ((i = ArgPos((char *) "-n_node", argc, argv)) > 0) { n_node_type = atoi(argv[i + 1]); } for (int i = 0; i < n_node_type; ++i) { nodes[i] =(struct ClassNode *) calloc(node_count_inc, sizeof(struct ClassNode)); max_sz_node[i] = node_count_inc; node_sample_power[i] = sample_power; } if ((i = ArgPos((char *) "-nodes", argc, argv)) > 0) { for (j = 0; j < n_node_type; ++j) { strcpy(node_names[j], argv[i + j + 1]); if (!strcmp(node_names[j], "author")) { author_type = j; } else if (!strcmp(node_names[j], "term")) { term_type = j; } else if (!strcmp(node_names[j], "paper")) { paper_type = j; } } } if ((i = ArgPos((char *) "-n_edge", argc, argv)) > 0) { n_edge_type = atoi(argv[i + 1]); } if ((i = ArgPos((char *) "-output_folder", argc, argv)) > 0) strcpy(output_folder, argv[i + 1]); if ((i = ArgPos((char *) "-input_folder", argc, argv)) > 0) strcpy(input_folder, argv[i + 1]); if ((i = ArgPos((char *) "-embed_folder", argc, argv)) > 0) strcpy(embed_folder, argv[i + 1]); if ((i = ArgPos((char *) "-weight_folder", argc, argv)) > 0) strcpy(weight_folder, argv[i + 1]); if ((i = ArgPos((char *) "-edges", argc, argv)) > 0) { for (j = 0; j < n_edge_type; ++j) { strcpy(edge_names[j], argv[i + j + 1]); sprintf(train_network_file[j], "%s/%s.net", input_folder, edge_names[j]); printf("Input %d: %s\n", j, train_network_file[j]); strcpy(edge_names[j], argv[i + 1 + j]); strcpy(str, edge_names[j]); int pch = strchr(str, '_') - str; str[pch] = '\0'; strcpy(source, str); strcpy(dest, &str[pch + 1]); for (k = 0; k < n_node_type; ++k) { if (strcmp(source, node_names[k]) == 0) { edge_node_type[j][0] = k; } else if (strcmp(dest, node_names[k]) == 0) { edge_node_type[j][1] = k; } } if (edge_node_type[j][0] == term_type && edge_node_type[j][1] == paper_type) { term_paper_edge_type = j; } valid_edge[edge_node_type[j][0]][edge_node_type[j][1]] = true; valid_edge[edge_node_type[j][1]][edge_node_type[j][0]] = true; } } // the regularization parameter for the embeddings if ((i = ArgPos((char *) "-beta", argc, argv)) >= 0) { for (int j = 0; j < n_node_type; ++j) { beta[j] = atof(argv[i + 1 + j]); } } if ((i = ArgPos((char *) "-prior_power", argc, argv)) >= 0) { prior_power = atof(argv[i + 1]); } if ((i = ArgPos((char *) "-sample_power", argc, argv)) >= 0) { for (int j = 0; j < n_node_type; ++j) { node_sample_power[j] = atof(argv[i + 1 + j]); } } if ((i = ArgPos((char *) "-choose_output", argc, argv)) >= 0) { for (int j = 0; j < n_node_type; ++j) { output_types[j] = (argv[i + 1][j] == '1'); } } if ((i = ArgPos((char *) "-load_embed", argc, argv)) >= 0) { printf("Loading embeddings is disabled..\n"); for (int j = 0; j < n_node_type; ++j) { if (argv[i + 1][j] == '1') { load_types[j] = true; } } } if ((i = ArgPos((char *) "-load_weight", argc, argv)) >= 0) { for (int j = 0; j < n_node_type; ++j) { if (argv[i + 1][j] == '1') { node_weight[j] = true; } } } if ((i = ArgPos((char *) "-edge_weight", argc, argv)) >= 0) { for (int j = 0; j < n_node_type; ++j) { if (argv[i + 1][j] == '1') { edge_weight[j] = true; } else { edge_weight[j] = false; } } } if ((i = ArgPos((char *) "-query_file", argc, argv)) >= 0) { strcpy(query_file, argv[i + 1]); } alpha = init_alpha; TrainModel(); return 0; }
{ "alphanum_fraction": 0.6224248892, "avg_line_length": 30.6755952381, "ext": "c", "hexsha": "3a514542d10a948c9bf1924cc5f32d94bc358824", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-12-29T21:31:52.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-14T21:46:09.000Z", "max_forks_repo_head_hexsha": "4ffd1c8e45401f2b504a582c1fef6364651810eb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "VincentGaoHJ/taxogen-implementation", "max_forks_repo_path": "code/embedding_deprecated/leef.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffd1c8e45401f2b504a582c1fef6364651810eb", "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": "VincentGaoHJ/taxogen-implementation", "max_issues_repo_path": "code/embedding_deprecated/leef.c", "max_line_length": 127, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4ffd1c8e45401f2b504a582c1fef6364651810eb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "VincentGaoHJ/taxogen-implementation", "max_stars_repo_path": "code/embedding_deprecated/leef.c", "max_stars_repo_stars_event_max_datetime": "2019-11-13T09:03:50.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-13T09:03:50.000Z", "num_tokens": 9028, "size": 30921 }
/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA From Robert M. Ziff, "Four-tap shift-register-sequence random-number generators," Computers in Physics 12(4), Jul/Aug 1998, pp 385-392. A generalized feedback shift-register (GFSR) is basically an xor-sum of particular past lagged values. A four-tap register looks like: ra[nd] = ra[nd-A] ^ ra[nd-B] ^ ra[nd-C] ^ ra[nd-D] Ziff notes that "it is now widely known" that two-tap registers have serious flaws, the most obvious one being the three-point correlation that comes from the defn of the generator. Nice mathematical properties can be derived for GFSR's, and numerics bears out the claim that 4-tap GFSR's with appropriately chosen offsets are as random as can be measured, using the author's test. This implementation uses the values suggested the the author's example on p392, but altered to fit the GSL framework. The "state" is 2^14 longs, or 64Kbytes; 2^14 is the smallest power of two that is larger than D, the largest offset. We really only need a state with the last D values, but by going to a power of two, we can do a masking operation instead of a modulo, and this is presumably faster, though I haven't actually tried it. The article actually suggested a short/fast hack: #define RandomInteger (++nd, ra[nd&M]=ra[(nd-A)&M]\ ^ra[(nd-B)&M]^ra[(nd-C)&M]^ra[(nd-D)&M]) so that (as long as you've defined nd,ra[M+1]), then you ca do things like: 'if (RandomInteger < p) {...}'. Note that n&M varies from 0 to M, *including* M, so that the array has to be of size M+1. Since M+1 is a power of two, n&M is a potentially quicker implementation of the equivalent n%(M+1). This implementation copyright (C) 1998 James Theiler, based on the example mt.c in the GSL, as implemented by Brian Gough. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> static inline unsigned long int gfsr4_get (void *vstate); static double gfsr4_get_double (void *vstate); static void gfsr4_set (void *state, unsigned long int s); /* Magic numbers */ #define A 471 #define B 1586 #define C 6988 #define D 9689 #define M 16383 /* = 2^14-1 */ /* #define M 0x0003fff */ typedef struct { int nd; unsigned long ra[M+1]; } gfsr4_state_t; static inline unsigned long gfsr4_get (void *vstate) { gfsr4_state_t *state = (gfsr4_state_t *) vstate; state->nd = ((state->nd)+1)&M; return state->ra[(state->nd)] = state->ra[((state->nd)+(M+1-A))&M]^ state->ra[((state->nd)+(M+1-B))&M]^ state->ra[((state->nd)+(M+1-C))&M]^ state->ra[((state->nd)+(M+1-D))&M]; } static double gfsr4_get_double (void * vstate) { return gfsr4_get (vstate) / 4294967296.0 ; } static void gfsr4_set (void *vstate, unsigned long int s) { gfsr4_state_t *state = (gfsr4_state_t *) vstate; int i, j; /* Masks for turning on the diagonal bit and turning off the leftmost bits */ unsigned long int msb = 0x80000000UL; unsigned long int mask = 0xffffffffUL; if (s == 0) s = 4357; /* the default seed is 4357 */ /* We use the congruence s_{n+1} = (69069*s_n) mod 2^32 to initialize the state. This works because ANSI-C unsigned long integer arithmetic is automatically modulo 2^32 (or a higher power of two), so we can safely ignore overflow. */ #define LCG(n) ((69069 * n) & 0xffffffffUL) /* Brian Gough suggests this to avoid low-order bit correlations */ for (i = 0; i <= M; i++) { unsigned long t = 0 ; unsigned long bit = msb ; for (j = 0; j < 32; j++) { s = LCG(s) ; if (s & msb) t |= bit ; bit >>= 1 ; } state->ra[i] = t ; } /* Perform the "orthogonalization" of the matrix */ /* Based on the orthogonalization used in r250, as suggested initially * by Kirkpatrick and Stoll, and pointed out to me by Brian Gough */ /* BJG: note that this orthogonalisation doesn't have any effect here because the the initial 6695 elements do not participate in the calculation. For practical purposes this orthogonalisation is somewhat irrelevant, because the probability of the original sequence being degenerate should be exponentially small. */ for (i=0; i<32; ++i) { int k=7+i*3; state->ra[k] &= mask; /* Turn off bits left of the diagonal */ state->ra[k] |= msb; /* Turn on the diagonal bit */ mask >>= 1; msb >>= 1; } state->nd = i; } static const gsl_rng_type gfsr4_type = {"gfsr4", /* name */ 0xffffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (gfsr4_state_t), &gfsr4_set, &gfsr4_get, &gfsr4_get_double}; const gsl_rng_type *gsl_rng_gfsr4 = &gfsr4_type;
{ "alphanum_fraction": 0.6564483947, "avg_line_length": 33.2108433735, "ext": "c", "hexsha": "10d15e76a4a5db253dc1505de5d267d2efe9f931", "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/rng/gfsr4.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/rng/gfsr4.c", "max_line_length": 72, "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/rng/gfsr4.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": 1594, "size": 5513 }
#ifndef STRUCTURES_H #define STRUCTURES_H #include <string> #include <vector> #include <gsl/gsl_matrix.h> #define NSYSTEMS 5 #define T 3 #define UI 5 #define UJ 1 struct grain { //Euler angles in radians double phi1, phi, phi2; gsl_matrix *rot_mat; std::vector<double> crss; grain() {} grain(double p1, double p, double p2); ~grain(); }; struct vect { double x, y, z; }; struct slip_system { std::string label; //planes vect n; //directions vect b; double crss; //deformation matrix gsl_matrix* def_mat=0; //symetry part of deformation matrix gsl_matrix* symp_def=0; //non symetry part of deformation matrix gsl_matrix* asymp_def=0; std::vector<double> activity; slip_system(const std::string &l, const vect &in, const vect &ib, double r, int max_def); ~slip_system(); }; struct slip_system_matrix { //m(ij)=bi*nj //slip systems matrix gsl_matrix *mat=0; //inverse slip systems matrix gsl_matrix *matinv=0; gsl_matrix *shear_stress=0; //combination of slip systems std::vector<int> comb; slip_system_matrix(); ~slip_system_matrix(); }; struct handler { gsl_matrix *hand; handler(); ~handler(); }; struct U_handler { gsl_matrix *U_hand; U_handler(); ~U_handler(); }; #endif // STRUCTURES_H
{ "alphanum_fraction": 0.6824902724, "avg_line_length": 15.4819277108, "ext": "h", "hexsha": "d4ba34c5ef27851b939d1ca1257ad706fa17a6b1", "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": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bainit/hextexsim", "max_forks_repo_path": "src/includes/structures.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "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": "bainit/hextexsim", "max_issues_repo_path": "src/includes/structures.h", "max_line_length": 90, "max_stars_count": 2, "max_stars_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bainit/hextexsim", "max_stars_repo_path": "src/includes/structures.h", "max_stars_repo_stars_event_max_datetime": "2018-03-20T14:07:43.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-24T13:21:03.000Z", "num_tokens": 371, "size": 1285 }
#pragma once #include <chrono> #include <fmt/printf.h> #include <gsl/gsl-lite.hpp> namespace angonoka::cli { /** Pretty-print values with as much info as possible. @var value Value to be pretty-printed */ template <typename T> struct verbose { T value; }; template <typename T> verbose(T) -> verbose<T>; namespace detail { /** Helper function to print verbose durations. @param name Duration (s, m, d, etc) @return Formatter function */ template <typename T> constexpr auto verbose_duration(gsl::czstring name) { return [=](auto& total, auto& ctx, bool& needs_space) { const auto dur = std::chrono::floor<T>(total); if (dur == dur.zero()) return; total -= dur; if (needs_space) fmt::format_to(ctx.out(), " "); needs_space = true; const auto ticks = dur.count(); fmt::format_to(ctx.out(), "{}{}", ticks, name); }; } } // namespace detail } // namespace angonoka::cli namespace fmt { using angonoka::cli::verbose; /** User-defined formatter for std::chrono durations. */ template <typename... Ts> struct fmt::formatter<verbose<std::chrono::duration<Ts...>>> { using value_type = verbose<std::chrono::duration<Ts...>>; static constexpr auto parse(format_parse_context& ctx) { return ctx.end(); } template <typename FormatContext> constexpr auto format(const value_type& obj, FormatContext& ctx) { using angonoka::cli::detail::verbose_duration; using namespace std::chrono; if (obj.value == obj.value.zero()) return format_to(ctx.out(), "0s"); bool needs_space = false; auto total = duration_cast<seconds>(obj.value); [&](auto&&... fns) { (fns(total, ctx, needs_space), ...); }(verbose_duration<months>("mo"), verbose_duration<days>("d"), verbose_duration<hours>("h"), verbose_duration<minutes>("m"), verbose_duration<seconds>("s")); return ctx.out(); } }; } // namespace fmt
{ "alphanum_fraction": 0.5939422622, "avg_line_length": 27.8026315789, "ext": "h", "hexsha": "6520e7a892d8c4d64d1a0186ab88c70c0b9893eb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_path": "src/cli/verbose.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_path": "src/cli/verbose.h", "max_line_length": 68, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_path": "src/cli/verbose.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "num_tokens": 483, "size": 2113 }
/* # Copyright (C) 2009-2013 Thierry Sousbie # University of Tokyo / CNRS, 2009 # # This file is part of porject DisPerSE # # Author : Thierry Sousbie # Contact : tsousbie@gmail.com # # Licenses : This file is 'dual-licensed', you have to choose one # of the two licenses below to apply. # # CeCILL-C # The CeCILL-C license is close to the GNU LGPL. # ( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html ) # # or CeCILL v2.0 # The CeCILL license is compatible with the GNU GPL. # ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html ) # # This software is governed either by the CeCILL or the CeCILL-C license # under French law and abiding by the rules of distribution of free software. # You can use, modify and or redistribute the software under the terms of # the CeCILL or CeCILL-C licenses as circulated by CEA, CNRS and INRIA # at the following URL : "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL and CeCILL-C licenses and that you accept its terms. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "dtfi.h" #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> // mu is the average value unsigned int randomPoisson(double mu) { static int first_call = 1; static const gsl_rng_type *T; static gsl_rng * r; if (first_call) { first_call=0; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); } return gsl_ran_poisson (r, mu); } void randomSimplexCoords(double **coord, int ndims, double *result, double *P) { static int first_call = 1; static const gsl_rng_type *T; static gsl_rng * r; int i,j,k; double u; //double P[50]; if (first_call) { first_call=0; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); } result[0]=gsl_rng_uniform (r); if (ndims==3) { u=gsl_rng_uniform (r); if (u<result[0]) { result[1]=result[0]; result[0]=u; } else result[1]=u; u=gsl_rng_uniform (r); if (u<result[0]) { result[2]=result[1]; result[1]=result[0]; result[0]=u; } else if (u<result[1]) { result[2]=result[1]; result[1]=u; } else result[2]=u; } else { for (i=1;i<ndims;i++) { u = gsl_rng_uniform (r); for (j=0;j<i;j++) if (u<result[j]) { result[i]=result[j]; result[j]=u; break; } if (j==i) result[i]=u; else { j++; for (;j<i;j++) for (k=j+1;k<=i;k++) { if (result[j]>result[k]) { double tmp = result[k]; result[k]=result[j]; result[j]=tmp; } } } } } P[0]=result[0]; for (i=1;i<ndims;i++) P[i]= result[i]-result[i-1]; P[ndims]=1.-result[ndims-1]; for (i=0;i<ndims;i++) result[i]=P[0]*coord[0][i]; for (i=1;i<ndims+1;i++) for (j=0;j<ndims;j++) result[j]+=P[i]*coord[i][j]; } void genDTFIInSimplex(double **coord, double *Proba, int ngen, int ndims, double **result_p) { if (*result_p==NULL) { *result_p=(double*)malloc(sizeof(double)*ngen*ndims); } double *result = *result_p; double P[ndims]; int i,n; double keepProba; double pmax_inv=0; static int first_call = 1; static const gsl_rng_type *T; static gsl_rng * r; //if (ngen>100) printf("negen = %d\n",ngen); if (first_call) { first_call=0; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); } if (Proba!=NULL) { pmax_inv=0; for (i=0;i<ndims+1;i++) if (Proba[i]>pmax_inv) pmax_inv=Proba[i]; pmax_inv=(double)1./pmax_inv; } for (n=0;n<ngen;) { randomSimplexCoords(coord,ndims,&(result[n*ndims]),P); if (Proba!=NULL) { keepProba=Proba[0]*pmax_inv*P[0]; for (i=1;i<ndims+1;i++) keepProba+=Proba[i]*pmax_inv*P[i]; if (gsl_rng_uniform (r)<=keepProba) n++; } else n++; } } #else unsigned int randomPoisson(double mu) { fprintf(stderr,"ERROR: Function 'randomPoisson' needs GSL.\n"); fprintf(stderr,"Please, recompile with GSL.\n"); return -1; } void randomSimplexCoords(double **coord, int ndims, double *result, double *P) { fprintf(stderr,"ERROR: Function 'randomSimplexCoords' needs GSL.\n"); fprintf(stderr,"Please, recompile with GSL.\n"); return -1; } void genDTFIInSimplex(double **coord, double *Proba, int ngen, int ndims, double **result_p) { fprintf(stderr,"ERROR: Function 'genDTFIInSimplex' needs GSL.\n"); fprintf(stderr,"Please, recompile with GSL.\n"); } #endif
{ "alphanum_fraction": 0.624719489, "avg_line_length": 25.1869565217, "ext": "c", "hexsha": "a183449a4b9a44ee2c5c1187df0af24c00a1e156", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-30T13:12:22.000Z", "max_forks_repo_head_hexsha": "5bb07c7901062452a34b73f376057cabc15a13c3", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "anmartinezs/pyseg_system", "max_forks_repo_path": "sys/install/disperse/0.9.24/disperse/src/C/dtfi.c", "max_issues_count": 8, "max_issues_repo_head_hexsha": "5bb07c7901062452a34b73f376057cabc15a13c3", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:11:28.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-19T19:34:56.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "anmartinezs/pyseg_system", "max_issues_repo_path": "sys/install/disperse/0.9.24/disperse/src/C/dtfi.c", "max_line_length": 92, "max_stars_count": 12, "max_stars_repo_head_hexsha": "5bb07c7901062452a34b73f376057cabc15a13c3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "anmartinezs/pyseg_system", "max_stars_repo_path": "sys/install/disperse/0.9.24/disperse/src/C/dtfi.c", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:25:34.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-08T01:33:02.000Z", "num_tokens": 1752, "size": 5793 }
/* multilarge/test.c * * Copyright (C) 2015 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_multilarge.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_ieee_utils.h> static void test_random_matrix_orth(gsl_matrix *m, const gsl_rng *r); static void test_random_matrix_ill(gsl_matrix *m, const gsl_rng *r); static void test_random_vector(gsl_vector *v, const gsl_rng *r, const double lower, const double upper); static void test_random_matrix(gsl_matrix *m, const gsl_rng *r, const double lower, const double upper); static void test_random_vector_noise(const gsl_rng *r, gsl_vector *y); static void test_compare_vectors(const double tol, const gsl_vector * a, const gsl_vector * b, const char * desc); static void test_multifit_solve(const double lambda, const gsl_matrix * X, const gsl_vector * y, const gsl_vector * wts, const gsl_vector * diagL, const gsl_matrix * L, double *rnorm, double *snorm, gsl_vector * c); static void test_multilarge_solve(const gsl_multilarge_linear_type * T, const double lambda, const gsl_matrix * X, const gsl_vector * y, gsl_vector * wts, const gsl_vector * diagL, const gsl_matrix * L, double *rnorm, double *snorm, gsl_vector * c); /* generate random square orthogonal matrix via QR decomposition */ static void test_random_matrix_orth(gsl_matrix *m, const gsl_rng *r) { const size_t M = m->size1; gsl_matrix *A = gsl_matrix_alloc(M, M); gsl_vector *tau = gsl_vector_alloc(M); gsl_matrix *R = gsl_matrix_alloc(M, M); test_random_matrix(A, r, -1.0, 1.0); gsl_linalg_QR_decomp(A, tau); gsl_linalg_QR_unpack(A, tau, m, R); gsl_matrix_free(A); gsl_matrix_free(R); gsl_vector_free(tau); } /* construct ill-conditioned matrix via SVD */ static void test_random_matrix_ill(gsl_matrix *m, const gsl_rng *r) { const size_t M = m->size1; const size_t N = m->size2; gsl_matrix *U = gsl_matrix_alloc(M, M); gsl_matrix *V = gsl_matrix_alloc(N, N); gsl_vector *S = gsl_vector_alloc(N); gsl_matrix_view Uv = gsl_matrix_submatrix(U, 0, 0, M, N); const double smin = 16.0 * GSL_DBL_EPSILON; const double smax = 10.0; const double ratio = pow(smin / smax, 1.0 / (N - 1.0)); double s; size_t j; test_random_matrix_orth(U, r); test_random_matrix_orth(V, r); /* compute U * S */ s = smax; for (j = 0; j < N; ++j) { gsl_vector_view uj = gsl_matrix_column(U, j); gsl_vector_scale(&uj.vector, s); s *= ratio; } /* compute m = (U * S) * V' */ gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &Uv.matrix, V, 0.0, m); gsl_matrix_free(U); gsl_matrix_free(V); gsl_vector_free(S); } static void test_random_vector(gsl_vector *v, const gsl_rng *r, const double lower, const double upper) { size_t i; size_t N = v->size; for (i = 0; i < N; ++i) { gsl_vector_set(v, i, gsl_rng_uniform(r) * (upper - lower) + lower); } } static void test_random_matrix(gsl_matrix *m, const gsl_rng *r, const double lower, const double upper) { size_t i, j; size_t M = m->size1; size_t N = m->size2; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { gsl_matrix_set(m, i, j, gsl_rng_uniform(r) * (upper - lower) + lower); } } } /* generate Vandermonde matrix using equally spaced input points * on [0,1] */ static void test_vander_matrix(gsl_matrix * m) { const size_t M = m->size1; const size_t N = m->size2; const double dt = 1.0 / (M - 1.0); size_t i, j; for (i = 0; i < M; ++i) { double ti = i * dt; double mij = 1.0; for (j = 0; j < N; ++j) { gsl_matrix_set(m, i, j, mij); mij *= ti; } } } static void test_random_vector_noise(const gsl_rng *r, gsl_vector *y) { size_t i; for (i = 0; i < y->size; ++i) { double *ptr = gsl_vector_ptr(y, i); *ptr += 1.0e-3 * gsl_rng_uniform(r); } } static void test_compare_vectors(const double tol, const gsl_vector * a, const gsl_vector * b, const char * desc) { size_t i; for (i = 0; i < a->size; ++i) { double ai = gsl_vector_get(a, i); double bi = gsl_vector_get(b, i); gsl_test_rel(bi, ai, tol, "%s i=%zu", desc, i); } } /* solve least squares system with multifit SVD */ static void test_multifit_solve(const double lambda, const gsl_matrix * X, const gsl_vector * y, const gsl_vector * wts, const gsl_vector * diagL, const gsl_matrix * L, double *rnorm, double *snorm, gsl_vector * c) { const size_t n = X->size1; const size_t p = X->size2; gsl_multifit_linear_workspace *w = gsl_multifit_linear_alloc(n, p); gsl_matrix *Xs = gsl_matrix_alloc(n, p); gsl_vector *ys = gsl_vector_alloc(n); gsl_vector *cs = gsl_vector_alloc(p); gsl_matrix *LQR = NULL; gsl_vector *Ltau = NULL; gsl_matrix *M = NULL; /* convert to standard form */ if (diagL) { gsl_multifit_linear_wstdform1(diagL, X, wts, y, Xs, ys, w); } else if (L) { const size_t m = L->size1; LQR = gsl_matrix_alloc(m, p); Ltau = gsl_vector_alloc(GSL_MIN(m, p)); M = (m >= p) ? gsl_matrix_alloc(m, p) : gsl_matrix_alloc(n, p); gsl_matrix_memcpy(LQR, L); gsl_multifit_linear_L_decomp(LQR, Ltau); gsl_multifit_linear_wstdform2(LQR, Ltau, X, wts, y, Xs, ys, M, w); } else { gsl_matrix_memcpy(Xs, X); gsl_vector_memcpy(ys, y); } gsl_multifit_linear_svd(Xs, w); gsl_multifit_linear_solve(lambda, Xs, ys, cs, rnorm, snorm, w); /* convert to general form */ if (diagL) gsl_multifit_linear_genform1(diagL, cs, c, w); else if (L) gsl_multifit_linear_wgenform2(LQR, Ltau, X, wts, y, cs, M, c, w); else gsl_vector_memcpy(c, cs); gsl_multifit_linear_free(w); gsl_matrix_free(Xs); gsl_vector_free(ys); gsl_vector_free(cs); if (LQR) gsl_matrix_free(LQR); if (Ltau) gsl_vector_free(Ltau); if (M) gsl_matrix_free(M); } /* solve least squares system with multilarge */ static void test_multilarge_solve(const gsl_multilarge_linear_type * T, const double lambda, const gsl_matrix * X, const gsl_vector * y, gsl_vector * wts, const gsl_vector * diagL, const gsl_matrix * L, double *rnorm, double *snorm, gsl_vector * c) { const size_t n = X->size1; const size_t p = X->size2; const size_t nblock = 5; const size_t nrows = n / nblock; /* number of rows per block */ gsl_multilarge_linear_workspace *w = gsl_multilarge_linear_alloc(T, p); gsl_matrix *Xs = gsl_matrix_alloc(nrows, p); gsl_vector *ys = gsl_vector_alloc(nrows); gsl_vector *cs = gsl_vector_alloc(p); gsl_matrix *LQR = NULL; gsl_vector *Ltau = NULL; size_t rowidx = 0; if (L) { const size_t m = L->size1; LQR = gsl_matrix_alloc(m, p); Ltau = gsl_vector_alloc(p); gsl_matrix_memcpy(LQR, L); gsl_multilarge_linear_L_decomp(LQR, Ltau); } while (rowidx < n) { size_t nleft = n - rowidx; size_t nr = GSL_MIN(nrows, nleft); gsl_matrix_const_view Xv = gsl_matrix_const_submatrix(X, rowidx, 0, nr, p); gsl_vector_const_view yv = gsl_vector_const_subvector(y, rowidx, nr); gsl_vector_view wv; gsl_matrix_view Xsv = gsl_matrix_submatrix(Xs, 0, 0, nr, p); gsl_vector_view ysv = gsl_vector_subvector(ys, 0, nr); if (wts) wv = gsl_vector_subvector(wts, rowidx, nr); /* convert to standard form */ if (diagL) { gsl_multilarge_linear_wstdform1(diagL, &Xv.matrix, wts ? &wv.vector : NULL, &yv.vector, &Xsv.matrix, &ysv.vector, w); } else if (L) { gsl_multilarge_linear_wstdform2(LQR, Ltau, &Xv.matrix, wts ? &wv.vector : NULL, &yv.vector, &Xsv.matrix, &ysv.vector, w); } else { gsl_matrix_memcpy(&Xsv.matrix, &Xv.matrix); gsl_vector_memcpy(&ysv.vector, &yv.vector); } gsl_multilarge_linear_accumulate(&Xsv.matrix, &ysv.vector, w); rowidx += nr; } gsl_multilarge_linear_solve(lambda, cs, rnorm, snorm, w); if (diagL) gsl_multilarge_linear_genform1(diagL, cs, c, w); else if (L) gsl_multilarge_linear_genform2(LQR, Ltau, cs, c, w); else gsl_vector_memcpy(c, cs); gsl_multilarge_linear_free(w); gsl_matrix_free(Xs); gsl_vector_free(ys); gsl_vector_free(cs); if (LQR) gsl_matrix_free(LQR); if (Ltau) gsl_vector_free(Ltau); } static void test_random(const gsl_multilarge_linear_type * T, const size_t n, const size_t p, const double tol, const gsl_rng * r) { const double tol1 = 1.0e3 * tol; gsl_matrix *X = gsl_matrix_alloc(n, p); gsl_vector *y = gsl_vector_alloc(n); gsl_vector *c = gsl_vector_alloc(p); gsl_vector *w = gsl_vector_alloc(n); gsl_vector *diagL = gsl_vector_alloc(p); gsl_matrix *Lsqr = gsl_matrix_alloc(p, p); gsl_matrix *Ltall = gsl_matrix_alloc(5*p, p); gsl_vector *c0 = gsl_vector_alloc(p); gsl_vector *c1 = gsl_vector_alloc(p); double rnorm0, snorm0; double rnorm1, snorm1; char str[2048]; size_t i; /* generate LS system */ test_random_matrix_ill(X, r); /*test_random_matrix(X, r, -1.0, 1.0);*/ test_random_vector(c, r, -1.0, 1.0); /* compute y = X c + noise */ gsl_blas_dgemv(CblasNoTrans, 1.0, X, c, 0.0, y); test_random_vector_noise(r, y); /* random weights */ test_random_vector(w, r, 0.0, 1.0); /* random diag(L) */ test_random_vector(diagL, r, 1.0, 5.0); /* random square L */ test_random_matrix(Lsqr, r, -5.0, 5.0); /* random tall L */ test_random_matrix(Ltall, r, -10.0, 10.0); for (i = 0; i < 2; ++i) { double lambda = pow(10.0, -(double) i); /* unweighted with L = I */ { test_multifit_solve(lambda, X, y, NULL, NULL, NULL, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, NULL, NULL, NULL, &rnorm1, &snorm1, c1); sprintf(str, "random %s unweighted stdform n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } /* weighted, L = diag(L) */ { test_multifit_solve(lambda, X, y, w, diagL, NULL, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, w, diagL, NULL, &rnorm1, &snorm1, c1); sprintf(str, "random %s weighted diag(L) n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } /* unweighted, L = diag(L) */ { test_multifit_solve(lambda, X, y, NULL, diagL, NULL, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, NULL, diagL, NULL, &rnorm1, &snorm1, c1); sprintf(str, "random %s unweighted diag(L) n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } /* weighted, L = square */ { test_multifit_solve(lambda, X, y, w, NULL, Lsqr, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, w, NULL, Lsqr, &rnorm1, &snorm1, c1); sprintf(str, "random %s weighted Lsqr n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } /* unweighted, L = square */ { test_multifit_solve(lambda, X, y, NULL, NULL, Lsqr, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, NULL, NULL, Lsqr, &rnorm1, &snorm1, c1); sprintf(str, "random %s unweighted Lsqr n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } /* weighted, L = tall */ { test_multifit_solve(lambda, X, y, w, NULL, Ltall, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, w, NULL, Ltall, &rnorm1, &snorm1, c1); sprintf(str, "random %s weighted Ltall n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } /* unweighted, L = tall */ { test_multifit_solve(lambda, X, y, NULL, NULL, Ltall, &rnorm0, &snorm0, c0); test_multilarge_solve(T, lambda, X, y, NULL, NULL, Ltall, &rnorm1, &snorm1, c1); sprintf(str, "random %s unweighted Ltall n=%zu p=%zu lambda=%g", T->name, n, p, lambda); test_compare_vectors(tol, c0, c1, str); gsl_test_rel(rnorm1, rnorm0, tol1, "rnorm %s", str); gsl_test_rel(snorm1, snorm0, tol, "snorm %s", str); } } gsl_matrix_free(X); gsl_vector_free(y); gsl_vector_free(c); gsl_vector_free(w); gsl_vector_free(diagL); gsl_matrix_free(Lsqr); gsl_matrix_free(Ltall); gsl_vector_free(c0); gsl_vector_free(c1); } int main (void) { gsl_rng *r = gsl_rng_alloc(gsl_rng_default); gsl_ieee_env_setup(); { const double tol1 = 1.0e-8; const double tol2 = 1.0e-11; const size_t n_vals[] = { 40, 356, 501 }; const size_t p_vals[] = { 40, 213, 345 }; size_t i; for (i = 0; i < 2; ++i) { size_t n = n_vals[i]; size_t p = p_vals[i]; /* generate random ill-conditioned LS system and test */ test_random(gsl_multilarge_linear_normal, n, p, tol1, r); test_random(gsl_multilarge_linear_tsqr, n, p, tol2, r); } } gsl_rng_free(r); exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.6093942339, "avg_line_length": 29.9127906977, "ext": "c", "hexsha": "02651e57fb958d4976f564fd7b32d76347d18d73", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge/test.c", "max_line_length": 95, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/multilarge/test.c", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:15:00.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-18T13:15:00.000Z", "num_tokens": 4766, "size": 15435 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <petsc.h> #include <petscmat.h> #include <petscvec.h> #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include "common-driver-utils.h" #include "stokes_block_scaling.h" #include "stokes_Kblock_scaling.h" #include <StgFEM/libStgFEM/src/StgFEM.h> #include <PICellerator/libPICellerator/src/PICellerator.h> #include <Underworld/libUnderworld/src/Underworld.h> #include "Solvers/SLE/src/SLE.h" /* to give the AugLagStokes_SLE type */ #include "Solvers/KSPSolvers/src/KSPSolvers.h" /* for __KSP_COMMON */ #include "BSSCR.h" #undef __FUNCT__ #define __FUNCT__ "KSPUnscale_BSSCR" PetscErrorCode KSPUnscale_BSSCR(KSP ksp) { KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data; Mat Amat,Pmat; Vec B,X; Mat ApproxS; MatStokesBlockScaling BA=bsscr->BA; PetscTruth sym; MatStructure pflag; PetscErrorCode ierr; PetscFunctionBegin; X = ksp->vec_sol; B = ksp->vec_rhs; ApproxS = bsscr->preconditioner->matrix; sym = bsscr->DIsSym; ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr); if( BA->scaling_exists == PETSC_FALSE ){ PetscPrintf( PETSC_COMM_WORLD, "SCALING does not EXIST in %s\n", __func__); }else{ if( DEFAULT == bsscr->scaletype ){ PetscPrintf( PETSC_COMM_WORLD, "Operator scales (pre-Unscaling)\n"); BSSCR_MatStokesBlockReportOperatorScales(Amat, sym); BSSCR_MatStokesBlockUnScaleSystem( BA, Amat, B, X, ApproxS, sym); PetscPrintf( PETSC_COMM_WORLD, "Operator scales (post-Unscaling)\n"); BSSCR_MatStokesBlockReportOperatorScales(Amat, sym); } if( KONLY == bsscr->scaletype ){ PetscPrintf( PETSC_COMM_WORLD, "Operator scales KONLY (pre-Unscaling)\n"); BSSCR_MatStokesKBlockReportOperatorScales(Amat, sym); BSSCR_MatStokesKBlockUnScaleSystem( BA, Amat, B, X, ApproxS, sym); PetscPrintf( PETSC_COMM_WORLD, "Operator scales KONLY (post-Unscaling)\n"); BSSCR_MatStokesKBlockReportOperatorScales(Amat, sym); } } bsscr->scaled = PETSC_FALSE; PetscFunctionReturn(0); } /* KSPScale_BSSCR constructs scaling and applies scaling to system. Want to do both here when doing nonlinear iterations to keep the scaling up to date with each iteration. */ #undef __FUNCT__ #define __FUNCT__ "KSPScale_BSSCR" PetscErrorCode KSPScale_BSSCR(KSP ksp) { KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data; Mat Amat,Pmat; Vec B,X; Mat ApproxS; MatStokesBlockScaling BA=bsscr->BA; PetscTruth sym; MatStructure pflag; PetscErrorCode ierr; PetscFunctionBegin; X = ksp->vec_sol; B = ksp->vec_rhs; ApproxS = bsscr->preconditioner->matrix; sym = bsscr->DIsSym; ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr); if( DEFAULT == bsscr->scaletype ){ if( BA->scaling_exists ){ BSSCR_MatStokesBlockDefaultBuildScaling( BA, Amat);/* rebuild scaling vectors on struct */ BA->scalings_have_been_inverted = PETSC_FALSE; }else{ BSSCR_MatBlock_ConstructScaling( BA, Amat, B, X );/* allocates scaling vectors then calls the above function */ BA->scalings_have_been_inverted = PETSC_FALSE;/* above function sets this but I am making it explicit here */ } PetscPrintf( PETSC_COMM_WORLD, "Operator scales (pre-scaling)\n"); BSSCR_MatStokesBlockReportOperatorScales(Amat, sym); BSSCR_MatStokesBlockScaleSystem( BA, Amat, B, X, ApproxS, sym ); PetscPrintf( PETSC_COMM_WORLD, "Operator scales (post-scaling)\n"); BSSCR_MatStokesBlockReportOperatorScales(Amat, sym); bsscr->scaled = PETSC_TRUE; } if( KONLY == bsscr->scaletype ){ if( BA->scaling_exists ){ BSSCR_MatStokesKBlockDefaultBuildScaling( BA, Amat, B, X, sym);/* rebuild scaling vectors on struct */ BA->scalings_have_been_inverted = PETSC_FALSE; }else{ BSSCR_MatKBlock_ConstructScaling( BA, Amat, B, X, sym);/* allocates scaling vectors then calls the above function */ BA->scalings_have_been_inverted = PETSC_FALSE;/* above function sets this but I am making it explicit here */ } PetscPrintf( PETSC_COMM_WORLD, "Operator scales KONLY (pre-scaling)\n"); BSSCR_MatStokesKBlockReportOperatorScales(Amat, sym); BSSCR_MatStokesKBlockScaleSystem( BA, Amat, B, X, ApproxS, sym ); PetscPrintf( PETSC_COMM_WORLD, "Operator scales KONLY (post-scaling)\n"); BSSCR_MatStokesKBlockReportOperatorScales(Amat, sym); bsscr->scaled = PETSC_TRUE; } PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6449659349, "avg_line_length": 41.9365079365, "ext": "c", "hexsha": "2ce12e7a24bad82a3deb24145eb23b6117ed6a70", "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": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_scale.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_scale.c", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_scale.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1614, "size": 5284 }
#include "mpi.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <string.h> #include <stdbool.h> #ifdef __APPLE__ #include <cblas.h> #include <libiomp/omp.h> #define set_num_threads(x) openblas_set_num_threads(x) #define get_num_threads() openblas_get_num_threads() #else #include <mkl.h> #include <omp.h> #define set_num_threads(x) mkl_set_num_threads(x) #define get_num_threads() mkl_get_num_threads() #endif double norm_inf_mat_Y11(double *X, int n); int main(int argc, char **argv) { char *filename = NULL; int option = 0, omp_threads = 1; while ((option = getopt(argc, argv, "f:t:")) != -1) { switch (option) { case 'f': filename = optarg; break; case 't': omp_threads = atoi(optarg); break; default: printf("Usage: mpi_mexp -f string -t num_threads \n"); return 0; } } if (filename == NULL) { printf("Usage: mpi_mexp -f string -t num_threads \n"); return 0; } set_num_threads(omp_threads); omp_set_num_threads(omp_threads); int numTasks, rank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numTasks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int qProcs = (int) sqrt(numTasks); if (qProcs - sqrt(numTasks) != 0) { if (rank == 0) printf("np must be a square number\n"); MPI_Finalize(); return 0; } int q_root = qProcs - 1; int world_root = numTasks - 1; int n, dims[2] = {qProcs, qProcs}, periods[2] = {0, 0}, reorder = 0, coords[2], rc, i; MPI_Comm cartComm; MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, reorder, &cartComm); MPI_Comm_rank(cartComm, &rank); MPI_Cart_coords(cartComm, rank, 2, coords); MPI_File matFile; rc = MPI_File_open(cartComm, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &matFile); if (rc && (rank == 0)) { printf("Unable to open file %s\n", filename); fflush(stdout); } MPI_Status status; MPI_File_read(matFile, &n, 1, MPI_INT, &status); int blockSize = (n + qProcs) / qProcs; /* number of rows in _block_ */ int lastBlock = n + 1 - (qProcs - 1) * blockSize; double *LocalA = (double *) malloc(blockSize * blockSize * sizeof(double)); MPI_Datatype readFileType; MPI_Type_vector(blockSize, blockSize, n, MPI_DOUBLE, &readFileType); MPI_Type_commit(&readFileType); MPI_Offset offset = (MPI_Offset) (1 * sizeof(int) + sizeof(double) * (blockSize * coords[1] + blockSize * n * coords[0])); MPI_File_set_view(matFile, offset, MPI_DOUBLE, readFileType, "native", MPI_INFO_NULL); MPI_File_read_at(matFile, 0, LocalA, blockSize * blockSize, MPI_DOUBLE, &status); MPI_Type_free(&readFileType); if (coords[0] == q_root) { memset(LocalA + (lastBlock - 1) * blockSize, 0, (blockSize + 1 - lastBlock) * blockSize * sizeof(double)); } if (coords[1] == q_root) { int kk = 0; for (kk = 0; kk < blockSize; ++kk) { memset(LocalA + kk * blockSize + lastBlock - 1, 0, (blockSize + 1 - lastBlock) * sizeof(double)); } } double loc_d_var; double *loc_vec_var = (double *) malloc(blockSize * sizeof(double)); memset(loc_vec_var, 0, blockSize * sizeof(double)); offset = (MPI_Offset) (1 * sizeof(int) + sizeof(double) * n * n); MPI_File_set_view(matFile, offset, MPI_DOUBLE, MPI_DOUBLE, "native", MPI_INFO_NULL); offset = coords[0] * blockSize; MPI_File_read_at_all(matFile, offset, loc_vec_var, coords[0] == qProcs - 1 ? lastBlock : blockSize, MPI_DOUBLE, &status); MPI_File_close(&matFile); MPI_Comm rowComm, colComm; MPI_Comm_split(MPI_COMM_WORLD, coords[0], rank, &rowComm); MPI_Comm_split(MPI_COMM_WORLD, coords[1], rank, &colComm); int row_rank, col_rank; MPI_Comm_rank(colComm, &col_rank); MPI_Comm_rank(rowComm, &row_rank); if (coords[1] == qProcs - 1) { cblas_dcopy(blockSize, loc_vec_var, 1, LocalA + lastBlock - 1, blockSize); } double mpi_start = MPI_Wtime(); //compute inf norm of matA for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) { loc_vec_var[i] = cblas_dasum((row_rank == q_root ? lastBlock - 1 : blockSize), LocalA + i * blockSize, 1); } if (row_rank == q_root) { MPI_Reduce(MPI_IN_PLACE, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm); } else { MPI_Reduce(loc_vec_var, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm); } if (row_rank == q_root) { loc_d_var = 0; for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) { if (loc_vec_var[i] > loc_d_var) loc_d_var = loc_vec_var[i]; } if (col_rank == q_root) { MPI_Reduce(MPI_IN_PLACE, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm); } else { MPI_Reduce(&loc_d_var, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm); } } MPI_Bcast(&loc_d_var, 1, MPI_DOUBLE, world_root, MPI_COMM_WORLD); //init Y martix for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) { cblas_dscal((row_rank == q_root ? lastBlock - 1 : blockSize), -1 / loc_d_var, LocalA + i * blockSize, 1); } if (row_rank == q_root) { cblas_dscal((col_rank == q_root ? lastBlock - 1 : blockSize), 1 / loc_d_var, LocalA + lastBlock - 1, blockSize); } if (row_rank == col_rank) { for (i = 0; i < (row_rank == q_root ? lastBlock-1 : blockSize); ++i) { LocalA[i * blockSize + i] += 1; } } if (rank == world_root) { LocalA[(lastBlock - 1) * (blockSize + 1)] = 1; } //loop double tolerance = 1e-8; int loopBreak = 0, iteration = 0; double *col_mat = (double *) malloc(qProcs * blockSize * blockSize * sizeof(double)); memset(col_mat, 0, qProcs * blockSize * blockSize * sizeof(double)); double *row_mat = (double *) malloc(qProcs * blockSize * blockSize * sizeof(double)); memset(row_mat, 0, qProcs * blockSize * blockSize * sizeof(double)); while (true) { //norm mat //compute inf norm of matA for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) { loc_vec_var[i] = cblas_dasum((row_rank == q_root ? lastBlock - 1 : blockSize), LocalA + i * blockSize, 1); } if (row_rank == q_root) { MPI_Reduce(MPI_IN_PLACE, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm); } else { MPI_Reduce(loc_vec_var, loc_vec_var, blockSize, MPI_DOUBLE, MPI_SUM, q_root, rowComm); } if (row_rank == q_root) { loc_d_var = 0; for (i = 0; i < (col_rank == q_root ? lastBlock - 1 : blockSize); ++i) { if (loc_vec_var[i] > loc_d_var) loc_d_var = loc_vec_var[i]; } if (col_rank == q_root) { MPI_Reduce(MPI_IN_PLACE, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm); } else { MPI_Reduce(&loc_d_var, &loc_d_var, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm); } size_t index = cblas_idamax((col_rank == q_root ? lastBlock - 1 : blockSize), LocalA + lastBlock - 1, blockSize); double norm2b; MPI_Reduce(&LocalA[index * blockSize + lastBlock - 1], &norm2b, 1, MPI_DOUBLE, MPI_MAX, q_root, colComm); if (col_rank == q_root) { printf("normM:%.4f, normB:%.4f\n", loc_d_var, norm2b); loopBreak = (loc_d_var / norm2b < tolerance) ? 1 : 0; } } MPI_Bcast(&loopBreak, 1, MPI_INT, world_root, MPI_COMM_WORLD); if (loopBreak > 0) break; iteration++; //gather loc mat MPI_Allgather(LocalA, blockSize * blockSize, MPI_DOUBLE, col_mat, blockSize * blockSize, MPI_DOUBLE, colComm); MPI_Allgather(LocalA, blockSize * blockSize, MPI_DOUBLE, row_mat, blockSize * blockSize, MPI_DOUBLE, rowComm); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, blockSize, blockSize, blockSize, 1, row_mat, blockSize, col_mat, blockSize, 0.0, LocalA, blockSize); for (i = 1; i < qProcs; ++i) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, blockSize, blockSize, blockSize, 1, row_mat + i * (blockSize * blockSize), blockSize, col_mat + i * (blockSize * blockSize), blockSize, 1, LocalA, blockSize); } } if (rank == world_root) { printf("mpi_mexp_iter:%d \n", iteration); printf("mpi_mexp_time: %f\n", MPI_Wtime() - mpi_start); } if (row_rank == q_root) { for (i = 0; i < (row_rank == qProcs - 1 ? lastBlock : blockSize); ++i) { if (fabs(LocalA[i * blockSize + lastBlock - 1] - 1) > 1e-3) { printf("MPI_MEXP_ERR %f \n", LocalA[i * blockSize + lastBlock - 1]); break; } } } MPI_Comm_free(&cartComm); MPI_Comm_free(&colComm); MPI_Comm_free(&rowComm); MPI_Finalize(); }
{ "alphanum_fraction": 0.5837407014, "avg_line_length": 35.7794676806, "ext": "c", "hexsha": "c56c9f57c5199c8fb6239b47e7fe53140843286c", "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": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "baishuai/MEXP", "max_forks_repo_path": "mpi/mpi_mexp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "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": "baishuai/MEXP", "max_issues_repo_path": "mpi/mpi_mexp.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "baishuai/MEXP", "max_stars_repo_path": "mpi/mpi_mexp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2661, "size": 9410 }
#ifndef STDAFX__H #define STDAFX__H #if defined(_WIN32) #include <SDKDDKVer.h> #if !defined(_STL_EXTRA_DISABLED_WARNINGS) #define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4800 4820 4987 5026 5027 5039 #endif #if !defined(_SCL_SECURE_NO_WARNINGS) #define _SCL_SECURE_NO_WARNINGS 1 #endif #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS 1 #endif #if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING) #define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1 #endif #if !defined(_SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING) #define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING 1 #endif #if !defined(_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING) #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 1 #endif #define STRICT #define NOMINMAX #pragma warning(disable: 4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught #pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' #pragma warning(disable: 4710) // warning C4710: '%s': function not inlined #pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion #pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s' #pragma warning(disable: 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified #include <Windows.h> #pragma warning(push) #pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition #include <Winternl.h> #include <ntstatus.h> #pragma warning(pop) #else // defined(_WIN32) #include <cpuid.h> #endif #if defined(_MSC_VER) // currently broken (triggers on iterators and other objects that are usually unnamed) #pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923). // disable for everything #pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label #pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier #pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed #pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted #pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted #pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted #pragma warning(disable: 4710) // warning C4710: '%s': function not inlined #pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s' #pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted #pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted #pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'. #pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919). #pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413) #pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414). #pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415) #pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417) #pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s' // disable for standard headers #pragma warning(push) #pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474) #pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474) #pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483) #pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485) #pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479) #pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'. #pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d. #pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner. #pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d. #pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable. #pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923). #pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684) #pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417). #pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413) #pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414) #pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417) #pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420) #pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421) #pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422) #pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969) #pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970) #else // linux warnings go here #endif #include <cstddef> #include <map> #include <set> #include <vector> #include <string> #include <algorithm> #include <iostream> #include <fstream> #include <iomanip> #include <type_traits> #include <utility> #include <memory> #include <tuple> #include <thread> #include <cstdlib> #include <codecvt> #if defined(_MSC_VER) // disable additionally for third-party libraries #pragma warning(push) #pragma warning(disable: 4456) // warning C4456: declaration of '%s' hides previous local declaration #pragma warning(disable: 4458) // warning C4458: declaration of '%s' hides class member #pragma warning(disable: 4459) // warning C4459: declaration of '%s' hides global declaration #pragma warning(disable: 4702) // warning C4702: unreacha3eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeble code #include <CppCoreCheck\Warnings.h> #pragma warning(disable: ALL_CPPCORECHECK_WARNINGS) #endif #ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE #define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE #endif #include <boost/algorithm/string.hpp> #include <boost/xpressive/xpressive.hpp> #include <gsl/gsl> #include <fmt/format.h> #if defined(_MSC_VER) #pragma warning(pop) #pragma warning(pop) #else // linux warning restoration goes here #endif #endif
{ "alphanum_fraction": 0.770637239, "avg_line_length": 55.6807228916, "ext": "h", "hexsha": "be0f69a5a8b08f4eefe44903c18d7986446db67a", "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": "f8901c5c7b9a4a62f550d835a2a14fc6eec147e5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "DrPizza/cpuid", "max_forks_repo_path": "libcpuid/tests/src/cpuid/stdafx.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f8901c5c7b9a4a62f550d835a2a14fc6eec147e5", "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": "DrPizza/cpuid", "max_issues_repo_path": "libcpuid/tests/src/cpuid/stdafx.h", "max_line_length": 256, "max_stars_count": 3, "max_stars_repo_head_hexsha": "f8901c5c7b9a4a62f550d835a2a14fc6eec147e5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "DrPizza/cpuid", "max_stars_repo_path": "libcpuid/tests/src/cpuid/stdafx.h", "max_stars_repo_stars_event_max_datetime": "2021-06-29T06:46:39.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-06T08:00:56.000Z", "num_tokens": 2457, "size": 9243 }
/* * Simple example of NLopt usage from: * http://nlopt.readthedocs.io/en/latest/NLopt_Tutorial/ */ #include <stdio.h> #include <math.h> #include <nlopt.h> int count = 0; // // Objective function. // double myfunc(unsigned n, const double *x, double *grad, void *my_func_data) { count++; if (grad) { grad[0] = 0.0; grad[1] = 0.5 / sqrt(x[1]); } return sqrt(x[1]); } typedef struct { double a, b; } my_constraint_data; // // Constraint function. // double myconstraint(unsigned n, const double *x, double *grad, void *data) { my_constraint_data *d = (my_constraint_data*) data; double a = d->a, b = d->b; if (grad) { grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b); grad[1] = -1.0; } return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]); } int main() { // Select algorithm. // // Global optimization // // nlopt_algorithm algorithm = NLOPT_GN_DIRECT; // DIviding RECTangles algorithm for global optimization // nlopt_algorithm algorithm = NLOPT_GN_DIRECT_L; // locally biased variant of DIRECT // nlopt_algorithm algorithm = NLOPT_GN_DIRECT_L_RAND; // slightly randomized variant of DIRECT-L // nlopt_algorithm algorithm = NLOPT_GN_CRS2_LM; // Controlled Random Search with local mutation // nlopt_algorithm algorithm = NLOPT_G_MLSL; // Multi-Level Single-Linkage // nlopt_algorithm algorithm = NLOPT_G_MLSL_LDS; // modification of MLSL with low-discrepancy sequence // nlopt_algorithm algorithm = NLOPT_GD_STOGO; // StoGO // nlopt_algorithm algorithm = NLOPT_GD_STOGO_RAND; // randomized variant of StoGO // nlopt_algorithm algorithm = NLOPT_GN_ISRES; // Improved Stochastic Ranking Evolution Strategy // nlopt_algorithm algorithm = NLOPT_GN_ESCH; // evolutionary algorithm // // Local derivative-free optimization // // nlopt_algorithm algorithm = NLOPT_LN_COBYLA; // Constrained Optimization BY Linear Approximations // nlopt_algorithm algorithm = NLOPT_LN_BOBYQA; // BOBYQA, iterative quadratic approximation // nlopt_algorithm algorithm = NLOPT_LN_NEWUOA; // NEWUOA, quadratic approximation // nlopt_algorithm algorithm = NLOPT_LN_NEWUOA_BOUND; // variant of NEWUOA with bound constraints // nlopt_algorithm algorithm = NLOPT_LN_PRAXIS; // PRincipal AXIS // nlopt_algorithm algorithm = NLOPT_LN_NELDERMEAD; // Nelder-Mead Simplex // nlopt_algorithm algorithm = NLOPT_LN_SBPLX; // re-implementation of Subplex algorithm // // Local gradient-based optimization // nlopt_algorithm algorithm = NLOPT_LD_MMA; // Method of Moving Asymptotes // nlopt_algorithm algorithm = NLOPT_LD_CCSAQ; // conservative convex separable approximation, quadratic // nlopt_algorithm algorithm = NLOPT_LD_SLSQP; // Sequential Least-Squares Quadratic Programming // nlopt_algorithm algorithm = NLOPT_LD_LBFGS; // Low-storage BFGS // nlopt_algorithm algorithm = NLOPT_LD_TNEWTON; // Truncated Newton // nlopt_algorithm algorithm = NLOPT_LD_VAR1; // shifted limited-memory variable-metric algorithm, rank-1 // nlopt_algorithm algorithm = NLOPT_LD_VAR2; // shifted limited-memory variable-metric algorithm, rank-2 // Create optimizer object. // Select dimensionality. nlopt_opt opt = nlopt_create(algorithm, 2); // Set objective function. nlopt_set_min_objective(opt, myfunc, NULL); // Specify bounds. double lb[2] = { -HUGE_VAL, 0 }; // lower bounds nlopt_set_lower_bounds(opt, lb); //TODO: nlopt_set_upper_bounds(); // Add constraints. my_constraint_data data[2] = { {2, 0}, {-1, 1} }; nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8); nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8); // Stopping criteria, or. a relative tolerance on the optimization parameters. nlopt_set_xtol_rel(opt, 1e-4); // Perform the optimization, starting with some initial guess. double x[2] = { 1.234, 5.678 }; // initial guess double minf; // the minimum objective value upon return if (nlopt_optimize(opt, x, &minf) < 0) { printf("nlopt failed!\n"); } else { printf("found minimum after %d evaluations\n", count); printf("found minimum at f(%g, %g) = %0.10g\n", x[0], x[1], minf); } nlopt_destroy(opt); return 0; }
{ "alphanum_fraction": 0.6670388566, "avg_line_length": 38.2735042735, "ext": "c", "hexsha": "79cca56a6a49b54735e9ee4515612fed72c3095f", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-11-13T15:00:41.000Z", "max_forks_repo_forks_event_min_datetime": "2017-06-19T23:04:00.000Z", "max_forks_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "sergev/vak-opensource", "max_forks_repo_path": "languages/c-language/nlopt-example.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "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": "sergev/vak-opensource", "max_issues_repo_path": "languages/c-language/nlopt-example.c", "max_line_length": 115, "max_stars_count": 34, "max_stars_repo_head_hexsha": "e1912b83dabdbfab2baee5e7a9a40c3077349381", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sergev/vak-opensource", "max_stars_repo_path": "languages/c-language/nlopt-example.c", "max_stars_repo_stars_event_max_datetime": "2022-02-12T21:27:43.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-29T19:50:34.000Z", "num_tokens": 1272, "size": 4478 }
// -------------------------------------------------------------------------- // 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: Clemens Groepl $ // $Authors: $ // -------------------------------------------------------------------------- #ifndef OPENMS_TRANSFORMATIONS_FEATUREFINDER_LEVMARQFITTER1D_H #define OPENMS_TRANSFORMATIONS_FEATUREFINDER_LEVMARQFITTER1D_H #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/Fitter1D.h> #include <gsl/gsl_rng.h> // gsl random number generators #include <gsl/gsl_randist.h> // gsl random number distributions #include <gsl/gsl_vector.h> // gsl vector and matrix definitions #include <gsl/gsl_multifit_nlin.h> // gsl multidimensional fitting #include <gsl/gsl_blas.h> // gsl linear algebra stuff #include <OpenMS/DATASTRUCTURES/ListUtils.h> namespace OpenMS { /** @brief Abstract class for 1D-model fitter using Levenberg-Marquardt algorithm for parameter optimization. */ class OPENMS_DLLAPI LevMarqFitter1D : public Fitter1D { public: typedef std::vector<double> ContainerType; /// Default constructor LevMarqFitter1D() : Fitter1D() { this->defaults_.setValue("max_iteration", 500, "Maximum number of iterations using by Levenberg-Marquardt algorithm.", ListUtils::create<String>("advanced")); this->defaults_.setValue("deltaAbsError", 0.0001, "Absolute error used by the Levenberg-Marquardt algorithm.", ListUtils::create<String>("advanced")); this->defaults_.setValue("deltaRelError", 0.0001, "Relative error used by the Levenberg-Marquardt algorithm.", ListUtils::create<String>("advanced")); } /// copy constructor LevMarqFitter1D(const LevMarqFitter1D & source) : Fitter1D(source), max_iteration_(source.max_iteration_), abs_error_(source.abs_error_), rel_error_(source.rel_error_) { } /// destructor virtual ~LevMarqFitter1D() { } /// assignment operator virtual LevMarqFitter1D & operator=(const LevMarqFitter1D & source) { if (&source == this) return *this; Fitter1D::operator=(source); max_iteration_ = source.max_iteration_; abs_error_ = source.abs_error_; rel_error_ = source.rel_error_; return *this; } protected: /// GSL status Int gsl_status_; /// Parameter indicates symmetric peaks bool symmetric_; /// Maximum number of iterations Int max_iteration_; /** Test for the convergence of the sequence by comparing the last iteration step dx with the absolute error epsabs and relative error epsrel to the current position x */ /// Absolute error CoordinateType abs_error_; /// Relative error CoordinateType rel_error_; /** Display the intermediate state of the solution. The solver state contains the vector s->x which is the current position, and the vector s->f with corresponding function values */ virtual void printState_(Int iter, gsl_multifit_fdfsolver * s) = 0; /// Return GSL status as string const String getGslStatus_() { return gsl_strerror(gsl_status_); } /** @brief Optimize start parameter @exception Exception::UnableToFit is thrown if fitting cannot be performed */ void optimize_(const RawDataArrayType & set, Int num_params, CoordinateType x_init[], Int (* residual)(const gsl_vector * x, void * params, gsl_vector * f), Int (* jacobian)(const gsl_vector * x, void * params, gsl_matrix * J), Int (* evaluate)(const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J), void * advanced_params ) { const gsl_multifit_fdfsolver_type * T; gsl_multifit_fdfsolver * s; Int status; Int iter = 0; const UInt n = (UInt)set.size(); // number of parameters to be optimized UInt p = num_params; // gsl always expects N>=p or default gsl error handler invoked, // cause Jacobian be rectangular M x N with M>=N if (n < p) throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, "UnableToFit-FinalSet", "Skipping feature, gsl always expects N>=p"); // allocate space for a covariance matrix of size p by p gsl_matrix * covar = gsl_matrix_alloc(p, p); gsl_multifit_function_fdf f; gsl_vector_view x = gsl_vector_view_array(x_init, p); gsl_rng_env_setup(); // set up the function to be fit f.f = (residual); // the function of residuals f.df = (jacobian); // the gradient of this function f.fdf = (evaluate); // combined function and gradient f.n = set.size(); // number of points in the data set f.p = p; // number of parameters in the fit function f.params = advanced_params; // // structure with the data and error bars T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc(T, n, p); gsl_multifit_fdfsolver_set(s, &f, &x.vector); #ifdef DEBUG_FEATUREFINDER printState_(iter, s); #endif // this is the loop for fitting do { iter++; // perform a single iteration of the fitting routine status = gsl_multifit_fdfsolver_iterate(s); #ifdef DEBUG_FEATUREFINDER // customized routine to print out current parameters printState_(iter, s); #endif /* check if solver is stuck */ if (status) break; // test for convergence with an absolute and relative error status = gsl_multifit_test_delta(s->dx, s->x, abs_error_, rel_error_); } while (status == GSL_CONTINUE && iter < max_iteration_); // This function uses Jacobian matrix J to compute the covariance matrix of the best-fit parameters, covar. // The parameter epsrel (0.0) is used to remove linear-dependent columns when J is rank deficient. gsl_multifit_covar(s->J, 0.0, covar); #ifdef DEBUG_FEATUREFINDER gsl_matrix_fprintf(stdout, covar, "covar %g"); #endif #define FIT(i) gsl_vector_get(s->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar, i, i)) // Set GSl status gsl_status_ = status; #ifdef DEBUG_FEATUREFINDER { // chi-squared value DoubleReal chi = gsl_blas_dnrm2(s->f); DoubleReal dof = n - p; DoubleReal c = GSL_MAX_DBL(1, chi / sqrt(dof)); printf("chisq/dof = %g\n", pow(chi, 2.0) / dof); for (Size i = 0; i < p; ++i) { std::cout << i; printf(".Parameter = %.5f +/- %.5f\n", FIT(i), c * ERR(i)); } } #endif // set optimized parameters for (Size i = 0; i < p; ++i) { x_init[i] = FIT(i); } gsl_multifit_fdfsolver_free(s); gsl_matrix_free(covar); } void updateMembers_() { Fitter1D::updateMembers_(); max_iteration_ = this->param_.getValue("max_iteration"); abs_error_ = this->param_.getValue("deltaAbsError"); rel_error_ = this->param_.getValue("deltaRelError"); } }; } #endif // OPENMS_TRANSFORMATIONS_FEATUREFINDER_LEVMARQFITTER1D_H
{ "alphanum_fraction": 0.6468165628, "avg_line_length": 36.0803212851, "ext": "h", "hexsha": "7950ea4a4a5b0d70ccb33f09735bd1731b9f7a9c", "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/TRANSFORMATIONS/FEATUREFINDER/LevMarqFitter1D.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/TRANSFORMATIONS/FEATUREFINDER/LevMarqFitter1D.h", "max_line_length": 174, "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/TRANSFORMATIONS/FEATUREFINDER/LevMarqFitter1D.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": 2106, "size": 8984 }
/* * siegert_neuron.h * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef SIEGERT_NEURON_H #define SIEGERT_NEURON_H #include "config.h" #ifdef HAVE_GSL // C includes: #include <gsl/gsl_integration.h> // Includes from nestkernel: #include "archiving_node.h" #include "connection.h" #include "event.h" #include "nest_types.h" #include "node.h" #include "normal_randomdev.h" #include "poisson_randomdev.h" #include "ring_buffer.h" #include "recordables_map.h" #include "universal_data_logger.h" namespace nest { /* BeginDocumentation Name: siegert_neuron Description: siegert_neuron is an implementation of a rate model with the non-linearity given by the gain function of the leaky-integrate-and-fire neuron with delta or exponentially decaying synapses [2] and [3, their eq. 25]. The model can be used for a mean-field analysis of spiking networks. The model supports connections to other rate models with zero delay, and uses the secondary_event concept introduced with the gap-junction framework. Parameters: The following parameters can be set in the status dictionary. rate double - Rate (1/s) tau double - Time constant in ms. mean double - Additional constant input The following parameters can be set in the status directory and are used in the evaluation of the gain function. Parameters as in iaf_psc_exp/delta. tau_m double - Membrane time constant in ms. tau_syn double - Time constant of postsynaptic currents in ms. t_ref double - Duration of refractory period in ms. theta double - Threshold relative to resting potential in mV. V_reset double - Reset relative to resting membrane potential in mV. Notes: References: [1] Hahne, J., Dahmen, D., Schuecker, J., Frommer, A., Bolten, M., Helias, M. and Diesmann, M. (2017). Integration of Continuous-Time Dynamics in a Spiking Neural Network Simulator. Front. Neuroinform. 11:34. doi: 10.3389/fninf.2017.00034 [2] Fourcaud, N and Brunel, N. (2002). Dynamics of the firing probability of noisy integrate-and-fire neurons, Neural computation, 14:9, pp 2057--2110 [3] Schuecker, J., Diesmann, M. and Helias, M. (2015). Modulated escape from a metastable state driven by colored noise. Physical Review E 92:052119 [4] Hahne, J., Helias, M., Kunkel, S., Igarashi, J., Bolten, M., Frommer, A. and Diesmann, M. (2015). A unified framework for spiking and gap-junction interactions in distributed neuronal network simulations. Front. Neuroinform. 9:22. doi: 10.3389/fninf.2015.00022 Sends: DiffusionConnectionEvent Receives: DiffusionConnectionEvent, DataLoggingRequest Author: Jannis Schuecker, David Dahmen, Jan Hahne SeeAlso: diffusion_connection */ class siegert_neuron : public Archiving_Node { public: typedef Node base; siegert_neuron(); siegert_neuron( const siegert_neuron& ); /** * Import sets of overloaded virtual functions. * @see Technical Issues / Virtual Functions: Overriding, Overloading, and * Hiding */ using Node::handle; using Node::sends_secondary_event; void handle( DiffusionConnectionEvent& ); void handle( DataLoggingRequest& ); port handles_test_event( DiffusionConnectionEvent&, rport ); port handles_test_event( DataLoggingRequest&, rport ); void sends_secondary_event( DiffusionConnectionEvent& ) { } void get_status( DictionaryDatum& ) const; void set_status( const DictionaryDatum& ); private: void init_state_( const Node& proto ); void init_buffers_(); void calibrate(); /** This is the actual update function. The additional boolean parameter * determines if the function is called by update (false) or wfr_update (true) */ bool update_( Time const&, const long, const long, const bool ); void update( Time const&, const long, const long ); bool wfr_update( Time const&, const long, const long ); // siegert functions and helpers double siegert( double, double ); double siegert1( double, double, double, double ); double siegert2( double, double, double, double ); // The next two classes need to be friends to access the State_ class/member friend class RecordablesMap< siegert_neuron >; friend class UniversalDataLogger< siegert_neuron >; // ---------------------------------------------------------------- /** * Independent parameters of the model. */ struct Parameters_ { /** Time constant in ms. */ double tau_; /** Membrane time constant in ms. */ double tau_m_; /** Synaptic time constant in ms. */ double tau_syn_; /** Refractory period in ms. */ double t_ref_; /** Constant input in Hz. */ double mean_; /** Threshold in mV. */ double theta_; /** reset value in mV. */ double V_reset_; Parameters_(); //!< Sets default parameter values void get( DictionaryDatum& ) const; //!< Store current values in dictionary void set( const DictionaryDatum& ); }; // ---------------------------------------------------------------- /** * State variables of the model. */ struct State_ { double r_; //!< Rate State_(); //!< Default initialization void get( DictionaryDatum& ) const; void set( const DictionaryDatum& ); }; // ---------------------------------------------------------------- /** * Buffers of the model. */ struct Buffers_ { Buffers_( siegert_neuron& ); Buffers_( const Buffers_&, siegert_neuron& ); std::vector< double > drift_input_; //!< buffer for drift term received by DiffusionConnection std::vector< double > diffusion_input_; //!< buffer for diffusion term // received by DiffusionConnection std::vector< double > last_y_values; //!< remembers y_values from last wfr_update UniversalDataLogger< siegert_neuron > logger_; //!< Logger for all analog data }; // ---------------------------------------------------------------- /** * Internal variables of the model. */ struct Variables_ { // propagators double P1_; double P2_; }; //! Read out the rate double get_rate_() const { return S_.r_; } // ---------------------------------------------------------------- Parameters_ P_; State_ S_; Variables_ V_; Buffers_ B_; //! Mapping of recordables names to access functions static RecordablesMap< siegert_neuron > recordablesMap_; }; inline void siegert_neuron::update( Time const& origin, const long from, const long to ) { update_( origin, from, to, false ); } inline bool siegert_neuron::wfr_update( Time const& origin, const long from, const long to ) { State_ old_state = S_; // save state before wfr update const bool wfr_tol_exceeded = update_( origin, from, to, true ); S_ = old_state; // restore old state return not wfr_tol_exceeded; } inline port siegert_neuron::handles_test_event( DiffusionConnectionEvent&, rport receptor_type ) { if ( receptor_type == 0 ) return 0; else if ( receptor_type == 1 ) return 1; else throw UnknownReceptorType( receptor_type, get_name() ); } inline port siegert_neuron::handles_test_event( DataLoggingRequest& dlr, rport receptor_type ) { if ( receptor_type != 0 ) throw UnknownReceptorType( receptor_type, get_name() ); return B_.logger_.connect_logging_device( dlr, recordablesMap_ ); } inline void siegert_neuron::get_status( DictionaryDatum& d ) const { P_.get( d ); S_.get( d ); Archiving_Node::get_status( d ); ( *d )[ names::recordables ] = recordablesMap_.get_list(); } inline void siegert_neuron::set_status( const DictionaryDatum& d ) { Parameters_ ptmp = P_; // temporary copy in case of errors ptmp.set( d ); // throws if BadProperty State_ stmp = S_; // temporary copy in case of errors stmp.set( d ); // throws if BadProperty // We now know that (ptmp, stmp) are consistent. We do not // write them back to (P_, S_) before we are also sure that // the properties to be set in the parent class are internally // consistent. Archiving_Node::set_status( d ); // if we get here, temporaries contain consistent set of properties P_ = ptmp; S_ = stmp; } } // namespace #endif // HAVE_GSL #endif // SIEGERT_NEURON_H
{ "alphanum_fraction": 0.6711841813, "avg_line_length": 26.7916666667, "ext": "h", "hexsha": "63abd1f5d4561c837d70a35c506183c036528c03", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_path": "NEST-14.0-FPGA/models/siegert_neuron.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_path": "NEST-14.0-FPGA/models/siegert_neuron.h", "max_line_length": 80, "max_stars_count": 45, "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_path": "NEST-14.0-FPGA/models/siegert_neuron.h", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "num_tokens": 2251, "size": 9002 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <petsc.h> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #include <petscsnes.h> #include <petscversion.h> #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) ) #if (PETSC_VERSION_MINOR >=6) #include "petsc/private/vecimpl.h" #include "petsc/private/matimpl.h" #include "petsc/private/pcimpl.h" #include "petsc/private/kspimpl.h" #include "petsc/private/snesimpl.h" #else #include "petsc-private/vecimpl.h" #include "petsc-private/matimpl.h" #include "petsc-private/pcimpl.h" #include "petsc-private/kspimpl.h" #include "petsc-private/snesimpl.h" #endif #else #include "private/vecimpl.h" #include "private/matimpl.h" #include "private/pcimpl.h" #include "private/kspimpl.h" #include "private/snesimpl.h" #endif #include "common-driver-utils.h" #define BSSCR_report_op(op,v,i,func_name) \ if((op)) { PetscViewerASCIIPrintf((v), "[%.2d] %s: valid operation \n", i, func_name ); } \ else { PetscViewerASCIIPrintf((v), "[%.2d] %s: OPERATION NOT DEFINED \n", i, func_name ); } \ PetscErrorCode BSSCR_MatListOperations( Mat A, PetscViewer v ) { MatOps ops = A->ops; MatType type; PetscInt i; MatGetType( A, &type ); PetscViewerASCIIPrintf(v, "Operations available for MatType: %s \n", type ); PetscViewerASCIIPushTab( v ); i=0; PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->setvalues, v, i++, "MatSetValues" ); BSSCR_report_op( ops->getrow, v, i++, "MatSetValues" ); BSSCR_report_op( ops->restorerow, v, i++, "MatRestoreRow" ); BSSCR_report_op( ops->mult, v, i++, "MatMult" ); BSSCR_report_op( ops->multadd, v, i++, "MatMultAdd" ); BSSCR_report_op( ops->multtranspose, v, i++, "MatMultTranspose" ); BSSCR_report_op( ops->multtransposeadd, v, i++, "MatMultTransposeAdd" ); BSSCR_report_op( ops->solve, v, i++, "MatSolve" ); BSSCR_report_op( ops->solveadd, v, i++, "MatSolveAdd" ); BSSCR_report_op( ops->solvetranspose, v, i++, "MatSolveTranspose" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->solvetransposeadd, v, i++, "MatSolveTransposeAdd" ); BSSCR_report_op( ops->lufactor, v, i++, "MatLUFactor" ); BSSCR_report_op( ops->choleskyfactor, v, i++, "MatCholeskyFactor" ); #if( ( PETSC_VERSION_MAJOR >= 3 ) && ( PETSC_VERSION_MINOR > 0 ) ) BSSCR_report_op( ops->sor, v, i++, "MatSor" ); #else BSSCR_report_op( ops->relax, v, i++, "MatRelax" ); #endif BSSCR_report_op( ops->transpose, v, i++, "MatTranspose" ); BSSCR_report_op( ops->getinfo, v, i++, "MatGetInfo" ); BSSCR_report_op( ops->equal, v, i++, "MatEqual" ); BSSCR_report_op( ops->getdiagonal, v, i++, "MatGetDiagonal" ); BSSCR_report_op( ops->diagonalscale, v, i++, "MatDiagonalScale" ); BSSCR_report_op( ops->norm, v, i++, "MatNorm" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->assemblybegin, v, i++, "MatAssemblyBegin" ); BSSCR_report_op( ops->assemblyend, v, i++, "MatAssemblyEnd" ); #if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 1 ) ) || ( PETSC_VERSION_MAJOR <= 2 ) ) BSSCR_report_op( ops->compress, v, i++, "MatCompress" ); #endif BSSCR_report_op( ops->setoption, v, i++, "MatSetOption" ); BSSCR_report_op( ops->zeroentries, v, i++, "MatZeroEntries" ); BSSCR_report_op( ops->zerorows, v, i++, "Stg_MatZeroRows" ); BSSCR_report_op( ops->lufactorsymbolic, v, i++, "MatLUFactorSymbolic" ); BSSCR_report_op( ops->lufactornumeric, v, i++, "MatLUFactorNumeric" ); BSSCR_report_op( ops->choleskyfactorsymbolic, v, i++, "MatCholeskyFactorSymbolic" ); BSSCR_report_op( ops->choleskyfactornumeric, v, i++, "MatCholeskyFactorNumeric" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->ilufactorsymbolic, v, i++, "MatILUFactorSymbolic" ); BSSCR_report_op( ops->iccfactorsymbolic, v, i++, "MatICCFactorSymbolic" ); BSSCR_report_op( ops->duplicate, v, i++, "MatDuplicate" ); BSSCR_report_op( ops->forwardsolve, v, i++, "MatForwardSolve" ); BSSCR_report_op( ops->backwardsolve, v, i++, "MatBackwardSolve" ); BSSCR_report_op( ops->ilufactor, v, i++, "MatILUFactor" ); BSSCR_report_op( ops->iccfactor, v, i++, "MatICCFactor" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->axpy, v, i++, "MatAXPY" ); #if( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR > 7) ) BSSCR_report_op( ops->createsubmatrices, v, i++, "MatCreateSubMatrices" ); #else BSSCR_report_op( ops->getsubmatrices, v, i++, "MatGetSubMatrices" ); #endif BSSCR_report_op( ops->increaseoverlap, v, i++, "MatIncreaseOverlap" ); BSSCR_report_op( ops->getvalues, v, i++, "MatGetValues" ); BSSCR_report_op( ops->copy, v, i++, "MatCopy" ); BSSCR_report_op( ops->getrowmax, v, i++, "MatGetRowMax" ); BSSCR_report_op( ops->scale, v, i++, "MatScale" ); BSSCR_report_op( ops->shift, v, i++, "MatShift" ); BSSCR_report_op( ops->diagonalset, v, i++, "MatDiagonalSet" ); #if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 1 ) ) || ( PETSC_VERSION_MAJOR <= 2 ) ) BSSCR_report_op( ops->iludtfactor, v, i++, "MatILUDTFactor" ); #endif PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->getrowij, v, i++, "MatGetRowIJ" ); BSSCR_report_op( ops->restorerowij, v, i++, "MatRestoreRowIJ" ); BSSCR_report_op( ops->getcolumnij, v, i++, "MatGetColumnIJ" ); BSSCR_report_op( ops->restorecolumnij, v, i++, "MatRestoreColumnIJ" ); BSSCR_report_op( ops->fdcoloringcreate, v, i++, "MatFDColoringCreate" ); BSSCR_report_op( ops->coloringpatch, v, i++, "MatColoringPatch" ); BSSCR_report_op( ops->setunfactored, v, i++, "MatSetUnFactored" ); BSSCR_report_op( ops->permute, v, i++, "MatPermute" ); BSSCR_report_op( ops->setvaluesblocked, v, i++, "MatSetValuesBlocked" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); #if( (PETSC_VERSION_MAJOR == 3) && (PETSC_VERSION_MINOR > 7) ) BSSCR_report_op( ops->createsubmatrix, v, i++, "MatCreateSubMatrix" ); #else BSSCR_report_op( ops->getsubmatrix, v, i++, "MatGetSubMatrix" ); #endif BSSCR_report_op( ops->destroy, v, i++, "MatDestroy" ); BSSCR_report_op( ops->view, v, i++, "MatView" ); BSSCR_report_op( ops->convertfrom, v, i++, "MatConvertFrom" ); BSSCR_report_op( ops->setlocaltoglobalmapping, v, i++, "MatSetLocalToGlobalMapping" ); BSSCR_report_op( ops->setvalueslocal, v, i++, "MatSetValuesLocal" ); BSSCR_report_op( ops->zerorowslocal, v, i++, "Stg_MatZeroRowsLocal" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->getrowmaxabs, v, i++, "MatGetRowMaxAbs" ); BSSCR_report_op( ops->convert, v, i++, "MatConvert" ); // BSSCR_report_op( ops->setcoloring, v, i++, "MatSetColoring" ); NOT SURE IF THIS IS AVAIL IN 3.8 BSSCR_report_op( ops->setvaluesadifor, v, i++, "MatSetValuesAdicfor" ); BSSCR_report_op( ops->fdcoloringapply, v, i++, "MatFDCloringApply" ); BSSCR_report_op( ops->setfromoptions, v, i++, "MatSetFromOptions" ); BSSCR_report_op( ops->multconstrained, v, i++, "MatMultConstrained" ); BSSCR_report_op( ops->multtransposeconstrained, v, i++, "MatMultTransposeConstrained" ); /* data member depreciated from PETSc v. 3.0.0 */ #if( PETSC_VERSION_MAJOR <= 2 ) BSSCR_report_op( ops->ilufactorsymbolicconstrained, v, i++, "MatILUFactorSymbolicConstrained" ); #endif PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); #if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 2 ) ) ) BSSCR_report_op( ops->permutesparsify, v, i++, "MatPermuteSparsify" ); #endif BSSCR_report_op( ops->mults, v, i++, "MatMults" ); BSSCR_report_op( ops->solves, v, i++, "MatSolves" ); BSSCR_report_op( ops->getinertia, v, i++, "MatGetInertia" ); BSSCR_report_op( ops->load, v, i++, "MatLoad" ); BSSCR_report_op( ops->issymmetric, v, i++, "MatIsSymmetric" ); BSSCR_report_op( ops->ishermitian, v, i++, "MatIsHermitian" ); BSSCR_report_op( ops->isstructurallysymmetric, v, i++, "MatIsStructurallySymmetric" ); #if( ( ( PETSC_VERSION_MAJOR == 3 ) && ( PETSC_VERSION_MINOR < 1 ) ) || ( PETSC_VERSION_MAJOR <= 2 ) ) BSSCR_report_op( ops->pbrelax, v, i++, "MatPBRelax" ); #endif BSSCR_report_op( ops->getvecs, v, i++, "MatGetVec" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->matmult, v, i++, "MatMatMult" ); BSSCR_report_op( ops->matmultsymbolic, v, i++, "MatMatMultSymbolic" ); BSSCR_report_op( ops->matmultnumeric, v, i++, "MatMatMultNumeric" ); BSSCR_report_op( ops->ptap, v, i++, "MatPtAP" ); BSSCR_report_op( ops->ptapsymbolic, v, i++, "MatPtAPSymbolic" ); BSSCR_report_op( ops->ptapnumeric, v, i++, "MatPtAPNumeric" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->conjugate, v, i++, "MatConjugate" ); //BSSCR_report_op( ops->setsizes, v, i++, "MatSetSizes" ); BSSCR_report_op( ops->setvaluesrow, v, i++, "MatSetValuesRow" ); BSSCR_report_op( ops->realpart, v, i++, "MatRealPart" ); BSSCR_report_op( ops->imaginarypart, v, i++, "MatImaginaryPart" ); BSSCR_report_op( ops->getrowuppertriangular, v, i++, "MatGetRowUpperTriangular" ); BSSCR_report_op( ops->restorerowuppertriangular, v, i++, "MatRestoreRowUpperTriangular" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->matsolve, v, i++, "MatMatSolve" ); #if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) ) BSSCR_report_op( ops->getredundantmatrix, v, i++, "MatGetRedundantMatrix" ); #endif BSSCR_report_op( ops->getrowmin, v, i++, "MatGetRowMin" ); BSSCR_report_op( ops->getcolumnvector, v, i++, "MatGetColumnVector" ); PetscViewerASCIIPopTab( v ); PetscFunctionReturn(0); } PetscErrorCode BSSCR_VecListOperations( Vec x, PetscViewer v ) { VecOps ops = x->ops; VecType type; PetscInt i; VecGetType( x, &type ); PetscViewerASCIIPrintf(v, "Operations available for VecType: %s \n", type ); PetscViewerASCIIPushTab( v ); PetscViewerASCIIPopTab( v ); PetscFunctionReturn(0); } PetscErrorCode BSSCR_KSPListOperations( KSP ksp, PetscViewer v ) { KSPOps ops = ksp->ops; KSPType type; PetscInt i; KSPGetType( ksp, &type ); PetscViewerASCIIPrintf(v, "Operations available for KSPType: %s \n", type ); PetscViewerASCIIPushTab( v ); i=0; PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->buildsolution, v, i++, "KSPBuildSolution" ); BSSCR_report_op( ops->buildresidual, v, i++, "KSPBuildResidual" ); BSSCR_report_op( ops->solve, v, i++, "KSPSolve" ); BSSCR_report_op( ops->setup, v, i++, "KSPSetUp" ); BSSCR_report_op( ops->setfromoptions, v, i++, "KSPSetFromOptions" ); BSSCR_report_op( ops->publishoptions, v, i++, "KSPPublishOptions" ); BSSCR_report_op( ops->computeextremesingularvalues, v, i++, "KSPComputeExtremeSingularValues" ); BSSCR_report_op( ops->computeeigenvalues, v, i++, "KSPComputeEigenvalues" ); BSSCR_report_op( ops->destroy, v, i++, "BSSCR_KSPDestroy" ); BSSCR_report_op( ops->view, v, i++, "KSPView" ); PetscViewerASCIIPopTab( v ); PetscFunctionReturn(0); } PetscErrorCode BSSCR_PCListOperations( PC pc, PetscViewer v ) { PCOps ops = pc->ops; PCType type; PetscInt i; PCGetType( pc, &type ); PetscViewerASCIIPrintf(v, "Operations available for PCType: %s \n", type ); PetscViewerASCIIPushTab( v ); i=0; PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->setup, v, i++, "PCSetUp" ); BSSCR_report_op( ops->apply, v, i++, "PCApply" ); BSSCR_report_op( ops->applyrichardson, v, i++, "PCApplyRichardson" ); BSSCR_report_op( ops->applyBA, v, i++, "PCApplyBA" ); BSSCR_report_op( ops->applytranspose, v, i++, "PCApplyTranspose" ); BSSCR_report_op( ops->applyBAtranspose, v, i++, "PCApplyBATranspose" ); BSSCR_report_op( ops->setfromoptions, v, i++, "PCSetFromOptions" ); BSSCR_report_op( ops->presolve, v, i++, "PCPreSolve" ); BSSCR_report_op( ops->postsolve, v, i++, "PCPostSolve" ); BSSCR_report_op( ops->getfactoredmatrix, v, i++, "PCGetFactoredMatrix" ); PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->applysymmetricleft, v, i++, "PCApplySymmetricLeft" ); BSSCR_report_op( ops->applysymmetricright, v, i++, "PCApplySymmetricRight" ); BSSCR_report_op( ops->setuponblocks, v, i++, "PCSetupOnBlocks" ); BSSCR_report_op( ops->destroy, v, i++, "PCDestroy" ); BSSCR_report_op( ops->view, v, i++, "PCView" ); PetscViewerASCIIPopTab( v ); PetscFunctionReturn(0); } PetscErrorCode BSSCR_SNESListOperations( SNES snes, PetscViewer v ) { SNESOps ops = snes->ops; SNESType type; PetscInt i; SNESGetType( snes, &type ); PetscViewerASCIIPrintf(v, "Operations available for SNESType: %s \n", type ); PetscViewerASCIIPushTab( v ); i=0; PetscViewerASCIIPrintf(v, "------------------------------------------------\n"); BSSCR_report_op( ops->computescaling, v, i++, "SNESComputeScaling" ); BSSCR_report_op( ops->update, v, i++, "SNESUpdate" ); BSSCR_report_op( ops->converged, v, i++, "SNESConverged" ); BSSCR_report_op( ops->setup, v, i++, "SNESSetUp" ); BSSCR_report_op( ops->solve, v, i++, "SNESSolve" ); BSSCR_report_op( ops->view, v, i++, "SNESView" ); BSSCR_report_op( ops->setfromoptions, v, i++, "SNESSetFromOptions" ); BSSCR_report_op( ops->destroy, v, i++, "SNESDestroy" ); PetscViewerASCIIPopTab( v ); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6038296467, "avg_line_length": 42.0694444444, "ext": "c", "hexsha": "2632ac1401ba59fa5a4879cccf87f05a4556875d", "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": "6da9f52268d366ae08533374afebb6f278c04576", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "jmansour/underworld2", "max_forks_repo_path": "libUnderworld/Solvers/KSPSolvers/src/BSSCR/list_operations.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6da9f52268d366ae08533374afebb6f278c04576", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "jmansour/underworld2", "max_issues_repo_path": "libUnderworld/Solvers/KSPSolvers/src/BSSCR/list_operations.c", "max_line_length": 106, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6da9f52268d366ae08533374afebb6f278c04576", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "jmansour/underworld2", "max_stars_repo_path": "libUnderworld/Solvers/KSPSolvers/src/BSSCR/list_operations.c", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:00:12.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-28T20:00:12.000Z", "num_tokens": 4908, "size": 15145 }
#include <stdio.h> #include <stdlib.h> #include <float.h> #include <math.h> #include <gsl/gsl_interp.h> #include "field.h" #define StartTest -4E-7 #define StopTest 4E-7 signal_type * formatExpImpResp(int numPnts, double *timeValues, double *voltageValues, int samplingFrequencyHz, int verbose) { double *newTimeValues; double *newVoltageValues; double timeAtMaxIntensity; double minTime = DBL_MIN; double maxTime = -DBL_MIN; double maxVoltage = -DBL_MIN; double stepSize; int i, j, maxVoltageIndex, numSteps; int startIndex, stopIndex; signal_type *impulseResponse; int pntsSampled; /* find the max voltage */ for (i = 0; i < numPnts; i++) { if (maxVoltage < voltageValues[i]) { maxVoltage = voltageValues[i]; maxVoltageIndex = i; } } if (verbose >= 1) fprintf(stderr, "index %d max voltage %e\n", maxVoltageIndex, maxVoltage); /* normalize the voltages */ for (i = 0; i < numPnts; i++) voltageValues[i] /= maxVoltage; /* * center the time axis around the max intensity. the matlab code recalculated * the index of the maximum value, but the normalization shouldn't change * that, so I skipped it. note that I have to save the time associated with * the max intensity, because in the time array, it goes to 0 as I do the * centering. */ timeAtMaxIntensity = timeValues[maxVoltageIndex]; for (i = 0; i < numPnts; i++) timeValues[i] = timeValues[i] - timeAtMaxIntensity; /* now find the min and max times */ for (i = 0; i < numPnts; i++) { if (minTime > timeValues[i]) minTime = timeValues[i]; if (maxTime < timeValues[i]) maxTime = timeValues[i]; } if (verbose >= 1) fprintf(stderr, "min time %e max time %e\n", minTime, maxTime); /* re-sample the data to match the Field II sampling frequency */ if (verbose >= 1) fprintf(stderr, "sampling %d\n", samplingFrequencyHz); stepSize = 1.0 / samplingFrequencyHz; if (verbose >= 1) fprintf(stderr, "diff %e\n", maxTime - minTime); numSteps = (int )ceil(((maxTime - minTime) * samplingFrequencyHz)); if (verbose >= 1) fprintf(stderr, "step size %e numSteps %d\n", stepSize, numSteps); if ((newTimeValues = (double *)malloc(sizeof(double) * numSteps)) == NULL) { fprintf(stderr, "in readExpData, couldn't allocate space for new times\n"); return(0); } for (i = 0; i < numSteps; i++) { newTimeValues[i] = minTime + i * stepSize; } /* * now we find the voltage values at each of the new times by interpolating * from the old times and voltages. */ /* initialize and allocate the gsl objects */ gsl_interp *interpolation = gsl_interp_alloc (gsl_interp_linear, numPnts); gsl_interp_init(interpolation, timeValues, voltageValues, numPnts); gsl_interp_accel * accelerator = gsl_interp_accel_alloc(); /* get interpolation the new times */ if ((newVoltageValues = (double *)malloc(sizeof(double) * numSteps)) == NULL) { fprintf(stderr, "in readExpData, couldn't allocate space for new voltage\n"); return(0); } for (i = 0; i < numSteps; i++) { newVoltageValues[i] = gsl_interp_eval(interpolation, timeValues, voltageValues, newTimeValues[i], accelerator); if (verbose >= 3) fprintf(stderr, "\n%e", newVoltageValues[i]); } /* find the indices of NewTime to use for the Field II impulse response */ for (i = 0; i < numSteps; i++) { if (newTimeValues[i] > StartTest) { startIndex = i; break; } } for (i = 0; i < numSteps; i++) if (newTimeValues[i] > StopTest) { stopIndex = i; break; } pntsSampled = stopIndex - startIndex; if (verbose >= 1) fprintf(stderr, "\nstartIndex %d, stopIndex %d pntsSampled %d\n", startIndex, stopIndex, pntsSampled); impulseResponse = alloc_signal(pntsSampled, 0); for (i = startIndex, j = 0; i < stopIndex; i++, j++) { impulseResponse->data[j] = newVoltageValues[i]; if (verbose >= 3) fprintf(stderr, "%e\n", newVoltageValues[i]); } return(impulseResponse); }
{ "alphanum_fraction": 0.6855670103, "avg_line_length": 26.7586206897, "ext": "c", "hexsha": "d2fc470ee82e82564aa6327660eed830b5d7958e", "lang": "C", "max_forks_count": 28, "max_forks_repo_forks_event_max_datetime": "2021-08-12T23:43:39.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-19T00:30:52.000Z", "max_forks_repo_head_hexsha": "77fcfb49ea64f81628a5dbcf3951091f0a1d1e8d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "suyashkumar/fem", "max_forks_repo_path": "fieldC/formatExpImpResp.c", "max_issues_count": 91, "max_issues_repo_head_hexsha": "77fcfb49ea64f81628a5dbcf3951091f0a1d1e8d", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:01:05.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-19T18:33:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "suyashkumar/fem", "max_issues_repo_path": "fieldC/formatExpImpResp.c", "max_line_length": 85, "max_stars_count": 29, "max_stars_repo_head_hexsha": "77fcfb49ea64f81628a5dbcf3951091f0a1d1e8d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "suyashkumar/fem", "max_stars_repo_path": "fieldC/formatExpImpResp.c", "max_stars_repo_stars_event_max_datetime": "2022-01-05T22:54:08.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-26T06:04:33.000Z", "num_tokens": 1117, "size": 3880 }
// File: nlopt_wrapper.c // Author: Jannis Harder // Description: Wrapper for nlopt using context switching #include <stdlib.h> #include <ucontext.h> #include <string.h> #include <stdio.h> // For debugging TODO: remove #include <nlopt.h> #define STACKSIZE (8 * 1024 * 1024) enum status { ST_IDLE = 0, ST_RUNNING, ST_VALUE, ST_GRAD, ST_DONE }; struct function { struct wrapper * w; struct function * next; int id; }; struct wrapper { struct function f; nlopt_opt opt; int n; ucontext_t julia_ctx; ucontext_t nlopt_ctx; char *nlopt_stack; double final_f; double *opt_x; double *eval_x; double *eval_grad; double eval_f; int force_stop; int result; int function_id; enum status status; }; double nlopt_wrapper_f(unsigned n, const double *x, double *grad, void *f_data); void nlopt_wrapper_optimize_thread(struct wrapper* w); void nlopt_wrapper_version(int *version) { nlopt_version(&version[0], &version[1], &version[2]); version[3] = 2; version[4] = 2; version[5] = 4; version[6] = 0; } struct wrapper *nlopt_wrapper_create(int type_id, int dimensions) { nlopt_opt opt = nlopt_create(type_id, dimensions); if (!opt) return NULL; struct wrapper *w = calloc(1, sizeof(struct wrapper)); w->n = dimensions; w->opt = opt; w->f.w = w; w->f.id = 1; return w; } void nlopt_wrapper_free(struct wrapper *w) { nlopt_destroy(w->opt); free(w->opt_x); struct function *f = &w->f; while (f) { struct function *next = f->next; free(f); f = next; } } int nlopt_wrapper_objective(struct wrapper *w, int max) { if (max) return nlopt_set_max_objective(w->opt, &nlopt_wrapper_f, &w->f); else return nlopt_set_min_objective(w->opt, &nlopt_wrapper_f, &w->f); } double nlopt_wrapper_f(unsigned n, const double *x, double *grad, void *f_data) { struct function *f = f_data; struct wrapper *w = f->w; w->function_id = f->id; w->status = grad ? ST_GRAD : ST_VALUE; memcpy(w->eval_x, x, n * sizeof(double)); swapcontext(&w->nlopt_ctx, &w->julia_ctx); if (w->force_stop) nlopt_force_stop(w->opt); if (grad) memcpy(grad, w->eval_grad, n * sizeof(double)); return w->eval_f; } void nlopt_wrapper_optimize_start(struct wrapper *w, double *x) { int i; getcontext(&w->nlopt_ctx); w->nlopt_stack = calloc(1, STACKSIZE); w->nlopt_ctx.uc_stack.ss_sp = w->nlopt_stack; w->nlopt_ctx.uc_stack.ss_size = STACKSIZE; w->nlopt_ctx.uc_link = &w->julia_ctx; makecontext(&w->nlopt_ctx, (void(*)())&nlopt_wrapper_optimize_thread, 1, w); w->opt_x = calloc(w->n, sizeof(double)); memcpy(w->opt_x, x, w->n * sizeof(double)); } int nlopt_wrapper_optimize_callback(struct wrapper *w, double *x, double *grad, double f, int force_stop, int *function_id) { w->eval_f = f; w->eval_x = x; w->eval_grad = grad; w->force_stop = force_stop; swapcontext(&w->julia_ctx, &w->nlopt_ctx); *function_id = w->function_id; return w->status; } int nlopt_wrapper_optimize_finalize(struct wrapper *w, double *x, double *f) { memcpy(x, w->opt_x, w->n * sizeof(double)); free(w->opt_x); w->opt_x = NULL; *f = w->final_f; free(w->nlopt_stack); w->nlopt_stack = NULL; return w->result; } void nlopt_wrapper_optimize_thread(struct wrapper *w) { w->result = nlopt_optimize(w->opt, w->opt_x, &w->final_f); w->status = ST_DONE; } void nlopt_wrapper_dimopt(struct wrapper *w, double *x, int i) { switch (i) { case 0: nlopt_set_lower_bounds(w->opt, x); break; case 1: nlopt_set_upper_bounds(w->opt, x); break; case 2: nlopt_set_xtol_abs(w->opt, x); break; } } void nlopt_wrapper_doubleopt(struct wrapper *w, double v, int i) { switch (i) { case 0: nlopt_set_stopval(w->opt, v); break; case 1: nlopt_set_ftol_rel(w->opt, v); break; case 2: nlopt_set_ftol_abs(w->opt, v); break; case 3: nlopt_set_xtol_rel(w->opt, v); break; case 4: nlopt_set_maxtime(w->opt, v); break; } } void nlopt_wrapper_intopt(struct wrapper *w, long int v, int i) { switch (i) { case 0: nlopt_set_maxeval(w->opt, v); break; case 1: nlopt_set_population(w->opt, v < 0 ? 0 : v); break; case 2: nlopt_srand(v); break; } } void nlopt_wrapper_add_constraint(struct wrapper *w, int id, double tolerance, int equality) { struct function *f = calloc(1, sizeof(struct function)); f->w = w; f->next = w->f.next; f->id = id; w->f.next = f; if (equality) nlopt_add_equality_constraint(w->opt, &nlopt_wrapper_f, f, tolerance); else nlopt_add_inequality_constraint(w->opt, &nlopt_wrapper_f, f, tolerance); } void nlopt_wrapper_local_optimizer(struct wrapper *w, struct wrapper *local_w) { nlopt_set_local_optimizer(w->opt, local_w->opt); }
{ "alphanum_fraction": 0.6967572305, "avg_line_length": 22.9346733668, "ext": "c", "hexsha": "cf3845311235dd9f655ea7f40145ff573905584f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:11:07.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-01T18:11:07.000Z", "max_forks_repo_head_hexsha": "7308e113fd2e8940b2691301a7957a6b525c032a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MetalNinjas/julia-nlopt", "max_forks_repo_path": "src/nlopt/nlopt_wrapper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7308e113fd2e8940b2691301a7957a6b525c032a", "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": "MetalNinjas/julia-nlopt", "max_issues_repo_path": "src/nlopt/nlopt_wrapper.c", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "7308e113fd2e8940b2691301a7957a6b525c032a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MetalNinjas/julia-nlopt", "max_stars_repo_path": "src/nlopt/nlopt_wrapper.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1460, "size": 4564 }
#define _MAIN #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpHalos.h> #include <sys/stat.h> #include <gsl/gsl_errno.h> #define GADGET_BUFFER_SIZE_LOCAL 128 * SID_SIZE_OF_MEGABYTE #define _FILE_OFFSET_BITS 64 typedef struct params_info_local params_info_local; struct params_info_local { GBPREAL *x_array; GBPREAL *y_array; GBPREAL *z_array; GBPREAL *vx_array; GBPREAL *vy_array; GBPREAL *vz_array; size_t * ids_array; size_t * halo_sort_index; size_t first_particle_offset; }; double p_i_local(void *params, int i_coord, int j_particle); double p_i_local(void *params, int i_coord, int j_particle) { double r_val; size_t k_particle = ((params_info_local *)params)->halo_sort_index[((params_info_local *)params)->first_particle_offset + j_particle]; switch(i_coord) { case 0: r_val = ((params_info_local *)params)->x_array[k_particle]; break; case 1: r_val = ((params_info_local *)params)->y_array[k_particle]; break; case 2: r_val = ((params_info_local *)params)->z_array[k_particle]; break; } return (r_val); } double v_i_local(void *params, int i_coord, int j_particle); double v_i_local(void *params, int i_coord, int j_particle) { double r_val; size_t k_particle = ((params_info_local *)params)->halo_sort_index[((params_info_local *)params)->first_particle_offset + j_particle]; switch(i_coord) { case 0: r_val = ((params_info_local *)params)->vx_array[k_particle]; break; case 1: r_val = ((params_info_local *)params)->vy_array[k_particle]; break; case 2: r_val = ((params_info_local *)params)->vz_array[k_particle]; break; } return (r_val); } size_t id_i_local(void *params, int j_particle); size_t id_i_local(void *params, int j_particle) { size_t k_particle = ((params_info_local *)params)->halo_sort_index[((params_info_local *)params)->first_particle_offset + j_particle]; return (((params_info_local *)params)->ids_array[k_particle]); } void read_gadget_binary_local(char *filename_root_in, int snapshot_number, plist_info *plist); void read_gadget_binary_local(char *filename_root_in, int snapshot_number, plist_info *plist) { char ** pname; char * name_initpositions; char filename[SID_MAX_FILENAME_LENGTH]; char * read_catalog; size_t i, j, k, l, jj; size_t i_list_offset[N_GADGET_TYPE]; size_t n_particles_file; size_t n_particles_kept; size_t n_of_type_rank[N_GADGET_TYPE]; size_t n_of_type[N_GADGET_TYPE]; int n_type_used; int n_particles_all_in_groups; int n_particles_in_groups; size_t n_particles_rank; size_t n_particles_all; size_t i_p, i_p_temp; size_t id_min, id_max; double mass_array[N_GADGET_TYPE]; int unused[GADGET_HEADER_SIZE]; size_t n_all[N_GADGET_TYPE]; int n_all_tmp[N_GADGET_TYPE]; int flag_metals; int flag_ages; int flag_entropyICs; double expansion_factor; double h_Hubble; double box_size; double d_value; double d1_value; double d2_value; double d3_value; float f_value; int i_value; int i1_value; int i2_value; int i3_value; int n_warning; GBPREAL * x_array[N_GADGET_TYPE]; GBPREAL * y_array[N_GADGET_TYPE]; GBPREAL * z_array[N_GADGET_TYPE]; GBPREAL * vx_array[N_GADGET_TYPE]; GBPREAL * vy_array[N_GADGET_TYPE]; GBPREAL * vz_array[N_GADGET_TYPE]; size_t * id_array[N_GADGET_TYPE]; size_t * id_list; size_t * id_list_offset; size_t * id_list_in; size_t * id_list_index; size_t n_id_list; unsigned int record_length_open; unsigned int record_length_close; int n_return; size_t s_load; char * keep; int n_keep[N_GADGET_TYPE]; int flag_keep_IDs = GBP_TRUE; int flag_multifile = GBP_FALSE; int flag_multimass = GBP_FALSE; int flag_file_type = 0; int flag_filefound = GBP_FALSE; int flag_gas = GBP_FALSE; int flag_initpositions = GBP_FALSE; int flag_no_velocities = GBP_FALSE; int flag_LONGIDS = GBP_FALSE; int flag_read_marked = GBP_FALSE; int flag_read_catalog = GBP_FALSE; int flag_all_read_all = GBP_FALSE; int i_file; int i_rank; int n_files; int n_files_in; double x_scale; double y_scale; double z_scale; double x_offset; double y_offset; double z_offset; double x_period; double y_period; double z_period; int flag_xscale; int flag_yscale; int flag_zscale; int flag_xoffset; int flag_yoffset; int flag_zoffset; int flag_xperiod; int flag_yperiod; int flag_zperiod; FILE * fp; void * buffer; size_t * buffer_index = NULL; void * buffer_i; size_t id_search; size_t id_value; size_t n_buffer; int n_non_zero; int seed = 1073743; int read_mode; int mark_mode; double x_min_read; double x_max_read; double y_min_read; double y_max_read; double z_min_read; double z_max_read; double x_min_bcast; double x_max_bcast; double y_min_bcast; double y_max_bcast; double z_min_bcast; double z_max_bcast; gadget_header_info header; // Determine file format n_files = 1; for(i_file = 0; i_file < 3 && !flag_filefound; i_file++) { if(i_file == 0) sprintf(filename, "%s/snapshot_%03d/snapshot_%03d", filename_root_in, snapshot_number, snapshot_number); else if(i_file == 1) sprintf(filename, "%s/snapshot_%03d", filename_root_in, snapshot_number); else if(i_file == 2) sprintf(filename, "%s_%03d", filename_root_in, snapshot_number); fp = fopen(filename, "r"); if(fp != NULL) { flag_filefound = GBP_TRUE; flag_multifile = GBP_FALSE; flag_file_type = i_file; } // ... if that doesn't work, check for multi-file else { strcat(filename, ".0"); fp = fopen(filename, "r"); if(fp != NULL) { flag_filefound = GBP_TRUE; flag_multifile = GBP_TRUE; flag_file_type = i_file; } } } // A file was found ... SID_log("Reading GADGET binary file {%s}...", SID_LOG_OPEN | SID_LOG_TIMER, filename_root_in); if(flag_filefound) { pname = plist->species; // Header record length SID_log("Reading header...", SID_LOG_OPEN); SID_fread_verify(&record_length_open, 4, 1, fp); if(record_length_open != GADGET_HEADER_SIZE) SID_log_warning("Problem with GADGET record size (opening size of header is wrong)", SID_ERROR_LOGIC); // Read header SID_fread_verify(&header, sizeof(gadget_header_info), 1, fp); // Number of particles for each species in this file for(i = 0; i < N_GADGET_TYPE; i++) n_of_type[i] = (size_t)header.n_file[i]; // Expansion factor (or time) expansion_factor = header.time; ADaPS_store(&(plist->data), (void *)(&expansion_factor), "expansion_factor", ADaPS_SCALAR_DOUBLE); ADaPS_store(&(plist->data), (void *)(&(header.time)), "time", ADaPS_SCALAR_DOUBLE); // Redshift d_value = (double)header.redshift; ADaPS_store(&(plist->data), (void *)(&d_value), "redshift", ADaPS_SCALAR_DOUBLE); // Number of particles for each species in all files for(i = 0; i < N_GADGET_TYPE; i++) n_all[i] = (size_t)header.n_all_lo_word[i]; // Number of files in this snapshot ADaPS_store(&(plist->data), (void *)(&(header.n_files)), "n_files", ADaPS_SCALAR_INT); if(flag_multifile) n_files = header.n_files; // Cosmology // Omega_o d_value = (double)header.Omega_M; ADaPS_store(&(plist->data), (void *)(&d_value), "Omega_M", ADaPS_SCALAR_DOUBLE); // Omega_Lambda d_value = (double)header.Omega_Lambda; ADaPS_store(&(plist->data), (void *)(&d_value), "Omega_Lambda", ADaPS_SCALAR_DOUBLE); // Hubble parameter h_Hubble = (double)header.h_Hubble; if(h_Hubble < 1e-10) h_Hubble = 1.; box_size = header.box_size * plist->length_unit / h_Hubble; ADaPS_store(&(plist->data), (void *)(&box_size), "box_size", ADaPS_SCALAR_DOUBLE); ADaPS_store(&(plist->data), (void *)(&h_Hubble), "h_Hubble", ADaPS_SCALAR_DOUBLE); for(i = 0; i < N_GADGET_TYPE; i++) { mass_array[i] = header.mass_array[i]; if(header.n_all_hi_word[i] > 0) n_all[i] += (((size_t)(header.n_all_hi_word[i])) << 32); } // Count the total number of particles n_particles_all = 0; for(i = 0, n_non_zero = 0; i < N_GADGET_TYPE; i++) { if(n_all[i] > 0) { n_particles_all += n_all[i]; n_non_zero++; } } // List numbers of particles in the log output SID_log("%lld", SID_LOG_CONTINUE, n_particles_all); if(n_non_zero > 0) SID_log(" (", SID_LOG_CONTINUE, n_particles_all); for(i = 0; i < N_GADGET_TYPE; i++) { if(n_all[i] > 0) { if(i == n_non_zero - 1) { if(n_non_zero > 1) SID_log("and %lld %s", SID_LOG_CONTINUE, n_all[i], pname[i]); else SID_log("%lld %s", SID_LOG_CONTINUE, n_all[i], pname[i]); } else { if(n_non_zero > 1) SID_log("%lld %s, ", SID_LOG_CONTINUE, n_all[i], pname[i]); else SID_log("%lld %s", SID_LOG_CONTINUE, n_all[i], pname[i]); } } } if(n_non_zero > 0) SID_log(") particles...", SID_LOG_CONTINUE); else SID_log(" particles...", SID_LOG_CONTINUE); // Check closing record length SID_fread_verify(&record_length_close, 4, 1, fp); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of header)", SID_ERROR_LOGIC); // Close file fclose(fp); SID_log("Done.", SID_LOG_CLOSE); // Store mass array for(i = 0; i < N_GADGET_TYPE; i++) { if(n_all[i] > 0) { mass_array[i] *= plist->mass_unit / h_Hubble; if(mass_array[i] != 0.) { d_value = mass_array[i]; ADaPS_store(&(plist->data), (void *)(&d_value), "mass_array_%s", ADaPS_SCALAR_DOUBLE, plist->species[i]); } } else mass_array[i] = 0.; } // Is this a multimass snapshot? flag_multimass = GBP_FALSE; for(i = 0; i < N_GADGET_TYPE; i++) if(n_all[i] > 0 && mass_array[i] == 0.) flag_multimass = GBP_TRUE; // Is sph being used? if(n_all[GADGET_TYPE_GAS] > 0) flag_gas = GBP_TRUE; else flag_gas = GBP_FALSE; // Fetch (and sort by id) local group particles SID_log("Sorting group particle ids...", SID_LOG_OPEN); n_particles_rank = ((size_t *)ADaPS_fetch(plist->data, "n_particles_%03d", snapshot_number))[0]; n_particles_all_in_groups = ((size_t *)ADaPS_fetch(plist->data, "n_particles_all_%03d", snapshot_number))[0]; id_list = (size_t *)ADaPS_fetch(plist->data, "particle_ids_%03d", snapshot_number); merge_sort((void *)id_list, (size_t)n_particles_rank, &id_list_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); for(i = 0; i < N_GADGET_TYPE; i++) n_of_type_rank[i] = 0; n_of_type[GADGET_TYPE_DARK] = n_particles_all_in_groups; n_of_type_rank[GADGET_TYPE_DARK] = n_particles_rank; SID_log("Done.", SID_LOG_CLOSE); // Check integretry of particle ids SID_log("Checking integrity of group particle ids...", SID_LOG_OPEN); for(j = 1, n_warning = 0; j < n_particles_rank && n_warning < 10; j++) { if(id_list[id_list_index[j]] == id_list[id_list_index[j - 1]] && n_warning < 100) { fprintf(stderr, "WARNING: group particle id=%zd is duplicated on rank=%d!\n", id_list[id_list_index[j]], SID.My_rank); n_warning++; } } if(n_warning > 0) SID_exit_error("Error in group particle ids!", SID_ERROR_LOGIC); SID_log("Done.", SID_LOG_CLOSE); // Allocate data arrays for(i = 0; i < N_GADGET_TYPE; i++) { if(n_of_type_rank[i] > 0) { id_array[i] = (size_t *)SID_malloc(sizeof(size_t) * (size_t)n_of_type_rank[i]); x_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]); y_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]); z_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]); vx_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]); vy_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]); vz_array[i] = (GBPREAL *)SID_malloc(sizeof(GBPREAL) * (size_t)n_of_type_rank[i]); } } // Set offsets for(i = 0; i < N_GADGET_TYPE; i++) i_list_offset[i] = 0; // Read data for(i_file = 0, n_particles_kept = 0; i_file < n_files; i_file++) { if(n_files > 1) SID_log("Reading file %d of %d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file + 1, n_files); else SID_log("Performing read...", SID_LOG_OPEN | SID_LOG_TIMER); if(flag_file_type == 0) sprintf(filename, "%s/snapshot_%03d/snapshot_%03d", filename_root_in, snapshot_number, snapshot_number); else if(flag_file_type == 1) sprintf(filename, "%s/snapshot_%03d", filename_root_in, snapshot_number); else if(flag_file_type == 2) sprintf(filename, "%s_%03d", filename_root_in, snapshot_number); if(flag_multifile) sprintf(filename, "%s.%d", filename, i_file); // Read header and set positions pointer FILE *fp_positions; if(SID.I_am_Master) { fp_positions = fopen(filename, "r"); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_positions); SID_fread_verify(&header, sizeof(gadget_header_info), 1, fp_positions); SID_fread_verify(&record_length_close, sizeof(int), 1, fp_positions); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of header)", SID_ERROR_LOGIC); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_positions); } SID_Bcast(&header, sizeof(gadget_header_info), SID_CHAR, SID_MASTER_RANK, SID_COMM_WORLD); for(i = 0, n_particles_file = 0; i < N_GADGET_TYPE; i++) n_particles_file += (size_t)header.n_file[i]; // Set velocities pointer FILE *fp_velocities; if(SID.I_am_Master) { fp_velocities = fopen(filename, "r"); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_velocities); fseeko(fp_velocities, (off_t)record_length_open, SEEK_CUR); SID_fread_verify(&record_length_close, sizeof(int), 1, fp_velocities); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of header)", SID_ERROR_LOGIC); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_velocities); fseeko(fp_velocities, (off_t)record_length_open, SEEK_CUR); SID_fread_verify(&record_length_close, sizeof(int), 1, fp_velocities); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of positions)", SID_ERROR_LOGIC); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_velocities); } // Set IDs pointer FILE *fp_IDs; if(SID.I_am_Master) { fp_IDs = fopen(filename, "r"); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs); fseeko(fp_IDs, (off_t)record_length_open, SEEK_CUR); SID_fread_verify(&record_length_close, sizeof(int), 1, fp_IDs); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of header)", SID_ERROR_LOGIC); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs); fseeko(fp_IDs, (off_t)record_length_open, SEEK_CUR); SID_fread_verify(&record_length_close, sizeof(int), 1, fp_IDs); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of positions)", SID_ERROR_LOGIC); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs); fseeko(fp_IDs, (off_t)record_length_open, SEEK_CUR); SID_fread_verify(&record_length_close, sizeof(int), 1, fp_IDs); if(record_length_open != record_length_close) SID_log_warning("Problem with GADGET record size (close of velocities)", SID_ERROR_LOGIC); SID_fread_verify(&record_length_open, sizeof(int), 1, fp_IDs); if((size_t)record_length_open / n_particles_file == sizeof(long long)) { SID_log("(long long IDs)...", SID_LOG_CONTINUE); flag_LONGIDS = GBP_TRUE; } else if((size_t)record_length_open / n_particles_file == sizeof(int)) { SID_log("(int IDs)...", SID_LOG_CONTINUE); flag_LONGIDS = GBP_FALSE; } else SID_exit_error( "IDs record length (%d) does not set a sensible id byte size for the number of particles given in the header (%s)", SID_ERROR_LOGIC, record_length_open, n_particles_file); } SID_Bcast(&flag_LONGIDS, 1, SID_INT, SID_MASTER_RANK, SID_COMM_WORLD); // Allocate buffers int n_buffer_max = GBP_MIN(n_particles_file, 4 * 1024 * 1024); GBPREAL *buffer_positions; GBPREAL *buffer_velocities; size_t * buffer_IDs; buffer_positions = (GBPREAL *)SID_malloc(3 * n_buffer_max * sizeof(GBPREAL)); buffer_velocities = (GBPREAL *)SID_malloc(3 * n_buffer_max * sizeof(GBPREAL)); buffer_IDs = (size_t *)SID_malloc(n_buffer_max * sizeof(size_t)); // Perform read int i_buffer; int n_buffer_left; int n_buffer; int i_species; int i_particle; int j_particle; int i_list; size_t *buffer_index = NULL; for(i_species = 0, i_buffer = n_buffer_max, i_list = 0, n_buffer_left = n_particles_file; i_species < N_GADGET_TYPE; i_species++) { n_keep[i_species] = 0; if(header.n_file[i_species] > 0) { for(i_particle = 0; i_particle < header.n_file[i_species]; i_particle++) { // Perform a buffered read if(i_buffer >= n_buffer_max) { n_buffer = GBP_MIN(n_buffer_max, n_buffer_left); if(SID.I_am_Master) { SID_fread_verify(buffer_positions, sizeof(GBPREAL), 3 * n_buffer, fp_positions); SID_fread_verify(buffer_velocities, sizeof(GBPREAL), 3 * n_buffer, fp_velocities); if(!flag_LONGIDS) { int *buffer_IDs_int = (int *)buffer_IDs; SID_fread_verify(buffer_IDs_int, sizeof(int), n_buffer, fp_IDs); for(j_particle = n_buffer - 1; j_particle >= 0; j_particle--) buffer_IDs[j_particle] = (size_t)buffer_IDs_int[j_particle]; } else SID_fread_verify(buffer_IDs, sizeof(size_t), n_buffer, fp_IDs); } SID_Bcast(buffer_positions, 3 * n_buffer, SID_REAL, SID_MASTER_RANK, SID_COMM_WORLD); SID_Bcast(buffer_velocities, 3 * n_buffer, SID_REAL, SID_MASTER_RANK, SID_COMM_WORLD); SID_Bcast(buffer_IDs, n_buffer, SID_SIZE_T, SID_MASTER_RANK, SID_COMM_WORLD); SID_free(SID_FARG buffer_index); merge_sort(buffer_IDs, (size_t)n_buffer, &buffer_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); n_buffer_left -= n_buffer; i_buffer = 0; i_list = 0; } if(i_list < n_particles_rank) { // Move to the next particle size_t id_test; size_t j_buffer = buffer_index[i_buffer]; id_test = buffer_IDs[j_buffer]; while(id_list[id_list_index[i_list]] < id_test && i_list < (n_particles_rank - 1)) i_list++; // If we've found a particle, add it to the arrays if(id_list[id_list_index[i_list]] == id_test) { GBPREAL f1_value; GBPREAL f2_value; GBPREAL f3_value; GBPREAL f4_value; GBPREAL f5_value; GBPREAL f6_value; f1_value = ((GBPREAL *)buffer_positions)[3 * j_buffer + 0]; f2_value = ((GBPREAL *)buffer_positions)[3 * j_buffer + 1]; f3_value = ((GBPREAL *)buffer_positions)[3 * j_buffer + 2]; f4_value = ((GBPREAL *)buffer_velocities)[3 * j_buffer + 0]; f5_value = ((GBPREAL *)buffer_velocities)[3 * j_buffer + 1]; f6_value = ((GBPREAL *)buffer_velocities)[3 * j_buffer + 2]; id_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = id_test; x_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = f1_value * (GBPREAL)(plist->length_unit / h_Hubble); y_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = f2_value * (GBPREAL)(plist->length_unit / h_Hubble); z_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = f3_value * (GBPREAL)(plist->length_unit / h_Hubble); vx_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = f4_value * (GBPREAL)(plist->velocity_unit * sqrt(expansion_factor)); vy_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = f5_value * (GBPREAL)(plist->velocity_unit * sqrt(expansion_factor)); vz_array[i_species][n_keep[i_species] + i_list_offset[i_species]] = f6_value * (GBPREAL)(plist->velocity_unit * sqrt(expansion_factor)); n_keep[i_species]++; n_particles_kept++; i_list++; } } i_buffer++; } // i_particle } // if n>0 } // i_species // Update offsets for(i_species = 0; i_species < N_GADGET_TYPE; i_species++) i_list_offset[i_species] += n_keep[i_species]; // Clean-up SID_free(SID_FARG buffer_positions); SID_free(SID_FARG buffer_velocities); SID_free(SID_FARG buffer_IDs); SID_free(SID_FARG buffer_index); if(SID.I_am_Master) { fclose(fp_positions); fclose(fp_velocities); fclose(fp_IDs); } SID_log("Done.", SID_LOG_CLOSE); } // i_file // Check that the right number of particles have been read if(n_particles_kept != n_particles_rank) SID_log_warning("Rank %d did not receive the right number of particles (ie. %d!=%d)", SID_ERROR_LOGIC, SID.My_rank, n_particles_kept, n_particles_rank); // Store everything in the data structure... // ... particle counts ... for(i = 0; i < N_GADGET_TYPE; i++) { if(n_of_type[i] > 0) { SID_Allreduce(&(n_of_type_rank[i]), &(n_of_type[i]), 1, SID_SIZE_T, SID_SUM, SID_COMM_WORLD); ADaPS_store(&(plist->data), (void *)(&(n_of_type_rank[i])), "n_%s", ADaPS_SCALAR_SIZE_T, pname[i]); ADaPS_store(&(plist->data), (void *)(&(n_of_type[i])), "n_all_%s", ADaPS_SCALAR_SIZE_T, pname[i]); } } ADaPS_store(&(plist->data), (void *)(&n_particles_all), "n_particles_all", ADaPS_SCALAR_SIZE_T); // ... positions ... for(i = 0; i < N_GADGET_TYPE; i++) { if(n_of_type_rank[i] > 0) { ADaPS_store(&(plist->data), (void *)x_array[i], "x_%s", ADaPS_DEFAULT, pname[i]); ADaPS_store(&(plist->data), (void *)y_array[i], "y_%s", ADaPS_DEFAULT, pname[i]); ADaPS_store(&(plist->data), (void *)z_array[i], "z_%s", ADaPS_DEFAULT, pname[i]); } } // ... velocities ... for(i = 0; i < N_GADGET_TYPE; i++) { if(n_of_type_rank[i] > 0) { ADaPS_store(&(plist->data), (void *)vx_array[i], "vx_%s", ADaPS_DEFAULT, pname[i]); ADaPS_store(&(plist->data), (void *)vy_array[i], "vy_%s", ADaPS_DEFAULT, pname[i]); ADaPS_store(&(plist->data), (void *)vz_array[i], "vz_%s", ADaPS_DEFAULT, pname[i]); } } // ... ids ... for(i = 0; i < N_GADGET_TYPE; i++) { if(n_of_type_rank[i] > 0) ADaPS_store(&(plist->data), (void *)id_array[i], "id_%s", ADaPS_DEFAULT, pname[i]); } SID_free(SID_FARG id_list_index); SID_log("Done.", SID_LOG_CLOSE); } else SID_exit_error("Could not find file with root {%s}", SID_ERROR_IO_OPEN, filename_root_in); } int main(int argc, char *argv[]) { plist_info plist; char filename_groups_root[256]; char filename_out_root[256]; char filename_snapshot_root[256]; char filename_snapshot[256]; char * filename_number; char filename_output_properties_dir[256]; char filename_output_properties[256]; char filename_output_profiles_dir[256]; char filename_output_profiles[256]; char filename_output_indices[256]; char filename_output_indices_dir[256]; char filename_output_properties_temp[256]; char filename_output_profiles_temp[256]; char filename_output_indices_temp[256]; char group_text_prefix[4]; int n_groups_process; int n_groups; int n_groups_all; int i_rank; int i_group; int i_file_lo; int i_file_hi; int i_file; int i_file_skip; int i_particle; int j_particle; int i_process; int n_particles; int n_particles_max; GBPREAL * x_array; GBPREAL * y_array; GBPREAL * z_array; GBPREAL * vx_array; GBPREAL * vy_array; GBPREAL * vz_array; int * n_particles_groups_process; int * n_particles_groups; int * n_particles_subgroups; size_t * group_offset; size_t n_particles_in_groups; size_t * ids_snapshot; size_t * ids_groups; size_t * ids_sort_index; size_t * ids_snapshot_sort_index; size_t * ids_groups_sort_index; size_t n_particles_snapshot; int i_value; double h_Hubble; double Omega_M; double Omega_b; double Omega_Lambda; double f_gas; double Omega_k; double sigma_8; double n_spec; double redshift; double expansion_factor; double box_size; double particle_mass; int r_val; struct stat file_stats; size_t n_bytes; size_t n_bytes_buffer; void * buffer; FILE * fp_properties; FILE * fp_profiles; FILE * fp_indices; halo_properties_info properties; halo_profile_info profile; int n_temp; int n_truncated_local; int n_truncated; int largest_truncated; int largest_truncated_local; int flag_write_properties = GBP_TRUE; int flag_write_profiles = GBP_TRUE; int flag_write_indices = GBP_TRUE; int flag_manual_centre = GBP_TRUE; SID_Init(&argc, &argv, NULL); // Fetch user inputs strcpy(filename_snapshot_root, argv[1]); strcpy(filename_groups_root, argv[2]); strcpy(filename_out_root, argv[3]); i_file_lo = atoi(argv[4]); i_file_hi = atoi(argv[5]); i_file_skip = atoi(argv[6]); flag_manual_centre = atoi(argv[7]); if(!flag_manual_centre) flag_write_indices = GBP_FALSE; else flag_write_indices = GBP_TRUE; SID_log("Processing group/subgroup statistics for files #%d->#%d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file_lo, i_file_hi); SID_log("Properties structure size=%d bytes", SID_LOG_COMMENT, sizeof(halo_properties_info)); SID_log("Profiles structure size=%d bytes", SID_LOG_COMMENT, sizeof(halo_profile_bin_info)); for(i_file = i_file_lo; i_file <= i_file_hi; i_file += i_file_skip) { filename_number = (char *)SID_malloc(sizeof(char) * 10); sprintf(filename_number, "%03d", i_file); SID_log("Processing file #%d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file); // Read group and particle info init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY); // sprintf(filename_number,"read_catalog"); ADaPS_store(&(plist.data), (void *)filename_number, "read_catalog", ADaPS_DEFAULT); read_groups(filename_groups_root, i_file, READ_GROUPS_ALL, &plist, filename_number); n_particles_in_groups = ((size_t *)ADaPS_fetch(plist.data, "n_particles_%s", filename_number))[0]; n_groups_all = ((int *)ADaPS_fetch(plist.data, "n_groups_all_%s", filename_number))[0]; if(n_groups_all > 0) { read_gadget_binary_local(filename_snapshot_root, i_file, &plist); // read_gadget_binary(filename_snapshot_root,i_file,&plist,READ_GADGET_DEFAULT); if(ADaPS_exist(plist.data, "id_dark")) { n_particles_snapshot = ((size_t *)ADaPS_fetch(plist.data, "n_dark"))[0]; ids_snapshot = (size_t *)ADaPS_fetch(plist.data, "id_dark"); ids_groups = (size_t *)ADaPS_fetch(plist.data, "particle_ids_%s", filename_number); particle_mass = ((double *)ADaPS_fetch(plist.data, "mass_array_dark"))[0]; x_array = (GBPREAL *)ADaPS_fetch(plist.data, "x_dark"); y_array = (GBPREAL *)ADaPS_fetch(plist.data, "y_dark"); z_array = (GBPREAL *)ADaPS_fetch(plist.data, "z_dark"); vx_array = (GBPREAL *)ADaPS_fetch(plist.data, "vx_dark"); vy_array = (GBPREAL *)ADaPS_fetch(plist.data, "vy_dark"); vz_array = (GBPREAL *)ADaPS_fetch(plist.data, "vz_dark"); } else n_particles_snapshot = 0; // Initialize cosmology cosmo_info *cosmo = NULL; box_size = ((double *)ADaPS_fetch(plist.data, "box_size"))[0]; h_Hubble = ((double *)ADaPS_fetch(plist.data, "h_Hubble"))[0]; redshift = ((double *)ADaPS_fetch(plist.data, "redshift"))[0]; expansion_factor = ((double *)ADaPS_fetch(plist.data, "expansion_factor"))[0]; Omega_M = ((double *)ADaPS_fetch(plist.data, "Omega_M"))[0]; Omega_Lambda = ((double *)ADaPS_fetch(plist.data, "Omega_Lambda"))[0]; Omega_k = 1. - Omega_Lambda - Omega_M; Omega_b = 0.; // not needed, so doesn't matter f_gas = Omega_b / Omega_M; sigma_8 = 0.; // not needed, so doesn't matter n_spec = 0.; // not needed, so doesn't matter char cosmo_name[16]; sprintf(cosmo_name, "Gadget file's"); init_cosmo(&cosmo, cosmo_name, Omega_Lambda, Omega_M, Omega_k, Omega_b, f_gas, h_Hubble, sigma_8, n_spec); // Compute sort indices for ids in snapshot and group catalog SID_log("Sorting IDs...", SID_LOG_OPEN | SID_LOG_TIMER); if(n_particles_snapshot > 0) { merge_sort((void *)ids_snapshot, n_particles_snapshot, &ids_snapshot_sort_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); merge_sort((void *)ids_groups, n_particles_in_groups, &ids_groups_sort_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); // Create snapshot-indices for each particle in the group catalog ids_sort_index = (size_t *)SID_malloc(sizeof(size_t) * n_particles_in_groups); for(i_particle = 0, j_particle = 0; i_particle < n_particles_in_groups; i_particle++) { while(ids_snapshot[ids_snapshot_sort_index[j_particle]] < ids_groups[ids_groups_sort_index[i_particle]]) { j_particle++; if(j_particle >= n_particles_snapshot) SID_exit_error("There's a particle id in the group catalog that's not in the snapshot!", SID_ERROR_LOGIC); } ids_sort_index[ids_groups_sort_index[i_particle]] = ids_snapshot_sort_index[j_particle]; } } else { ids_snapshot_sort_index = NULL; ids_groups_sort_index = NULL; ids_sort_index = NULL; } SID_log("Done.", SID_LOG_CLOSE); // Create the output directory if(SID.I_am_Master) mkdir(filename_out_root, 02755); // Print stats; groups first and then subgroups for(i_process = 0; i_process < 2; i_process++) { // Initialize a bunch of stuff depending on whether we are // computing group or subgroup properties switch(i_process) { case 0: sprintf(group_text_prefix, ""); break; case 1: sprintf(group_text_prefix, "sub"); break; } n_groups = ((int *)ADaPS_fetch(plist.data, "n_%sgroups_%s", group_text_prefix, filename_number))[0]; n_groups_all = ((int *)ADaPS_fetch(plist.data, "n_%sgroups_all_%s", group_text_prefix, filename_number))[0]; // Fetch some stuff n_particles_groups = (int *)ADaPS_fetch(plist.data, "n_particles_%sgroup_%s", group_text_prefix, filename_number); group_offset = (size_t *)ADaPS_fetch(plist.data, "particle_offset_%sgroup_%s", group_text_prefix, filename_number); // Create filenames, directories, etc sprintf(filename_output_properties_temp, "%s_%s.catalog_%sgroups_properties", filename_out_root, filename_number, group_text_prefix); sprintf(filename_output_profiles_temp, "%s_%s.catalog_%sgroups_profiles", filename_out_root, filename_number, group_text_prefix); sprintf(filename_output_indices_temp, "%s_%s.catalog_%sgroups_indices", filename_out_root, filename_number, group_text_prefix); if(SID.n_proc > 1) { // Create property filenames if(flag_write_properties) { char properties_root[SID_MAX_FILENAME_LENGTH]; strcpy(properties_root, filename_output_properties_temp); strip_path(properties_root); strcpy(filename_output_properties_dir, filename_output_properties_temp); if(SID.I_am_Master) mkdir(filename_output_properties_dir, 02755); SID_Barrier(SID_COMM_WORLD); sprintf(filename_output_properties, "%s/%s.%d", filename_output_properties_dir, properties_root, SID.My_rank); } // Create profile filenames if(flag_write_profiles) { char profiles_root[SID_MAX_FILENAME_LENGTH]; strcpy(profiles_root, filename_output_profiles_temp); strip_path(profiles_root); strcpy(filename_output_profiles_dir, filename_output_profiles_temp); if(SID.I_am_Master) mkdir(filename_output_profiles_dir, 02755); SID_Barrier(SID_COMM_WORLD); sprintf(filename_output_profiles, "%s/%s.%d", filename_output_profiles_dir, profiles_root, SID.My_rank); } // Create sort indices filenames if(flag_write_indices) { char indices_root[SID_MAX_FILENAME_LENGTH]; strcpy(indices_root, filename_output_indices_temp); strip_path(indices_root); strcpy(filename_output_indices_dir, filename_output_indices_temp); if(SID.I_am_Master) mkdir(filename_output_indices_dir, 02755); SID_Barrier(SID_COMM_WORLD); sprintf(filename_output_indices, "%s/%s.%d", filename_output_indices_dir, indices_root, SID.My_rank); } } else { strcpy(filename_output_properties, filename_output_properties_temp); strcpy(filename_output_profiles, filename_output_profiles_temp); strcpy(filename_output_indices, filename_output_indices_temp); } SID_Barrier(SID_COMM_WORLD); // This makes sure that any created directories are there before proceeding // Open files SID_log("Processing %sgroups...", SID_LOG_OPEN | SID_LOG_TIMER, group_text_prefix); if(flag_write_properties) fp_properties = fopen(filename_output_properties, "w"); else fp_properties = NULL; if(flag_write_profiles) fp_profiles = fopen(filename_output_profiles, "w"); else fp_profiles = NULL; if(flag_write_indices) fp_indices = fopen(filename_output_indices, "w"); else fp_indices = NULL; // Write header if(fp_properties != NULL) { fwrite(&(SID.My_rank), sizeof(int), 1, fp_properties); fwrite(&(SID.n_proc), sizeof(int), 1, fp_properties); fwrite(&n_groups, sizeof(int), 1, fp_properties); fwrite(&n_groups_all, sizeof(int), 1, fp_properties); } if(fp_profiles != NULL) { fwrite(&(SID.My_rank), sizeof(int), 1, fp_profiles); fwrite(&(SID.n_proc), sizeof(int), 1, fp_profiles); fwrite(&n_groups, sizeof(int), 1, fp_profiles); fwrite(&n_groups_all, sizeof(int), 1, fp_profiles); } if(fp_indices != NULL) { fwrite(&(SID.My_rank), sizeof(int), 1, fp_indices); fwrite(&(SID.n_proc), sizeof(int), 1, fp_indices); fwrite(&n_groups, sizeof(int), 1, fp_indices); fwrite(&n_groups_all, sizeof(int), 1, fp_indices); } // Turn off the gsl error handler gsl_error_handler_t *original_handler; original_handler = gsl_set_error_handler_off(); // Create and write the properties and profiles of each group/subgroup in turn // Allocate some temporary arrays for particle positions/velocities int n_particles_alloc; double *x; double *y; double *z; double *vx; double *vy; double *vz; double *R; size_t *R_index = NULL; calc_max(n_particles_groups, &n_particles_alloc, n_groups, SID_INT, CALC_MODE_DEFAULT); x = (double *)SID_malloc(sizeof(double) * n_particles_alloc); y = (double *)SID_malloc(sizeof(double) * n_particles_alloc); z = (double *)SID_malloc(sizeof(double) * n_particles_alloc); vx = (double *)SID_malloc(sizeof(double) * n_particles_alloc); vy = (double *)SID_malloc(sizeof(double) * n_particles_alloc); vz = (double *)SID_malloc(sizeof(double) * n_particles_alloc); R = (double *)SID_malloc(sizeof(double) * n_particles_alloc); params_info_local params; params.ids_array = ids_snapshot; params.x_array = x_array; params.y_array = y_array; params.z_array = z_array; params.vx_array = vx_array; params.vy_array = vy_array; params.vz_array = vz_array; params.halo_sort_index = ids_sort_index; for(i_group = 0, n_truncated_local = 0, largest_truncated_local = 0; i_group < n_groups; i_group++) { params.first_particle_offset = group_offset[i_group]; if(compute_group_analysis(&properties, &profile, p_i_local, v_i_local, id_i_local, &params, box_size, particle_mass, n_particles_groups[i_group], expansion_factor, x, y, z, vx, vy, vz, R, &R_index, flag_manual_centre, GBP_TRUE, cosmo) != GBP_TRUE) { n_truncated_local++; largest_truncated_local = GBP_MAX(largest_truncated_local, n_particles_groups[i_group]); } write_group_analysis(fp_properties, fp_profiles, fp_indices, &properties, &profile, R_index, n_particles_groups[i_group]); SID_free(SID_FARG R_index); } // Free arrays SID_free(SID_FARG x); SID_free(SID_FARG y); SID_free(SID_FARG z); SID_free(SID_FARG vx); SID_free(SID_FARG vy); SID_free(SID_FARG vz); SID_free(SID_FARG R); if(fp_properties != NULL) fclose(fp_properties); if(fp_profiles != NULL) fclose(fp_profiles); if(fp_indices != NULL) fclose(fp_indices); calc_sum_global(&n_truncated_local, &n_truncated, 1, SID_INT, CALC_MODE_DEFAULT, SID_COMM_WORLD); calc_max_global(&largest_truncated_local, &largest_truncated, 1, SID_INT, CALC_MODE_DEFAULT, SID_COMM_WORLD); // Restore the original handler gsl_set_error_handler(original_handler); SID_Barrier(SID_COMM_WORLD); SID_log( "Done. (f_truncated=%6.2lf%% largest=%d)", SID_LOG_CLOSE, 100. * (double)n_truncated / (double)n_groups_all, largest_truncated); } // Clean-up free_cosmo(&cosmo); SID_free(SID_FARG ids_snapshot_sort_index); SID_free(SID_FARG ids_groups_sort_index); SID_free(SID_FARG ids_sort_index); } // If the group catalog or snapshot is empty, create an empty file else { SID_log("Creating empty analysis files...", SID_LOG_OPEN); if(SID.I_am_Master) { for(i_process = 0; i_process < 2; i_process++) { switch(i_process) { case 0: sprintf(group_text_prefix, ""); break; case 1: sprintf(group_text_prefix, "sub"); break; } n_groups_all = 0; n_temp = 1; if(flag_write_properties) { sprintf( filename_output_properties, "%s_%s.catalog_%sgroups_properties", filename_out_root, filename_number, group_text_prefix); fp_properties = fopen(filename_output_properties, "w"); fwrite(&(SID.My_rank), sizeof(int), 1, fp_properties); fwrite(&n_temp, sizeof(int), 1, fp_properties); fwrite(&n_groups_all, sizeof(int), 1, fp_properties); fwrite(&n_groups_all, sizeof(int), 1, fp_properties); fclose(fp_properties); } if(flag_write_profiles) { sprintf(filename_output_profiles, "%s_%s.catalog_%sgroups_profiles", filename_out_root, filename_number, group_text_prefix); fp_profiles = fopen(filename_output_profiles, "w"); fwrite(&(SID.My_rank), sizeof(int), 1, fp_profiles); fwrite(&n_temp, sizeof(int), 1, fp_profiles); fwrite(&n_groups_all, sizeof(int), 1, fp_profiles); fwrite(&n_groups_all, sizeof(int), 1, fp_profiles); fclose(fp_profiles); } } } SID_log("Done.", SID_LOG_CLOSE); } free_plist(&plist); SID_log("Done.", SID_LOG_CLOSE); } SID_log("Done.", SID_LOG_CLOSE); SID_Finalize(); }
{ "alphanum_fraction": 0.531727889, "avg_line_length": 48.8392685274, "ext": "c", "hexsha": "a2e494dd31ff356109cb2382aa63b68b301e93d7", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpAstro/gbpHalos/make_group_analysis.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpAstro/gbpHalos/make_group_analysis.c", "max_line_length": 149, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpAstro/gbpHalos/make_group_analysis.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 11022, "size": 50744 }
#include <netlib-jni.h> #include <cblas.h> // these CBLAS get* helpers are really irritating because // the first thing the cblas_ methods do is to do a reverse // lookup for the char and then pass it to the fortran lib! CBLAS_TRANSPOSE getCblasTrans(const char * fortranChar) { switch (fortranChar[0]) { case 'N': return CblasNoTrans; case 'n': return CblasNoTrans; case 'T': return CblasTrans; case 't': return CblasTrans; default: return -1; } } CBLAS_UPLO getCblasUpLo(const char * fortranChar) { switch (fortranChar[0]) { case 'U': return CblasUpper; case 'u': return CblasUpper; case 'L': return CblasLower; case 'l': return CblasLower; default: return -1; } } CBLAS_SIDE getCblasSide(const char * fortranChar) { switch (fortranChar[0]) { case 'L': return CblasLeft; case 'l': return CblasLeft; case 'R': return CblasRight; case 'r': return CblasRight; default: return -1; } } CBLAS_DIAG getCblasDiag(const char * fortranChar) { switch (fortranChar[0]) { case 'N': return CblasNonUnit; case 'n': return CblasNonUnit; case 'U': return CblasUnit; case 'u': return CblasUnit; default: return -1; } } inline void check_memory(JNIEnv * env, void * arg) { if (arg != NULL) { return; } /* * WARNING: Memory leak * * This doesn't clean up successful allocations prior to throwing this exception. * However, it's a pretty dire situation to be anyway and the client code is not * expected to recover. */ (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/OutOfMemoryError"), "Out of memory transferring array to native code in F2J JNI"); } inline int jboolean2int(jboolean b) { switch (b) { case JNI_TRUE: return 1; default: return 0; } } inline jboolean int2jboolean(int i) { switch (i) { case 1: return JNI_TRUE; default: return JNI_FALSE; } } int* jbooleanArray2intArray(JNIEnv * env, jboolean * a, jint size) { int * j = (int*) malloc(size * sizeof(int)); check_memory(env, j); int i; for (i = 0 ; i < size ; i++) { j[i] = jboolean2int(a[i]); } return j; } void intArray2jbooleanArray(int * a, jboolean * b, jint size) { int i; for (i = 0 ; i < size ; i++) { b[i] = int2jboolean(a[i]); } }
{ "alphanum_fraction": 0.6521164021, "avg_line_length": 23.625, "ext": "c", "hexsha": "1484635fc3668147aaa66f0ccc9e8177e987846e", "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": "f6973ee73a520529a1d28fa66261fbada27a05a2", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "almson/netlib-java", "max_forks_repo_path": "netlib/JNI/netlib-jni.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6973ee73a520529a1d28fa66261fbada27a05a2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "almson/netlib-java", "max_issues_repo_path": "netlib/JNI/netlib-jni.c", "max_line_length": 82, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f6973ee73a520529a1d28fa66261fbada27a05a2", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "almson/netlib-java", "max_stars_repo_path": "netlib/JNI/netlib-jni.c", "max_stars_repo_stars_event_max_datetime": "2021-04-28T01:29:18.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-28T01:29:18.000Z", "num_tokens": 682, "size": 2268 }
#include <bindings.cmacros.h> #include <gsl/gsl_math.h> BC_INLINE2(GSL_FN_EVAL,gsl_function*,double,double) BC_INLINE2(GSL_FN_FDF_EVAL_F,gsl_function_fdf*,double,double) BC_INLINE2(GSL_FN_FDF_EVAL_DF,gsl_function_fdf*,double,double) BC_INLINE3(GSL_FN_VEC_EVAL,gsl_function_vec*,double,double*,double) BC_INLINE4VOID(GSL_FN_FDF_EVAL_F_DF,gsl_function_fdf*,double,double*,double*)
{ "alphanum_fraction": 0.8552631579, "avg_line_length": 42.2222222222, "ext": "c", "hexsha": "466477ace05a07cd918df4873eb76b59226eee42", "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/MathematicalFunctions.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/MathematicalFunctions.c", "max_line_length": 77, "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/MathematicalFunctions.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": 109, "size": 380 }
#include "ccv.h" #include <ctype.h> #include <getopt.h> #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif #ifdef HAVE_GSL static ccv_dense_matrix_t* _ccv_aflw_slice_with_rect(gsl_rng* rng, ccv_dense_matrix_t* image, ccv_rect_t rect, ccv_size_t size, ccv_margin_t margin, float deform_angle, float deform_scale, float deform_shift) { ccv_dense_matrix_t* resize = 0; ccv_slice(image, (ccv_matrix_t**)&resize, 0, rect.y, rect.x, rect.height, rect.width); assert(rect.width == rect.height); float scale = gsl_rng_uniform(rng); // to make the scale evenly distributed, for example, when deforming of 1/2 ~ 2, we want it to distribute around 1, rather than any average of 1/2 ~ 2 scale = (1 + deform_scale * scale) / (1 + deform_scale * (1 - scale)); int new_width = (int)(rect.width * scale + 0.5); int new_height = (int)(rect.height * scale + 0.5); ccv_point_t offset = ccv_point((int)((deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) * rect.width + 0.5 + (rect.width - new_width) * 0.5), (int)((deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) * rect.height + 0.5 + (rect.height - new_height) * 0.5)); rect.x += offset.x; rect.y += offset.y; ccv_dense_matrix_t* b = 0; if (size.width > rect.width) ccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom, size.width + margin.left + margin.right, CCV_INTER_CUBIC); else ccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom, size.width + margin.left + margin.right, CCV_INTER_AREA); ccv_matrix_free(resize); return b; } #endif int main(int argc, char** argv) { #ifdef HAVE_GSL assert(argc == 4); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); FILE* r = fopen(argv[1], "r"); char* base_dir = argv[2]; int dirlen = (base_dir != 0) ? strlen(base_dir) + 1 : 0; char* file = (char*)malloc(1024); int i = 0; ccv_rect_t rect; ccv_decimal_pose_t pose; // rect.x, rect.y, rect.width, rect.height roll pitch yaw while (fscanf(r, "%s %d %d %d %d %f %f %f", file, &rect.x, &rect.y, &rect.width, &rect.height, &pose.roll, &pose.pitch, &pose.yaw) != EOF) { if (pose.pitch < CCV_PI * 22.5 / 180 && pose.pitch > -CCV_PI * 22.5 / 180 && pose.roll < CCV_PI * 22.5 / 180 && pose.roll > -CCV_PI * 22.5 / 180 && pose.yaw < CCV_PI * 20 / 180 && pose.yaw > -CCV_PI * 20 / 180 && rect.width >= 15 && rect.height >= 15) { // resize to a more proper sizes char* filename = (char*)malloc(1024); strncpy(filename, base_dir, 1024); filename[dirlen - 1] = '/'; strncpy(filename + dirlen, file, 1024 - dirlen); ccv_dense_matrix_t* image = 0; ccv_read(filename, &image, CCV_IO_ANY_FILE | CCV_IO_GRAY); char* savefile = (char*)malloc(1024); ccv_dense_matrix_t* b = _ccv_aflw_slice_with_rect(rng, image, rect, ccv_size(48, 48), ccv_margin(0, 0, 0, 0), 10, 0.1, 0.05); snprintf(savefile, 1024, "%s/aflw-%07d-bw.png", argv[3], i); ccv_write(b, savefile, 0, CCV_IO_PNG_FILE, 0); ccv_matrix_free(b); ccv_matrix_free(image); image = 0; ccv_read(filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR); b = _ccv_aflw_slice_with_rect(rng, image, rect, ccv_size(48, 48), ccv_margin(0, 0, 0, 0), 10, 0.1, 0.05); snprintf(savefile, 1024, "%s/aflw-%07d-rgb.png", argv[3], i); ccv_write(b, savefile, 0, CCV_IO_PNG_FILE, 0); ccv_matrix_free(b); ccv_matrix_free(image); i++; free(savefile); free(filename); } } fclose(r); free(file); gsl_rng_free(rng); #else assert(0 && "aflw requires GSL library support"); #endif return 0; }
{ "alphanum_fraction": 0.6731097214, "avg_line_length": 40.9069767442, "ext": "c", "hexsha": "e729cef61fa6d8bad2dbac7d6b6201041421cccf", "lang": "C", "max_forks_count": 940, "max_forks_repo_forks_event_max_datetime": "2022-03-24T23:27:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-02T02:21:34.000Z", "max_forks_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "sunkaianna/ccv", "max_forks_repo_path": "bin/aflw.c", "max_issues_count": 111, "max_issues_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_issues_repo_issues_event_max_datetime": "2022-01-05T18:13:11.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-12T15:55:58.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "sunkaianna/ccv", "max_issues_repo_path": "bin/aflw.c", "max_line_length": 269, "max_stars_count": 3296, "max_stars_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "sunkaianna/ccv", "max_stars_repo_path": "bin/aflw.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:29:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-01T02:05:51.000Z", "num_tokens": 1208, "size": 3518 }
/** @file @brief Utilities to perform vectorized LU and LDU decomposition with complete row and column pivoting, based on nonvectorized version of LU decomposition with complete row and column pivoting written by Roger Wehage. @author Kristopher Wehage @date 2016 @version 1.1 @remark THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifdef KSL_WITH_BLAS_ #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #endif #include "ksl/array.h" #include "ksl/linalg.h" /*! @brief Function for performing modified double precision Gram-Schmidt orthonormalization This function implements a compact version of the Gram-Schmidt algorithm to orthonormalize the columns of a matrix which has full column rank. The matrix, whose columns are to be orthonormalized, is passed in as A[m][n] where m and n are the respective row and column dimensions of A[][]. The orthonormalized columns are passed back in A[][]. @param m row dimension @param n column dimension @param A[m][n] a rectangular matrix to be orthonormalized, the orthonormalized matrix is returned in A */ void ksl_linalg_gramSchmidt(double* restrict A, const int m, const int n) { for(int k = 0; k < n; k++) { #ifdef KSL_WITH_BLAS double R = 1.0 / cblas_dnrm2(m, A + k, n); cblas_dscal(m, R, A + k, n); #else double R = 0.0; for(int i = 0; i < m; i++) { R += A[i * n + k] * A[i * n + k]; } R = 1.0 / sqrt(R); for(int i = 0; i < m; i++) { A[i * n + k] *= R; } #endif for(int j = k + 1; j < n; j++) { R = 0; for(int i = 0; i < m; i++) { R += A[i * n + k] * A[i * n + j]; } for(int i = 0; i < m; i++) { A[i * n + j] -= A[i * n + k] * R; } } } } /*! @brief Function for performing single precision modified Gram-Schmidt orthonormalization This function implements a compact version of the Gram-Schmidt algorithm to orthonormalize the columns of a matrix which has full column rank. The matrix, whose columns are to be orthonormalized, is passed in as A[m][n] where m and n are the respective row and column dimensions of A[][]. The orthonormalized columns are passed back in A[][]. @param m row dimension @param n column dimension @param A[m][n] a rectangular matrix to be orthonormalized, the orthonormalized matrix is returned in A */ void ksl_linalg_gramSchmidtf(float* restrict A, const int m, const int n) { for(int k = 0; k < n; k++) { #ifdef KSL_WITH_BLAS double R = 1.0 / cblas_snrm2(m, A + k, n); cblas_sscal(m, R, A + k, n); #else double R = 0.0; for(int i = 0; i < m; i++) { R += A[i * n + k] * A[i * n + k]; } R = 1.0 / sqrt(R); for(int i = 0; i < m; i++) { A[i * n + k] *= R; } #endif for(int j = k + 1; j < n; j++) { R = 0; for(int i = 0; i < m; i++) { R += A[i * n + k] * A[i * n + j]; } for(int i = 0; i < m; i++) { A[i * n + j] -= A[i * n + k] * R; } } } } /*! @brief Row Major Order LU Decomposition with complete row and column pivoting ksl_linalg_lu_full_rmo factors a double precision matrix, A[rowDim * colDim], stored in Row Major Order using full row and column pivoting. Matrix A need not have full row or column rank. The integer variable 'rank' represents the matrix rank and internally is always one less than the true rank to be consistent with C's indexing from zero. Upon return from the function, rank will be set to the correct value. The lower triangular (rank+1) by (rank+1) Lr matrix, except its unity diagonal, is stored below the diagonal in A[0:rank][0:rank]. The upper triangular (rank+1) by (rank+1) Ur matrix is stored on and above the diagonal in A[0:rank][0:rank]. Following the first major matrix decomposition step, A[0:rank][rank+1:colDim] stores the residual matrix UR and A[rank+1:rowDim][0:rank] stores the residual matrix LR. The following operations on this matrix are optionally performed after ksl_linalg_lu_full_rmo() has factored A. ksl_linalg_lu_setBMatrix_rmo() computes and stores B = inverse(Ur)*UR and stores it back in A[0:rank][rank+1:colDim]. ksl_linalg_lu_setCMatrix_rmo() computes and stores C = LR*inverse(Lr) and stores it back in A[rank+1:rowDim][0:rank]. The remaining A[rank+1:rowDim][rank+1:colDim] submatrix contains numbers whose absolute values are all smaller than eps times the absolutely largest entry in the original matrix. This part of the matrix is not used. @param rowDim [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param *A [in/out] matrix to be factored with dimensions A[0:rowDim-1][0:colDim-1], LU factors are overwritten in original matrix @param eps [in] input tolerance on the order of machine roundoff. @param pr [out] output row permutation array with dimensions pr[0:rowDim-1] @param pc [out] output column permutation array with dimensions pc[0:colDim-1] @return rank of matrix A */ int ksl_linalg_lu_full_rmo(const int rowDim, const int colDim, double* restrict A, const double eps, int* restrict pr, int* restrict pc) { // printf("Jacobian matrix in fullFactor_LU\n"); // for(int i = 0; i < rowDim; i++) { // for(int j = 0; j < colDim; j++) // printf("% 2.4f ", A[i * colDim + j]); // printf("\n"); // } int rank; /* (rank+1) is the matrix rank */ int pivotRow; /* row with current pivotal element */ int pivotCol; /* column with current pivotal element */ double pivot = 0.0; /* current pivotal element, holds the current pivotal element value */ double tol; /* tolerance for checking residual matrix infinity norm against */ double save; /* variable for holding intermediate results*/ double size = rowDim * colDim; /*overall size of matrix */ /* Return failure if a bad row or column dimension was found. */ if((rowDim <= 0) || (colDim <= 0)) { return (-1); } /* Consistent with C-indexing, rank always has a value of one less than the true value. rank+1 is returned. */ rank = -1; /* initialize for indexing */ /* Search through the entire A matrix to find the absolutely largest element for assigning to pivot. Save that row and column number in pivotRow and pivotCol. Also intialize the row permutation array pr. */ #ifdef KSL_WITH_BLAS_ int index = cblas_idamax(size, A, 1); #else int index = ksl_maxIndex(size, A); #endif // div_t result = div(index, colDim); // pivotRow = result.quot; // pivotCol = result.rem; pivotRow = index / colDim; pivotCol = index - pivotRow * colDim; pivot = A[index]; // printf("pivotRow: %d, pivotCol: %d\n", pivotRow, pivotCol); /* Initialize the column permutation array. */ for(int col = 0; col < colDim; col++) { pc[col] = col; } for(int row = 0; row < rowDim; row++) { pr[row] = row; } /* Set tolerance to check all zero-elements against. pivot = infinity norm of A. */ tol = fabs(eps * pivot); /* Major loop to permute and factor the matrix. Generate factors column by column, so outer loop sweeps over columns. */ for(int col = 0; col < colDim; col++) { /* If the current pivotal element is <= tol, the remaining submatrix is zero and factorization is complete. The else statement for the following if test breaks out of this loop so not to waste time going through the remaining columns. */ if(fabs(pivot) > tol) { /* Increase rank for the current column. */ ++rank; /* pivotRow can never be less than rank. If pivotRow==rank, then no permutation is needed. If pivotRow>rank, then need to swap rows. */ if(pivotRow > rank) { /* Swap entire rows A[rank][:] and A[pivotRow][:]. This also swaps rows in the LR matrix to this point. swap rows: N = colDim stride = 1 Start of replaced row is A + colDim * rank & stride is 1 Start of pivot row is A + colDim * pivotRow & stride is 1 */ #ifdef KSL_WITH_BLAS_ cblas_dswap(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1); #else ksl_swapArray(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1); #endif /* Swap row permutation entries pr[rank] and pr[pivotRow] to reflect row swaps in A. */ ksl_swapi(pr + rank, pr + pivotRow); } /* pivotCol can never be less than rank. If pivotCol==rank, then no permutation is needed. If pivotCol>rank, then need to swap columns. */ if(pivotCol > rank) { // printf("rank: %d, pivotCol: %d\n", rank, pivotCol); // printf("colDim %d\n", colDim); /* Swap entire columns A[:][rank] and A[:][pivotCol]. This also swaps columns in the UR matrix to this point. swap columns: N = rowDim stride = colDim Start of replaced column is A + rank & stride is colDim Start of pivot column is A + pivotCol & stride is colDim */ #ifdef KSL_WITH_BLAS_ cblas_dswap(rowDim, A + rank, colDim, A + pivotCol, colDim); #else ksl_swapArray(rowDim, A + rank, colDim, A + pivotCol, colDim); #endif /* Swap column permutation entries pc[rank] and pr[pivotCol] to reflect column swaps. */ ksl_swapi(pc + rank, pc + pivotCol); } /* rank cannot be > rowDim-1. If rank < rowDim-1 there is still some processing left to do. If rank == rowDim-1, there is only a 1 on the diagonal of this column of Lr. This loop factors the matrix and searches for a new pivotal element for the next factorization step. */ if(rank < rowDim - 1) { /* Copy the current pivotal element into save so new pivotal element can be stored back in pivot. */ save = pivot; pivot = 0; /* Need only process the rows from rank+1 to rowDim. */ for(int i = rank + 1; i < rowDim; i++) { /* Evaluate the current entry in the L matrix.*/ A[i * colDim + rank] /= save; /* rank cannot be >= colDim. If rank < colDim there is still some processing left to do. If rank == colDim-1, only a pivot remains on the diagonal. */ if(rank < colDim) { /* This next loop computes the remaining U matrix, searches for the largest pivotal element, and remembers the new pivotal element row and colum. */ for(int j = rank + 1; j < colDim; j++) { A[i * colDim + j] -= A[i * colDim + rank] * A[rank * colDim + j]; if(fabs(A[i * colDim + j]) > fabs(pivot)) { pivot = A[i * colDim + j]; pivotRow = i; pivotCol = j; } /*End if*/ } /*End for j*/ } /*End if rank*/ } /*Endfor i = rank+1*/ } /*Endif (rank<rowDim-1)*/ else { break; /*No more rows to process.*/ } } /*End if*/ else { break; /*Done if remainder of matrix is at noise level.*/ } } /*End for col*/ return (rank + 1); } /*! @brief Row Major Order LU Decomposition with complete row and column pivoting with one specified coordinate ksl_linalg_lu_full_specified_rmo factors a double precision matrix, A[rowDim * colDim], stored in Row Major Order using full row and column pivoting. Matrix A need not have full row or column rank. The integer variable 'rank' represents the matrix rank and internally is always one less than the true rank to be consistent with C's indexing from zero. Upon return from the function, rank will be set to the correct value. The lower triangular (rank+1) by (rank+1) Lr matrix, except its unity diagonal, is stored below the diagonal in A[0:rank][0:rank]. The upper triangular (rank+1) by (rank+1) Ur matrix is stored on and above the diagonal in A[0:rank][0:rank]. Following the first major matrix decomposition step, A[0:rank][rank+1:colDim] stores the residual matrix UR and A[rank+1:rowDim][0:rank] stores the residual matrix LR. ksl_linalg_lu_setBMatrix_rmo() computes and stores B = inverse(Ur)*UR and stores it back in A[0:rank][rank+1:colDim]. ksl_linalg_lu_setCMatrix_rmo() computes and stores C = LR*inverse(Lr) and stores it back in A[rank+1:rowDim][0:rank]. The remaining A[rank+1:rowDim][rank+1:colDim-1] submatrix contains numbers whose absolute values are all smaller than eps times the absolutely largest entry in the original matrix. This part of the matrix is not used. The remainig A[rank+1:rowDim][colDim] submatrix could contain numbers whose absolute values are greater than eps times the absolutely largest entry in the original matrix. Adding a check here would be one way to assert that the specified variable has sufficient mobility. @param rowDim input row dimension of matrix A. @param colDim input column dimension of matrix A. @param **A input/output matrix to be factored with dimensions A[0:rowDim-1][0:colDim-1]: @param eps input tolerance on the order of machine roundoff. @param pr output row permutation array with dimensions pr[0:rowDim-1] @param pc output column permutation array with dimensions pc[0:colDim-1] @return rank of matrix A */ int ksl_linalg_lu_full_specified_rmo(const int rowDim, const int colDim, double* restrict A, double eps, int* restrict pr, int* restrict pc, const int specifiedIndex) { // printf("Jacobian matrix in fullFactor_LU\n"); // for(int i = 0; i < rowDim; i++) { // for(int j = 0; j < colDim; j++) // printf("% 2.4f ", A[i * colDim + j]); // printf("\n"); // } int rank; /* (rank+1) is the matrix rank */ int pivotRow; /* row with current pivotal element */ int pivotCol; /* column with current pivotal element */ double pivot = 0.0; /* current pivotal element, holds the current pivotal element */ double tol; /* tolerance for checking residual matrix infinity norm against */ double save; /* variable for holding intermediate results*/ // double size = rowDim * colDim; /*overall size of matrix */ /* Return failure if a bad row or column dimension was found. */ if((rowDim <= 0) || (colDim <= 1)) { return (-1); } /* Consistent with C-indexing, rank always has a value of one less than the true value. rank+1 is returned. */ rank = -1; /* initialize for indexing */ /* Initialize permutation arrays */ for(int row = 0; row < rowDim; row++) { pr[row] = row; } for(int col = 0; col < colDim; col++) { pc[col] = col; } /* Swap the specified column to the last position in the input matrix Swap entire columns A[:][specifiedIndex] and A[:][colDim - 1]. swap columns: N = rowDim stride = colDim Start of specefied column is A + specifiedIndex & stride is colDim Start of last column is A + colDim - 1 & stride is colDim */ if(specifiedIndex != colDim - 1) { #ifdef KSL_WITH_BLAS cblas_dswap(rowDim, A + specifiedIndex, colDim, A + colDim - 1, colDim); #else ksl_swapArray(rowDim, A + specifiedIndex, colDim, A + colDim - 1, colDim); #endif /* Swap column permutation entries pc[] and pc[pivotRow] to reflect row swaps in A. */ ksl_swapi(pc + specifiedIndex, pc + colDim - 1); } /* Search through matrix A except the last column to find the absolutely largest element for assigning to pivot. Save that row and column number in pivotRow and pivotCol. This could cause numerical problems if the last column contains one or more entries substantially absolutely larger than all other entries in A. */ pivot = A[0]; pivotRow = 0; pivotCol = 0; for(int row = 0; row < rowDim; row++) { for(int col = 0; col < colDim - 1; col++) { if(fabs(A[row * colDim + col]) > fabs(pivot)) { pivot = A[row * colDim + col]; pivotRow = row; pivotCol = col; } } } // printf("pivotRow: %d, pivotCol: %d\n", pivotRow, pivotCol); /* Set tolerance to check all zero-elements against. pivot = infinity norm of A. */ tol = fabs(eps * pivot); /* Major loop to permute and factor the matrix. Generate factors column by column, so outer loop sweeps over columns. */ for(int col = 0; col < colDim; col++) { /* If the current pivotal element is <= tol, the remaining submatrix is zero and factorization is complete. The else statement for the following if test breaks out of this loop so not to waste time going through the remaining columns. */ if(fabs(pivot) > tol) { /* Increase rank for the current column. */ ++rank; /* pivotRow can never be less than rank. If pivotRow==rank, then no permutation is needed. If pivotRow>rank, then need to swap rows. */ if(pivotRow > rank) { /* Need to swap entire row A[rank][:] and A[pivotRow][:]. This also swaps rows in the Lr matrix to this point. swap rows: N = colDim stride = 1 Start of replaced row is A + colDim * rank & stride is 1 Start of pivot row is A + colDim * pivotRow & stride is 1 */ #ifdef KSL_WITH_BLAS_ cblas_dswap(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1); #else ksl_swapArray(colDim, A + colDim * rank, 1, A + colDim * pivotRow, 1); #endif /* Swap row permutation entries pr[rank] and pr[pivotRow] to reflect row swaps in A. */ ksl_swapi(pr + rank, pr + pivotRow); } /* pivotCol can never be less than rank. If pivotCol==rank, then no permutation is needed. If pivotCol>rank, then need to swap columns. */ if(pivotCol > rank) { // printf("rank: %d, pivotCol: %d\n", rank, pivotCol); // printf("colDim %d\n", colDim); /* Swap entire columns A[:][rank] and A[:][pivotCol]. This also swaps columns in the UR matrix to this point. swap columns: N = rowDim stride = colDim Start of replaced column is A + rank & stride is colDim Start of pivot column is A + pivotCol & stride is colDim */ #ifdef KSL_WITH_BLAS_ cblas_dswap(rowDim, A + rank, colDim, A + pivotCol, colDim); #else ksl_swapArray(rowDim, A + rank, colDim, A + pivotCol, colDim); #endif /* Swap column permutation entries pc[rank] and pr[pivotCol] to reflect column swaps. */ ksl_swapi(pc + rank, pc + pivotCol); } /* rank cannot be > rowDim-1. If rank < rowDim-1 there is still some processing left to do. If rank == rowDim-1, there is only a 1 on the diagonal of this column of Lr. This loop factors the matrix and searches for a new pivotal element for the next factorization step. */ if(rank < rowDim - 1) { /* Copy the current pivotal element into save so new pivotal element can be stored back in pivot. */ save = pivot; pivot = 0; /* Need only process the rows from rank+1 to rowDim. */ for(int i = rank + 1; i < rowDim; i++) { /* Evaluate the current entry in the L matrix.*/ A[i * colDim + rank] /= save; /* rank cannot be >= colDim. If rank < colDim there is still some processing left to do. If rank == colDim-1, only a pivot remains on the diagonal. */ if(rank < colDim) { /* This next loop computes the remaining U matrix, searches for the largest pivotal element, and remembers the new pivotal element row and colum. */ for(int j = rank + 1; j < colDim; j++) { A[i * colDim + j] -= A[i * colDim + rank] * A[rank * colDim + j]; } for(int j = rank + 1; j < colDim - 1; j++) { if(fabs(A[i * colDim + j]) > fabs(pivot)) { pivot = A[i * colDim + j]; pivotRow = i; pivotCol = j; } /*End if*/ } /*End for j*/ } /*End if rank*/ } /*Endfor i = rank+1*/ } /*Endif (rank<rowDim-1)*/ else { break; /*No more rows to process.*/ } } /*End if*/ else { break; /*Done if remainder of matrix is at noise level.*/ } } /*End for col*/ return (rank + 1); } /*! @brief *Fast* Row Major Order LU Decomposition with no row or column pivoting for a rectangular matrix This function LU factors a double precision matrix, A[rank][colDim], using no row or column pivoting. This function should be used only if the left rank by rank submatrix is known to be nonsingular. rank <= colDim or error. The lower triangular rank by rank Lr matrix, except the unity diagonal, is stored below the diagonal in A[0:rank-1][0:rank-1]. The upper triangular rank by rank Ur matrix is stored on and above the diagonal in A[0:rank-1][0:rank-1]. Note that this minimal algorithm variation does not compute the product B = inverse(Ur)*UR @param rank [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param *A [in/out] matrix to be factored with dimensions A[0:rank-1][0:colDim-1]: */ inline void ksl_linalg_lu_rmo(const int rank, const int colDim, double* restrict A) { if(rank > colDim) { // Error message & exit } /* Major loop to factor the matrix. Generate factors column by column */ for(int row = 0; row < rank; row++) { /* i iterates over rows of A, up to rank-1 */ for(int i = row + 1; i < rank; i++) { /* Evaluate the current entry in the L matrix.*/ A[i * colDim + row] /= A[row * colDim + row]; /* Compute U matrix */ for(int j = row + 1; j < colDim; j++) { A[i * colDim + j] -= A[i * colDim + row] * A[row * colDim + j]; } } } } /*! @brief compute Row Major Order B matrix (inverse(Ur) * UR) This block overwrites UR with inverse(Ur) * UR If rank == 0 or rank == colDim nothing to process, so exit with message. This loop computes A[0:rank-1][rank:colDim-1] = inverse(Ur)*UR where UR is stored in A[0:rank-1][rank:colDim-1] and Ur is stored in upper part of A[0:rank-1][0:rank-1]. i is the row number in Ur. j is the column number in Ur & row number in UR. k is the column number in UR. @param rowDim [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param rank [in] rank of matrix A. @param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]: */ inline void ksl_linalg_lu_setBMatrix_rmo(const int rowDim, const int colDim, const int rank, double* restrict A) { if(rank > 0 && rank < colDim) { for(int i = rank - 1; i > -1; i--) { /* rows of B */ for(int k = rank; k < colDim; k++) { /* columns of B */ double save = 0; for(int j = rank - 1; j > i; j--) { /* columns of Ur */ save += A[i * colDim + j] * A[j * colDim + k]; } A[i * colDim + k] = (A[i * colDim + k] - save) / A[i * colDim + i]; } } } else { // Error & do something. } } /*! @brief compute Row Major Order C matrix This block overwrites LR with LR*inverse(Lr) If rank==1, the Lr matrix is a 1 by 1 identity matrix, so there is nothing to do here. This loop computes A[rank:rowDim-1][0:rank-1]=LR*inverse(Lr) where LR is stored in A[rank:rowDim-1][0:rank-1] and Lr is stored in A[0:rank-1][0:rank-1]. j is the column number in LR. It ends at 1 because the diagonal entry in row 0 of Lr is 1. i is the row number in LR. k is the column number in Lr @param rowDim [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param rank [in] rank of matrix A. @param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]: */ void ksl_linalg_lu_setCMatrix_rmo(int rowDim, int colDim, int rank, double* A) { if(rank > 1) { for(int j = rank - 1; j > 0; j--) { for(int i = rowDim - 1; i > rank - 1; i--) { for(int k = 0; k < j; k++) A[i * colDim + k] -= A[i * colDim + j] * A[j * colDim + k]; } } } else { // Error & do something. } } /*! @brief computes the Row Major Order L D L^T decomposition of a symmetric positive definite matrix without pivoting returns the matrix L D L^T in the original matrix A @param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]: @param n row and column dimension of matrix A. */ int ksl_linalg_ldlt_rmo(double* restrict A, const int n) { for(int k = 0; k < n; k++) { double pivot_inv = A[k * n + k]; if(pivot_inv > 0.0) { pivot_inv = 1.0 / A[k * n + k]; } else { return k + 1; } for(int j = k + 1; j < n; j++) { A[k * n + j] = A[j * n + k]; A[j * n + k] *= pivot_inv; } for(int j = k + 1; j < n; j++) { for(int i = k + 1; i < j + 1; i++) { A[j * n + i] -= A[j * n + k] * A[k * n + i]; } } } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { A[i * n + j] = A[j * n + i]; } } return 0; } /*! @brief perform Row Major Order Cholesky (L * L^T) decomposition of a symmetric matrix without pivoting returns the matrix factor L in the lower triangular portion of matrix A @param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]: @param n row and column dimension of matrix A. */ int ksl_linalg_cholesky_rmo(double* restrict A, const int n) { for(int k = 0; k < n; k++) { if(A[k * n + k] > 0.0) { A[k * n + k] = sqrt(A[k * n + k]); } else { return k + 1; } double pivot_inv = 1.0 / A[k * n + k]; for(int j = k + 1; j < n; j++) { A[j * n + k] *= pivot_inv; } for(int j = k + 1; j < n; j++) { for(int i = k + 1; i < j + 1; i++) { A[j * n + i] -= A[j * n + k] * A[i * n + k]; } } } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { A[i * n + j] = A[j * n + i]; } } return 0; } /*! @brief used to solve a system of equations L * y = b for y using forward elimination where L IS Row Major Order unit lower triangular y = L^-1 * b @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *y [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_ldlt_forwardElimination_rmo(const double* restrict L, const double* restrict b, double* restrict y, const int n) { for(int i = 0; i < n; i++) { y[i] = b[i]; for(int j = 0; j < i; j++) { y[i] -= L[i * n + j] * y[j]; } } } /*! @brief used to solve a system of equations L^T * x = y using backward substitution where L IS Row Major Order unit lower triangular x = L^-T * y @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *y [in] n by 1 column of right-hand side b[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], y[], x[]: */ inline void ksl_linalg_ldlt_backwardSubstitution_rmo(const double* restrict L, const double* restrict y, double* restrict x, const int n) { x[n - 1] = y[n - 1]; for(int i = n - 2; i > -1; i--) { x[i] = y[i]; for(int j = i + 1; j < n; j++) { x[i] -= L[j * n + i] * x[j]; } } } /*! @brief used to solve a system of equations L * y = b for y using forward elimination where L is Row Major Order and IS NOT unit lower triangular y = L^-1 * b @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *y [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_cholesky_forwardElimination_rmo(const double* restrict L, const double* restrict b, double* restrict y, const int n) { for(int i = 0; i < n; i++) { double t = b[i]; for(int j = 0; j < i; j++) { t -= L[i * n + j] * y[j]; } y[i] = t / L[i * n + i]; } } /*! @brief used to solve a system of equations L^T * x = y using backward substitution where L is Row Major Order and IS NOT unit lower triangular x = L^-T * y @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *y [in] n by 1 column of right-hand side y[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], y[], x[]: */ inline void ksl_linalg_cholesky_backwardSubstitution_rmo(const double* restrict L, const double* restrict y, double* restrict x, const int n) { x[n - 1] = y[n - 1] / L[(n - 1) * n + (n - 1)]; for(int i = n - 2; i > -1; i--) { double t = y[i]; for(int j = i + 1; j < n; j++) { t -= L[j * n + i] * x[j]; } x[i] = t / L[i * n + i]; } } /*! @brief solve the system of equations A * x = b where A is Row Major Order and a symmetric positive definite matrix A ksl_linalg_ldlt must be called on A prior to calling this function @param *A [in] n by n matrix A[0:n-1][0:n-1] containing Choleski-factored matrix: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_ldlt_solve_rmo(const double* restrict A, const double* restrict b, double* restrict x, const int n) { double y[n]; ksl_linalg_ldlt_forwardElimination_rmo(A, b, y, n); for(int i = 0; i < n; i++) { y[i] /= A[i * n + i]; } ksl_linalg_ldlt_backwardSubstitution_rmo(A, y, x, n); } /*! @brief solve the system of equations A * x = b where A is Row Major Order and a symmetric positive definite matrix A ksl_linalg_cholesky must be called on A prior to calling this function @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *y [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_cholesky_solve_rmo(const double* restrict A, const double* restrict b, double* restrict x, const int n) { double y[n]; ksl_linalg_cholesky_forwardElimination_rmo(A, b, y, n); ksl_linalg_cholesky_backwardSubstitution_rmo(A, y, x, n); } /*! @brief compute inverse of a symmetric positive definite matrix A where A and A_inverse are in Row Major Order. */ inline int ksl_linalg_symmetricMatrixInverse_rmo(double* restrict A, const int n) { int status = ksl_linalg_ldlt_rmo(A, n); if(status > 0) { return status; } for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { A[i * n + j] = 0.0; } } for(int i = 0; i < n; i++) { A[i * n + i] = 1.0 / A[i * n + i]; } for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1 for(int j = n - 1; j > i; j--) { // j = n:-1:i+1 for(int k = j; k > i; k--) { // k = j:-1:i+1 A[i * n + j] -= A[k * n + i] * A[k * n + j]; // A(i,j) = A(i,j) - A(k,i)*A(k,j); } } } for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1 for(int j = 0; j <= i; j++) { // j = 1:1:i for(int k = i + 1; k < n; k++) { // k = i+1:1:n A[j * n + i] -= A[j * n + k] * A[k * n + i]; // A(j,i) = A(j,i) - A(j,k)*A(k,i); } } } for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { A[j * n + i] = A[i * n + j]; } } return 0; } // inline int ksl_linalg_symmetricMatrixInverse_rmo(double* restrict A, const // int n) { // double A_inverse[n * n]; // double a[n]; // // int status = ksl_linalg_ldlt_rmo(A, n); // if(status > 0) { // return status; // } // for(int i = 0; i < n; i++) { // memset(a, 0, n * sizeof(double)); // a[i] = 1.0; // ksl_linalg_ldlt_solve_rmo(A, a, &A_inverse[i * n + 0], n); // } // memcpy(A, A_inverse, n * n * sizeof(double)); // return 0; // } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*! @brief Column Major Order LU Decomposition with complete row and column pivoting ksl_linalg_lu_full_cmo factors a double precision matrix, A[rowDim * colDim], stored in Column Major Order using full row and column pivoting. Matrix A need not have full row or column rank. The integer variable 'rank' represents the matrix rank and internally is always one less than the true rank to be consistent with C's indexing from zero. Upon return from the function, rank will be set to the correct value. The lower triangular (rank+1) by (rank+1) Lr matrix, except its unity diagonal, is stored below the diagonal in A[0:rank][0:rank]. The upper triangular (rank+1) by (rank+1) Ur matrix is stored on and above the diagonal in A[0:rank][0:rank]. Following the first major matrix decomposition step, A[0:rank][rank+1:colDim] stores the residual matrix UR and A[rank+1:rowDim][0:rank] stores the residual matrix LR. The following operations on this matrix are optionally performed after ksl_linalg_lu_full_cmo() has factored A. ksl_linalg_lu_setBMatrix_cmo() computes and stores B = inverse(Ur)*UR and stores it back in A[0:rank][rank+1:colDim]. ksl_linalg_lu_setCMatrix_cmo() computes and stores C = LR*inverse(Lr) and stores it back in A[rank+1:rowDim][0:rank]. The remaining A[rank+1:rowDim][rank+1:colDim] submatrix contains numbers whose absolute values are all smaller than eps times the absolutely largest entry in the original matrix. This part of the matrix is not used. @param rowDim [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param *A [in/out] matrix to be factored with dimensions A[0:rowDim-1][0:colDim-1], LU factors are overwritten in original matrix @param eps [in] input tolerance on the order of machine roundoff. @param pr [out] output row permutation array with dimensions pr[0:rowDim-1] @param pc [out] output column permutation array with dimensions pc[0:colDim-1] @return rank of matrix A */ int ksl_linalg_lu_full_cmo(const int rowDim, const int colDim, double* restrict A, const double eps, int* restrict pr, int* restrict pc) { // printf("Jacobian matrix in fullFactor_LU\n"); // for(int i = 0; i < rowDim; i++) { // for(int j = 0; j < colDim; j++) // printf("% 2.4f ", A[j * rowDim + i]); // printf("\n"); // } int rank; /* (rank+1) is the matrix rank */ int pivotRow; /* row with current pivotal element */ int pivotCol; /* column with current pivotal element */ double pivot = 0.0; /* current pivotal element, holds the current pivotal element value */ double tol; /* tolerance for checking residual matrix infinity norm against */ double save; /* variable for holding intermediate results*/ double size = rowDim * colDim; /*overall size of matrix */ /* Return failure if a bad row or column dimension was found. */ if((rowDim <= 0) || (colDim <= 0)) { return (-1); } /* Consistent with C-indexing, rank always has a value of one less than the true value. rank+1 is returned. */ rank = -1; /* initialize for indexing */ /* Search through the entire A matrix to find the absolutely largest element for assigning to pivot. Save that row and column number in pivotRow and pivotCol. Also intialize the row permutation array pr. */ #ifdef KSL_WITH_BLAS_ int index = cblas_idamax(size, A, 1); #else int index = ksl_maxIndex(size, A); #endif // div_t result = div(index, colDim); // pivotRow = result.quot; // pivotCol = result.rem; pivotCol = index / rowDim; pivotRow = index - pivotCol * rowDim; pivot = A[index]; // printf("pivotRow: %d, pivotCol: %d\n", pivotRow, pivotCol); /* Initialize the column permutation array. */ for(int col = 0; col < colDim; col++) { pc[col] = col; } for(int row = 0; row < rowDim; row++) { pr[row] = row; } /* Set tolerance to check all zero-elements against. pivot = infinity norm of A. */ tol = fabs(eps * pivot); /* Major loop to permute and factor the matrix. Generate factors column by column, so outer loop sweeps over columns. */ for(int col = 0; col < colDim; col++) { /* If the current pivotal element is <= tol, the remaining submatrix is zero and factorization is complete. The else statement for the following if test breaks out of this loop so not to waste time going through the remaining columns. */ if(fabs(pivot) > tol) { /* Increase rank for the current column. */ ++rank; /* pivotRow can never be less than rank. If pivotRow==rank, then no permutation is needed. If pivotRow>rank, then need to swap rows. */ if(pivotRow > rank) { /* Swap entire rows A[rank][:] and A[pivotRow][:]. This also swaps rows in the LR matrix to this point. swap rows: N = colDim stride = rowDim Start of replaced row is A + rank & stride is rowDim Start of pivot row is A + pivotRow & stride is rowDim */ #ifdef KSL_WITH_BLAS_ cblas_dswap(colDim, A + rank, rowDim, A + pivotRow, rowDim); #else ksl_swapArray(colDim, A + rank, rowDim, A + pivotRow, rowDim); #endif /* Swap row permutation entries pr[rank] and pr[pivotRow] to reflect row swaps in A. */ ksl_swapi(pr + rank, pr + pivotRow); } /* pivotCol can never be less than rank. If pivotCol==rank, then no permutation is needed. If pivotCol>rank, then need to swap columns. */ if(pivotCol > rank) { // printf("rank: %d, pivotCol: %d\n", rank, pivotCol); // printf("colDim %d\n", colDim); /* Swap entire columns A[:][rank] and A[:][pivotCol]. This also swaps columns in the UR matrix to this point. swap columns: N = rowDim stride = 1 Start of replaced column is A + rowDim * rank & stride is 1 Start of pivot column is A + rowDim * pivotCol & stride is 1 */ #ifdef KSL_WITH_BLAS_ cblas_dswap(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1); #else ksl_swapArray(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1); #endif /* Swap column permutation entries pc[rank] and pr[pivotCol] to reflect column swaps. */ ksl_swapi(pc + rank, pc + pivotCol); } /* rank cannot be > rowDim-1. If rank < rowDim-1 there is still some processing left to do. If rank == rowDim-1, there is only a 1 on the diagonal of this column of Lr. This loop factors the matrix and searches for a new pivotal element for the next factorization step. */ if(rank < rowDim - 1) { /* Copy the current pivotal element into save so new pivotal element can be stored back in pivot. */ save = pivot; pivot = 0; /* Need only process the rows from rank+1 to rowDim. */ for(int i = rank + 1; i < rowDim; i++) { /* Evaluate the current entry in the L matrix. (rank is always one less than the true rank.) The first rank columns of the A matrix are complete. Now working in column rank of the A matrix, so the offset to the start of the working column is rank * rowDim. */ A[rank * rowDim + i] /= save; /* rank cannot be >= colDim. If rank < colDim there is still some processing left to do. If rank == colDim-1, only a pivot remains on the diagonal. */ if(rank < colDim) { /* This next loop computes the remaining U matrix, searches for the largest pivotal element, and remembers the new pivotal element row and colum. */ for(int j = rank + 1; j < colDim; j++) { A[j * rowDim + i] -= A[rank * rowDim + i] * A[j * rowDim + rank]; if(fabs(A[j * rowDim + i]) > fabs(pivot)) { pivot = A[j * rowDim + i]; pivotRow = i; pivotCol = j; } /*End if*/ } /*End for j*/ } /*End if rank*/ } /*Endfor i = rank+1*/ } /*Endif (rank<rowDim-1)*/ else { break; /*No more rows to process.*/ } } /*End if*/ else { break; /*Done if remainder of matrix is at noise level.*/ } } /*End for col*/ return (rank + 1); } /*! @brief Column Major Order LU Decomposition with complete row and column pivoting with one specified coordinate ksl_linalg_lu_full_specified_cmo factors a double precision matrix, A[rowDim * colDim], stored in Column Major Order using full row and column pivoting. Matrix A need not have full row or column rank. The integer variable 'rank' represents the matrix rank and internally is always one less than the true rank to be consistent with C's indexing from zero. Upon return from the function, rank will be set to the correct value. The lower triangular (rank+1) by (rank+1) Lr matrix, except its unity diagonal, is stored below the diagonal in A[0:rank][0:rank]. The upper triangular (rank+1) by (rank+1) Ur matrix is stored on and above the diagonal in A[0:rank][0:rank]. Following the first major matrix decomposition step, A[0:rank][rank+1:colDim] stores the residual matrix UR and A[rank+1:rowDim][0:rank] stores the residual matrix LR. ksl_linalg_lu_setBMatrix_cmo() computes and stores B = inverse(Ur)*UR and stores it back in A[0:rank][rank+1:colDim]. ksl_linalg_lu_setCMatrix_cmo() computes and stores C = LR*inverse(Lr) and stores it back in A[rank+1:rowDim][0:rank]. The remaining A[rank+1:rowDim][rank+1:colDim-1] submatrix contains numbers whose absolute values are all smaller than eps times the absolutely largest entry in the original matrix. This part of the matrix is not used. The remainig A[rank+1:rowDim][colDim] submatrix could contain numbers whose absolute values are greater than eps times the absolutely largest entry in the original matrix. Adding a check here would be one way to assert that the specified variable has sufficient mobility. @param rowDim input row dimension of matrix A. @param colDim input column dimension of matrix A. @param **A input/output matrix to be factored with dimensions A[0:rowDim-1][0:colDim-1]: @param eps input tolerance on the order of machine roundoff. @param pr output row permutation array with dimensions pr[0:rowDim-1] @param pc output column permutation array with dimensions pc[0:colDim-1] @return rank of matrix A */ int ksl_linalg_lu_full_specified_cmo(const int rowDim, const int colDim, double* restrict A, double eps, int* restrict pr, int* restrict pc, const int specifiedIndex) { // printf("Jacobian matrix in fullFactor_LU\n"); // for(int i = 0; i < rowDim; i++) { // for(int j = 0; j < colDim; j++) // printf("% 2.4f ", A[j * rowDim + i]); // printf("\n"); // } int rank; /* (rank+1) is the matrix rank */ int pivotRow; /* row with current pivotal element */ int pivotCol; /* column with current pivotal element */ double pivot = 0.0; /* current pivotal element, holds the current pivotal element */ double tol; /* tolerance for checking residual matrix infinity norm against */ double save; /* variable for holding intermediate results*/ double size = rowDim * colDim; /*overall size of matrix */ /* Return failure if a bad row or column dimension was found. */ if((rowDim <= 0) || (colDim <= 1)) { return (-1); } /* Consistent with C-indexing, rank always has a value of one less than the true value. rank+1 is returned. */ rank = -1; /* initialize for indexing */ /* Initialize permutation arrays */ for(int row = 0; row < rowDim; row++) { pr[row] = row; } for(int col = 0; col < colDim; col++) { pc[col] = col; } /* Swap the specified column to the last position in the input matrix Swap entire columns A[:][specifiedIndex] and A[:][colDim - 1]. swap columns: N = rowDim stride = 1 Start of specefied column is A + rowDim * specifiedIndex & stride 1 Start of last column is A + rowDim * (colDim - 1) & stride is 1 */ if(specifiedIndex != colDim - 1) { #ifdef KSL_WITH_BLAS cblas_dswap(rowDim, A + rowDim * specifiedIndex, 1, A + rowDim * (colDim - 1), 1); #else ksl_swapArray(rowDim, A + rowDim * specifiedIndex, 1, A + rowDim * (colDim - 1), 1); #endif /* Swap column permutation entries pc[] and pc[pivotRow] to reflect row swaps in A. */ ksl_swapi(pc + specifiedIndex, pc + colDim - 1); } /* Search through matrix A except the last column to find the absolutely largest element for assigning to pivot. Save that row and column number in pivotRow and pivotCol. This could cause numerical problems if the last column contains one or more entries substantially absolutely larger than all other entries in A. */ pivot = A[0]; pivotRow = 0; pivotCol = 0; for(int col = 0; col < colDim - 1; col++) { for(int row = 0; row < rowDim; row++) { if(fabs(A[col * rowDim + row]) > fabs(pivot)) { pivot = A[col * rowDim + row]; pivotRow = row; pivotCol = col; } } } // printf("pivotRow: %d, pivotCol: %d\n", pivotRow, pivotCol); /* Set tolerance to check all zero-elements against. pivot = infinity norm of A. */ tol = fabs(eps * pivot); /* Major loop to permute and factor the matrix. Generate factors column by column, so outer loop sweeps over columns. */ for(int col = 0; col < colDim; col++) { /* If the current pivotal element is <= tol, the remaining submatrix is zero and factorization is complete. The else statement for the following if test breaks out of this loop so not to waste time going through the remaining columns. */ if(fabs(pivot) > tol) { /* Increase rank for the current column. */ ++rank; /* pivotRow can never be less than rank. If pivotRow==rank, then no permutation is needed. If pivotRow>rank, then need to swap rows. */ if(pivotRow > rank) { /* Need to swap entire row A[rank][:] and A[pivotRow][:]. This also swaps rows in the Lr matrix to this point. swap rows: N = colDim stride = rowDim Start of replaced row is A + rank & stride is rowDim Start of pivot row is A + pivotRow & stride is rowDim */ #ifdef KSL_WITH_BLAS_ cblas_dswap(colDim, A + rank, rowDim, A + pivotRow, rowDim); #else ksl_swapArray(colDim, A + rank, rowDim, A + pivotRow, rowDim); #endif /* Swap row permutation entries pr[rank] and pr[pivotRow] to reflect row swaps in A. */ ksl_swapi(pr + rank, pr + pivotRow); } /* pivotCol can never be less than rank. If pivotCol==rank, then no permutation is needed. If pivotCol>rank, then need to swap columns. */ if(pivotCol > rank) { // printf("rank: %d, pivotCol: %d\n", rank, pivotCol); // printf("colDim %d\n", colDim); /* Swap entire columns A[:][rank] and A[:][pivotCol]. This also swaps columns in the UR matrix to this point. swap columns: N = rowDim stride = 1 Start of replaced column is A + rowDim * rank & stride is 1 Start of pivot column is A + rowDim * pivotCol & stride is 1 */ #ifdef KSL_WITH_BLAS_ cblas_dswap(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1); #else ksl_swapArray(rowDim, A + rowDim * rank, 1, A + rowDim * pivotCol, 1); #endif /* Swap column permutation entries pc[rank] and pr[pivotCol] to reflect column swaps. */ ksl_swapi(pc + rank, pc + pivotCol); } /* rank cannot be > rowDim-1. If rank < rowDim-1 there is still some processing left to do. If rank == rowDim-1, there is only a 1 on the diagonal of this column of Lr. This loop factors the matrix and searches for a new pivotal element for the next factorization step. */ if(rank < rowDim - 1) { /* Copy the current pivotal element into save so new pivotal element can be stored back in pivot. */ save = pivot; pivot = 0; /* Need only process the rows from rank+1 to rowDim. */ for(int i = rank + 1; i < rowDim; i++) { /* Evaluate the current entry in the L matrix.*/ A[rank * rowDim + i] /= save; /* rank cannot be >= colDim. If rank < colDim there is still some processing left to do. If rank == colDim-1, only a pivot remains on the diagonal. */ if(rank < colDim) { /* This next loop computes the remaining U matrix, searches for the largest pivotal element, and remembers the new pivotal element row and colum. */ for(int j = rank + 1; j < colDim; j++) { A[j * rowDim + i] -= A[rank * rowDim + i] * A[j * rowDim + rank]; } for(int j = rank + 1; j < colDim - 1; j++) { if(fabs(A[j * rowDim + i]) > fabs(pivot)) { pivot = A[j * rowDim + i]; pivotRow = i; pivotCol = j; } /*End if*/ } /*End for j*/ } /*End if rank*/ } /*Endfor i = rank+1*/ } /*Endif (rank<rowDim-1)*/ else { break; /*No more rows to process.*/ } } /*End if*/ else { break; /*Done if remainder of matrix is at noise level.*/ } } /*End for col*/ return (rank + 1); } /*! @brief *Fast* Column Major Order LU Decomposition with no row or column pivoting for a rectangular matrix This function LU factors a double precision matrix, A[rank][colDim], using no row or column pivoting. This function should be used only if the left rank by rank submatrix is known to be nonsingular. rank <= colDim or error. The lower triangular rank by rank Lr matrix, except the unity diagonal, is stored below the diagonal in A[0:rank-1][0:rank-1]. The upper triangular rank by rank Ur matrix is stored on and above the diagonal in A[0:rank-1][0:rank-1]. Note that this minimal algorithm variation does not compute the product B = inverse(Ur)*UR @param rank [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param *A [in/out] matrix to be factored with dimensions A[0:rank-1][0:colDim-1]: */ inline void ksl_linalg_lu_cmo(const int rank, const int colDim, double* restrict A) { if(rank > colDim) { // Error message & exit } /* Major loop to factor the matrix. Generate factors column by column */ for(int row = 0; row < rank; row++) { /* i iterates over rows of A, up to rank-1 */ for(int i = row + 1; i < rank; i++) { /* Evaluate the current entry in the L matrix.*/ A[row * rank + i] /= A[row * rank + row]; /* Compute U matrix */ for(int j = row + 1; j < colDim; j++) { A[j * rank + i] -= A[row * rank + i] * A[j * rank + row]; } } } } /*! @brief compute Column Major Order B matrix (inverse(Ur) * UR) This block overwrites UR with inverse(Ur) * UR If rank == 0 or rank == colDim nothing to process, so exit with message. This loop computes A[0:rank-1][rank:colDim-1] = inverse(Ur)*UR where UR is stored in A[0:rank-1][rank:colDim-1] and Ur is stored in upper part of A[0:rank-1][0:rank-1]. i is the row number in Ur. j is the column number in Ur & row number in UR. k is the column number in UR. @param rowDim [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param rank [in] rank of matrix A. @param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]: */ inline void ksl_linalg_lu_setBMatrix_cmo(const int rowDim, const int colDim, const int rank, double* restrict A) { if(rank > 0 && rank < colDim) { for(int i = rank - 1; i > -1; i--) { /* rows of B */ for(int k = rank; k < colDim; k++) { /* columns of B */ double save = 0; for(int j = rank - 1; j > i; j--) { /* columns of Ur */ save += A[j * rowDim + i] * A[k * rowDim + j]; } A[k * rowDim + i] = (A[k * rowDim + i] - save) / A[i * rowDim + i]; } } } else { // Error & do something. } } /*! @brief compute Column Major Order C matrix This block overwrites LR with LR*inverse(Lr) If rank==1, the Lr matrix is a 1 by 1 identity matrix, so there is nothing to do here. This loop computes A[rank:rowDim-1][0:rank-1]=LR*inverse(Lr) where LR is stored in A[rank:rowDim-1][0:rank-1] and Lr is stored in A[0:rank-1][0:rank-1]. j is the column number in LR. It ends at 1 because the diagonal entry in row 0 of Lr is 1. i is the row number in LR. k is the column number in Lr @param rowDim [in] row dimension of matrix A. @param colDim [in] column dimension of matrix A. @param rank [in] rank of matrix A. @param *A [in/out] matrix with dimensions A[0:rowDim-1][0:colDim-1]: */ void ksl_linalg_lu_setCMatrix_cmo(int rowDim, int colDim, int rank, double* A) { if(rank > 1) { for(int j = rank - 1; j > 0; j--) { for(int i = rowDim - 1; i > rank - 1; i--) { for(int k = 0; k < j; k++) A[k * rowDim + i] -= A[j * rowDim + i] * A[k * rowDim + j]; } } } else { // Error & do something. } } /*! @brief computes the Column Major Order L D L^T decomposition of a symmetric matrix without pivoting returns the matrix L D L^T in the original matrix A @param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]: @param n row and column dimension of matrix A. */ int ksl_linalg_ldlt_cmo(double* restrict A, const int n) { for(int k = 0; k < n; k++) { double pivot_inv = A[k * n + k]; if(pivot_inv > 0.0) { pivot_inv = 1.0 / A[k * n + k]; } else { return k + 1; } for(int j = k + 1; j < n; j++) { A[j * n + k] = A[k * n + j]; A[k * n + j] *= pivot_inv; } for(int j = k + 1; j < n; j++) { for(int i = k + 1; i < j + 1; i++) { A[i * n + j] -= A[k * n + j] * A[i * n + k]; } } } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { A[j * n + i] = A[i * n + j]; } } return 0; } /*! @brief perform Column Major Order Cholesky (L * L^T) decomposition of a symmetric matrix without pivoting returns the matrix factor L in the lower triangular portion of matrix A @param *A [in/out] matrix with dimensions A[0:n-1][0:n-1]: @param n row and column dimension of matrix A. */ int ksl_linalg_cholesky_cmo(double* restrict A, const int n) { for(int k = 0; k < n; k++) { if(A[k * n + k] > 0.0) { A[k * n + k] = sqrt(A[k * n + k]); } else { return k + 1; } double pivot_inv = 1.0 / A[k * n + k]; for(int j = k + 1; j < n; j++) { A[k * n + j] *= pivot_inv; } for(int j = k + 1; j < n; j++) { for(int i = k + 1; i < j + 1; i++) { A[i * n + j] -= A[k * n + j] * A[k * n + i]; } } } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { A[j * n + i] = A[i * n + j]; } } return 0; } /*! @brief used to solve a system of equations L * y = b for y using forward elimination where L IS Column Major Order unit lower triangular y = L^-1 * b @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *y [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_ldlt_forwardElimination_cmo(const double* restrict L, const double* restrict b, double* restrict y, const int n) { for(int i = 0; i < n; i++) { y[i] = b[i]; } for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { y[j] -= L[i * n + j] * y[i]; } } } /*! @brief used to solve a system of equations L^T * x = y using backward substitution where L IS Column Major Order unit lower triangular x = L^-T * y @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *y [in] n by 1 column of right-hand side y[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], y[], x[]: */ inline void ksl_linalg_ldlt_backwardSubstitution_cmo(const double* restrict L, const double* restrict y, double* restrict x, const int n) { for(int i = n - 1; i > -1; i--) { x[i] = y[i]; } for(int i = n - 2; i > -1; i--) { for(int j = n - 1; j > i; j--) { x[i] -= L[i * n + j] * x[j]; } } } /*! @brief used to solve a system of equations L * y = b for y using forward elimination where L is Column Major Order and IS NOT unit lower triangular y = L^-1 * b @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *y [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_cholesky_forwardElimination_cmo(const double* restrict L, const double* restrict b, double* restrict y, const int n) { for(int i = 0; i < n; i++) { y[i] = b[i]; } for(int i = 0; i < n; i++) { y[i] /= L[i * n + i]; for(int j = i + 1; j < n; j++) { y[j] -= L[j * n + i] * y[i]; } } } /*! @brief used to solve a system of equations L^T * x = y using backward substitution where L is Column Major Order and IS NOT unit lower triangular x = L^-T * y @param *L [in] n by n matrix L[0:n-1][0:n-1]: @param *y [in] n by 1 column of right-hand side y[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], y[], x[]: */ inline void ksl_linalg_cholesky_backwardSubstitution_cmo(const double* restrict L, const double* restrict y, double* restrict x, const int n) { for(int i = 0; i < n; i++) { x[i] = y[i]; } x[n - 1] /= L[(n - 1) * n + (n - 1)]; for(int i = n - 2; i > -1; i--) { for(int j = i + 1; j < n; j++) { x[i] -= L[i * n + j] * x[j]; } x[i] /= L[i * n + i]; } } /*! @brief solve the system of equations A * x = b where A is Column Major Order and a symmetric positive definite matrix A ksl_linalg_ldlt_cmo must be called on A prior to calling this function @param *A [in] n by n matrix A[0:n-1][0:n-1] containing Choleski-factored matrix: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: */ inline void ksl_linalg_ldlt_solve_cmo(const double* restrict A, double* const restrict b, double* restrict x, const int n) { double y[n]; ksl_linalg_ldlt_forwardElimination_cmo(A, b, y, n); for(int i = 0; i < n; i++) { y[i] /= A[i * n + i]; } ksl_linalg_ldlt_backwardSubstitution_cmo(A, y, x, n); } /*! @brief solve the system of equations A * x = b where A is Column Major Order and a symmetric positive definite matrix A @param *A [in] n by n matrix A[0:n-1][0:n-1] containing Choleski-factored matrix: @param *b [in] n by 1 column of right-hand side y[0:n-1]. @param *x [out] n by 1 column of unknowns. @param n [in] dimension of L[][], b[], y[]: ksl_linalg_cholesky must be called on A prior to calling this function */ inline void ksl_linalg_cholesky_solve_cmo(const double* restrict A, const double* restrict b, double* restrict x, const int n) { double y[n]; ksl_linalg_cholesky_forwardElimination_cmo(A, b, y, n); ksl_linalg_cholesky_backwardSubstitution_cmo(A, y, x, n); } /*! @brief compute inverse of a symmetric positive definite matrix A where A and A_inverse are in Column Major Order. */ inline int ksl_linalg_symmetricMatrixInverse_cmo(double* restrict A, const int n) { int status = ksl_linalg_ldlt_cmo(A, n); if(status > 0) { return status; } for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { A[j * n + i] = 0.0; } } for(int i = 0; i < n; i++) { A[i * n + i] = 1.0 / A[i * n + i]; } for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1 for(int j = n - 1; j > i; j--) { // j = n:-1:i+1 for(int k = j; k > i; k--) { // k = j:-1:i+1 A[j * n + i] -= A[i * n + k] * A[j * n + k]; // A(j,i) = A(j,i) - A(i,k)*A(j,k); } } } for(int i = n - 2; i >= 0; i--) { // i = n-1:-1:1 for(int j = 0; j <= i; j++) { // j = 1:1:i for(int k = i + 1; k < n; k++) { // k = i+1:1:n A[i * n + j] -= A[k * n + j] * A[i * n + k]; // A(i,j) = A(i,j) - A(k,j)*A(k,i); } } } for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { A[i * n + j] = A[j * n + i]; } } return 0; } // inline int ksl_linalg_symmetricMatrixInverse_cmo(double* restrict A, const // int n) { // double A_inverse[n * n]; // double a[n]; // // int status = ksl_linalg_ldlt_cmo(A, n); // if(status > 0) { // return status; // } // for(int i = 0; i < n; i++) { // memset(a, 0, n * sizeof(double)); // a[i] = 1.0; // ksl_linalg_ldlt_solve_cmo(A, a, &A_inverse[i * n + 0], n); // } // memcpy(A, A_inverse, n * n * sizeof(double)); // return 0; // }
{ "alphanum_fraction": 0.5810988943, "avg_line_length": 32.5507319536, "ext": "c", "hexsha": "64185021cd9d9b8b4e5347764b016140682d5768", "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": "574b0121bcfca8e252a8bc8b55b25ee9775b1285", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ideaplexus/ksl", "max_forks_repo_path": "src/linalg.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "574b0121bcfca8e252a8bc8b55b25ee9775b1285", "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": "ideaplexus/ksl", "max_issues_repo_path": "src/linalg.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "574b0121bcfca8e252a8bc8b55b25ee9775b1285", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ideaplexus/ksl", "max_stars_repo_path": "src/linalg.c", "max_stars_repo_stars_event_max_datetime": "2019-01-22T05:52:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-22T05:52:08.000Z", "num_tokens": 18395, "size": 64483 }
/* A simple example program to square a number using GSL. */ #include <gsl/gsl_math.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { double x; char *startptr, *endptr; if (argc != 2) { fputs("Expected exactly one command line argument\n", stderr); return EXIT_FAILURE; } startptr = argv[1]; endptr = NULL; x = strtod(startptr, &endptr); if (startptr == endptr) { fputs("Expected command line argument to be a float\n", stderr); return EXIT_FAILURE; } x = gsl_pow_2(x); printf("%g\n", x); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5949367089, "avg_line_length": 19.75, "ext": "c", "hexsha": "04ea917f70dc15956ec1ee7598b67dd370513e81", "lang": "C", "max_forks_count": 110, "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:58:21.000Z", "max_forks_repo_forks_event_min_datetime": "2016-03-16T11:33:18.000Z", "max_forks_repo_head_hexsha": "83440f278c7c12c265c5e6d450305facc29f0a5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "luminartech/auditwheel", "max_forks_repo_path": "tests/integration/testpackage/testpackage/testprogram.c", "max_issues_count": 331, "max_issues_repo_head_hexsha": "83440f278c7c12c265c5e6d450305facc29f0a5e", "max_issues_repo_issues_event_max_datetime": "2022-03-25T01:30:27.000Z", "max_issues_repo_issues_event_min_datetime": "2016-02-01T19:19:31.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "luminartech/auditwheel", "max_issues_repo_path": "tests/integration/testpackage/testpackage/testprogram.c", "max_line_length": 72, "max_stars_count": 280, "max_stars_repo_head_hexsha": "83440f278c7c12c265c5e6d450305facc29f0a5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "luminartech/auditwheel", "max_stars_repo_path": "tests/integration/testpackage/testpackage/testprogram.c", "max_stars_repo_stars_event_max_datetime": "2022-03-26T05:28:26.000Z", "max_stars_repo_stars_event_min_datetime": "2016-02-07T18:41:15.000Z", "num_tokens": 168, "size": 632 }
#include <stdlib.h> #include <stddef.h> #include <assert.h> #include <stdio.h> #include <string.h> #include <cblas.h> #include "LCP_Solver.h" #include "debug.h" void numericsError(char * functionName, char* message) { char output[200] = "Numerics error - "; strcat(output, functionName); strcat(output, message); strcat(output, ".\n"); fprintf(stderr, "%s", output); exit(EXIT_FAILURE); } void prodNumericsMatrix(int sizeX, int sizeY, double alpha, const NumericsMatrix* const A, const double* const x, double beta, double* y) { assert(A); assert(x); assert(y); assert(A->size0 == sizeY); assert(A->size1 == sizeX); cblas_dgemv(CblasColMajor, CblasNoTrans, sizeY, sizeX, alpha, A->matrix0, sizeY, x, 1, beta, y, 1); } void deleteSolverOptions(SolverOptions* op) { if(op) { if (op->iparam != NULL) free(op->iparam); op->iparam = NULL; if (op->dparam != NULL) free(op->dparam); op->dparam = NULL; } } void lcp_lexicolemke(LinearComplementarityProblem* problem, double *zlem , double *wlem , int *info , SolverOptions* options) { /* matrix M of the lcp */ double * M = problem->M->matrix0; assert(M); /* size of the LCP */ int dim = problem->size; assert(dim>0); int dim2 = 2 * (dim + 1); int i, drive, block, Ifound; int ic, jc; int ITER; int nobasis; int itermax = options->iparam[0]; i=0; int n = problem->size; double *q = problem->q; while ((i < (n - 1)) && (q[i] >= 0.)) i++; if ((i == (n - 1)) && (q[n - 1] >= 0.)) { /* TRIVIAL CASE : q >= 0 * z = 0 and w = q is solution of LCP(q,M) */ for (int j = 0 ; j < n; j++) { zlem[j] = 0.0; wlem[j] = q[j]; } *info = 0; options->iparam[1] = 0; /* Number of iterations done */ options->dparam[1] = 0.0; /* Error */ if (options->verboseMode > 0) printf("lcp_lexicolemke: found trivial solution for the LCP (positive vector q => z = 0 and w = q). \n"); return ; } double z0, zb, dblock; double pivot, tovip; double tmp; int *basis; double** A; /*output*/ options->iparam[1] = 0; /* Allocation */ basis = (int *)malloc(dim * sizeof(int)); A = (double **)malloc(dim * sizeof(double*)); for (ic = 0 ; ic < dim; ++ic) A[ic] = (double *)malloc(dim2 * sizeof(double)); /* construction of A matrix such that * A = [ q | Id | -d | -M ] with d = (1,...1) */ /* We need to init only the part corresponding to Id */ for (ic = 0 ; ic < dim; ++ic) for (jc = 1 ; jc <= dim; ++jc) A[ic][jc] = 0.0; for (ic = 0 ; ic < dim; ++ic) for (jc = 0 ; jc < dim; ++jc) A[ic][jc + dim + 2] = -M[dim * jc + ic]; assert(problem->q); for (ic = 0 ; ic < dim; ++ic) A[ic][0] = problem->q[ic]; for (ic = 0 ; ic < dim; ++ic) A[ic][ic + 1 ] = 1.0; for (ic = 0 ; ic < dim; ++ic) A[ic][dim + 1] = -1.0; DEBUG_PRINT("total matrix\n"); DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i) { for(unsigned int j = 0 ; j < dim2; ++j) { DEBUG_PRINTF("%1.2e ", A[i][j]) } DEBUG_PRINT("\n")}); /* End of construction of A */ Ifound = 0; for (ic = 0 ; ic < dim ; ++ic) basis[ic] = ic + 1; drive = dim + 1; block = 0; z0 = A[block][0]; ITER = 0; /* Start research of argmin lexico */ /* With this first step the covering vector enter in the basis */ for (ic = 1 ; ic < dim ; ++ic) { zb = A[ic][0]; if (zb < z0) { z0 = zb; block = ic; } else if (zb == z0) { for (jc = 0 ; jc < dim ; ++jc) { dblock = A[block][1 + jc] - A[ic][1 + jc]; if (dblock < 0) { break; } else if (dblock > 0) { block = ic; break; } } } } /* Stop research of argmin lexico */ DEBUG_PRINTF("Pivoting %i and %i\n", block, drive); pivot = A[block][drive]; tovip = 1.0 / pivot; /* Pivot < block , drive > */ A[block][drive] = 1; for (ic = 0 ; ic < drive ; ++ic) A[block][ic] = A[block][ic] * tovip; for (ic = drive + 1 ; ic < dim2 ; ++ic) A[block][ic] = A[block][ic] * tovip; /* */ for (ic = 0 ; ic < block ; ++ic) { tmp = A[ic][drive]; for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -= tmp * A[block][jc]; } for (ic = block + 1 ; ic < dim ; ++ic) { tmp = A[ic][drive]; for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -= tmp * A[block][jc]; } nobasis = basis[block]; basis[block] = drive; DEBUG_EXPR_WE( DEBUG_PRINT("new basis: ") for (unsigned int i = 0; i < dim; ++i) { DEBUG_PRINTF("%i ", basis[i])} DEBUG_PRINT("\n")); DEBUG_PRINT("total matrix\n"); DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i) { for(unsigned int j = 0 ; j < dim2; ++j) { DEBUG_PRINTF("%1.2e ", A[i][j]) } DEBUG_PRINT("\n")}); while (ITER < itermax && !Ifound) { ++ITER; if (nobasis < dim + 1) drive = nobasis + (dim + 1); else if (nobasis > dim + 1) drive = nobasis - (dim + 1); DEBUG_PRINTF("driving variable %i \n", drive); /* Start research of argmin lexico for minimum ratio test */ pivot = 1e20; block = -1; for (ic = 0 ; ic < dim ; ++ic) { zb = A[ic][drive]; if (zb > 0.0) { z0 = A[ic][0] / zb; if (z0 > pivot) continue; if (z0 < pivot) { pivot = z0; block = ic; } else { for (jc = 1 ; jc < dim + 1 ; ++jc) { assert(block >=0 && "lcp_lexicolemke: block <0"); dblock = A[block][jc] / pivot - A[ic][jc] / zb; if (dblock < 0.0) break; else if (dblock > 0.0) { block = ic; break; } } } } } if (block == -1) { Ifound = 1; DEBUG_PRINT("The pivot column is nonpositive !\n" "It either means that the algorithm failed or that the LCP is infeasible\n" "Check the class of the M matrix to find out the meaning of this\n"); break; } if (basis[block] == dim + 1) Ifound = 1; /* Pivot < block , drive > */ pivot = A[block][drive]; tovip = 1.0 / pivot; A[block][drive] = 1; for (ic = 0 ; ic < drive ; ++ic) A[block][ic] = A[block][ic] * tovip; for (ic = drive + 1 ; ic < dim2 ; ++ic) A[block][ic] = A[block][ic] * tovip; /* */ for (ic = 0 ; ic < block ; ++ic) { tmp = A[ic][drive]; for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -= tmp * A[block][jc]; } for (ic = block + 1 ; ic < dim ; ++ic) { tmp = A[ic][drive]; for (jc = 0 ; jc < dim2 ; ++jc) A[ic][jc] -= tmp * A[block][jc]; } nobasis = basis[block]; basis[block] = drive; DEBUG_EXPR_WE( DEBUG_PRINT("new basis: ") for (unsigned int i = 0; i < dim; ++i) { DEBUG_PRINTF("%i ", basis[i])} DEBUG_PRINT("\n")); DEBUG_PRINT("total matrix\n"); DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i) { for(unsigned int j = 0 ; j < dim2; ++j) { DEBUG_PRINTF("%1.2e ", A[i][j]) } DEBUG_PRINT("\n")}); } /* end while*/ DEBUG_EXPR_WE( DEBUG_PRINT("new basis: ") for (unsigned int i = 0; i < dim; ++i) { DEBUG_PRINTF("%i ", basis[i])} DEBUG_PRINT("\n")); DEBUG_PRINT("total matrix\n"); DEBUG_EXPR_WE(for (unsigned int i = 0; i < dim; ++i) { for(unsigned int j = 0 ; j < dim2; ++j) { DEBUG_PRINTF("%1.2e ", A[i][j]) } DEBUG_PRINT("\n")}); for (ic = 0 ; ic < dim; ++ic) { drive = basis[ic]; if (drive < dim + 1) { zlem[drive - 1] = 0.0; wlem[drive - 1] = A[ic][0]; } else if (drive > dim + 1) { zlem[drive - dim - 2] = A[ic][0]; wlem[drive - dim - 2] = 0.0; } } options->iparam[1] = ITER; if (Ifound) *info = 0; else *info = 1; free(basis); for (i = 0 ; i < dim ; ++i) free(A[i]); free(A); } int linearComplementarity_driver(LinearComplementarityProblem* problem, double *z , double *w, SolverOptions* options) { /******************** * 0 - Check inputs * ********************/ if (options == NULL) numericsError("lcp_driver", "null input for solver options"); if (problem == NULL || z == NULL || w == NULL) numericsError("lcp_driver", "null input for LinearComplementarityProblem and/or unknowns (z,w)"); int NoDefaultOptions = options->isSet; /* true(1) if the SolverOptions structure has been filled in else false(0) */ if (NoDefaultOptions == 0) { numericsError("lcp_driver_DenseMatrix", "options for solver have not been set"); } if (options->verboseMode > 0) printSolverOptions(options); /* Output info. : 0: ok - >0: problem (depends on solver) */ int info = -1; /****************************************** * 1 - Check for trivial solution ******************************************/ int i = 0; int n = problem->size; double *q = problem->q; /* if (!((options->solverId == SICONOS_LCP_ENUM) && (options->iparam[0] == 1 )))*/ { while ((i < (n - 1)) && (q[i] >= 0.)) i++; if ((i == (n - 1)) && (q[n - 1] >= 0.)) { /* TRIVIAL CASE : q >= 0 * z = 0 and w = q is solution of LCP(q,M) */ for (int j = 0 ; j < n; j++) { z[j] = 0.0; w[j] = q[j]; } info = 0; options->dparam[1] = 0.0; /* Error */ if (options->verboseMode > 0) printf("LCP_driver_DenseMatrix: found trivial solution for the LCP (positive vector q => z = 0 and w = q). \n"); return info; } } /************************************************* * 2 - Call Lemke solver (if no trivial sol.) *************************************************/ if (options->verboseMode == 1) printf(" ========================== Call Lemke solver for Linear Complementarity problem ==========================\n"); /****** Lemke algorithm ******/ /* IN: itermax OUT: iter */ lcp_lexicolemke(problem, z , w , &info , options); /************************************************* * 3 - Computes w = Mz + q and checks validity *************************************************/ if (options->filterOn > 0) { int info_ = lcp_compute_error(problem, z, w, options->dparam[0], &(options->dparam[1]), options->verboseMode); if (info <= 0) /* info was not setor the solver was happy */ info = info_; } return info; } void lcp_compute_error_only(unsigned int n, double *z , double *w, double * error) { /* Checks complementarity */ *error = 0.; double zi, wi; for (unsigned int i = 0 ; i < n ; i++) { zi = z[i]; wi = w[i]; if (zi < 0.0) { *error += -zi; if (wi < 0.0) *error += zi * wi; } if (wi < 0.0) *error += -wi; if ((zi > 0.0) && (wi > 0.0)) *error += zi * wi; } } int lcp_compute_error(LinearComplementarityProblem* problem, double *z , double *w, double tolerance, double * error, int verbose) { /* Checks inputs */ if (problem == NULL || z == NULL || w == NULL) numericsError("lcp_compute_error", "null input for problem and/or z and/or w"); /* Computes w = Mz + q */ int incx = 1, incy = 1; unsigned int n = problem->size; cblas_dcopy(n , problem->q , incx , w , incy); // w <-q prodNumericsMatrix(n, n, 1.0, problem->M, z, 1.0, w); double normq = cblas_dnrm2(n , problem->q , incx); lcp_compute_error_only(n, z, w, error); *error = *error / (normq + 1.0); /* Need some comments on why this is needed */ if (*error > tolerance) { if (verbose > 0) printf(" Numerics - lcp_compute_error : error = %g > tolerance = %g.\n", *error, tolerance); return 1; } else return 0; } int linearComplementarity_lexicolemke_setDefaultSolverOptions(SolverOptions* options) { /* if (options->verboseMode > 0) */ /* { */ /* printf("Set the Default SolverOptions for the Lemke Solver\n"); */ /* } */ options->isSet = 1; options->filterOn = 1; options->iSize = 5; options->dSize = 5; options->iparam = (int *)calloc(options->iSize, sizeof(int)); options->dparam = (double *)calloc(options->dSize, sizeof(double)); options->verboseMode = 0; options->dparam[0] = 1e-6; options->iparam[0] = 10000; return 0; } void printSolverOptions(SolverOptions* options) { printf("\n ========== Numerics Non Smooth Solver parameters: \n"); if (options->isSet == 0) printf("The solver parameters have not been set. \t options->isSet = %i \n", options->isSet); else { printf("The solver parameters below have been set \t options->isSet = %i\n", options->isSet); printf("Name of the solver\t\t\t\t Lemke \n"); if (options->iparam != NULL) { printf("int parameters \t\t\t\t\t options->iparam\n"); printf("size of the int parameters\t\t\t options->iSize = %i\n", options->iSize); for (int i = 0; i < options->iSize; ++i) printf("\t\t\t\t\t\t options->iparam[%i] = %d\n", i, options->iparam[i]); } if (options->dparam != NULL) { printf("double parameters \t\t\t\t options->dparam\n"); printf("size of the double parameters\t\t\t options->dSize = %i\n", options->dSize); for (int i = 0; i < options->iSize; ++i) printf("\t\t\t\t\t\t options->dparam[%i] = %.6le\n", i, options->dparam[i]); } } printf("See Lemke documentation for parameters definition)\n"); printf("\n"); }
{ "alphanum_fraction": 0.5145768258, "avg_line_length": 27, "ext": "c", "hexsha": "06d261667033f9295a553048e6bbf8bfbe5a4863", "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": "653c19c6553643a15a535e82d763901c2fe90356", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "fairbrot/Cones.jl", "max_forks_repo_path": "src/LCP_Solver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "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": "fairbrot/Cones.jl", "max_issues_repo_path": "src/LCP_Solver.c", "max_line_length": 137, "max_stars_count": 4, "max_stars_repo_head_hexsha": "653c19c6553643a15a535e82d763901c2fe90356", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "fairbrot/Cones.jl", "max_stars_repo_path": "src/LCP_Solver.c", "max_stars_repo_stars_event_max_datetime": "2022-03-15T17:21:29.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-07T23:52:10.000Z", "num_tokens": 4384, "size": 13446 }
/* * rand.h * Random number generation * * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN * Copyright 2011-2015 * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan. * All rights reserved. * * Ver. 1.0.0 * Last modified on 2015.09.17 */ #ifndef DEF_RAND #define DEF_RAND #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void initRan(); void freeRan(); double ranInRange( double, double ); double enoise( double ); double interval( double ); #endif //
{ "alphanum_fraction": 0.6984126984, "avg_line_length": 17.3793103448, "ext": "h", "hexsha": "be253ea9c2ac08faf28eb6483fb0320b023dbc1c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_path": "C/rand.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_path": "C/rand.h", "max_line_length": 77, "max_stars_count": 7, "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_path": "C/rand.h", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "num_tokens": 153, "size": 504 }
/* gsl_histogram_copy.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 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 library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /*************************************************************** * * File gsl_histogram_copy.c: * Routine to copy an histogram. * Need GSL library and headers. * * Author: S. Piccardi * Jan. 2000 * ***************************************************************/ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> /* * gsl_histogram_copy: * copy the contents of an histogram into another */ int gsl_histogram_memcpy (gsl_histogram * dest, const gsl_histogram * src) { size_t n = src->n; size_t i; if (dest->n != src->n) { GSL_ERROR ("histograms have different sizes, cannot copy", GSL_EINVAL); } for (i = 0; i <= n; i++) { dest->range[i] = src->range[i]; } for (i = 0; i < n; i++) { dest->bin[i] = src->bin[i]; } return GSL_SUCCESS; } /* * gsl_histogram_duplicate: * duplicate an histogram creating * an identical new one */ gsl_histogram * gsl_histogram_clone (const gsl_histogram * src) { size_t n = src->n; size_t i; gsl_histogram *h; h = gsl_histogram_calloc_range (n, src->range); if (h == 0) { GSL_ERROR_VAL ("failed to allocate space for histogram struct", GSL_ENOMEM, 0); } for (i = 0; i < n; i++) { h->bin[i] = src->bin[i]; } return h; }
{ "alphanum_fraction": 0.6070763501, "avg_line_length": 23.347826087, "ext": "c", "hexsha": "848dcf10a31d33b80300c4bc5cc6c0734fbc988c", "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/histogram/copy.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/histogram/copy.c", "max_line_length": 70, "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/histogram/copy.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": 547, "size": 2148 }
#ifndef GBNET_RVNODE #define GBNET_RVNODE #include <string> #include <vector> #include <gsl/gsl_rng.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_rstat.h> extern gsl_rng *rng; namespace gbn { class RVNode { private: protected: public: unsigned int var_size, n_outcomes, n_stats; bool is_discrete; std::string name, uid, id; // // allow for several histograms in a single node. // // useful for multivariate distributions // gsl_histogram ** histogram; // online statistics gsl_rstat_workspace ** stats; RVNode (); virtual ~RVNode (); RVNode (std::string, std::string, bool, unsigned int, unsigned int); void print_id (); void burn_stats(); virtual double get_own_likelihood (); double get_own_loglikelihood (); virtual double get_children_loglikelihood (); double get_blanket_loglikelihood (); virtual void sample (gsl_rng *, bool=false); double mean(unsigned int = 0); double variance(unsigned int = 0); double chain_length(); }; } #endif
{ "alphanum_fraction": 0.572, "avg_line_length": 22.3214285714, "ext": "h", "hexsha": "14b194ed9d26e9b2663b762aa44ef6c533ce87a0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umbibio/gbnet", "max_forks_repo_path": "libgbnet/include/RVNode.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "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": "umbibio/gbnet", "max_issues_repo_path": "libgbnet/include/RVNode.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umbibio/gbnet", "max_stars_repo_path": "libgbnet/include/RVNode.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 256, "size": 1250 }
#pragma once #include <thrust/host_vector.h> #include <sstream> #include "IsingLattice2D.h" #include "class_mc_io.h" #include "Matrix.h" #include "MemTimeTester.h" extern "C" { #include "random.h" } #include <gsl/gsl_sf_zeta.h> #include <cmath> #include "obs_calc_fast.cuh" double real_trigamma_cmplxarg(double x, double y, int m, int l); class GeneralLRW{ //This is a more lightweight version of the long range wolff class, designed to be //more general - hopefully to admit the use of user-defined "test_spins" functions //so that it can be used for many different MC simulations. It does not hold the //lattice in order to keep the lattice easily available for GPU computations std::vector<std::vector<double>> interactions;//interaction matrix std::vector<std::vector<double>> interaction_sum;//values from interaction sum integral std::vector<double> site_sums;//absolute sum of interactions at each site double mag;//current magnetization double h; //applied field std::vector<spin> buffer;//holds the indices of spins to check std::vector<std::vector<int>> cluster;//0 at indices that are not in cluster, 1 at indices that are int cluster_size;//size of the cluster during a given MC step int cluster_mag;//total magnetization of the cluster void set_spin_boson_model_wc_exp(class_mc_params);//version for finite cutoff frequency with exponential tail void set_spin_boson_model_wc_hard(class_mc_params);//version for finite cutoff frequency with sharp cutoff void set_spin_boson_model(class_mc_params);//create interaction matrix for the spin boson model with infinite cutoff frequency void set_interaction_sum(); void set_site_sums(); MemTimeTester timer; inline double kernel_integrand(double alpha, int Nt, double rbv, double taub, double u){ //evaluate the integrand of the kernel of the spin-boson effective interactions return 2.0 * alpha / Nt / Nt * u * cos(rbv*u)*(exp(u*(-taub)) + exp(u*(taub - 1.0)))/(1 - exp(-u)); } double simpson_3_8(double alpha, int Nt, double bomc, double rbv, double taub, int N_points){ //perform an integration of the spin-boson kernel with a hard, finite cutoff bomc. Evaluated at //site distance rbv = r/(beta*v), taub = tau/beta, with number of time slices Nt and number of //integration slices N_points (this method will multiply N_points by 3 and use simpson's 3/8 rule) double du = (bomc)/(3.0*N_points); double result = 3.0*du*(4.0*alpha / Nt / Nt + kernel_integrand(alpha, Nt, rbv, taub, bomc))/8.0; for (int i = 1; i < 3*N_points; ++i){ if(3*(i/3) == i){ result += 0.75*du*kernel_integrand(alpha, Nt, rbv, taub, i*du); } else{ result += 9.0*du*kernel_integrand(alpha, Nt, rbv, taub, i*du)/8.0; } } return result; } public: GeneralLRW(class_mc_params); void print_timers(){ timer.print_timers(); } void step(IsingLattice2D& lat); bool step_one_site(IsingLattice2D& lat, double *prev_action, thrust::host_vector<double>& corr_ref); bool step_one_site_prealloc(IsingLattice2D& lat, double *prev_action, thrust::host_vector<double>& corr_ref, cufftHandle *full_forward_plan, cufftHandle *full_backward_plan, cufftHandle *onesite_forward_plan, cufftHandle *onesite_backward_plan, cudaError cuda_status, cufftDoubleReal *full_state_rs, cufftDoubleComplex *full_state_ft, cufftDoubleReal *onesite_state_rs, cufftDoubleComplex *onesite_state_ft); bool step_one_site_prealloc_lowmem(IsingLattice2D& lat, double *prev_action, thrust::host_vector<double>& corr_ref, thrust::host_vector<double>& ,thrust::host_vector<double>& ,thrust::host_vector<double>& ,thrust::host_vector<double>& , thrust::host_vector<double>& ,thrust::host_vector<double>& , cufftHandle *full_forward_plan, cufftHandle *full_backward_plan, cufftHandle *onesite_forward_plan, cufftHandle *onesite_backward_plan, cudaError cuda_status, cufftDoubleReal *full_state_rs, cufftDoubleComplex *full_state_ft, cufftDoubleReal *onesite_state_rs, cufftDoubleComplex *onesite_state_ft); bool metropolis_step(IsingLattice2D& lat, double *action); bool fast_metropolis_step(IsingLattice2D& lat, double *action); void test_spins(spin, IsingLattice2D& lat); void test_spins_one_site(spin, IsingLattice2D& lat); void set_mag(IsingLattice2D& lat){ mag = 0; for (int i = 0; i < lat.get_Lx(); ++i){ for (int j = 0; j < lat.get_Ly(); ++j){ mag += lat.get_spin(i, j); } } mag = ((double) mag) / lat.get_N(); } double get_mag(){ return mag; } double get_cluster_size() { return (double)cluster_size; } void get_thrust_interactions(thrust::host_vector<double>& result){ if(result.size() != interactions.size()*interactions[0].size()){ result.resize(interactions.size()*interactions[0].size()); } for (int i = 0; i < interactions.size(); ++i){ for (int j = 0; j < interactions[i].size(); ++j){ result[i*interactions[i].size() + j] = interactions[i][j]; } } } std::vector<double> get_interaction_vector(){ std::vector<double> result(interactions.size()*interactions[0].size()); int Ly = interactions[0].size(); for (int x = 0; x < interactions.size(); ++x){ for (int y = 0; y < Ly; ++y){ result[x*Ly + y] = interactions[x][y]; } } return result; } std::vector<std::vector<double>> get_interactions(){ return interactions; } double calc_mqt0_abs(IsingLattice2D&, double); double calc_mqt0_2_abs(IsingLattice2D&, double); double calc_mqt0_4_abs(IsingLattice2D&, double); double calc_mqt0_gpu(thrust::host_vector<double>&, double, int); double calc_locw1(IsingLattice2D&, double); double calc_sx(IsingLattice2D&); double calc_space_kinks(IsingLattice2D& lat); double calc_sz_stagger(IsingLattice2D&); double calc_xmag(IsingLattice2D&); double calc_xmag2(IsingLattice2D&); double calc_xmag4(IsingLattice2D&); double calc_mag(IsingLattice2D&); double calc_loc(IsingLattice2D&); double calc_loc2(IsingLattice2D&); double calc_loc4(IsingLattice2D&); double calc_s1s2(IsingLattice2D&); double calc_action_slow(IsingLattice2D&); double calc_point_action_slow(IsingLattice2D&,int, int); double calc_point_action_fast(IsingLattice2D&, int, int); void print_site_sums(){ std::cout << "Site sums:\n" << vec2str(site_sums) << "\n"; } void print_interactions() { std::stringstream outstring; outstring << "Interactions:\n"; for (int i = 0; i < interactions.size(); ++i){ outstring << vec2str(interactions[i]) << "\n"; } std::cout << outstring.str() << "\n"; } void print_interaction_sum() { std::stringstream outstring; outstring << "Interaction sum:\n"; for (int i = 0; i < interaction_sum.size(); ++i){ outstring << vec2str(interaction_sum[i]) << "\n"; } std::cout << outstring.str() << "\n"; } std::string get_int_string() { std::stringstream ss; ss << "Interactions:\n" ; for (int i = 0; i < interactions.size(); ++i){ ss << vec2str(interactions[i]) << "\n"; } return ss.str(); } };
{ "alphanum_fraction": 0.6990669823, "avg_line_length": 35.905, "ext": "h", "hexsha": "9011c2f7eacd1e14ff8af3e05b129e1c84478f9a", "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": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "butchertx/spin_boson_mc", "max_forks_repo_path": "lib/LongRangeWolff2D.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "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": "butchertx/spin_boson_mc", "max_issues_repo_path": "lib/LongRangeWolff2D.h", "max_line_length": 167, "max_stars_count": null, "max_stars_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "butchertx/spin_boson_mc", "max_stars_repo_path": "lib/LongRangeWolff2D.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2031, "size": 7181 }
/************************************************************************************************************* Calculate shear Gaussian + non-Gaussian covariance using CosmoLike. Gaussian, super-sample and connected non-Gaussian contributions can each be switched on and off independently. This loops over all combinations of z bins, saving each to disk separately. Provide two command line arguments: 1. Path to ini file with all the configuration (see the example_input/example.ini). 2. Index of the first power spectrum, spec1_idx. This will then iterate over all spec2_idx <= spec1_idx. **************************************************************************************************************/ #include <string.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_sf_expint.h> // CosmoLike includes (std & GSL includes must be above here) #include <cosmolike_core/theory/structs.c> #include <cosmolike_core/theory/basics.c> #include <cosmolike_core/theory/recompute.c> #include <cosmolike_core/theory/cosmo3D.c> #include <cosmolike_core/theory/redshift_spline.c> #include <cosmolike_core/theory/cosmo2D_fourier.c> #include <cosmolike_core/theory/halo.c> #include <cosmolike_core/theory/covariances_3D.c> #include <cosmolike_core/theory/covariances_fourier.c> #include <covs/init.c> // Cl covariance params typedef struct { int lmin; int lmax; char ell_str[200]; char output_dir[200]; int do_g; int do_ss; int do_cng; } clcov_par; clcov_par clcov_params = {.lmin = 2, .lmax = -1, .ell_str = "NULL", .do_g = 0, .do_ss = 0, .do_cng = 0}; // Set Cl covariance params from ini file void set_clcov_parameters(char *paramfile, int output) { char line[256]; int iline=0; FILE* input = fopen(paramfile, "r"); while(fgets(line, 256, input) != NULL) { char name[128], val[128]; iline++; if(line[0] == '#') continue; sscanf(line, "%128s : %128s", name, val); if(strcmp(name, "lmin") == 0) { sscanf(val, "%d", &clcov_params.lmin); if(output == 1) printf("lmin %d \n", clcov_params.lmin); } else if(strcmp(name, "lmax") == 0) { sscanf(val, "%d", &clcov_params.lmax); if(output == 1) printf("lmax %d \n", clcov_params.lmax); } else if(strcmp(name, "output_dir") == 0) { sprintf(clcov_params.output_dir, "%s", val); if(output == 1) printf("output_dir %s \n", clcov_params.output_dir); } else if(strcmp(name, "c_footprint_file") == 0) { sprintf(covparams.C_FOOTPRINT_FILE, "%s", val); if(output == 1) printf("c_footprint_file %s \n", covparams.C_FOOTPRINT_FILE); } else if(strcmp(name, "ell") == 0) { sprintf(clcov_params.ell_str, "%s", val); if(output == 1) printf("ell_str %s \n", clcov_params.ell_str); } else if(strcmp(name, "do_g") == 0) { sscanf(val, "%d", &clcov_params.do_g); if(output == 1) printf("do_g %d \n", clcov_params.do_g); } else if(strcmp(name, "do_ss") == 0) { sscanf(val, "%d", &clcov_params.do_ss); if(output == 1) printf("do_ss %d \n", clcov_params.do_ss); } else if(strcmp(name, "do_cng") == 0) { sscanf(val, "%d", &clcov_params.do_cng); if(output == 1) printf("do_cng %d \n", clcov_params.do_cng); } } } // 2D version of numpy savetxt. Use header = "0" for no header int savetxt_2d(char *path, double **array, int n_row, int n_col, char *header) { FILE *file = fopen(path, "w"); if (strncmp(header, "0", 2) != 0) fprintf(file, "# %s\n", header); for (int i = 0; i < n_row; i++) { printf("Saving %d / %d ... \r", i + 1, n_row); for (int j = 0; j < n_col; j++) { fprintf(file, "%.10e", array[i][j]); if (j < n_col - 1) { fprintf(file, " "); } } fprintf(file, "\n"); } fclose(file); return 0; } int main(int argc, char** argv) { if (argc != 3){ fprintf(stderr, "Syntax: %s config_file spec1_idx\n", argv[0]); exit(1); } setbuf(stdout, NULL); // Set this to 1 to output details about inputs for diagnostics int output = 1; // Set cosmo, survey and Cl covariance params from ini file char *inifile = argv[1]; set_cosmological_parameters(inifile, output); set_survey_parameters(inifile, output); covparams.full_tomo = 1; set_clcov_parameters(inifile, output); init_source_sample(redshift.shear_REDSHIFT_FILE, tomo.shear_Nbin); init_lens_sample(redshift.clustering_REDSHIFT_FILE, tomo.clustering_Nbin); // Determine which contributions to include char cov_str[9] = ""; printf("Including Gaussian contribution: "); if (clcov_params.do_g) { printf("yes \n"); sprintf(cov_str, "%sg_", cov_str); } else printf("no \n"); printf("Including super-sample contribution: "); if (clcov_params.do_ss) { printf("yes \n"); sprintf(cov_str, "%sss_", cov_str); } else printf("no \n"); printf("Including connected non-Gaussian contribution: "); if (clcov_params.do_cng) { printf("yes \n"); sprintf(cov_str, "%scng_", cov_str); } else printf("no \n"); covparams.ssc = clcov_params.do_ss; covparams.cng = clcov_params.do_cng; // Obtain the number of z bins from config int n_zbin; if (tomo.shear_Nbin != tomo.clustering_Nbin) error("tomo.shear_Nbin != tomo.clustering_Nbin"); else n_zbin = tomo.shear_Nbin; // Determine ells, either from the list provided in the config or the provided lmin and lmax // Do this in 2 steps: first determine the number of ells, then the ells themselves int n_ell; if (strcmp(clcov_params.ell_str, "NULL") == 0) { if (clcov_params.lmax < clcov_params.lmin) error("lmax < lmin, make sure lmax is provided"); n_ell = clcov_params.lmax - clcov_params.lmin + 1; } else { // Count the number of commas + 1 n_ell = 1; const char *remaining_str = clcov_params.ell_str; while ((remaining_str = strstr(remaining_str, ","))) { n_ell++; remaining_str++; } } int ell[n_ell]; if (strcmp(clcov_params.ell_str, "NULL") == 0) { for (int l = clcov_params.lmin; l <= clcov_params.lmax; l++) { ell[l - clcov_params.lmin] = l; } } else { char* rem_str = calloc(strlen(clcov_params.ell_str) + 1, sizeof(char)); strcpy(rem_str, clcov_params.ell_str); int l_idx = 0; char *token = strtok(rem_str, ","); while (token != NULL) { ell[l_idx] = strtol(token, NULL, 10); token = strtok(NULL, ","); l_idx++; } } // Prepare a string about the ells to go in the header of the output text files char ell_header_str[200]; if (strcmp(clcov_params.ell_str, "NULL") == 0) { sprintf(ell_header_str, "lmin %d, lmax %d", clcov_params.lmin, clcov_params.lmax); } else { sprintf(ell_header_str, "ell: %s", clcov_params.ell_str); } printf("%s \n", ell_header_str); // Generate list of power spectra within the shear data vector // Rows are the different spectra, cols are: z1, z2 int n_spectra_sametype = n_zbin * (n_zbin + 1) / 2; int spectra_sametype[n_spectra_sametype][2]; int spec_idx = 0; for (int diag = 0; diag < n_zbin; diag++) { for (int row = 0; row < n_zbin - diag; row++) { spectra_sametype[spec_idx][0] = row; spectra_sametype[spec_idx][1] = row + diag; spec_idx++; } } // Read in the provided spec1_idx and check it is allowed int spec1_idx = atoi(argv[2]); if (spec1_idx < 0 || spec1_idx >= n_spectra_sametype) { error("spec1_idx provided is not valid"); } else { printf("Requested spec1_idx is %d \n", spec1_idx); } // Common variables for the covariance blocks int z1, z2, z3, z4, l1, l2; double cov; char save_path[250]; char header[250]; // Shear-shear covariance (symmetric so only do spec2_idx <= spec1_idx) for (int spec2_idx = 0; spec2_idx <= spec1_idx; spec2_idx++) { // Allocate memory for the block and fill with nans double** cov_shear_shear = (double**) malloc(n_ell * sizeof(double*)); for (int i = 0; i < n_ell; i++) cov_shear_shear[i] = (double*) malloc(n_ell * sizeof(double)); for (int l1_idx = 0; l1_idx < n_ell; l1_idx++) { for (int l2_idx = 0; l2_idx < n_ell; l2_idx++) { cov_shear_shear[l1_idx][l2_idx] = NAN; } } // Loop over all combinations of (l1, l2), unless the two spectra are the same in which case only need l2 <= l1 for (int l1_idx = 0; l1_idx < n_ell; l1_idx++) { printf("spec2_idx %d / %d, l1_idx %d / %d \n", spec2_idx, spec1_idx, l1_idx, n_ell); int l2_idx_max; if (spec2_idx == spec1_idx) { l2_idx_max = l1_idx; } else { l2_idx_max = n_ell - 1; } for (int l2_idx = 0; l2_idx <= l2_idx_max; l2_idx++) { l1 = ell[l1_idx]; l2 = ell[l2_idx]; z1 = spectra_sametype[spec1_idx][0]; z2 = spectra_sametype[spec1_idx][1]; z3 = spectra_sametype[spec2_idx][0]; z4 = spectra_sametype[spec2_idx][1]; cov = 0.0; if (clcov_params.do_g) cov += cov_G_shear_shear_tomo(l1, l2, z1, z2, z3, z4); if (clcov_params.do_ss || clcov_params.do_cng) cov += cov_NG_shear_shear_tomo(l1, l2, z1, z2, z3, z4); cov_shear_shear[l1_idx][l2_idx] = cov; if (spec2_idx == spec1_idx) { cov_shear_shear[l2_idx][l1_idx] = cov; } } } // Save block to disk and free memory sprintf(save_path, "%s/cov_%sspec1_%d_spec2_%d.txt", clcov_params.output_dir, cov_str, spec1_idx, spec2_idx); sprintf(header, "cov_shear_shear for spec_idx %d and %d with do_g=%d, do_ss=%d, do_cng=%d, %s", spec1_idx, spec2_idx, clcov_params.do_g, clcov_params.do_ss, clcov_params.do_cng, ell_header_str); if (savetxt_2d(save_path, cov_shear_shear, n_ell, n_ell, header) == 0) printf("\nSaved %s\n", save_path); for (int i = 0; i < n_ell; i++) free(cov_shear_shear[i]); free(cov_shear_shear); } // next spec2_idx for this fixed spec1_idx printf("Done \n"); return 0; }
{ "alphanum_fraction": 0.6285656688, "avg_line_length": 35.9456521739, "ext": "c", "hexsha": "0a4b361726669c5c70f7a17f93bcd91c16876777", "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": "afa02abe76ad1e7b0fc17f43d7f271cb466948c1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "robinupham/CosmoCov_ClCov", "max_forks_repo_path": "get_shear_clcov.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "afa02abe76ad1e7b0fc17f43d7f271cb466948c1", "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": "robinupham/CosmoCov_ClCov", "max_issues_repo_path": "get_shear_clcov.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "afa02abe76ad1e7b0fc17f43d7f271cb466948c1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "robinupham/CosmoCov_ClCov", "max_stars_repo_path": "get_shear_clcov.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3097, "size": 9921 }
#pragma once #pragma once #include "core/math/vec3.h" #include "core/math/vec4.h" #include "core/container/vector.h" #include "core/memory/linear_allocator.h" #include <lapacke.h> /* void compute_spline_coeff(uint n, float* coeff, float* y, uint stride, float* h, float constant_h) { LinearRegion region(get_temporary_allocator()); float* DL = TEMPORARY_ARRAY(float, n); float* D = TEMPORARY_ARRAY(float, n+1); float* DU = TEMPORARY_ARRAY(float, n); float* B = TEMPORARY_ARRAY(float, n + 1); for (uint i = 1; i < n; i++) { float h0 = h ? h[i - 1] : constant_h; float h1 = h ? h[i] : constant_h; float a0 = y[(i - 1) * stride]; float a1 = y[i * stride]; float a2 = y[(i + 1) * stride]; DL[i-1] = h0; D[i] = 2*(h0 + h1); DU[i] = h1; B[i] = 3/h1 * (a2 - a1) + 3/h0 * (a1 - a0); } B[0] = 0; B[n] = 0; D[0] = 1; D[n] = 1; DU[0] = 0; DL[n - 1] = 1; int info = LAPACKE_sgtsv(LAPACK_ROW_MAJOR, n+1, 1, DL, D, DU, B, 1); assert(info == 0); for (uint i = 0; i < n; i++) { float h0 = h ? h[i] : constant_h; float a0 = y[i * stride]; float a1 = y[(i + 1) * stride]; float c0 = B[i]; float c1 = B[i + 1]; coeff[i * 4 * stride + 0] = a0; coeff[i * 4 * stride + 1] = 1 / h0 * (a1 - a0) - h0 / 3 * (2 * c0 + c1); coeff[i * 4 + stride + 2] = c0; coeff[i * 4 + stride + 3] = (c1 - c0) / (3*h0); } } */ //Cubic hermitian spline class Spline { struct Cubic { vec3 a, b, c, d; }; vector<Cubic> coeff; vector<float> lengths; public: float total_length; Spline(slice<vec3> points) { build(points); } uint points() { return lengths.length; } void build(slice<vec3> points) { uint n = points.length - 1; coeff.resize(n+1); lengths.resize(n); LinearRegion region(get_temporary_allocator()); vec3* a = TEMPORARY_ARRAY(vec3, n + 1); for (int i = 1; i <= n - 1; i++) a[i] = 3 * ((points[i + 1] - 2 * points[i] + points[i - 1])); float* l = TEMPORARY_ARRAY(float, n+1); float* mu = TEMPORARY_ARRAY(float, n + 1); vec3* z = TEMPORARY_ARRAY(vec3, n + 1); l[0] = l[n] = 1; mu[0] = 0; z[0] = z[n] = vec3(); coeff[n].c = vec3(); for (int i = 1; i <= n - 1; i++) { l[i] = 4 - mu[i - 1]; mu[i] = 1 / l[i]; z[i] = (a[i] - z[i - 1]) / l[i]; } for (int i = 0; i < n+1; i++) coeff[i].a = points[i]; for (int j = n - 1; j >= 0; j--) { coeff[j].c = z[j] - mu[j] * coeff[j + 1].c; coeff[j].d = (1.0f / 3.0f) * (coeff[j + 1].c - coeff[j].c); coeff[j].b = points[j + 1] - points[j] - coeff[j].c - coeff[j].d; } /* float* DL = TEMPORARY_ARRAY(float, n); float* D = TEMPORARY_ARRAY(float, n + 1); float* DU = TEMPORARY_ARRAY(float, n); float* B = TEMPORARY_ARRAY(float, n + 1); for (uint k = 0; k < 3; k++) { for (uint i = 1; i < n; i++) { float a0 = points[i - 1][k]; float a1 = points[i][k]; float a2 = points[i + 1][k]; DL[i - 1] = 1.0; D[i] = 4.0; DU[i] = 1.0; B[i] = 3.0*(a2 - a1) + 3.0*(a1 - a0); } B[0] = 0; B[n] = 0; D[0] = 1; D[n] = 1; DL[n - 1] = 0; DU[0] = 0; if (true) { char spaces[256]; for (uint i = 0; i < 256; i++) spaces[i] = ' '; for (uint i = 0; i < n+1; i++) { if (i == 0) printf("[ %.2f, %.2f,%.*s][%i] = [%f]\n", D[i], DU[0], (n-1)*6, spaces, i, B[i]); else if (i == n) printf("[%.*s %.2f, %.2f ][%i] = [%f]\n", (i-1)*6, spaces, DL[i-1], D[i], i, B[i]); else printf("[%.*s %.2f, %.2f, %.2f,%.*s][%i] = [%f]\n", (i-1)*6, spaces, DL[i-1], D[i], DU[i], (n-1-i)*6, spaces, i, B[i]); } } int info = LAPACKE_sgtsv(LAPACK_ROW_MAJOR, n + 1, 1, DL, D, DU, B, 1); assert(info == 0); for (uint i = 0; i < n; i++) { float a0 = points[i][k]; float a1 = points[i + 1][k]; float c0 = B[i]; float c1 = B[i + 1]; coeff[i].a[k] = a0; coeff[i].b[k] = (a1 - a0) - 1.0 / 3 * (2 * c0 + c1); coeff[i].c[k] = c0; coeff[i].d[k] = (c1 - c0) / 3.0; } } */ total_length = 0; for (uint i = 0; i < n; i++) { lengths[i] = integrate(i,1.0); total_length += lengths[i]; } } vec3 at_time(float t) { uint i = min(t, coeff.length-1); float x = t - i; float xx = x * x; float xxx = xx * x; vec3 result = coeff[i].a + coeff[i].b * x + coeff[i].c * xx + coeff[i].d * xxx; return result; } vec3 tangent(float t) { uint i = min(t, coeff.length - 1); float x = t - i; float xx = x * x; vec3 result = coeff[i].b + 2.0f * coeff[i].c * x + 3.0f * coeff[i].d * xx; return normalize(result); } float arc_length_integrand(uint spline, float t) { float tt = t * t; vec3 result = coeff[spline].b + 2.0f * coeff[spline].c * t + 3.0f * coeff[spline].d * tt; return length(result); } float integrate(uint spline, float t) { uint n = 16; float h = t / n; float XI0 = arc_length_integrand(spline, t); float XI1 = 0; float XI2 = 0; for (uint i = 0; i < n; i++) { float X = i * h; if (i % 2 == 0) XI2 += arc_length_integrand(spline, X); else XI1 += arc_length_integrand(spline, X); } float XI = h * (XI0 + 2 * XI2 + 4 * XI1) / 3.0f; return XI; } float const_speed_reparam(float t, float speed) { float desired_distance = speed * t; float distance = 0.0f; uint spline; for (spline = 0; spline < lengths.length; spline++) { float new_distance = distance + lengths[spline]; if (new_distance >= desired_distance) break; distance = new_distance; } assert(spline < lengths.length); float d = desired_distance - distance; float s = 0.5f; for (uint i = 0; i < 10; i++) { float arc_length = integrate(spline, s); float arc_speed = arc_length_integrand(spline, s); //printf("S %f, arc length %f, arc speed %f\n", s, arc_length, arc_speed); s = s - (arc_length - d) / arc_speed; } return spline + s; } vec3 const_speed_at_time(float t, float speed) { return at_time(const_speed_reparam(t, speed)); } };
{ "alphanum_fraction": 0.4967257627, "avg_line_length": 24.5529411765, "ext": "h", "hexsha": "d7b6dd042588529bdff46de232826ba35f88bd91", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-06-17T16:47:57.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-02T06:46:56.000Z", "max_forks_repo_head_hexsha": "aa1a8e9d9370bce004dba00854701597cab74989", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CompilerLuke/NextEngine", "max_forks_repo_path": "CFD/include/numerical/spline.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "aa1a8e9d9370bce004dba00854701597cab74989", "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": "CompilerLuke/NextEngine", "max_issues_repo_path": "CFD/include/numerical/spline.h", "max_line_length": 144, "max_stars_count": 1, "max_stars_repo_head_hexsha": "aa1a8e9d9370bce004dba00854701597cab74989", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CompilerLuke/NextEngine", "max_stars_repo_path": "CFD/include/numerical/spline.h", "max_stars_repo_stars_event_max_datetime": "2021-09-10T18:19:16.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-10T18:19:16.000Z", "num_tokens": 2389, "size": 6261 }
/** * * @file core_scasum.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated c Tue Jan 7 11:44:46 2014 * **/ #include <cblas.h> #include <math.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex32_t * * CORE_scasum - Computes the sums of the absolute values of elements in a same * row or column. * This function is an auxiliary function to norm computations. * ******************************************************************************* * * @param[in] storev * Specifies whether the sums are made per column or row. * = PlasmaColumnwise: Computes the sum on each column * = PlasmaRowwise: Computes the sum on each row * * @param[in] uplo * Specifies whether the matrix A is upper triangular or lower triangular or general * = PlasmaUpperLower: All matrix A is referenced; * = PlasmaUpper: Upper triangle of A is referenced; * = PlasmaLower: Lower triangle of A is referenced. * * @param[in] M * M specifies the number of rows of the matrix A. M >= 0. * * @param[in] N * N specifies the number of columns of the matrix A. N >= 0. * * @param[in] A * A is a M-by-N matrix. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,M). * * @param[out] work * Array of dimension M if storev = PlasmaRowwise; N otherwise. * On exit, contains the sums of the absolute values per column or row. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_scasum = PCORE_scasum #define CORE_scasum PCORE_scasum #endif void CORE_scasum(PLASMA_enum storev, PLASMA_enum uplo, int M, int N, const PLASMA_Complex32_t *A, int lda, float *work) { const PLASMA_Complex32_t *tmpA; float *tmpW, sum, abs; int i,j; switch (uplo) { case PlasmaUpper: for (j = 0; j < N; j++) { tmpA = A+(j*lda); sum = 0.0; for (i = 0; i < j; i++) { abs = cabsf(*tmpA); sum += abs; work[i] += abs; tmpA++; } work[j] += sum + cabsf(*tmpA); } break; case PlasmaLower: for (j = 0; j < N; j++) { tmpA = A+(j*lda)+j; sum = 0.0; work[j] += cabsf(*tmpA); tmpA++; for (i = j+1; i < M; i++) { abs = cabsf(*tmpA); sum += abs; work[i] += abs; tmpA++; } work[j] += sum; } break; case PlasmaUpperLower: default: if (storev == PlasmaColumnwise) { for (j = 0; j < N; j++) { /* work[j] += cblas_scasum(M, &(A[j*lda]), 1); */ tmpA = A+(j*lda); for (i = 0; i < M; i++) { work[j] += cabsf(*tmpA); tmpA++; } } } else { for (j = 0; j < N; j++) { tmpA = A+(j*lda); tmpW = work; for (i = 0; i < M; i++) { /* work[i] += cabsf( A[j*lda+i] );*/ *tmpW += cabsf( *tmpA ); tmpA++; tmpW++; } } } } }
{ "alphanum_fraction": 0.4495087336, "avg_line_length": 29.5483870968, "ext": "c", "hexsha": "65dd0bd9db8878c0f6f5405cc8bf8c80323e6f1f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_scasum.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_scasum.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_scasum.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 967, "size": 3664 }
// // main.c // ODE_MODEL // // Created by Kari Heine on 28/10/2020. // Copyright © 2020 Kari Heine. All rights reserved. // #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_eigen.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <Accelerate/Accelerate.h> #include "particle_filters.h" #define MAX_TEST_MESH_SIZE 4000 // Mesh size for BPF and MLBPF level 1 (the truth mesh size) #define N_SETTINGS 500 // Number of different scenarios #define N_SCALES 1 // Scaling samplesizes to study convergence #define N_MEASUREMENTS 2 // Number of places where the beam deflection is measured void generate_signal(double* x, int len, double std_sig, double x0, gsl_rng* rng, double L); void create_dense_solver_matrix(double* A, int n); void init_with_zeros(double* array, long length); void make_lapack_band_matrix(double *A, int n, double *ab, int ku, int kl); double compute_estimation_error(double* x_hat, double* x_ref, int len); void particle_allocation_time_matching(int max_mesh_size, int* level_0_mesh_sizes, int n_level_0_mesh_sizes, int bpf_sample_size, double std_sig, double obs_std, int data_length, double x0, double *y, int kl, int ku, double* ab_bpf, int ldab, double w, double d, double E, double I, double h_bpf, double *ab0, double h1, double L, double* meass, int N_meas); void get_settings(int** settings); void write_beam_in_file(int data_length, int true_mesh_size, double h, double* beam); int main(void) { gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus); gsl_rng_set(rng,clock()); // gsl_rng_set(rng,42); /* Global parameters */ /* ----------------- */ int N_top = 250; // Top leve Monte Carlo iterations int kl = 3; // Lower diagonal bandwidth for the ODE solver int ku = 3; // upper diagonal bandwidth for the ODE solver int ldab = 2 * kl + ku + 1; // parameter for Lapack DGBSV int run_time_matching = 0; // This toggle (0 or 1) determines if we want to run time matching or filtering int N_ref = 100000; // Sample size for the reference filter /* Signal and observations */ /* ----------------------- */ int data_length = 50; // number of time steps double x0 = 2; // initial state double std_sig = 0.02; // signal noise standard deviation double obs_std = 0.0002; // observation noise standard deviation // Data arrays for the signal and observations double* x = (double*) malloc(data_length * sizeof(double)); double* y = (double*) malloc(N_MEASUREMENTS * data_length * sizeof(double)); FILE * data_out; /* Euler-Bernoulli beam parameters */ /* ------------------------------- */ double L = 4; // Length (m) double w = 0.3; // Width (m) double d = 0.03; // thickness (m) double E = 1e10; // Young's modulus double I = w * d * d * d / (double) 12; // Inertia double measurements[N_MEASUREMENTS] = {1, 1.75}; // deflection measurement points along the beam (m) int minds[N_MEASUREMENTS]; // mesh point indices for the deflection measurement points /* Beam solver setup for data generation */ /* ------------------------------------- */ int true_mesh_size = MAX_TEST_MESH_SIZE; double* A = (double*) malloc(MAX_TEST_MESH_SIZE * MAX_TEST_MESH_SIZE * sizeof(double)); int* ipiv = (int*) malloc(MAX_TEST_MESH_SIZE * sizeof(int)); double* ab = (double*) malloc(ldab * MAX_TEST_MESH_SIZE * sizeof(double)); double* ab_copy = (double*) malloc(ldab * MAX_TEST_MESH_SIZE * sizeof(double)); double* signal_payload = (double*) malloc(MAX_TEST_MESH_SIZE * data_length * sizeof(double)); double h = L / (double)(true_mesh_size-1); int ldb = true_mesh_size, info = 0; // Calculate the indices for the deflection measurement points. for(int i = 0; i < N_MEASUREMENTS; i++) { minds[i] = (int)((measurements[i] / L) * (double) true_mesh_size); } create_dense_solver_matrix(A, true_mesh_size); /* Convert the design matrix to general band representation */ init_with_zeros(ab, ldab * true_mesh_size); make_lapack_band_matrix(A, true_mesh_size, ab, ku, kl); /* COMPARISON SETUP */ /* ---------------- */ FILE * error_out = fopen("error.txt", "w"); double bpf_MSE = 0; double mlbpf_MSE = 0; double scaler = 1; double bpf_MSE_error_matched = 0; /* BPF SETUP */ /* --------- */ double *x_hat_bpf = (double*) malloc(data_length * sizeof(double)); double *x_ref = (double*) malloc(data_length * sizeof(double)); double *p_ref = (double*) malloc(data_length * sizeof(double)); FILE* ref_out; double filtering_time[4]; // array for time recording int N = 500; int mesh_size_bpf = MAX_TEST_MESH_SIZE; double* ab_bpf = ab; int* ipiv_bpf = ipiv; double h_bpf = L / (double) (mesh_size_bpf-1); create_dense_solver_matrix(A, mesh_size_bpf); init_with_zeros(ab_bpf, ldab*mesh_size_bpf); make_lapack_band_matrix(A, mesh_size_bpf, ab_bpf, ku, kl); /* MLBPF SETUP */ /* ----------- */ double worst_case_sign_ratio[1] = { 100 }; // This is basically sustitute for "Inf" double *x_hats_mlbpf = (double*) malloc(data_length * sizeof(double)); int mesh_sizes[2] = {10, 500}; // these values will be overwritten int N0, N1; double* ab0 = (double*) malloc(ldab * MAX_TEST_MESH_SIZE * sizeof(double)); double* ab1 = ab; int* ipiv0 = ipiv; int* ipiv1 = ipiv; double h0; init_with_zeros(ab0, ldab * MAX_TEST_MESH_SIZE); init_with_zeros(ab1, ldab * MAX_TEST_MESH_SIZE); // We can create the solver matrices for level 1 only which has fixed mesh size create_dense_solver_matrix(A, MAX_TEST_MESH_SIZE); make_lapack_band_matrix(A, MAX_TEST_MESH_SIZE, ab1, ku, kl); double h1 = L / (double)(MAX_TEST_MESH_SIZE - 1); if(run_time_matching) { /* * Particle allocation time matching * * This part of the code should be run when trying to find the correct N0 sample sizes to match the * BPF running time */ int max_mesh_size = MAX_TEST_MESH_SIZE; int level_0_mesh_sizes[20] = {100, 105, 110, 115, 120, 130, 140, 150, 160, 180, 200, 220, 240, 260, 280, 320, 360, 400, 440, 500}; int n_level_0_mesh_sizes = 20; generate_signal(x, data_length, std_sig, x0, rng, L); create_payload(data_length, true_mesh_size, signal_payload, w, d, x, h, E, I, L); array_copy(ab, ab_copy, ldab * true_mesh_size); // Restore undamaged band matrix // Solve the Euler-Bernoulli beam dgbsv_(&true_mesh_size, &kl, &ku, &data_length, ab_copy, &ldab, ipiv, signal_payload, &ldb, &info); // Generate measurements for(int i = 0; i < data_length; i++) for(int j = 0; j < N_MEASUREMENTS; j++) y[i + j * data_length] = signal_payload[i * true_mesh_size + minds[j]] + gsl_ran_gaussian(rng, obs_std); particle_allocation_time_matching(max_mesh_size, level_0_mesh_sizes, n_level_0_mesh_sizes, N, std_sig, obs_std, data_length, x0, y, kl, ku, ab_bpf, ldab, w, d, E, I, h_bpf, ab0, h1, L, measurements, N_MEASUREMENTS); printf("Particle allocation time matching done! Exiting...\n"); return 0; // the code exits } /* * THIS IS THE ACTUAL FILTER COMPARISON PART */ // Settings are hard coded here. TODO: This should be changed to reading a file. int** settings = (int **)malloc(N_SETTINGS * sizeof(int*)); for(int i = 0; i < N_SETTINGS; i++) settings[i] = (int *) malloc(4*sizeof(int)); int sample_sizes[2] = {0,0}; get_settings(settings); // Top level iteration for(int nmc = 0; nmc < N_top; nmc++) { printf("Top level iteration %i out of %i.*****************************\n", nmc + 1, N_top); /* To save computational time and also to take into account the possibility that a particular data set is more favourable to one or the other algorithm, we create new data every nth top level iteration, and compute the reference filter. */ if (nmc % 10 == 0) { // Create the signal generate_signal(x, data_length, std_sig, x0, rng, L); printf("Signal generated\n"); fflush(stdout); create_payload(data_length, true_mesh_size, signal_payload, w, d, x, h, E, I, L); printf("Payload created\n"); fflush(stdout); array_copy(ab, ab_copy, ldab * true_mesh_size); // Solve the Euler-Bernoulli beam dgbsv_(&true_mesh_size, &kl, &ku, &data_length, ab_copy, &ldab, ipiv, signal_payload, &ldb, &info); printf("\nBeam solved. Info: %i\n\n",info); fflush(stdout); // write_beam_in_file(data_length, true_mesh_size, h, signal_payload); // Generate the noisy measurements data_out = fopen("data.txt","w"); for(int i = 0; i < data_length; i++) { // Noisy measurements for one time step but all measurement points for(int j = 0; j < N_MEASUREMENTS; j++) { y[i + j*data_length] = signal_payload[i * true_mesh_size + minds[j]] + gsl_ran_gaussian(rng, obs_std); } fprintf(data_out,"%i %e ",i, x[i]); // write true signal into a file for(int j = 0; j < N_MEASUREMENTS; j++) { // write noisy and noiseless observation into a file fprintf(data_out,"%6.6e %6.6e ", y[i+j*data_length], signal_payload[i * true_mesh_size + minds[j]]); } fprintf(data_out,"\n"); } fclose(data_out); printf("Data generated\n"); /* Compute a reference solution */ printf("Reference filter with N_ref = %i\n", N_ref); fflush(stdout); bootstrapfilter(y, std_sig, obs_std, data_length, x0, N_ref, x_ref, p_ref, filtering_time, mesh_size_bpf, kl, ku, ab_bpf, ldab, ipiv_bpf, mesh_size_bpf, info, w, d, E, I, h_bpf, L, measurements, (int)N_MEASUREMENTS); // Write the reference filter output into a file with columns: // step index, posterior mean, posterior variance, true signal, observation ref_out = fopen("ref_filter_out.txt","w"); for(int i = 0; i < data_length;i++) fprintf(ref_out,"%i %e %e %e %e\n",i,x_ref[i],p_ref[i],x[i],y[i]); fclose(ref_out); // return 0; // option to exit after reference filter may be useful in debugging } /* Run the benchmark BPF */ // NB: This is not the reference, but a comparison filter which is time is matched to MLBPF bootstrapfilter(y, std_sig, obs_std, data_length, x0, N, x_hat_bpf, NULL, filtering_time, mesh_size_bpf, kl, ku, ab_bpf, ldab, ipiv_bpf, mesh_size_bpf, info, w, d, E, I, h_bpf, L, measurements, (int)N_MEASUREMENTS); // bpf_MSE = compute_estimation_error(x_hat_bpf,x,data_length); // compute the error w.r.t. the truth bpf_MSE = compute_estimation_error(x_hat_bpf,x_ref,data_length); // Write the results in a file fprintf(error_out, "%e %i %i %f %i %e %e %f %e %f %i\n", bpf_MSE, 0, N, filtering_time[0], 0, filtering_time[1], filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler, mesh_size_bpf); /* Compute the error matched BPF */ // The ERROR matched filter, i.e. it produces roughly the same level of error, but hopefully takes // much longer to achieve it. printf("Error matched filter\n"); bootstrapfilter(y, std_sig, obs_std, data_length, x0, 4*N, x_hat_bpf, NULL, filtering_time, mesh_size_bpf, kl, ku, ab_bpf, ldab, ipiv_bpf, mesh_size_bpf, info, w, d, E, I, h_bpf, L, measurements, (int)N_MEASUREMENTS); // bpf_MSE = compute_estimation_error(x_hat_bpf,x,data_length); // compute the error w.r.t. the truth bpf_MSE_error_matched = compute_estimation_error(x_hat_bpf,x_ref,data_length); // Write the results in a file fprintf(error_out, "%e %i %i %f %i %e %e %f %e %f %i\n", bpf_MSE_error_matched, 0, N, filtering_time[0], -1, filtering_time[1], filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler, mesh_size_bpf); /* Iterate over different mesh size and particle allocation configurations */ for(int i_setting = 0; i_setting < N_SETTINGS; i_setting++) { // Rename sample_sizes[0] = settings[i_setting][0]; sample_sizes[1] = settings[i_setting][1]; mesh_sizes[0] = settings[i_setting][2]; mesh_sizes[1] = settings[i_setting][3]; // Ensure odd number of particles sample_sizes[0] = (sample_sizes[0] + sample_sizes[1]) % 2 == 0 ? sample_sizes[0] + 1 : sample_sizes[0]; init_with_zeros(ab0, ldab * mesh_sizes[0]); create_dense_solver_matrix(A, mesh_sizes[0]); make_lapack_band_matrix(A, mesh_sizes[0], ab0, ku, kl); h0 = L / (double)(mesh_sizes[0] - 1); printf("Setting %i out of %i\n",i_setting+1,N_SETTINGS); fflush(stdout); MLbootstrapfilter(y, std_sig, obs_std, data_length, x0, sample_sizes, worst_case_sign_ratio, x_hats_mlbpf, filtering_time, mesh_sizes, kl, ku, ab0, ab1, ldab, ipiv0, ipiv1, mesh_sizes[0], mesh_sizes[1], info, w, d, E, I, h0, h1, L, measurements, (int)N_MEASUREMENTS); // mlbpf_MSE = compute_estimation_error(x_hats_mlbpf,x,data_length); mlbpf_MSE = compute_estimation_error(x_hats_mlbpf,x_ref,data_length); N0 = sample_sizes[0]; N1 = sample_sizes[1]; fprintf(error_out, "%e %i %i %f %i %e %e %f %e %f %i\n", mlbpf_MSE, N0, N1, filtering_time[0], i_setting + 1, filtering_time[1], filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler, mesh_sizes[0]); fflush(error_out); } } /* Free all that was allocated */ free(x); free(y); free(A); free(ipiv); free(ab); free(ab_copy); free(signal_payload); free(x_hat_bpf); free(x_ref); free(p_ref); free(x_hats_mlbpf); free(ab0); for(int i = 0; i < N_SETTINGS; i++) free(settings[i]); free(settings); return 0; } void write_beam_in_file(int data_length, int true_mesh_size, double h, double* beam) { FILE * payload_out = fopen("payload.txt","w"); for(int i = 0; i < data_length; i++) for(int j = 0; j < true_mesh_size; j++) fprintf(payload_out, "%5.5e %5.10e \n", j * h, beam[i * true_mesh_size + j]); fclose(payload_out); printf("Payload written in file\n"); fflush(stdout); } void particle_allocation_time_matching(int max_mesh_size, int* level_0_mesh_sizes, int n_level_0_mesh_sizes, int bpf_sample_size, double std_sig, double obs_std, int data_length, double x0, double *y, int kl, int ku, double* ab_bpf, int ldab, double w, double d, double E, double I, double h_bpf, double *ab0, double h1, double L, double* meass, int N_meas) { int N1_step = 20; int N0_step = 10000; int N0_init = 10; int N_top = 5; double time_per_iteration; double time_tolerance = 1.00; // double filtering_time[4]; int info = 0; int* ipiv = (int *) malloc(max_mesh_size * sizeof(int)); double worst_case_sign_ratio[1] = { 100 }; double* ab_copy = (double*) malloc(ldab * max_mesh_size * sizeof(double)); double* ab0_copy = (double*) malloc(ldab * max_mesh_size * sizeof(double)); double h0; double* A0 = (double*) malloc(MAX_TEST_MESH_SIZE * MAX_TEST_MESH_SIZE * sizeof(double)); /* Find the reference time per iteration for BPF */ double bpf_time_per_iteration = 0; for(int nmc = 0; nmc < N_top; nmc++) { for(int i = 0; i < ldab * max_mesh_size; i++) ab_copy[i] = ab_bpf[i]; bootstrapfilter(y, std_sig, obs_std, data_length, x0, bpf_sample_size, NULL, NULL, filtering_time, max_mesh_size, kl, ku, ab_bpf, ldab, ipiv, max_mesh_size, info, w, d, E, I, h_bpf , L, meass, N_MEASUREMENTS); bpf_time_per_iteration += filtering_time[0] / (double) N_top; } printf("Time per iteration (BPF): %0.5f\n",bpf_time_per_iteration); fflush(stdout); int level_0_mesh_size; int sample_sizes[2] = {0,0}; int mesh_sizes[2]; int N0; short direction; FILE* out = fopen("time_matched_sample_sizes.txt","w"); /* Iterate over level 0 mesh sizes */ for(int j = 0; j < n_level_0_mesh_sizes; j++) { level_0_mesh_size = level_0_mesh_sizes[j]; mesh_sizes[0] = level_0_mesh_size; mesh_sizes[1] = max_mesh_size; // We have to create A0 again for each mesh size for(int i = 0; i < ldab * mesh_sizes[0]; i++) ab0[i] = 0; create_dense_solver_matrix(A0, mesh_sizes[0]); make_lapack_band_matrix(A0, mesh_sizes[0], ab0, ku, kl); h0 = L / (double)(mesh_sizes[0] - 1); /* For given L0 mesh, iterate over N1 */ for(int N1 = 0; N1 <= bpf_sample_size ; N1 = N1 + N1_step) { N0 = N0_init; N0_step = 10000; /* For given L0 mesh and N1 iterate over increasing N0 until MLBPF time per iteration exceeds BPF time per iteration */ time_per_iteration = 0; direction = 1; // up while(1) { sample_sizes[0] = N0; sample_sizes[1] = N1; /* Estimate the time per iteration by averaging N_top runs */ time_per_iteration = 0; for(int nmc = 0; nmc < N_top; nmc++) { for(int i = 0; i < ldab * max_mesh_size; i++) ab_copy[i] = ab_bpf[i]; for(int i = 0; i < ldab * level_0_mesh_size; i++) ab0_copy[i] = ab0[i]; MLbootstrapfilter(y, std_sig, obs_std, data_length, x0, sample_sizes, worst_case_sign_ratio, NULL, filtering_time, mesh_sizes, kl, ku, ab0_copy, ab_copy, ldab, ipiv, ipiv, mesh_sizes[0], max_mesh_size, info, w, d, E, I, h0, h1, L, meass, N_MEASUREMENTS); // printf("TIMES: %e %e %e %e\n", filtering_time[0], filtering_time[1], filtering_time[2], filtering_time[3]); // fflush(stdout); time_per_iteration += filtering_time[0] / (double) N_top; } if (direction == 1 && time_per_iteration > bpf_time_per_iteration * time_tolerance && N0_step > 10) { direction = -1; // start going down N0_step /= 2; // halve the step } else if (direction == -1 && time_per_iteration < bpf_time_per_iteration * 1.00 && N0_step > 10) { direction = 1; N0_step /= 2; } else if (N0_step < 10) { break; } N0 = N0 + direction * N0_step; if(N0 < 1) { // Make sure N0 remains positive and go up if this happens N0 = 1; direction = 1; } } fprintf(out,"%i %i %i %i\n",N0-N0_step,N1,mesh_sizes[0],mesh_sizes[1]); fflush(out); } } fclose(out); free(ipiv); free(ab_copy); free(ab0_copy); free(A0); } double compute_estimation_error(double* x_hat, double* x_ref, int len) { double MSE = 0; for(int i = 0; i < len; i++) { MSE += (x_hat[i]-x_ref[i])*(x_hat[i]-x_ref[i]) / (double) len; } return MSE; } void init_with_zeros(double *array, long length) { for (int i = 0; i < length; i++) array[i] = 0; } void generate_signal(double* x, int len, double std_sig, double x0, gsl_rng* rng, double L) { double lower_bound = 0.25; double upper_bound = L - 0.25; x[0] = x0; for (int i = 1; i < len; i++){ x[i] = x[i - 1] + gsl_ran_gaussian(rng, std_sig); // x[i] = 0.5 / ((double)1.0 + exp(-(double)10.0 * (x[i - 1] - 1))) + (double) 0.75 + gsl_ran_gaussian(rng, std_sig); if(x[i] < lower_bound) x[i] = lower_bound + lower_bound-x[i]; if(x[i] > upper_bound) x[i] = upper_bound - (x[i]-upper_bound); } } void make_lapack_band_matrix(double *A, int n, double *ab, int ku, int kl) { int lower, upper, baserow,baserowcand ; int n_rows = 2 * kl + ku + 1; for (int j = 0; j < n; j++) { // iterate columns lower = j - ku > 0 ? j - ku : 0; upper = j + kl < n ? j + kl : n-1; baserowcand = n_rows - upper - 1; baserow = baserowcand < n_rows - (ku+kl+1)? n_rows - (ku+kl+1) : baserowcand; for (int i = lower; i <= upper; i++) { ab[n_rows * j + baserow + i - lower] = A[j * n + i]; } } } void create_dense_solver_matrix(double* A, int n) { double pattern[5] = { 1, -4, 6, -4, 1 }; /* Make sure there are zeros */ for(int i = 0; i < n*n; i++) A[i] = 0; /* First two lines */ for (int i = 0; i < n; i++) { A[i * n] = 0; A[i * n + 1] = 0; } A[0] = 16; A[1] = -4; A[n + 0] = -9; A[n + 1] = 6; A[2 * n + 0] = (double) 8 / (double) 3; A[2 * n + 1] = -4; A[3 * n + 0] = -(double) 1 / (double) 4; A[3 * n + 1] = (double) 1; /* Last two lines */ for (int i = 0; i < n; i++) { A[i * n + n - 2] = 0; A[i * n + n - 1] = 0; } // A[(n - 4) * n + n - 2] = (double) 16 / (double) 17; A[(n - 4) * n + n - 2] = (double) 1; // A[(n - 4) * n + n - 1] = -(double) 12 / (double) 17; A[(n - 4) * n + n - 1] = -(double) 1 / (double) 4; // A[(n - 3) * n + n - 2] = -(double) 60 / (double) 17; A[(n - 3) * n + n - 2] = -(double) 4; // A[(n - 3) * n + n - 1] = (double) 96 / (double) 17; A[(n - 3) * n + n - 1] = (double) 8 / (double) 3; // A[(n - 2) * n + n - 2] = (double) 72 / (double) 17; A[(n - 2) * n + n - 2] = (double) 6; // A[(n - 2) * n + n - 1] = -(double) 156 / (double) 17; A[(n - 2) * n + n - 1] = -(double) 9; // A[(n - 1) * n + n - 2] = -(double) 28 / (double) 17; A[(n - 1) * n + n - 2] = -(double) 4; // A[(n - 1) * n + n - 1] = (double) 72 / (double) 17; A[(n - 1) * n + n - 1] = (double) 16; /* The rest */ for (int i = 2; i < n - 2; i++) { // row for (int j = 0; j < n; j++) { A[j * n + i] = 0; } for (int j = 0; j < 5; j++) A[(j + i - 2) * n + i] = pattern[j]; } } void get_settings(int** settings) { // /* THIS IS FOR N = 1000 */ // int hc_settings[N_SETTINGS][4] = { // {38000, 0, 100, 4000}, //{36835, 40, 100, 4000}, //{36054, 80, 100, 4000}, //{36439, 120, 100, 4000}, //{35867, 160, 100, 4000}, //{35658, 200, 100, 4000}, //{34954, 240, 100, 4000}, //{34888, 280, 100, 4000}, //{34570, 320, 100, 4000}, //{34237, 360, 100, 4000}, //{33456, 400, 100, 4000}, //{32811, 440, 100, 4000}, //{32127, 480, 100, 4000}, //{30799, 520, 100, 4000}, //{29146, 560, 100, 4000}, //{27180, 600, 100, 4000}, //{24810, 640, 100, 4000}, //{22713, 680, 100, 4000}, //{20024, 720, 100, 4000}, //{17349, 760, 100, 4000}, //{14049, 800, 100, 4000}, //{10800, 840, 100, 4000}, //{7812, 880, 100, 4000}, //{4960, 920, 100, 4000}, //{2408, 960, 100, 4000}, //{36965, 0, 105, 4000}, //{36354, 40, 105, 4000}, //{35552, 80, 105, 4000}, //{34341, 120, 105, 4000}, //{34073, 160, 105, 4000}, //{33840, 200, 105, 4000}, //{33970, 240, 105, 4000}, //{33444, 280, 105, 4000}, //{33079, 320, 105, 4000}, //{32883, 360, 105, 4000}, //{32615, 400, 105, 4000}, //{32173, 440, 105, 4000}, //{31021, 480, 105, 4000}, //{29393, 520, 105, 4000}, //{27453, 560, 105, 4000}, //{25473, 600, 105, 4000}, //{23605, 640, 105, 4000}, //{21639, 680, 105, 4000}, //{19367, 720, 105, 4000}, //{16693, 760, 105, 4000}, //{13229, 800, 105, 4000}, //{10143, 840, 105, 4000}, //{7134, 880, 105, 4000}, //{4543, 920, 105, 4000}, //{2108, 960, 105, 4000}, //{35266, 0, 110, 4000}, //{35461, 40, 110, 4000}, //{35409, 80, 110, 4000}, //{35058, 120, 110, 4000}, //{34531, 160, 110, 4000}, //{33971, 200, 110, 4000}, //{33437, 240, 110, 4000}, //{33026, 280, 110, 4000}, //{32804, 320, 110, 4000}, //{32765, 360, 110, 4000}, //{32550, 400, 110, 4000}, //{31659, 440, 110, 4000}, //{30162, 480, 110, 4000}, //{28254, 520, 110, 4000}, //{26203, 560, 110, 4000}, //{24055, 600, 110, 4000}, //{21965, 640, 110, 4000}, //{19192, 680, 110, 4000}, //{16087, 720, 110, 4000}, //{12969, 760, 110, 4000}, //{10438, 800, 110, 4000}, //{8172, 840, 110, 4000}, //{5045, 880, 110, 4000}, //{2513, 920, 110, 4000}, //{605, 960, 110, 4000}, //{32765, 0, 115, 4000}, //{33038, 40, 115, 4000}, //{33013, 80, 115, 4000}, //{32440, 120, 115, 4000}, //{31593, 160, 115, 4000}, //{31444, 200, 115, 4000}, //{31444, 240, 115, 4000}, //{31235, 280, 115, 4000}, //{30265, 320, 115, 4000}, //{29243, 360, 115, 4000}, //{29035, 400, 115, 4000}, //{28579, 440, 115, 4000}, //{27928, 480, 115, 4000}, //{26274, 520, 115, 4000}, //{24568, 560, 115, 4000}, //{22960, 600, 115, 4000}, //{21743, 640, 115, 4000}, //{19972, 680, 115, 4000}, //{17707, 720, 115, 4000}, //{14634, 760, 115, 4000}, //{11717, 800, 115, 4000}, //{8586, 840, 115, 4000}, //{6040, 880, 115, 4000}, //{3749, 920, 115, 4000}, //{1867, 960, 115, 4000}, //{34171, 0, 120, 4000}, //{33248, 40, 120, 4000}, //{32916, 80, 120, 4000}, //{33066, 120, 120, 4000}, //{32969, 160, 120, 4000}, //{32323, 200, 120, 4000}, //{31901, 240, 120, 4000}, //{31776, 280, 120, 4000}, //{31932, 320, 120, 4000}, //{31580, 360, 120, 4000}, //{29759, 400, 120, 4000}, //{29077, 440, 120, 4000}, //{27950, 480, 120, 4000}, //{27637, 520, 120, 4000}, //{25709, 560, 120, 4000}, //{23834, 600, 120, 4000}, //{22322, 640, 120, 4000}, //{20388, 680, 120, 4000}, //{18175, 720, 120, 4000}, //{15142, 760, 120, 4000}, //{12278, 800, 120, 4000}, //{9471, 840, 120, 4000}, //{6984, 880, 120, 4000}, //{4640, 920, 120, 4000}, //{2362, 960, 120, 4000}, //{32765, 0, 130, 4000}, //{32765, 40, 130, 4000}, //{32622, 80, 130, 4000}, //{32244, 120, 130, 4000}, //{31763, 160, 130, 4000}, //{31249, 200, 130, 4000}, //{30553, 240, 130, 4000}, //{29629, 280, 130, 4000}, //{29062, 320, 130, 4000}, //{28794, 360, 130, 4000}, //{28585, 400, 130, 4000}, //{27778, 440, 130, 4000}, //{26463, 480, 130, 4000}, //{24966, 520, 130, 4000}, //{23411, 560, 130, 4000}, //{22420, 600, 130, 4000}, //{20878, 640, 130, 4000}, //{18827, 680, 130, 4000}, //{15982, 720, 130, 4000}, //{13273, 760, 130, 4000}, //{10487, 800, 130, 4000}, //{7955, 840, 130, 4000}, //{6021, 880, 130, 4000}, //{4524, 920, 130, 4000}, //{2864, 960, 130, 4000}, //{31926, 0, 140, 4000}, //{31405, 40, 140, 4000}, //{30917, 80, 140, 4000}, //{30312, 120, 140, 4000}, //{29876, 160, 140, 4000}, //{29433, 200, 140, 4000}, //{29055, 240, 140, 4000}, //{28579, 280, 140, 4000}, //{28058, 320, 140, 4000}, //{27524, 360, 140, 4000}, //{26952, 400, 140, 4000}, //{26073, 440, 140, 4000}, //{24790, 480, 140, 4000}, //{23332, 520, 140, 4000}, //{22290, 560, 140, 4000}, //{21386, 600, 140, 4000}, //{20128, 640, 140, 4000}, //{17993, 680, 140, 4000}, //{15493, 720, 140, 4000}, //{12941, 760, 140, 4000}, //{10454, 800, 140, 4000}, //{7915, 840, 140, 4000}, //{4605, 880, 140, 4000}, //{1955, 920, 140, 4000}, //{151, 960, 140, 4000}, //{30538, 0, 150, 4000}, //{29758, 40, 150, 4000}, //{29140, 80, 150, 4000}, //{28560, 120, 150, 4000}, //{27948, 160, 150, 4000}, //{27336, 200, 150, 4000}, //{26984, 240, 150, 4000}, //{26607, 280, 150, 4000}, //{26458, 320, 150, 4000}, //{26295, 360, 150, 4000}, //{26256, 400, 150, 4000}, //{25643, 440, 150, 4000}, //{24537, 480, 150, 4000}, //{23157, 520, 150, 4000}, //{22245, 560, 150, 4000}, //{21144, 600, 150, 4000}, //{19712, 640, 150, 4000}, //{17473, 680, 150, 4000}, //{15058, 720, 150, 4000}, //{12538, 760, 150, 4000}, //{10024, 800, 150, 4000}, //{7544, 840, 150, 4000}, //{5396, 880, 150, 4000}, //{3281, 920, 150, 4000}, //{1581, 960, 150, 4000}, //{22765, 0, 160, 4000}, //{22186, 40, 160, 4000}, //{21873, 80, 160, 4000}, //{21821, 120, 160, 4000}, //{21827, 160, 160, 4000}, //{21827, 200, 160, 4000}, //{21827, 240, 160, 4000}, //{21801, 280, 160, 4000}, //{21217, 320, 160, 4000}, //{20965, 360, 160, 4000}, //{20026, 400, 160, 4000}, //{19770, 440, 160, 4000}, //{18369, 480, 160, 4000}, //{17388, 520, 160, 4000}, //{15949, 560, 160, 4000}, //{15012, 600, 160, 4000}, //{13845, 640, 160, 4000}, //{12595, 680, 160, 4000}, //{11241, 720, 160, 4000}, //{9887, 760, 160, 4000}, //{8306, 800, 160, 4000}, //{6561, 840, 160, 4000}, //{4634, 880, 160, 4000}, //{2800, 920, 160, 4000}, //{1212, 960, 160, 4000}, //{26379, 0, 180, 4000}, //{26815, 40, 180, 4000}, //{26880, 80, 180, 4000}, //{26556, 120, 180, 4000}, //{26235, 160, 180, 4000}, //{25864, 200, 180, 4000}, //{25637, 240, 180, 4000}, //{25246, 280, 180, 4000}, //{24940, 320, 180, 4000}, //{24399, 360, 180, 4000}, //{23846, 400, 180, 4000}, //{23163, 440, 180, 4000}, //{22564, 480, 180, 4000}, //{21874, 520, 180, 4000}, //{20963, 560, 180, 4000}, //{19739, 600, 180, 4000}, //{17562, 640, 180, 4000}, //{14182, 680, 180, 4000}, //{11115, 720, 180, 4000}, //{8364, 760, 180, 4000}, //{6770, 800, 180, 4000}, //{5407, 840, 180, 4000}, //{4314, 880, 180, 4000}, //{3304, 920, 180, 4000}, //{1678, 960, 180, 4000}, //{25989, 0, 200, 4000}, //{25488, 40, 200, 4000}, //{25142, 80, 200, 4000}, //{24654, 120, 200, 4000}, //{24510, 160, 200, 4000}, //{24119, 200, 200, 4000}, //{23787, 240, 200, 4000}, //{23384, 280, 200, 4000}, //{22974, 320, 200, 4000}, //{22558, 360, 200, 4000}, //{22024, 400, 200, 4000}, //{21729, 440, 200, 4000}, //{21020, 480, 200, 4000}, //{19978, 520, 200, 4000}, //{18430, 560, 200, 4000}, //{16893, 600, 200, 4000}, //{15331, 640, 200, 4000}, //{13443, 680, 200, 4000}, //{11502, 720, 200, 4000}, //{9549, 760, 200, 4000}, //{7778, 800, 200, 4000}, //{6007, 840, 200, 4000}, //{4360, 880, 200, 4000}, //{2870, 920, 200, 4000}, //{1486, 960, 200, 4000}, //{23624, 0, 220, 4000}, //{23285, 40, 220, 4000}, //{22934, 80, 220, 4000}, //{22472, 120, 220, 4000}, //{22075, 160, 220, 4000}, //{21827, 200, 220, 4000}, //{21814, 240, 220, 4000}, //{21678, 280, 220, 4000}, //{21327, 320, 220, 4000}, //{20871, 360, 220, 4000}, //{20343, 400, 220, 4000}, //{19595, 440, 220, 4000}, //{18599, 480, 220, 4000}, //{17219, 520, 220, 4000}, //{15890, 560, 220, 4000}, //{14406, 600, 220, 4000}, //{12882, 640, 220, 4000}, //{11105, 680, 220, 4000}, //{9314, 720, 220, 4000}, //{7517, 760, 220, 4000}, //{5818, 800, 220, 4000}, //{4165, 840, 220, 4000}, //{2694, 880, 220, 4000}, //{1382, 920, 220, 4000}, //{497, 960, 220, 4000}, //{21398, 0, 240, 4000}, //{21047, 40, 240, 4000}, //{20754, 80, 240, 4000}, //{20422, 120, 240, 4000}, //{20154, 160, 240, 4000}, //{19861, 200, 240, 4000}, //{19607, 240, 240, 4000}, //{19269, 280, 240, 4000}, //{18892, 320, 240, 4000}, //{18508, 360, 240, 4000}, //{18098, 400, 240, 4000}, //{17518, 440, 240, 4000}, //{16593, 480, 240, 4000}, //{15441, 520, 240, 4000}, //{14230, 560, 240, 4000}, //{12994, 600, 240, 4000}, //{11594, 640, 240, 4000}, //{9999, 680, 240, 4000}, //{8320, 720, 240, 4000}, //{6698, 760, 240, 4000}, //{5188, 800, 240, 4000}, //{3827, 840, 240, 4000}, //{2532, 880, 240, 4000}, //{1271, 920, 240, 4000}, //{432, 960, 240, 4000}, //{21730, 0, 260, 4000}, //{21210, 40, 260, 4000}, //{20839, 80, 260, 4000}, //{20519, 120, 260, 4000}, //{20083, 160, 260, 4000}, //{19627, 200, 260, 4000}, //{19223, 240, 260, 4000}, //{18819, 280, 260, 4000}, //{18383, 320, 260, 4000}, //{18436, 360, 260, 4000}, //{18449, 400, 260, 4000}, //{18221, 440, 260, 4000}, //{17270, 480, 260, 4000}, //{16079, 520, 260, 4000}, //{14790, 560, 260, 4000}, //{13515, 600, 260, 4000}, //{12141, 640, 260, 4000}, //{10780, 680, 260, 4000}, //{9257, 720, 260, 4000}, //{7811, 760, 260, 4000}, //{6313, 800, 260, 4000}, //{4894, 840, 260, 4000}, //{3631, 880, 260, 4000}, //{2545, 920, 260, 4000}, //{1614, 960, 260, 4000}, //{21262, 0, 280, 4000}, //{20890, 40, 280, 4000}, //{20545, 80, 280, 4000}, //{20129, 120, 280, 4000}, //{19771, 160, 280, 4000}, //{19367, 200, 280, 4000}, //{18785, 240, 280, 4000}, //{18355, 280, 280, 4000}, //{17965, 320, 280, 4000}, //{17739, 360, 280, 4000}, //{17310, 400, 280, 4000}, //{16619, 440, 280, 4000}, //{15714, 480, 280, 4000}, //{14588, 520, 280, 4000}, //{13403, 560, 280, 4000}, //{12238, 600, 280, 4000}, //{10988, 640, 280, 4000}, //{9673, 680, 280, 4000}, //{8293, 720, 280, 4000}, //{6984, 760, 280, 4000}, //{5690, 800, 280, 4000}, //{4491, 840, 280, 4000}, //{3359, 880, 280, 4000}, //{2362, 920, 280, 4000}, //{1388, 960, 280, 4000}, //{13585, 0, 320, 4000}, //{13391, 40, 320, 4000}, //{13202, 80, 320, 4000}, //{12936, 120, 320, 4000}, //{12610, 160, 320, 4000}, //{12252, 200, 320, 4000}, //{11985, 240, 320, 4000}, //{11776, 280, 320, 4000}, //{11567, 320, 320, 4000}, //{11320, 360, 320, 4000}, //{10989, 400, 320, 4000}, //{10585, 440, 320, 4000}, //{9993, 480, 320, 4000}, //{9263, 520, 320, 4000}, //{8462, 560, 320, 4000}, //{7785, 600, 320, 4000}, //{7232, 640, 320, 4000}, //{6685, 680, 320, 4000}, //{6047, 720, 320, 4000}, //{5304, 760, 320, 4000}, //{4503, 800, 320, 4000}, //{3598, 840, 320, 4000}, //{2648, 880, 320, 4000}, //{1737, 920, 320, 4000}, //{881, 960, 320, 4000}, //{16086, 0, 360, 4000}, //{15669, 40, 360, 4000}, //{15330, 80, 360, 4000}, //{15096, 120, 360, 4000}, //{14796, 160, 360, 4000}, //{14465, 200, 360, 4000}, //{14075, 240, 360, 4000}, //{13743, 280, 360, 4000}, //{13455, 320, 360, 4000}, //{13150, 360, 360, 4000}, //{12786, 400, 360, 4000}, //{12284, 440, 360, 4000}, //{11554, 480, 360, 4000}, //{10630, 520, 360, 4000}, //{9686, 560, 360, 4000}, //{8827, 600, 360, 4000}, //{7960, 640, 360, 4000}, //{6945, 680, 360, 4000}, //{5904, 720, 360, 4000}, //{4824, 760, 360, 4000}, //{3840, 800, 360, 4000}, //{2922, 840, 360, 4000}, //{2108, 880, 360, 4000}, //{1386, 920, 360, 4000}, //{682, 960, 360, 4000}, //{13802, 0, 400, 4000}, //{13579, 40, 400, 4000}, //{13338, 80, 400, 4000}, //{13098, 120, 400, 4000}, //{12799, 160, 400, 4000}, //{12500, 200, 400, 4000}, //{12180, 240, 400, 4000}, //{11900, 280, 400, 4000}, //{11613, 320, 400, 4000}, //{11327, 360, 400, 4000}, //{11021, 400, 400, 4000}, //{10558, 440, 400, 4000}, //{9920, 480, 400, 4000}, //{9061, 520, 400, 4000}, //{8260, 560, 400, 4000}, //{7551, 600, 400, 4000}, //{6847, 640, 400, 4000}, //{5988, 680, 400, 4000}, //{4992, 720, 400, 4000}, //{4048, 760, 400, 4000}, //{3188, 800, 400, 4000}, //{2406, 840, 400, 4000}, //{1684, 880, 400, 4000}, //{1027, 920, 400, 4000}, //{480, 960, 400, 4000}, //{12200, 0, 440, 4000}, //{11984, 40, 440, 4000}, //{11737, 80, 440, 4000}, //{11483, 120, 440, 4000}, //{11229, 160, 440, 4000}, //{10949, 200, 440, 4000}, //{10631, 240, 440, 4000}, //{10365, 280, 440, 4000}, //{10156, 320, 440, 4000}, //{9946, 360, 440, 4000}, //{9646, 400, 440, 4000}, //{9224, 440, 440, 4000}, //{8657, 480, 440, 4000}, //{7941, 520, 440, 4000}, //{7270, 560, 440, 4000}, //{6593, 600, 440, 4000}, //{5878, 640, 440, 4000}, //{5039, 680, 440, 4000}, //{4200, 720, 440, 4000}, //{3424, 760, 440, 4000}, //{2700, 800, 440, 4000}, //{2017, 840, 440, 4000}, //{1385, 880, 440, 4000}, //{838, 920, 440, 4000}, //{382, 960, 440, 4000}, //{10206, 0, 500, 4000}, //{10018, 40, 500, 4000}, //{9829, 80, 500, 4000}, //{9608, 120, 500, 4000}, //{9386, 160, 500, 4000}, //{9152, 200, 500, 4000}, //{8931, 240, 500, 4000}, //{8697, 280, 500, 4000}, //{8476, 320, 500, 4000}, //{8261, 360, 500, 4000}, //{8027, 400, 500, 4000}, //{7669, 440, 500, 4000}, //{7200, 480, 500, 4000}, //{6608, 520, 500, 4000}, //{5989, 560, 500, 4000}, //{5357, 600, 500, 4000}, //{4699, 640, 500, 4000}, //{4042, 680, 500, 4000}, //{3398, 720, 500, 4000}, //{2778, 760, 500, 4000}, //{2160, 800, 500, 4000}, //{1554, 840, 500, 4000}, //{1036, 880, 500, 4000}, //{538, 920, 500, 4000}, // {200, 960, 500, 4000}}; /* THIS IS FOR N = 500 */ int hc_settings[N_SETTINGS][4] = { {19432, 0, 100, 4000}, {17976, 20, 100, 4000}, {17413, 40, 100, 4000}, {17524, 60, 100, 4000}, {17159, 80, 100, 4000}, {16432, 100, 100, 4000}, {15611, 120, 100, 4000}, {14817, 140, 100, 4000}, {13937, 160, 100, 4000}, {13338, 180, 100, 4000}, {12623, 200, 100, 4000}, {12284, 220, 100, 4000}, {11594, 240, 100, 4000}, {11080, 260, 100, 4000}, {10267, 280, 100, 4000}, {9648, 300, 100, 4000}, {8933, 320, 100, 4000}, {8340, 340, 100, 4000}, {7630, 360, 100, 4000}, {6983, 380, 100, 4000}, {6346, 400, 100, 4000}, {5709, 420, 100, 4000}, {4680, 440, 100, 4000}, {3456, 460, 100, 4000}, {1792, 480, 100, 4000}, {18429, 0, 105, 4000}, {17238, 20, 105, 4000}, {16495, 40, 105, 4000}, {15845, 60, 105, 4000}, {15584, 80, 105, 4000}, {15136, 100, 105, 4000}, {14420, 120, 105, 4000}, {13951, 140, 105, 4000}, {13261, 160, 105, 4000}, {12909, 180, 105, 4000}, {12408, 200, 105, 4000}, {11978, 220, 105, 4000}, {11398, 240, 105, 4000}, {10838, 260, 105, 4000}, {9959, 280, 105, 4000}, {9374, 300, 105, 4000}, {8715, 320, 105, 4000}, {8337, 340, 105, 4000}, {7706, 360, 105, 4000}, {7121, 380, 105, 4000}, {6425, 400, 105, 4000}, {5650, 420, 105, 4000}, {4310, 440, 105, 4000}, {3021, 460, 105, 4000}, {1423, 480, 105, 4000}, {17632, 0, 110, 4000}, {16920, 20, 110, 4000}, {16340, 40, 110, 4000}, {15910, 60, 110, 4000}, {15402, 80, 110, 4000}, {14849, 100, 110, 4000}, {14244, 120, 110, 4000}, {13651, 140, 110, 4000}, {13058, 160, 110, 4000}, {12486, 180, 110, 4000}, {11900, 200, 110, 4000}, {11366, 220, 110, 4000}, {10819, 240, 110, 4000}, {10260, 260, 110, 4000}, {9596, 280, 110, 4000}, {9017, 300, 110, 4000}, {8371, 320, 110, 4000}, {7967, 340, 110, 4000}, {7381, 360, 110, 4000}, {6867, 380, 110, 4000}, {6177, 400, 110, 4000}, {5520, 420, 110, 4000}, {4648, 440, 110, 4000}, {3398, 460, 110, 4000}, {1789, 480, 110, 4000}, {16904, 0, 115, 4000}, {16411, 20, 115, 4000}, {15943, 40, 115, 4000}, {15500, 60, 115, 4000}, {15057, 80, 115, 4000}, {14601, 100, 115, 4000}, {14010, 120, 115, 4000}, {13366, 140, 115, 4000}, {12650, 160, 115, 4000}, {12082, 180, 115, 4000}, {11554, 200, 115, 4000}, {11138, 220, 115, 4000}, {10695, 240, 115, 4000}, {10200, 260, 115, 4000}, {9588, 280, 115, 4000}, {8970, 300, 115, 4000}, {8449, 320, 115, 4000}, {7889, 340, 115, 4000}, {7336, 360, 115, 4000}, {6686, 380, 115, 4000}, {6133, 400, 115, 4000}, {5494, 420, 115, 4000}, {4497, 440, 115, 4000}, {3266, 460, 115, 4000}, {1665, 480, 115, 4000}, {16498, 0, 120, 4000}, {16055, 20, 120, 4000}, {15631, 40, 120, 4000}, {15194, 60, 120, 4000}, {14751, 80, 120, 4000}, {14295, 100, 120, 4000}, {13624, 120, 120, 4000}, {12993, 140, 120, 4000}, {12343, 160, 120, 4000}, {11848, 180, 120, 4000}, {11333, 200, 120, 4000}, {10760, 220, 120, 4000}, {10213, 240, 120, 4000}, {9692, 260, 120, 4000}, {9204, 280, 120, 4000}, {8723, 300, 120, 4000}, {8189, 320, 120, 4000}, {7648, 340, 120, 4000}, {7049, 360, 120, 4000}, {6516, 380, 120, 4000}, {5917, 400, 120, 4000}, {5214, 420, 120, 4000}, {4328, 440, 120, 4000}, {3116, 460, 120, 4000}, {1658, 480, 120, 4000}, {14992, 0, 130, 4000}, {14608, 20, 130, 4000}, {14224, 40, 130, 4000}, {13891, 60, 130, 4000}, {13488, 80, 130, 4000}, {13065, 100, 130, 4000}, {12538, 120, 130, 4000}, {11940, 140, 130, 4000}, {11386, 160, 130, 4000}, {10872, 180, 130, 4000}, {10390, 200, 130, 4000}, {9856, 220, 130, 4000}, {9420, 240, 130, 4000}, {8873, 260, 130, 4000}, {8358, 280, 130, 4000}, {7739, 300, 130, 4000}, {7264, 320, 130, 4000}, {6789, 340, 130, 4000}, {6366, 360, 130, 4000}, {5903, 380, 130, 4000}, {5448, 400, 130, 4000}, {4797, 420, 130, 4000}, {3938, 440, 130, 4000}, {2830, 460, 130, 4000}, {1496, 480, 130, 4000}, {14152, 0, 140, 4000}, {13710, 20, 140, 4000}, {13286, 40, 140, 4000}, {12941, 60, 140, 4000}, {12505, 80, 140, 4000}, {12075, 100, 140, 4000}, {11554, 120, 140, 4000}, {11098, 140, 140, 4000}, {10604, 160, 140, 4000}, {10200, 180, 140, 4000}, {9692, 200, 140, 4000}, {9210, 220, 140, 4000}, {8748, 240, 140, 4000}, {8305, 260, 140, 4000}, {7850, 280, 140, 4000}, {7264, 300, 140, 4000}, {6750, 320, 140, 4000}, {6307, 340, 140, 4000}, {5884, 360, 140, 4000}, {5447, 380, 140, 4000}, {4952, 400, 140, 4000}, {4458, 420, 140, 4000}, {3729, 440, 140, 4000}, {2668, 460, 140, 4000}, {1366, 480, 140, 4000}, {13138, 0, 150, 4000}, {12792, 20, 150, 4000}, {12551, 40, 150, 4000}, {12212, 60, 150, 4000}, {11828, 80, 150, 4000}, {11469, 100, 150, 4000}, {11073, 120, 150, 4000}, {10643, 140, 150, 4000}, {10025, 160, 150, 4000}, {9536, 180, 150, 4000}, {9159, 200, 150, 4000}, {8767, 220, 150, 4000}, {8338, 240, 150, 4000}, {7843, 260, 150, 4000}, {7453, 280, 150, 4000}, {7062, 300, 150, 4000}, {6593, 320, 150, 4000}, {6072, 340, 150, 4000}, {5682, 360, 150, 4000}, {5226, 380, 150, 4000}, {4849, 400, 150, 4000}, {4354, 420, 150, 4000}, {3742, 440, 150, 4000}, {2759, 460, 150, 4000}, {1447, 480, 150, 4000}, {11320, 0, 160, 4000}, {11060, 20, 160, 4000}, {10787, 40, 160, 4000}, {10513, 60, 160, 4000}, {10083, 80, 160, 4000}, {9712, 100, 160, 4000}, {9485, 120, 160, 4000}, {9276, 140, 160, 4000}, {9037, 160, 160, 4000}, {8743, 180, 160, 4000}, {8437, 200, 160, 4000}, {8110, 220, 160, 4000}, {7680, 240, 160, 4000}, {7257, 260, 160, 4000}, {6867, 280, 160, 4000}, {6483, 300, 160, 4000}, {6053, 320, 160, 4000}, {5643, 340, 160, 4000}, {5220, 360, 160, 4000}, {4803, 380, 160, 4000}, {4379, 400, 160, 4000}, {3892, 420, 160, 4000}, {3241, 440, 160, 4000}, {2303, 460, 160, 4000}, {1189, 480, 160, 4000}, {11125, 0, 180, 4000}, {10799, 20, 180, 4000}, {10526, 40, 180, 4000}, {10213, 60, 180, 4000}, {9920, 80, 180, 4000}, {9484, 100, 180, 4000}, {9016, 120, 180, 4000}, {8553, 140, 180, 4000}, {8156, 160, 180, 4000}, {7843, 180, 180, 4000}, {7576, 200, 180, 4000}, {7297, 220, 180, 4000}, {6985, 240, 180, 4000}, {6659, 260, 180, 4000}, {6346, 280, 180, 4000}, {5994, 300, 180, 4000}, {5604, 320, 180, 4000}, {5161, 340, 180, 4000}, {4751, 360, 180, 4000}, {4335, 380, 180, 4000}, {3963, 400, 180, 4000}, {3410, 420, 180, 4000}, {2720, 440, 180, 4000}, {1802, 460, 180, 4000}, {891, 480, 180, 4000}, {9699, 0, 200, 4000}, {9426, 20, 200, 4000}, {9159, 40, 200, 4000}, {8892, 60, 200, 4000}, {8612, 80, 200, 4000}, {8293, 100, 200, 4000}, {7955, 120, 200, 4000}, {7590, 140, 200, 4000}, {7284, 160, 200, 4000}, {6938, 180, 200, 4000}, {6600, 200, 200, 4000}, {6229, 220, 200, 4000}, {5891, 240, 200, 4000}, {5578, 260, 200, 4000}, {5252, 280, 200, 4000}, {4947, 300, 200, 4000}, {4576, 320, 200, 4000}, {4244, 340, 200, 4000}, {3879, 360, 200, 4000}, {3599, 380, 200, 4000}, {3286, 400, 200, 4000}, {2928, 420, 200, 4000}, {2368, 440, 200, 4000}, {1633, 460, 200, 4000}, {813, 480, 200, 4000}, {8859, 0, 220, 4000}, {8637, 20, 220, 4000}, {8397, 40, 220, 4000}, {8130, 60, 220, 4000}, {7844, 80, 220, 4000}, {7563, 100, 220, 4000}, {7277, 120, 220, 4000}, {6932, 140, 220, 4000}, {6601, 160, 220, 4000}, {6255, 180, 220, 4000}, {5969, 200, 220, 4000}, {5682, 220, 220, 4000}, {5383, 240, 220, 4000}, {5057, 260, 220, 4000}, {4732, 280, 220, 4000}, {4439, 300, 220, 4000}, {4166, 320, 220, 4000}, {3840, 340, 220, 4000}, {3534, 360, 220, 4000}, {3214, 380, 220, 4000}, {2889, 400, 220, 4000}, {2512, 420, 220, 4000}, {2030, 440, 220, 4000}, {1444, 460, 220, 4000}, {741, 480, 220, 4000}, {7980, 0, 240, 4000}, {7766, 20, 240, 4000}, {7538, 40, 240, 4000}, {7323, 60, 240, 4000}, {7115, 80, 240, 4000}, {6848, 100, 240, 4000}, {6561, 120, 240, 4000}, {6196, 140, 240, 4000}, {5897, 160, 240, 4000}, {5604, 180, 240, 4000}, {5331, 200, 240, 4000}, {5064, 220, 240, 4000}, {4784, 240, 240, 4000}, {4491, 260, 240, 4000}, {4237, 280, 240, 4000}, {3969, 300, 240, 4000}, {3729, 320, 240, 4000}, {3436, 340, 240, 4000}, {3143, 360, 240, 4000}, {2850, 380, 240, 4000}, {2563, 400, 240, 4000}, {2277, 420, 240, 4000}, {1854, 440, 240, 4000}, {1294, 460, 240, 4000}, {636, 480, 240, 4000}, {7414, 0, 260, 4000}, {7180, 20, 260, 4000}, {6939, 40, 260, 4000}, {6712, 60, 260, 4000}, {6471, 80, 260, 4000}, {6262, 100, 260, 4000}, {6008, 120, 260, 4000}, {5734, 140, 260, 4000}, {5402, 160, 260, 4000}, {5142, 180, 260, 4000}, {4920, 200, 260, 4000}, {4712, 220, 260, 4000}, {4458, 240, 260, 4000}, {4178, 260, 260, 4000}, {3943, 280, 260, 4000}, {3696, 300, 260, 4000}, {3449, 320, 260, 4000}, {3189, 340, 260, 4000}, {2949, 360, 260, 4000}, {2701, 380, 260, 4000}, {2434, 400, 260, 4000}, {2121, 420, 260, 4000}, {1698, 440, 260, 4000}, {1157, 460, 260, 4000}, {565, 480, 260, 4000}, {6652, 0, 280, 4000}, {6503, 20, 280, 4000}, {6301, 40, 280, 4000}, {6093, 60, 280, 4000}, {5884, 80, 280, 4000}, {5689, 100, 280, 4000}, {5441, 120, 280, 4000}, {5193, 140, 280, 4000}, {4934, 160, 280, 4000}, {4693, 180, 280, 4000}, {4452, 200, 280, 4000}, {4217, 220, 280, 4000}, {3996, 240, 280, 4000}, {3775, 260, 280, 4000}, {3567, 280, 280, 4000}, {3326, 300, 280, 4000}, {3098, 320, 280, 4000}, {2850, 340, 280, 4000}, {2616, 360, 280, 4000}, {2382, 380, 280, 4000}, {2134, 400, 280, 4000}, {1880, 420, 280, 4000}, {1502, 440, 280, 4000}, {1033, 460, 280, 4000}, {499, 480, 280, 4000}, {5226, 0, 320, 4000}, {5142, 20, 320, 4000}, {5038, 40, 320, 4000}, {4933, 60, 320, 4000}, {4797, 80, 320, 4000}, {4654, 100, 320, 4000}, {4498, 120, 320, 4000}, {4335, 140, 320, 4000}, {4172, 160, 320, 4000}, {4002, 180, 320, 4000}, {3821, 200, 320, 4000}, {3580, 220, 320, 4000}, {3365, 240, 320, 4000}, {3157, 260, 320, 4000}, {2987, 280, 320, 4000}, {2785, 300, 320, 4000}, {2596, 320, 320, 4000}, {2414, 340, 320, 4000}, {2212, 360, 320, 4000}, {1978, 380, 320, 4000}, {1757, 400, 320, 4000}, {1528, 420, 320, 4000}, {1242, 440, 320, 4000}, {812, 460, 320, 4000}, {376, 480, 320, 4000}, {4874, 0, 360, 4000}, {4718, 20, 360, 4000}, {4556, 40, 360, 4000}, {4380, 60, 360, 4000}, {4211, 80, 360, 4000}, {4062, 100, 360, 4000}, {3906, 120, 360, 4000}, {3723, 140, 360, 4000}, {3527, 160, 360, 4000}, {3358, 180, 360, 4000}, {3202, 200, 360, 4000}, {3032, 220, 360, 4000}, {2863, 240, 360, 4000}, {2720, 260, 360, 4000}, {2571, 280, 360, 4000}, {2388, 300, 360, 4000}, {2193, 320, 360, 4000}, {2004, 340, 360, 4000}, {1847, 360, 360, 4000}, {1678, 380, 360, 4000}, {1509, 400, 360, 4000}, {1294, 420, 360, 4000}, {1047, 440, 360, 4000}, {688, 460, 360, 4000}, {337, 480, 360, 4000}, {4153, 0, 400, 4000}, {4042, 20, 400, 4000}, {3911, 40, 400, 4000}, {3787, 60, 400, 4000}, {3657, 80, 400, 4000}, {3533, 100, 400, 4000}, {3364, 120, 400, 4000}, {3189, 140, 400, 4000}, {3006, 160, 400, 4000}, {2889, 180, 400, 4000}, {2752, 200, 400, 4000}, {2635, 220, 400, 4000}, {2465, 240, 400, 4000}, {2316, 260, 400, 4000}, {2166, 280, 400, 4000}, {2024, 300, 400, 4000}, {1874, 320, 400, 4000}, {1711, 340, 400, 4000}, {1561, 360, 400, 4000}, {1418, 380, 400, 4000}, {1262, 400, 400, 4000}, {1093, 420, 400, 4000}, {892, 440, 400, 4000}, {598, 460, 400, 4000}, {292, 480, 400, 4000}, {3664, 0, 440, 4000}, {3541, 20, 440, 4000}, {3437, 40, 440, 4000}, {3332, 60, 440, 4000}, {3221, 80, 440, 4000}, {3091, 100, 440, 4000}, {2948, 120, 440, 4000}, {2805, 140, 440, 4000}, {2674, 160, 440, 4000}, {2544, 180, 440, 4000}, {2420, 200, 440, 4000}, {2303, 220, 440, 4000}, {2192, 240, 440, 4000}, {2062, 260, 440, 4000}, {1919, 280, 440, 4000}, {1782, 300, 440, 4000}, {1652, 320, 440, 4000}, {1522, 340, 440, 4000}, {1398, 360, 440, 4000}, {1255, 380, 440, 4000}, {1105, 400, 440, 4000}, {923, 420, 440, 4000}, {766, 440, 440, 4000}, {512, 460, 440, 4000}, {265, 480, 440, 4000}, {3077, 0, 500, 4000}, {2974, 20, 500, 4000}, {2948, 40, 500, 4000}, {2877, 60, 500, 4000}, {2799, 80, 500, 4000}, {2629, 100, 500, 4000}, {2498, 120, 500, 4000}, {2446, 140, 500, 4000}, {2388, 160, 500, 4000}, {2349, 180, 500, 4000}, {2161, 200, 500, 4000}, {1991, 220, 500, 4000}, {1815, 240, 500, 4000}, {1704, 260, 500, 4000}, {1593, 280, 500, 4000}, {1470, 300, 500, 4000}, {1354, 320, 500, 4000}, {1236, 340, 500, 4000}, {1125, 360, 500, 4000}, {1001, 380, 500, 4000}, {871, 400, 500, 4000}, {741, 420, 500, 4000}, {611, 440, 500, 4000}, {379, 460, 500, 4000}, {171, 480, 500, 4000}}; for(int i = 0; i < N_SETTINGS; i++) for(int j = 0; j < 4; j++) settings[i][j] = hc_settings[i][j]; }
{ "alphanum_fraction": 0.5881454453, "avg_line_length": 29.9288888889, "ext": "c", "hexsha": "e2d0a1ea9aed0400ad74366fd009f0e1082d88f9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "heinekmp/MLBPF", "max_forks_repo_path": "ODE_MODEL/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "heinekmp/MLBPF", "max_issues_repo_path": "ODE_MODEL/main.c", "max_line_length": 359, "max_stars_count": null, "max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "heinekmp/MLBPF", "max_stars_repo_path": "ODE_MODEL/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 21395, "size": 47138 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef batch_8317ae94_87f4_4cc2_8dab_1eef2919a461_h #define batch_8317ae94_87f4_4cc2_8dab_1eef2919a461_h #include <ariel/config.h> #include <gslib/rtree.h> #include <ariel/loopblinn.h> __ariel_begin__ struct bat_triangle; struct bat_line; struct bat_batch; typedef vector<bat_triangle*> bat_triangles; typedef vector<bat_line*> bat_lines; typedef rtree_entity<bat_triangle*> bat_rtree_entity; typedef rtree_node<bat_rtree_entity> bat_rtree_node; typedef _tree_allocator<bat_rtree_node> bat_rtree_alloc; typedef tree<bat_rtree_entity, bat_rtree_node, bat_rtree_alloc> bat_tree; typedef rtree<bat_rtree_entity, quadratic_split_alg<16, 6, bat_tree>, bat_rtree_node, bat_rtree_alloc> bat_rtree; typedef vector<bat_batch*> bat_batches; enum bat_type { bf_start, bf_cr = bf_start, /* pt, cr */ bf_klm_cr, /* pt, klm, cr */ bf_klm_tex, /* pt, klm, tex */ bf_end = bf_klm_tex, bs_start, bs_coef_cr = bs_start, /* pt, coef, cr */ bs_coef_tex, /* pt, coef, tex */ bs_end = bs_coef_tex, }; struct bat_triangle { lb_joint* _joints[3]; vec2 _reduced[3]; /* get a reduced triangle so that no overlapping caused by error would be detected. */ float _zorder; bool _is_reduced; public: bat_triangle(); bat_triangle(lb_joint* i, lb_joint* j, lb_joint* k); ~bat_triangle() {} void make_rect(rectf& rc) const; void set_joint(int i, lb_joint* p) { _joints[i] = p; } lb_joint* get_joint(int i) const { return _joints[i]; } const vec2& get_point(int i) const { return _joints[i]->get_point(); } void* get_lb_binding(int i) const { return _joints[i]->get_binding(); } bat_type decide(uint brush_tag) const; bool has_klm_coords() const; const vec2& get_reduced_point(int i) const; bool is_overlapped(const bat_triangle& other) const; void ensure_make_reduced(); void set_zorder(float z) { _zorder = z; } float get_zorder() const { return _zorder; } void get_center(vec2& c) const; void tracing() const; void trace_reduced_points() const; }; struct bat_line { vec2 _points[2]; vec2 _contourpt[4]; /* calculated contour pts */ lb_joint* _srcjs[2]; vec3 _coef; float _width; float _zorder; uint _tag; /* pen tag */ bool _half; /* is half line? */ bool _recalc; /* need recalculation? */ public: bat_line(); void set_start_point(const vec2& p) { _points[0] = p; } void set_end_point(const vec2& p) { _points[1] = p; } void set_source_joint(int i, lb_joint* j) { _srcjs[i] = j; } lb_joint* get_source_joint(int i) const { return _srcjs[i]; } const vec2& get_start_point() const { return _points[0]; } const vec2& get_end_point() const { return _points[1]; } void set_pen_tag(uint t) { _tag = t; } void setup_coef(); void set_coef(const vec3& c) { _coef = c; } const vec3& get_coef() const { return _coef; } void set_zorder(float z) { _zorder = z; } float get_zorder() const { return _zorder; } void set_line_width(float w) { _width = w; } float get_line_width() const { return _width; } void set_half_line(bool hl) { _half = hl; } bool is_half_line() const { return _half; } bat_type decide() const; void get_bound_rect(rectf& rc) const; int clip_triangle(bat_line output[2], const bat_triangle* triangle) const; void calc_contour_points(); const vec2& get_contour_point(int i) const { return _contourpt[i]; } void set_contour_point(int i, const vec2& p) { _contourpt[i] = p; } bool set_need_recalc(bool b) { _recalc = b; } bool need_recalc() const { return _recalc; } void trim_contour(bat_line& line); void tracing() const; public: static bat_line* create_line(lb_joint* i, lb_joint* j, float w, float z, uint t, bool half); static bat_line* create_half_line(lb_joint* i, lb_joint* j, const vec2& p1, const vec2& p2, float w, float z, uint t); }; struct bat_batch { bat_type _type; public: bat_batch(bat_type t): _type(t) {} virtual ~bat_batch() {} bat_type get_type() const { return _type; } }; struct bat_fill_batch: public bat_batch { bat_rtree _rtree; public: bat_fill_batch(bat_type t): bat_batch(t) {} bat_rtree& get_rtree() { return _rtree; } const bat_rtree& const_rtree() const { return _rtree; } }; struct bat_stroke_batch: public bat_batch { bat_lines _lines; public: bat_stroke_batch(bat_type t): bat_batch(t) {} void add_line(bat_line* p) { _lines.push_back(p); } bat_lines& get_lines() { return _lines; } const bat_lines& const_lines() const { return _lines; } }; struct bat_stroke_host_batch: public bat_stroke_batch { public: bat_stroke_host_batch(bat_type t): bat_stroke_batch(t) {} virtual ~bat_stroke_host_batch(); }; class batch_processor { public: typedef bat_batches::iterator bat_iter; typedef bat_batches::const_iterator bat_const_iter; typedef bat_batches::reverse_iterator bat_reversed_iter; friend class rose; public: batch_processor(); ~batch_processor(); void set_antialias(bool b) { _antialias = b; } bool is_aa_enabled() const { return _antialias; } void add_non_tex_polygon(lb_polygon* poly, float z, uint brush_tag); bat_batch* add_tex_polygons(lb_polygon_list& polys, float z); bat_line* add_line(lb_joint* i, lb_joint* j, float w, float z, uint pen_tag); bat_line* add_aa_border(lb_joint* i, lb_joint* j, float z, uint pen_tag); void finish_batching(); bat_batches& get_batches() { return _batches; } void clear_batches(); protected: bat_triangles _triangles; bat_lines _lines; bat_batches _batches; bool _antialias; protected: template<class _batch> _batch* create_batch(bat_type t); bat_triangle* create_triangle(lb_joint* i, lb_joint* j, lb_joint* k, float z); bat_line* create_line(lb_joint* i, lb_joint* j, float w, float z, uint t, bool half); bat_line* create_half_line(lb_joint* i, lb_joint* j, const vec2& p1, const vec2& p2, float w, float z, uint t); void add_triangle(lb_joint* i, lb_joint* j, lb_joint* k, bool b[3], float z, uint brush_tag); void collect_aa_borders(bat_triangle* triangle, bool b[3], uint pen_tag); void proceed_line_batch(); void gather_tex_triangles(bat_triangles& triangles, lb_polygon* poly, float z); bat_batch* find_containable_tex_batch(const bat_triangles& triangles); bat_stroke_batch* find_associated_tex_stroke_batch(const bat_batch* bat); }; __ariel_end__ #endif
{ "alphanum_fraction": 0.6624954879, "avg_line_length": 37.269058296, "ext": "h", "hexsha": "3d91c886dd68b125ff192ec9a86cb579171ffc18", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/ariel/batch.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/ariel/batch.h", "max_line_length": 131, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/ariel/batch.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 2197, "size": 8311 }