File size: 133,922 Bytes
803451e | 1 2 3 4 5 | {"text": "#ifndef _CHAIN_H_\n#define _CHAIN_H_\n\n\n\n/* ---------------------------------------------------------\n headers\n --------------------------------------------------------- */\n#include <stdio.h>\n#include <string>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n\n// my headers\n#include <md.h>\n#include <debug.h>\n\n\n#include \"dcdio.h\"\n\n\n// headers 3rd\n/* #include <armadillo> */\n/* #include <gsl/gsl_math.h> */\n/* #include <gsl/gsl_eigen.h> */\n\n/* #include \"boost/multi_array.hpp\" */\n#include <cassert>\n\n/* SYMLINK: Eigen /usr/local/include/. */\n/* [dale~/sop_dev/contacts/segment]$lt /usr/local/include/eigen */\n/* lrwxrwxrwx 1 root root 25 09.25.2015 21:04 /usr/local/include/eigen -> /usr/include/eigen3/Eigen/ */\n/* #include<Eigen/Eigenvalues> */\n/* #include <Eigen/Dense> */\n\n#ifdef INERTIA\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\nusing namespace Eigen;\n#endif // INERTIA\n\n/* using namespace Eigen; */\n\n\n\n // namespaces\n/* using namespace arma; */\n\n/* ---------------------------------------------------------\n definitions\n --------------------------------------------------------- */\n/* 2000, 100; 700,20; 500,50 */\n#if defined ONEMOL || defined ALLATOM\n#define MOLECULE_INITIAL_SIZE 6900\n#define MOLECULE_INITIAL_SIZE_MT 6900\n#else\n#define MOLECULE_INITIAL_SIZE 700\n#define MOLECULE_INITIAL_SIZE_MT 700\n#endif // ONEMOL\n#define MAX_CONTACTS 24 /* per atom */\n\nclass Contact {\npublic:\n /* int resid; */\n int cresid;\n\n int total;\n\n int index; // index\n int cindex; // contacted index\n\n double eh; // energy scaling (well depth)\n double distance;\n\n\n // Constructor\n Contact (); // Constructor declared.\n\n\n // Destructors:\n ~Contact() {\n /* delete [] pos; */\n };\n\n};\ninline Contact::Contact() {\n cresid = -1;\n index = -1;\n cindex = -1;\n total = -1;\n eh = 0.0; // keep at 0.0, used in assign_contact_eh as default\n distance = 0.0;\n}\n\n\n\ntypedef struct Chain Molecule;\n\n\nclass Chain {\npublic:\n char filename[46];\n\n int chainid;\n int num_atoms;\n int num_atoms_ca;\n\n int index;\n int findex;\n int pf_pos_low; // for selecting index near midpoint of centroids, curvature of PF\n int pf_pos_high;\n int file_line_begin;\n int file_line_end;\n\n char atomtype[MOLECULE_INITIAL_SIZE][4];\n char resname[MOLECULE_INITIAL_SIZE][4];\n int resid[MOLECULE_INITIAL_SIZE];\n int indices[MOLECULE_INITIAL_SIZE]; // not used yet.\n\n Vector pos[MOLECULE_INITIAL_SIZE];\n Contact contacts[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];\n\n int total_num_contacts_2x;\n int tally_num_contacts_2x[MOLECULE_INITIAL_SIZE];\n int num_contacts_2x_persist_ref[MOLECULE_INITIAL_SIZE];\n\n Vector centroid;\n int nearest_targets[32];\n double nearest_targets_dist[32];\n int nearestneighbors_chainid[8];\n double nearestneighbors_dist[8];\n\n\n int LonN; // contacted monomer\n int LatE;\n int LonS;\n int LatW;\n int LonN_total2x; // total\n int LatE_total2x;\n int LonS_total2x;\n int LatW_total2x;\n\n\n // general inter\n Contact intercontacts[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];\n\n // latlon contacts\n Contact contactsLonN[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];\n Contact contactsLatE[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];\n Contact contactsLonS[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];\n Contact contactsLatW[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];\n\n\n\n // Constructors:\n Chain(int a=-1, int b = 0, double p = 0.0, double q = -1.0) {\n chainid = a;\n num_atoms = a;\n num_atoms_ca = a;\n index = a;\n findex = a;\n pf_pos_low = a;\n pf_pos_high = a;\n file_line_begin = a;\n file_line_end = a;\n total_num_contacts_2x = a;\n\n centroid.x = p;\n centroid.y = p;\n centroid.z = p;\n\n LonN = a;\n LonS = a;\n LatW = a;\n LatE = a;\n\n // initialize to 0.0 p\n for (int i=0; i < MOLECULE_INITIAL_SIZE; i++ ) {\n pos[i].x = p;\n pos[i].y = p;\n pos[i].z = p;\n\n // initialize to 0 b\n tally_num_contacts_2x[i] = b;\n num_contacts_2x_persist_ref[i] = b;\n\n\n for ( int j=0; j < MAX_CONTACTS; j++ ) {\n contacts[i][j].cresid = a;\n contacts[i][j].distance = p;\n }\n for ( int j=0; j < 8; j++ ) {\n nearestneighbors_chainid[j] = -1;\n nearestneighbors_dist[j] = p;\n }\n for ( int j=0; j < 32; j++ ) {\n nearest_targets[j] = a;\n }\n }\n }\n\n // Destructors:\n ~Chain() {\n /* delete [] pos; */\n /* std::cout << \"Object is being deleted\" << std::endl; */\n };\n\n // Declarations:\n void print_prop();\n void assign_indices();\n void fprintf_indices();\n void GetMomentofInertiaTensor();\n void ComputeCentroid();\n void print_centroid();\n\n int countcontacts(Contact (*map)[MAX_CONTACTS]);\n\n};\ninline void Chain::ComputeCentroid() {\n int i;\n double xtot = 0.0, ytot = 0.0, ztot = 0.0;\n /* printf(\"computing centroid ca: %d\\n\",num_atoms_ca); */\n for ( int i=0; i < num_atoms_ca; i++ ) {\n /* printf(\"%d\\n\",i); */\n xtot += pos[i].x;\n ytot += pos[i].y;\n ztot += pos[i].z;\n }\n centroid.x = xtot / num_atoms_ca;\n centroid.y = ytot / num_atoms_ca;\n centroid.z = ztot / num_atoms_ca;\n // PRINT HERE\n /* debug(\"c(%d): %f %f %f\\n\",chainid,centroid.x,centroid.y,centroid.z); */\n}\n\n// amazing!!\n/* By declared that method with inline keyword, compiler will either inline */\n/* the whole method or, if it decides not to, it will generate anonymous */\n/* method (same method but with some unique name for a given object file), */\n/* so there will be no conflicts in object files. For example: */\n/* class foo { */\n/* public: */\n/* void bar (); */\n/* }; */\n/* inline void foo::bar () */\n/* { */\n/* } */\ninline void Chain::print_prop() {\n /* printf(\"id: %d \",chainid); */\n /* printf(\" filename: %s\\n\",filename); */\n /* printf(\"CA: %d \",num_atoms_ca); */\n /* printf(\" index(%d) \",index); */\n /* printf(\" final_index(%d)\\n\",findex); */\n /* printf(\"begin_end: [ %d %d ]\\n\\n\",file_line_begin,file_line_end); */\n\n /* debug(\"id: %d CA: %d\\n\",chainid,num_atoms_ca); */\n /* debug(\" filename: %s\\n\",filename); */\n /* debug(\"CA: %d \\n\",num_atoms_ca); */\n /* debug(\" index(%d) \\n\",index); */\n /* debug(\" final_index(%d)\\n\",findex); */\n /* debug(\"begin_end: [ %d %d ]\\n\",file_line_begin,file_line_end); */\n\n printf(\"centroid: %f %f %f\\n\",centroid.x,centroid.y,centroid.z);\n}\ninline void Chain::print_centroid() {\n printf(\"centroid: %f %f %f\\n\",centroid.x,centroid.y,centroid.z);\n}\ninline void Chain::assign_indices() {\n /* printf(\"id: %d \",chainid); */\n /* printf(\" filename: %s\\n\",filename); */\n /* printf(\"CA: %d \",num_atoms_ca); */\n /* printf(\" index(%d) \",index); */\n /* printf(\" final_index(%d)\\n\",findex); */\n /* printf(\"begin_end: [ %d %d ]\\n\\n\",file_line_begin,file_line_end); */\n\n debug(\"id: %d atoms:%d CA:%d\\n\",chainid,num_atoms,num_atoms_ca);\n /* debug(\" filename: %s\\n\",filename); */\n /* debug(\"CA: %d \\n\",num_atoms_ca); */\n /* debug(\" index(%d) \\n\",index); */\n /* debug(\" final_index(%d)\\n\",findex); */\n debug(\"begin_end: [ %d %d ]\\n\",file_line_begin,file_line_end);\n\n for( int i=0; i < num_atoms_ca; i++ ) {\n indices[i] = index + i;\n }\n}\ninline void Chain::fprintf_indices() {\n /* printf(\" index(%d) \",index); */\n /* printf(\" final_index(%d)\\n\",findex); */\n printf(\" %d__[%d|%d]\\n\",chainid,index,findex);\n\n FILE * fp_indices;\n fp_indices = fopen(\"indices_foreach_segments.dat\",\"a+\");\n for ( int i=0; i < num_atoms_ca; i++ ) {\n fprintf(fp_indices,\"%6d %6d %6d\\n\",chainid,index,findex);\n }\n fclose(fp_indices);\n\n /* for( int i=0; i < num_atoms_ca; i++ ) { */\n /* /\\* indices[i] = index + i; *\\/ */\n /* printf(\" %d\",indices[i]); */\n /* printf(\" \") */\n /* } */\n /* printf(\"\\n\"); */\n}\n\ninline int Chain::countcontacts(Contact (*map)[MAX_CONTACTS]) {\n\n /* printf(\"declare countcontacts!\\n\"); */\n int count = 0;\n\n // using 0,3 indices. 1,4, 2,5, ... 430,433\n for(int i=0; i<MOLECULE_INITIAL_SIZE; i++){\n // for(int j=0; j<MAX_CONTACTS; j++){\n for(int k=0; k<MAX_CONTACTS; k++){\n\n if(map[i][k].cresid == -1){\n break;\n } else {\n count ++;\n // printf(\"%d-%d (%d) %d/50\\n\",i,map[i][k].cresid,count,k);\n }\n // printf(\" %d\",map[i][k].index);\n // map[num1][k].cindex = chain[num1].indices[j];\n // double eh; // energy scaling (well depth)\n // map[num1][k].distance = dist;\n\n // if(map[i][k].cresid != -1){\n // count ++;\n // } // if\n // } // for 3\n // } // if\n } // for 2\n } // for 1\n\n if(count != 0){\n debug(\"declare total contacts in this map are: %d\\n\",count);\n } else {\n debug(\"empty map.\\n\");\n }\n // // map[chain_num].total = count;\n\n return count;\n}\n\n#ifdef INERTIA\ninline void Chain::GetMomentofInertiaTensor() {\n\n /* printf(\"chain: %d; atoms: %d;\\n\",chainid,num_atoms_ca); */\n double x2=0.0,y2=0.0,z2=0.0;\n double xy=0.0,xz=0.0,yz=0.0;\n\n double Ixx=0.0,Iyy=0.0,Izz=0.0;\n double Ixy=0.0,Ixz=0.0,Iyz=0.0;\n\n\n /* http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node64.html moment of Inertia Tensor */\n /* http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node67.html get eigenvectors */\n for(int a=0; a<num_atoms_ca; a++) {\n /* for(int a=0; a<5; a++) { */\n /* printf(\"%d\",a); */\n /* printf(\"%f %f %f\\n\",pos[a].x,pos[a].y,pos[a].z); */\n x2 += pos[a].x * pos[a].x;\n y2 += pos[a].y * pos[a].y;\n z2 += pos[a].z * pos[a].z;\n\n xy += pos[a].x * pos[a].y;\n xz += pos[a].x * pos[a].z;\n yz += pos[a].y * pos[a].z;\n\n Ixx += y2 + z2;\n Iyy += x2 + z2;\n Izz += x2 + y2;\n\n Ixy += pos[a].x * pos[a].y;\n Ixz += pos[a].x * pos[a].z;\n Iyz += pos[a].y * pos[a].z;\n }\n\n Ixy = Ixy * -1.0;\n Ixz = Ixz * -1.0;\n Iyz = Iyz * -1.0;\n\n\n printf(\"xx_yy_zz: %f %f %f\\n\",Ixx,Iyy,Izz);\n printf(\"xy_xz_yz: %f %f %f\\n\",Ixy,Ixz,Iyz);\n\n\n // begin eigen library\n\n Matrix3d A(3,3);\n A(0,0) = Ixx;\n A(0,1) = Ixy;\n A(0,2) = Ixz;\n\n A(1,0) = Ixy;\n A(1,1) = Iyy;\n A(1,2) = Iyz;\n\n A(2,0) = Ixz;\n A(2,1) = Iyz;\n A(2,2) = Izz;\n /* std::cout << \"Here is the matrix A:\\n\" << A << std::endl; */\n\n\n // build matrix\n double InertiaTensor[3][3] = {\n {Ixx, Ixy, Ixz},\n {Ixy, Iyy, Iyz},\n {Ixz, Iyz, Izz},\n };\n\n\n // Ixy xz yz are altered beyond this point.\n double lowest_value_diag = Ixx;\n if ( Iyy < Ixx ) {\n if ( Izz < Iyy ) {\n lowest_value_diag = Izz;\n } else {\n lowest_value_diag = Iyy;\n }\n } else if ( Izz < Ixx ) {\n lowest_value_diag = Izz;\n }\n\n double lowest_value_offdiag;\n if ( Ixy < 0.0 ) {\n Ixy = -1.0 * Ixy;\n }\n if ( Ixz < 0.0 ) {\n Ixz = -1.0 * Ixz;\n }\n if ( Iyz < 0.0 ) {\n Iyz = -1.0 * Iyz;\n }\n\n lowest_value_offdiag = Ixy;\n if ( Ixz < Ixy ) {\n if ( Iyz < Ixz ) {\n lowest_value_offdiag = Iyz;\n } else {\n lowest_value_offdiag = Ixz;\n }\n } else if ( Iyz < Ixy ) {\n lowest_value_offdiag = Iyz;\n }\n\n double lowest_value;\n if ( lowest_value_offdiag < lowest_value_diag ) {\n lowest_value = lowest_value_offdiag;\n } else {\n lowest_value = lowest_value_offdiag;\n }\n\n printf(\"lv: %f\\n\",lowest_value);\n lowest_value = lowest_value * 0.95;\n /* printf(\"lv: %f\\n\",lowest_value); */\n // Matrix entries * lowest_value;\n\n\n\n /* // ORIGINAL EXAMPLE */\n /* // Create a 3D array that is 3 x 4 x 2 */\n /* typedef boost::multi_array<double, 3> array_type; */\n /* typedef array_type::index index; */\n /* array_type A(boost::extents[3][4][2]); */\n\n /* // Assign values to the elements */\n /* int values = 0; */\n /* for(index i = 0; i != 3; ++i) */\n /* for(index j = 0; j != 4; ++j) */\n /* for(index k = 0; k != 2; ++k) */\n /* A[i][j][k] = values++; */\n\n /* // Verify values */\n /* int verify = 0; */\n /* for(index i = 0; i != 3; ++i) */\n /* for(index j = 0; j != 4; ++j) */\n /* for(index k = 0; k != 2; ++k) */\n /* assert(A[i][j][k] == verify++); */\n /* /\\* return 0; *\\/ */\n\n\n\n /* ---------------------------------------------------------\n boost! no eigenvalue/eigenvector\n --------------------------------------------------------- */\n /* // Create a 3D array that is 3 x 4 x 2 */\n /* typedef boost::multi_array<double, 2> array_type; */\n /* typedef array_type::index index; */\n /* array_type A(boost::extents[3][3]); */\n /* array_type B(boost::extents[3][3]); */\n\n\n /* // x row */\n /* A[0][0] = Ixx; */\n /* A[0][1] = Ixy; */\n /* A[0][2] = Ixz; */\n\n /* // y row */\n /* A[1][0] = Ixy; */\n /* A[1][1] = Iyy; */\n /* A[1][2] = Iyz; */\n\n /* // y row */\n /* A[2][0] = Ixz; */\n /* A[2][1] = Iyz; */\n /* A[2][2] = Izz; */\n\n\n\n /* /\\* // Verify values *\\/ */\n /* /\\* int verify = 0; *\\/ */\n /* /\\* for(index i = 0; i != 3; i++) { *\\/ */\n /* /\\* for(index j = 0; j != 3; j++) { *\\/ */\n /* /\\* /\\\\* assert(A[i][j] == verify++); *\\\\/ *\\/ */\n /* /\\* // reassign by lowest_value scaling *\\/ */\n /* /\\* printf(\"A: %f\\n\",A[i][j]); *\\/ */\n /* /\\* } *\\/ */\n /* /\\* } *\\/ */\n\n /* // Verify values A */\n /* for(index i = 0; i != 3; i++) { */\n /* for(index j = 0; j != 3; j++) { */\n /* // reassign by lowest_value scaling */\n /* A[i][j] = A[i][j] / lowest_value; */\n /* printf(\"A/d: %f\\n\",A[i][j]); */\n /* } */\n /* } */\n /* ---------------------------------------------------------\n boost! no eigenvalue/eigenvector - END\n --------------------------------------------------------- */\n\n\n\n\n\n /* gsl_matrix_view m = gsl_matrix_view_array (InertiaTensor, 3, 3); */\n /* gsl_vector *eval = gsl_vector_alloc (3); */\n /* gsl_matrix *evec = gsl_matrix_alloc (3, 3); */\n\n /* gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3); */\n /* gsl_eigen_symmv (&m.matrix, eval, evec, w); */\n /* gsl_eigen_symmv_free (w); */\n /* gsl_eigen_symmv_sort (eval,evec,GSL_EIGEN_SORT_ABS_ASC); */\n /* { */\n /* int i; */\n\n /* for (i = 0; i < 4; i++) */\n /* { */\n /* double eval_i */\n /* = gsl_vector_get (eval, i); */\n /* gsl_vector_view evec_i */\n /* = gsl_matrix_column (evec, i); */\n\n /* printf (\"eigenvalue = %g\\n\", eval_i); */\n /* printf (\"eigenvector = \\n\"); */\n /* gsl_vector_fprintf (stdout, */\n /* &evec_i.vector, \"%g\"); */\n /* } */\n /* } */\n\n /* gsl_vector_free (eval); */\n /* gsl_matrix_free (evec); */\n\n /* return 0; */\n\n\n\n // eigen continued\n A = A / lowest_value;\n std::cout << \"Here is the matrix A:\\n\" << A << std::endl;\n\n VectorXcd eivals = A.eigenvalues();\n std::cout << \"The eigenvalues of the 3x3 matrix of ones are:\" << std::endl << eivals << std::endl;\n\n /* VectorXcd eivecs = A.eigenvectors(); */\n /* std::cout << \"The eigenvalues of the 3x3 matrix of ones are:\" << std::endl << eivecs << std::endl; */\n\n EigenSolver<MatrixXd> es(A);\n std::cout << \"The first eigenvector of the 3x3 matrix of ones is:\"\n << std::endl << es.eigenvectors().col(0) << std::endl;\n\n std::cout << \"The second eigenvector of the 3x3 matrix of ones is:\"\n << std::endl << es.eigenvectors().col(1) << std::endl;\n\n std::cout << \"The third eigenvector of the 3x3 matrix of ones is:\"\n << std::endl << es.eigenvectors().col(2) << std::endl;\n\n /* Matrix3d m = Matrix3d::(3,3); */\n /* cout << \"m =\" << endl << m << endl; */\n\n}\n#endif // INERTIA\n\n\n\n\n/* class Map { */\n/* /\\* int num_atoms,max_contacts_per_atom; *\\/ */\n/* public: */\n\n/* /\\* std::vector< std::vector< std::vector<int>>> map; *\\/ */\n/* std::vector< std::vector<int> > map; */\n/* /\\* std::vector *\\/ */\n/* std::vector<Contact> contacts; */\n\n/* // Constructor */\n/* /\\* Map(); *\\/ */\n\n/* /\\* declarations: *\\/ */\n/* /\\* void extend_map(int); *\\/ */\n/* void build_map_default(Chain *chain, int cid); // use chain_ref */\n\n/* }; */\n/* /\\* inline Map::extend_map(int ca){ *\\/ */\n/* /\\* for (int i=0; i<ca; i++) { *\\/ */\n/* /\\* map.push_back(i); // ADD the ROW. *\\/ */\n/* /\\* } *\\/ */\n/* /\\* } *\\/ */\n/* inline void Map::build_map_default(Chain *chain,int cid){ */\n/* // default: 8A */\n\n\n\n\n/* /\\* int count; *\\/ */\n/* double dist; */\n/* Contact x; */\n/* /\\* ,y; *\\/ */\n\n/* for (int i=0; i<chain[cid].num_atoms_ca; i++) { */\n/* /\\* printf(\"%d\\n\",i); *\\/ */\n\n/* for(int j=i; j<chain[cid].num_atoms_ca; j++) { */\n\n/* if ( i >= j-2 && i <= j+2) { */\n/* // exclude j = i +/- 2 */\n/* /\\* printf(\"%d\\t no --> %d j: %d %d\\n\",i,j,j-2,j+2); *\\/ */\n/* } else { */\n\n/* /\\* printf(\"%d\\n\",j); *\\/ */\n/* dist = distance(chain[cid].pos[i],chain[cid].pos[j]); */\n/* /\\* printf(\"%8.4f\\n\",dist); *\\/ */\n\n/* if ( dist <= 8.0 ) { */\n\n/* x.cresid = j; */\n/* x.distance = dist; */\n/* x.index = i + chain[cid].index; */\n/* x.cindex = j + chain[cid].index; */\n\n/* contacts.insert(contacts.end(),x); */\n/* } /\\* END 8.0 *\\/ */\n/* } // else/if */\n\n/* } // j */\n\n\n/* /\\* map.push_back(contacts); *\\/ */\n/* /\\* contacts.clear(); *\\/ */\n/* } // i */\n\n/* /\\* std::vector<int>::iterator it; *\\/ */\n/* /\\* for (it=contacts.begin(); it<contacts.end(); it++) { *\\/ */\n/* /\\* // std::cout << *it << ' ' << std::endl; *\\/ */\n/* /\\* printf(\"%d \",*it); *\\/ */\n/* /\\* } *\\/ */\n\n/* /\\* std::vector<int>::iterator iter; // declare a general iterator *\\/ */\n/* for ( int k = contacts.begin(); k < contacts.end(); k++){ */\n/* printf(\"%d\\n\",contacts[k].index); */\n/* } */\n\n/* } */\n\n\n/* inline Map::Map() { */\n/* // constructor */\n\n/* for (int i=0; i<num_atoms; i++ ) { */\n/* /\\* printf(\"%d\\n\",i); *\\/ */\n/* for (int j=0; j<max_contacts_per_atom; j++){ */\n/* /\\* if ( mol->contacts[i][j].cresid != 0 || mol->contacts[i][j].distance != 0.0) { *\\/ */\n/* /\\* printf(\"%d %f\\n\",mol->contacts[i][j].cresid,mol->contacts[i][j].distance); *\\/ */\n/* contacts[i][j].cresid = -1; */\n/* contacts[i][j].distance = 0.0; */\n/* } */\n/* } */\n/* } */\n/* inline void Map::get_contacts() { */\n\n/* } */\n/* inline void Map::set_values (int natoms, int max_contacts) { */\n/* num_atoms = natoms; */\n/* max_contacts_per_atom = max_contacts; */\n\n/* } */\n\n\n\n\n/* ---------------------------------------------------------\n Molecule preparations:\n --------------------------------------------------------- */\nvoid build_contact_map(Molecule *mol);\nvoid build_latlon_contact_map(Chain *chain, int num_chains, int start, int stop,\\\n Contact (*map)[MAX_CONTACTS],int sel);\nvoid build_contact_map_inter_monomer(Chain *chain,int cid, Contact (*map)[MAX_CONTACTS], int sel);\nvoid build_contact_map_inter(Chain *chain,int cid1,int cid2,Contact (*map)[MAX_CONTACTS]);\n\n\nvoid compare_contacts(Chain *chref,Chain *chain,int cid, int sel);\nvoid evaluate_original_contacts_now(Chain *chref,Chain *chain,int cid, int sel);\n\nvoid print_contact_map(Contact (*map)[MAX_CONTACTS]);\nvoid fprintf_count_of_contacts_2x_persist_from_reference( Molecule *m1, Molecule *m2);\nvoid fprintf_bond_vector_angle_with_tension_vector( Molecule *m1, Molecule *m2 );\nvoid fprintf_contacts_for_one_monomer_face(Chain *chain, int num_chains, int sel);\nvoid fprintf_contact_map_gsop(Contact (*map)[MAX_CONTACTS]);\nvoid fprintf_all_indices(Chain *chref,int num_chains);\n\n\nvoid tubulin_monomers_angles( Molecule *m1, Molecule *m2, int r1, int r2, FILE *fp);\nvoid get_tubulin_centroid( Molecule *m1, Vector *com);\nvoid get_centroid_from_array( Vector arr_centroid[],int i, int j, Vector *centroid);\nVector get_centroid_from_centroids(Chain *chain,int start_chain,int stop_chain);\nvoid get_centroid_movement(Chain *chain_ref,Chain *chain_later,int num_chains);\nvoid get_centroid_xyzposition_movement(Chain *chain_later,int chains_to_use,FILE *fp_xyzpos);\n/* void get_centroid_xyzposition_movement(chain_later,chains_to_use,fp_xyzpos); */\n\n\n/* void get_latangle_from35centroids(Chain *chain_ref,Chain *chain_later,int m,int sel); */\nvoid get_latangle_from35centroids(Chain *chain_ref,Chain *chain_later,int m,FILE *fp,int sel);\nstd::vector<double> get_3angles_dimerbyalpha(Chain *chain_ref,Chain *chain_later,int cid);\n\n/* void get_latangle_from35centroids(Chain *chain_ref,Chain *chain_later,int m,int sel,FILE *fp_ang); */\n\n\nvoid get_midpoint_reference_indices(Chain *chain,int i,int *index_ref_i,int *index_ref_c,int sel);\n/* get_midpoint_reference_indices(chain_ref,i,&index_ref_i,&index_ref_c,1); */\n\n\nvoid compute_nearest_neighbors(Chain *chain, int num_chains);\nvoid determine_latlon_neighbors(Chain *chains, int num_chains, Vector axis);\nvoid get_monomer_monomer_info( Molecule *m1, Molecule *m2,\\\n Vector ref_norm, Vector m1centroid,\\\n Vector m2centroid );\n\n\n\n/* void load_dcd_coords_to_chain(dcdhandle *dcd,Chain *chain,int num_chains); */\n/* void load_chain_coords_to_timestep(Chain *chain,int num_chains,\\ */\n/* const molfile_timestep_t *ts); */\n\nvoid print_chain_coords(Chain *chain,int num_chains);\n\n\n\n// overloaded.\nvoid assign_contact_eh(Contact (*map)[MAX_CONTACTS],float eh,int low_resid,\\\n int high_resid,int low_cresid,int high_cresid);\nvoid assign_contact_eh(Contact (*map)[MAX_CONTACTS],float eh);\n\n\n\n/* void dcd_to_chain(ddc,chain_0); */\n/* void dcd_to_chain(dcdhandle *v,Chain *chain); */\n\n/* void load_chain_coords_to_timestep(dcdhandle *dcd,Chain *chain,int num_chains,\\ */\n/* void *v, const molfile_timestep_t *ts,int natoms); */\n/* load_chain_coords_to_timestep(dcdw,chain_later,chains_to_use,vw,×tep_w,natoms_w); */\n\n/* static int read_next_timestep(void *v, int natoms, molfile_timestep_t *ts) { */\n/* static int write_timestep(void *v, const molfile_timestep_t *ts) { */\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "f3fbf603c60069b67c0967058a6ebdc233c85063", "size": 22969, "ext": "h", "lang": "C", "max_stars_repo_path": "include/chain.h", "max_stars_repo_name": "dmerz75/segment_analysis_md", "max_stars_repo_head_hexsha": "c4f014100bd7e0fc1af27f44febc8eccef35d829", "max_stars_repo_licenses": ["Zed"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/chain.h", "max_issues_repo_name": "dmerz75/segment_analysis_md", "max_issues_repo_head_hexsha": "c4f014100bd7e0fc1af27f44febc8eccef35d829", "max_issues_repo_licenses": ["Zed"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/chain.h", "max_forks_repo_name": "dmerz75/segment_analysis_md", "max_forks_repo_head_hexsha": "c4f014100bd7e0fc1af27f44febc8eccef35d829", "max_forks_repo_licenses": ["Zed"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3346104725, "max_line_length": 108, "alphanum_fraction": 0.5216160913, "num_tokens": 6829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.14330511684460068}}
{"text": "/**************************************************************************/\n/* This is the main simulation routine. It initializes either from given */\n/* inputs or from a checkpoint, runs the simulation, and assembles the */\n/* final results. */\n/**************************************************************************/\n\n#include \"init.h\"\n#include \"vader.h\"\n#include \"setup.h\"\n#include <string.h>\n#include <gsl/gsl_errno.h>\n\ndouble\nvader(\n /* Restart checkpoint name (empty string for new start) */\n const char *restart_file,\n /* Time parameters */\n const double tStart, const double tEnd,\n /* Equation of state parameters */\n const bool eos_func, const double gamma_val, \n const double delta_val,\n /* Dimensionless viscosity parameters */\n const bool alpha_func, const double alpha_val,\n /* Inner boundary condition parameters */\n const pres_bc_type ibc_pres, const enth_bc_type ibc_enth,\n const bool ibc_func, const double ibc_pres_val, \n const double ibc_enth_val,\n /* Outer boundary condition parameters */\n const pres_bc_type obc_pres, const enth_bc_type obc_enth,\n const bool obc_func, const double obc_pres_val, \n const double obc_enth_val,\n /* Source function parameters */\n const bool massSrc_func, const double massSrc_val,\n const bool intEnSrc_func, const double intEnSrc_val,\n /* Control and method parameters */\n const double dtStart,\n const double dtMin, \n const double dtTol, \n const double errTol,\n const double maxDtIncrease,\n const unsigned long maxIter,\n const unsigned long interpOrder,\n const unsigned long maxStep,\n const bool useBE,\n const bool preTimestep_func,\n const bool postTimestep_func,\n const unsigned long verbosity,\n /* Output control parameters */\n const unsigned long nSave, const double *tSave,\n const unsigned long nUserOut,\n const bool *userOutCum,\n const bool *writeCheckpoint,\n const char *checkname,\n const bool userReadCheckpoint,\n const bool userWriteCheckpoint,\n /* Computational grid (leave as NULL for a restart) */\n grid **grd_ptr,\n /* Starting data (leave as NULL for a restart) */\n double **col_init, double **pres_init, double **eInt_init,\n /* User-defined extra parameters */\n void *params,\n /* Diagnostic outputs */\n unsigned long *nStep, unsigned long *nIter,\n unsigned long *nFail,\n /* Output values; all the doubles should be passed in set to\n\t NULL, and will be allocated appropriately */\n unsigned long *nOut,\n double **tOut_ptr, double **colOut_ptr,\n double **presOut_ptr, double **eIntOut_ptr,\n double **mBndOut_ptr, double **eBndOut_ptr, \n double **mSrcOut_ptr, double **eSrcOut_ptr,\n double **userOut_ptr\n#ifdef TESTING_MODE\n /* Parameters used in code tests */\n , double *residSum, unsigned long *iterStep,\n double *driverTime, double *advanceTime,\n double *nextIterTime, double *userTime\n#endif\n ) {\n\n setup_status set_stat;\n gsl_error_handler_t *gslerr;\n double *col, *pres, *eInt;\n double *tOut, *colOut, *presOut, *eIntOut, *mBndOut, *eBndOut,\n *mSrcOut, *eSrcOut, *userOut;\n const double *tSave_tmp;\n const bool *writeCheckpoint_tmp, *userOutCum_tmp;\n grid *grd;\n unsigned long nOutMax, savePtr, chkNum;\n wksp *w;\n bool writeOut, restart;\n double t, dt, tSimEnd;\n\n /* Turn off GSL error handling, since we'll handle errors manually */\n gslerr = gsl_set_error_handler_off();\n\n /* Sanity check on the interpolation order */\n if ((interpOrder < 1) || (interpOrder > 3)) {\n fprintf(stderr, \"vader: error: interpOrder must be 1, 2, or 3\\n\");\n return(-1.0);\n }\n\n /* Do the initial setup */\n if (!restart_file) restart = false;\n else if (strlen(restart_file) == 0) restart = false;\n else restart = true;\n if (!restart) {\n\n /* We're starting new, so the initial data and grid should already\n be present, so make our working pointers point to them */\n grd = *grd_ptr;\n col = *col_init;\n pres = *pres_init;\n if (eos_func) eInt = *eInt_init;\n else eInt = NULL;\n\n /* Initialize time and counters */\n t = tStart;\n *nStep = 1;\n *nIter = *nFail = 0;\n nOutMax = nSave;\n *nOut = savePtr = chkNum = 0;\n\n /* Call the setup routine; this stores the first outputs if\n necessary and computes the first time step */\n set_stat =\n setup_new(tStart, tEnd,\n\t\teos_func, gamma_val, delta_val, alpha_func, alpha_val,\n\t\tibc_pres, ibc_enth, ibc_func, ibc_pres_val, ibc_enth_val,\n\t\tobc_pres, obc_enth, obc_func, obc_pres_val, obc_enth_val,\n\t\tmassSrc_func, massSrc_val, intEnSrc_func, intEnSrc_val,\n\t\tdtStart, dtMin, dtTol, errTol, maxDtIncrease,\n\t\tmaxIter, interpOrder, maxStep, useBE,\n\t\tuserWriteCheckpoint, verbosity,\n\t\tnSave, tSave, nUserOut, writeCheckpoint,\n\t\tcheckname,\n\t\tgrd, &w, col, pres, eInt, params,\n\t\ttOut_ptr, colOut_ptr, presOut_ptr, eIntOut_ptr, mBndOut_ptr,\n\t\teBndOut_ptr, mSrcOut_ptr, eSrcOut_ptr, userOut_ptr,\n\t\t&dt, nOut, &savePtr, &writeOut, &chkNum\n#ifdef TESTING_MODE\n\t\t, residSum, iterStep, advanceTime, nextIterTime,\n\t\tuserTime\n#endif\t\t\n\t\t);\n if (set_stat != GOOD_START) return -LARGE;\n\n } else {\n\n /* Set up from the checkpoint */\n set_stat =\n setup_checkpoint(restart_file, tStart, tEnd,\n\t\t eos_func, massSrc_func, intEnSrc_func,\n\t\t userReadCheckpoint, verbosity, nSave, tSave,\n\t\t nUserOut, userOutCum, &grd, &col, &pres, &eInt,\n\t\t nStep, nIter, nFail,\n\t\t tOut_ptr, colOut_ptr, presOut_ptr, eIntOut_ptr,\n\t\t mBndOut_ptr, eBndOut_ptr, mSrcOut_ptr, eSrcOut_ptr,\n\t\t userOut_ptr, params, &w, &t, &dt, nOut, &savePtr,\n\t\t &nOutMax, &writeOut, &chkNum);\n if (set_stat != GOOD_START) return -LARGE;\n\n /* Point inputs to allocated memory */\n *grd_ptr = grd;\n *col_init = col;\n *pres_init = pres;\n if (eos_func) *eInt_init = eInt;\n }\n\n /* Set pointers to output blocks and output controls; note that some\n of the control flags might be NULL, and we have to make sure to\n preserve those values, because they are significant in driver */\n tOut = *tOut_ptr;\n colOut = *colOut_ptr;\n presOut = *presOut_ptr;\n if (eos_func) eIntOut = *eIntOut_ptr; else eIntOut = NULL;\n mBndOut = *mBndOut_ptr;\n eBndOut = *eBndOut_ptr;\n if (massSrc_func) mSrcOut = *mSrcOut_ptr; else mSrcOut = NULL;\n if (massSrc_func || intEnSrc_func) eSrcOut = *eSrcOut_ptr;\n else eSrcOut = NULL;\n if (nUserOut > 0) userOut = *userOut_ptr; else userOut = NULL;\n if (tSave) tSave_tmp = tSave + savePtr; else tSave_tmp = NULL;\n if (writeCheckpoint) writeCheckpoint_tmp = writeCheckpoint + savePtr;\n else writeCheckpoint_tmp = NULL;\n if (userOutCum) userOutCum_tmp = userOutCum + savePtr;\n else userOutCum_tmp = NULL;\n\n /* Now call the driver routine to run the simulation */\n tSimEnd = driver(t, tEnd, eos_func, gamma_val, delta_val,\n\t\t alpha_func, alpha_val,\n\t\t ibc_pres, ibc_enth, ibc_func,\n\t\t ibc_pres_val, ibc_enth_val,\n\t\t obc_pres, obc_enth, obc_func,\n\t\t obc_pres_val, obc_enth_val,\n\t\t massSrc_func, massSrc_val,\n\t\t intEnSrc_func, intEnSrc_val,\n\t\t dt, dtMin, dtTol, errTol, maxDtIncrease,\n\t\t maxIter, interpOrder, maxStep,\n\t\t useBE, preTimestep_func, postTimestep_func,\n\t\t verbosity, nOutMax - *nOut,\n\t\t tSave_tmp, nUserOut, userOutCum_tmp,\n\t\t writeCheckpoint_tmp, checkname,\n\t\t userWriteCheckpoint, writeOut, \n\t\t chkNum, grd, w, col, pres, eInt,\n\t\t params, nStep, nIter, nFail,\n\t\t nOut, tOut, colOut, presOut, eIntOut,\n\t\t mBndOut, eBndOut, mSrcOut, eSrcOut,\n\t\t userOut\n#ifdef TESTING_MODE\n\t\t , residSum, iterStep, driverTime, advanceTime,\n\t\t nextIterTime, userTime\n#endif\n\t\t );\n\n /* If we didn't use up all the output slots because the calculation\n terminated early, free unneeded memory */\n if (*nOut < nOutMax) {\n outputResize(*nOut, eos_func, massSrc_func, intEnSrc_func,\n\t\t nUserOut, grd, tOut_ptr, colOut_ptr, presOut_ptr,\n\t\t eIntOut_ptr, mBndOut_ptr, eBndOut_ptr, mSrcOut_ptr,\n\t\t eSrcOut_ptr, userOut_ptr);\n }\n\n /* Free the workspace */\n wkspFree(w);\n \n /* Return */\n return tSimEnd;\n}\n", "meta": {"hexsha": "2389ade5b8081c5216fdeeee9d8a563ee917d57f", "size": 8239, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/vader.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/vader.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/vader.c", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 35.6666666667, "max_line_length": 76, "alphanum_fraction": 0.6637941498, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.25982564369245537, "lm_q1q2_score": 0.13397127650338214}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_errno.h>\n\n#include <class.h> /* from extern/ */\n\n#include \"ccl.h\"\n#include \"ccl_params.h\"\n#include \"ccl_emu17.h\"\n#include \"ccl_emu17_params.h\"\n\n\n/*------ ROUTINE: ccl_cosmology_compute_power_class -----\nINPUT: ccl_cosmology * cosmo\n*/\nstatic void ccl_free_class_structs(ccl_cosmology *cosmo,\n\t\t\t\t struct background *ba,\n\t\t\t\t struct thermo *th,\n\t\t\t\t struct perturbs *pt,\n\t\t\t\t struct transfers *tr,\n\t\t\t\t struct primordial *pm,\n\t\t\t\t struct spectra *sp,\n\t\t\t\t struct nonlinear *nl,\n\t\t\t\t struct lensing *le,\n\t\t\t\t int *init_arr,\n\t\t\t\t int * status)\n{\n int i_init=6;\n if(init_arr[i_init--]) {\n if (spectra_free(sp) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS spectra:%s\\n\", sp->error_message);\n return;\n }\n }\n\n if(init_arr[i_init--]) {\n if (transfer_free(tr) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS transfer:%s\\n\", tr->error_message);\n return;\n }\n }\n\n if(init_arr[i_init--]) {\n if (nonlinear_free(nl) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS nonlinear:%s\\n\", nl->error_message);\n return;\n }\n }\n\n if(init_arr[i_init--]) {\n if (primordial_free(pm) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS pm:%s\\n\", pm->error_message);\n return;\n }\n }\n\n if(init_arr[i_init--]) {\n if (perturb_free(pt) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS pt:%s\\n\", pt->error_message);\n return;\n }\n }\n\n if(init_arr[i_init--]) {\n if (thermodynamics_free(th) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS thermo:%s\\n\", th->error_message);\n return;\n }\n }\n\n if(init_arr[i_init--]) {\n if (background_free(ba) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_free_class_structs(): Error freeing CLASS bg:%s\\n\", ba->error_message);\n return;\n }\n }\n\n return;\n}\n\nstatic void ccl_class_preinit(struct background *ba,\n\t\t\t struct thermo *th,\n\t\t\t struct perturbs *pt,\n\t\t\t struct transfers *tr,\n\t\t\t struct primordial *pm,\n\t\t\t struct spectra *sp,\n\t\t\t struct nonlinear *nl,\n\t\t\t struct lensing *le)\n{\n //pre-initialize all fields that are freed by *_free() routine\n //prevents crashes if *_init()failed and did not initialize all tables freed by *_free()\n\n //init for background_free\n ba->tau_table = NULL;\n ba->z_table = NULL;\n ba->d2tau_dz2_table = NULL;\n ba->background_table = NULL;\n ba->d2background_dtau2_table = NULL;\n\n //init for thermodynamics_free\n th->z_table = NULL;\n th->thermodynamics_table = NULL;\n th->d2thermodynamics_dz2_table = NULL;\n\n //init for perturb_free\n pt->tau_sampling = NULL;\n pt->tp_size = NULL;\n pt->ic_size = NULL;\n pt->k = NULL;\n pt->k_size_cmb = NULL;\n pt->k_size_cl = NULL;\n pt->k_size = NULL;\n pt->sources = NULL;\n\n //init for primordial_free\n pm->amplitude = NULL;\n pm->tilt = NULL;\n pm->running = NULL;\n pm->lnpk = NULL;\n pm->ddlnpk = NULL;\n pm->is_non_zero = NULL;\n pm->ic_size = NULL;\n pm->ic_ic_size = NULL;\n pm->lnk = NULL;\n\n //init for nonlinear_free\n nl->k = NULL;\n nl->tau = NULL;\n nl->nl_corr_density = NULL;\n nl->k_nl = NULL;\n\n //init for transfer_free\n tr->tt_size = NULL;\n tr->l_size_tt = NULL;\n tr->l_size = NULL;\n tr->l = NULL;\n tr->q = NULL;\n tr->k = NULL;\n tr->transfer = NULL;\n\n //init for spectra_free\n //spectra_free checks all other data fields before freeing\n sp->is_non_zero = NULL;\n sp->ic_size = NULL;\n sp->ic_ic_size = NULL;\n}\n\nstatic void ccl_run_class(ccl_cosmology *cosmo,\n\t\t\t struct file_content *fc,\n\t\t\t struct precision* pr,\n\t\t\t struct background* ba,\n\t\t\t struct thermo* th,\n\t\t\t struct perturbs* pt,\n\t\t\t struct transfers* tr,\n\t\t\t struct primordial* pm,\n\t\t\t struct spectra* sp,\n\t\t\t struct nonlinear* nl,\n\t\t\t struct lensing* le,\n\t\t\t struct output* op,\n\t\t\t int *init_arr,\n\t\t\t int * status)\n{\n ErrorMsg errmsg; // for error messages\n int i_init=0;\n ccl_class_preinit(ba,th,pt,tr,pm,sp,nl,le);\n\n if(input_init(fc,pr,ba,th,pt,tr,pm,sp,nl,le,op,errmsg) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS input:%s\\n\", errmsg);\n return;\n }\n if (background_init(pr,ba) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS background:%s\\n\", ba->error_message);\n return;\n }\n init_arr[i_init++]=1;\n if (thermodynamics_init(pr,ba,th) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS thermodynamics:%s\\n\", th->error_message);\n return;\n }\n init_arr[i_init++]=1;\n if (perturb_init(pr,ba,th,pt) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS pertubations:%s\\n\", pt->error_message);\n return;\n }\n init_arr[i_init++]=1;\n if (primordial_init(pr,pt,pm) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS primordial:%s\\n\", pm->error_message);\n return;\n }\n init_arr[i_init++]=1;\n if (nonlinear_init(pr,ba,th,pt,pm,nl) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS nonlinear:%s\\n\", nl->error_message);\n return;\n }\n init_arr[i_init++]=1;\n if (transfer_init(pr,ba,th,pt,nl,tr) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS transfer:%s\\n\", tr->error_message);\n return;\n }\n init_arr[i_init++]=1;\n if (spectra_init(pr,ba,pt,pm,nl,tr,sp) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error running CLASS spectra:%s\\n\", sp->error_message);\n return;\n }\n init_arr[i_init++]=1;\n}\n\nstatic double ccl_get_class_As(ccl_cosmology *cosmo, struct file_content *fc, int position_As,\n\t\t\t double sigma8, int * status)\n{\n //structures for class test run\n struct precision pr; // for precision parameters\n struct background ba; // for cosmological background\n struct thermo th; // for thermodynamics\n struct perturbs pt; // for source functions\n struct transfers tr; // for transfer functions\n struct primordial pm; // for primordial spectra\n struct spectra sp; // for output spectra\n struct nonlinear nl; // for non-linear spectra\n struct lensing le;\n struct output op;\n\n //temporarily overwrite P_k_max_1/Mpc to speed up sigma8 calculation\n double k_max_old = 0.;\n int position_kmax =2;\n double A_s_guess;\n int init_arr[7]={0,0,0,0,0,0,0};\n\n if (strcmp(fc->name[position_kmax],\"P_k_max_1/Mpc\")) {\n k_max_old = strtof(fc->value[position_kmax],NULL);\n sprintf(fc->value[position_kmax],\"%.15e\",10.);\n }\n A_s_guess = 2.43e-9/0.87659*sigma8;\n sprintf(fc->value[position_As],\"%.15e\",A_s_guess);\n\n ccl_run_class(cosmo, fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status);\n if (cosmo->status != CCL_ERROR_CLASS) A_s_guess*=pow(sigma8/sp.sigma8,2.);\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n\n if (k_max_old >0) {\n sprintf(fc->value[position_kmax],\"%.15e\",k_max_old);\n }\n return A_s_guess;\n}\n\nstatic void ccl_fill_class_parameters(ccl_cosmology * cosmo, struct file_content * fc,\n\t\t\t\t int parser_length, int * status)\n\n{\n\n // initialize fc fields\n //silences Valgrind's \"Conditional jump or move depends on uninitialised value\" warning\n for (int i = 0; i< parser_length; i++){\n strcpy(fc->name[i],\" \");\n strcpy(fc->value[i],\" \");\n }\n\n strcpy(fc->name[0],\"output\");\n strcpy(fc->value[0],\"mPk\");\n\n strcpy(fc->name[1],\"non linear\");\n if (cosmo->config.matter_power_spectrum_method == ccl_halofit)\n strcpy(fc->value[1],\"Halofit\");\n else\n strcpy(fc->value[1],\"none\");\n\n strcpy(fc->name[2],\"P_k_max_1/Mpc\");\n sprintf(fc->value[2],\"%.15e\",ccl_splines->K_MAX_SPLINE); //in units of 1/Mpc, corroborated with ccl_constants.h\n\n strcpy(fc->name[3],\"z_max_pk\");\n sprintf(fc->value[3],\"%.15e\",1./ccl_splines->A_SPLINE_MINLOG_PK-1.);\n\n strcpy(fc->name[4],\"modes\");\n strcpy(fc->value[4],\"s\");\n\n strcpy(fc->name[5],\"lensing\");\n strcpy(fc->value[5],\"no\");\n\n // now, copy over cosmology parameters\n strcpy(fc->name[6],\"h\");\n sprintf(fc->value[6],\"%.15e\",cosmo->params.h);\n\n strcpy(fc->name[7],\"Omega_cdm\");\n sprintf(fc->value[7],\"%.15e\",cosmo->params.Omega_c);\n\n strcpy(fc->name[8],\"Omega_b\");\n sprintf(fc->value[8],\"%.15e\",cosmo->params.Omega_b);\n\n strcpy(fc->name[9],\"Omega_k\");\n sprintf(fc->value[9],\"%.15e\",cosmo->params.Omega_k);\n\n strcpy(fc->name[10],\"n_s\");\n sprintf(fc->value[10],\"%.15e\",cosmo->params.n_s);\n\n\n //cosmological constant?\n // set Omega_Lambda = 0.0 if w !=-1\n if ((cosmo->params.w0 !=-1.0) || (cosmo->params.wa !=0)) {\n strcpy(fc->name[11],\"Omega_Lambda\");\n sprintf(fc->value[11],\"%.15e\",0.0);\n\n strcpy(fc->name[12],\"w0_fld\");\n sprintf(fc->value[12],\"%.15e\",cosmo->params.w0);\n\n strcpy(fc->name[13],\"wa_fld\");\n sprintf(fc->value[13],\"%.15e\",cosmo->params.wa);\n }\n //neutrino parameters\n //massless neutrinos\n if (cosmo->params.N_nu_rel > 1.e-4) {\n strcpy(fc->name[14],\"N_ur\");\n sprintf(fc->value[14],\"%.15e\",cosmo->params.N_nu_rel);\n }\n else {\n strcpy(fc->name[14],\"N_ur\");\n sprintf(fc->value[14],\"%.15e\", 0.);\n }\n if (cosmo->params.N_nu_mass > 0) {\n strcpy(fc->name[15],\"N_ncdm\");\n sprintf(fc->value[15],\"%d\",cosmo->params.N_nu_mass);\n strcpy(fc->name[16],\"m_ncdm\");\n sprintf(fc->value[16],\"%f\", (cosmo->params.mnu)[0]);\n if (cosmo->params.N_nu_mass >=1){\n\t\tfor (int i = 1; i < cosmo->params.N_nu_mass; i++) {\n\t\t\tchar tmp[20];\n\t\t\tsprintf(tmp,\", %f\",(cosmo->params.mnu)[i]);\n\t\t\tstrcat(fc->value[16],tmp);\n\t\t}\n\t}\n\n }\n\n strcpy(fc->name[17],\"T_cmb\");\n sprintf(fc->value[17],\"%.15e\",cosmo->params.T_CMB);\n\n //normalization comes last, so that all other parameters are filled in for determining A_s if sigma8 is specified\n if (isfinite(cosmo->params.sigma8) && isfinite(cosmo->params.A_s)){\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: class_parameters(): Error initializing CLASS parameters: both sigma8 and A_s defined\\n\");\n return;\n }\n if (isfinite(cosmo->params.sigma8)) {\n strcpy(fc->name[parser_length-1],\"A_s\");\n sprintf(fc->value[parser_length-1],\"%.15e\",ccl_get_class_As(cosmo,fc,parser_length-1,cosmo->params.sigma8, status));\n }\n else if (isfinite(cosmo->params.A_s)) {\n strcpy(fc->name[parser_length-1],\"A_s\");\n sprintf(fc->value[parser_length-1],\"%.15e\",cosmo->params.A_s);\n }\n else {\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: class_parameters(): Error initializing CLASS pararmeters: neither sigma8 nor A_s defined\\n\");\n return;\n }\n\n}\n\nstatic void ccl_cosmology_compute_power_class(ccl_cosmology * cosmo, int * status)\n{\n struct precision pr; // for precision parameters\n struct background ba; // for cosmological background\n struct thermo th; // for thermodynamics\n struct perturbs pt; // for source functions\n struct transfers tr; // for transfer functions\n struct primordial pm; // for primordial spectra\n struct spectra sp; // for output spectra\n struct nonlinear nl; // for non-linear spectra\n struct lensing le;\n struct output op;\n struct file_content fc;\n\n ErrorMsg errmsg; // for error messages\n // generate file_content structure\n // CLASS configuration parameters will be passed through this structure,\n // to avoid writing and reading .ini files for every call\n int parser_length = 20;\n int init_arr[7]={0,0,0,0,0,0,0};\n if (parser_init(&fc,parser_length,\"none\",errmsg) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): parser init error:%s\\n\", errmsg);\n return;\n }\n\n ccl_fill_class_parameters(cosmo,&fc,parser_length, status);\n\n if (*status != CCL_ERROR_CLASS)\n ccl_run_class(cosmo, &fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status);\n\n if (*status == CCL_ERROR_CLASS) {\n //printed error message while running CLASS\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n return;\n }\n\n if (parser_free(&fc)== _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error freeing CLASS parser\\n\");\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n return;\n }\n\n //These are the limits of the splining range\n cosmo->data.k_min_lin=2*exp(sp.ln_k[0]);\n cosmo->data.k_max_lin=ccl_splines->K_MAX_SPLINE;\n\n //CLASS calculations done - now allocate CCL splines\n double kmin = cosmo->data.k_min_lin;\n double kmax = ccl_splines->K_MAX_SPLINE;\n //Compute nk from number of decades and N_K = # k per decade\n double ndecades = log10(kmax) - log10(kmin);\n int nk = (int)ceil(ndecades*ccl_splines->N_K);\n double amin = ccl_splines->A_SPLINE_MINLOG_PK;\n double amax = ccl_splines->A_SPLINE_MAX;\n int na = ccl_splines->A_SPLINE_NA_PK+ccl_splines->A_SPLINE_NLOG_PK-1;\n\n // The x array is initially k, but will later\n // be overwritten with log(k)\n double * x = ccl_log_spacing(kmin, kmax, nk);\n double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK);\n double * y2d_lin = malloc(nk * na * sizeof(double));\n double * y2d_nl = malloc(nk * na * sizeof(double));\n\n \n //If error, store status, we will free later\n if (a==NULL|| x==NULL || y2d_lin==NULL || y2d_nl==NULL) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): memory allocation error\\n\");\n }\n\n //Status flags\n int newstatus=0;\n int pwstatus=0;\n \n //If not, proceed\n if(!*status){\n \n // After this loop x will contain log(k)\n // all in Mpc, not Mpc/h units!\n double psout_l,ic;\n for (int i=0; i<nk; i++) {\n for (int j = 0; j < na; j++) {\n\t//The 2D interpolation routines access the function values y_{k_ia_j} with the following ordering:\n\t//y_ij = y2d[j*N_k + i]\n\t//with i = 0,...,N_k-1 and j = 0,...,N_a-1.\n\tnewstatus |= spectra_pk_at_k_and_z(&ba, &pm, &sp,x[i],1./a[j]-1., &psout_l,&ic);\n\ty2d_lin[j*nk+i] = log(psout_l);\n }\n x[i] = log(x[i]);\n }\n\n \n //If error, store status, we will free later\n if(newstatus) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error computing CLASS power spectrum\\n\");\n }\n\n \n }\n\n \n //If no error, proceed\n if(!*status) {\n \n gsl_spline2d * log_power = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na);\n pwstatus = gsl_spline2d_init(log_power, x, a, y2d_lin,nk,na);\n \n //If not, proceed\n if(!pwstatus){\n cosmo->data.p_lin = log_power;\n } else {\n gsl_spline2d_free(log_power);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error creating log_power spline\\n\");\n }\n\n }\n \n if(*status){ //Linear power spec failed, so we return without proceeding to nonlinear.\n free(x);\n free(a);\n free(y2d_nl);\n free(y2d_lin);\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n return;\n }\n\n //Non-linear power\n //At the moment KMIN can't be less than CLASS's kmin in the nonlinear case.\n \n //If error, store status, we will free later\n if (kmin<(exp(sp.ln_k[0]))) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): K_MIN is less than CLASS's kmin. Not yet supported for nonlinear P(k).\\n\");\n }\n\n //If not, proceed\n if(!*status){\n\n //These are the limits of the splining range\n cosmo->data.k_min_nl=2*exp(sp.ln_k[0]);\n cosmo->data.k_max_nl=ccl_splines->K_MAX_SPLINE;\n \n if(cosmo->config.matter_power_spectrum_method==ccl_halofit) {\n\t\n double psout_nl;\n for (int i=0; i<nk; i++) {\n\tfor (int j = 0; j < na; j++) {\n\t newstatus |= spectra_pk_nl_at_k_and_z(&ba, &pm, &sp,exp(x[i]),1./a[j]-1.,&psout_nl);\n\t y2d_nl[j*nk+i] = log(psout_nl);\n\t}\n }\n }\n\n if(newstatus){\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error computing CLASS power spectrum\\n\");\n }\n \n }\n\n if(!*status){\n\t\n gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PNL_SPLINE_TYPE, nk,na);\n pwstatus = gsl_spline2d_init(log_power_nl, x, a, y2d_nl,nk,na);\n \n if(!pwstatus){\n cosmo->data.p_nl = log_power_nl;\n } else {\n gsl_spline2d_free(log_power_nl);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error creating log_power_nl spline\\n\");\n }\n\n }\n \n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n free(x);\n free(a);\n free(y2d_nl);\n free(y2d_lin);\n\n return;\n \n}\n\n/* BCM correction \n See Schneider & Teyssier (2015) for details of the model.\n The equations inside this function correspond to those in that\n work for:\n gf -> G(k)\n scomp -> S(k)\n*/\ndouble ccl_bcm_model_fka(ccl_cosmology * cosmo, double k, double a, int *status){\n\n double fka;\n double b0;\n double bfunc, bfunc4;\n double kg;\n double gf,scomp;\n double kh;\n double z;\n\n z=1./a-1.;\n kh = k/cosmo->params.h; //convert to h/Mpc\n b0 = 0.105*cosmo->params.bcm_log10Mc-1.27; //Eq. 4.4\n bfunc = b0/(1.+pow(z/2.3,2.5)); //Eq. 4.3\n bfunc4 = (1-bfunc)*(1-bfunc)*(1-bfunc)*(1-bfunc); //B^4(z)\n kg = 0.7*bfunc4*pow(cosmo->params.bcm_etab,-1.6); //Eq. 4.3\n gf = bfunc/(1+pow(kh/kg,3.))+1.-bfunc; //Eq. 4.2, k in h/Mpc\n scomp = 1+(kh/cosmo->params.bcm_ks)*(kh/cosmo->params.bcm_ks); //Eq 4.5, k in h/Mpc\n fka = gf*scomp;\n return fka;\n}\n\nvoid ccl_cosmology_write_power_class_z(char *filename, ccl_cosmology * cosmo, double z, int * status)\n{\n struct precision pr; // for precision parameters\n struct background ba; // for cosmological background\n struct thermo th; // for thermodynamics\n struct perturbs pt; // for source functions\n struct transfers tr; // for transfer functions\n struct primordial pm; // for primordial spectra\n struct spectra sp; // for output spectra\n struct nonlinear nl; // for non-linear spectra\n struct lensing le;\n struct output op;\n struct file_content fc;\n\n ErrorMsg errmsg; // for error messages\n // generate file_content structure\n // CLASS configuration parameters will be passed through this structure,\n // to avoid writing and reading .ini files for every call\n int parser_length = 20;\n int init_arr[7]={0,0,0,0,0,0,0};\n if (parser_init(&fc,parser_length,\"none\",errmsg) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: write_power_class_z(): parser init error:%s\\n\", errmsg);\n return;\n }\n\n ccl_fill_class_parameters(cosmo,&fc,parser_length, status);\n\n if (*status != CCL_ERROR_CLASS)\n ccl_run_class(cosmo, &fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status);\n\n if (*status == CCL_ERROR_CLASS) {\n //printed error message while running CLASS\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n return;\n }\n if (parser_free(&fc)== _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: write_power_class_z(): Error freeing CLASS parser\\n\");\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n return;\n }\n FILE *f;\n f = fopen(filename,\"w\");\n if (!f){\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: write_power_class_z(): Error opening output file\\n\");\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n fclose(f);\n return;\n }\n double psout_l,ic;\n int s=0;\n for (int i=0; i<sp.ln_k_size; i++) {\n s |= spectra_pk_at_k_and_z(&ba, &pm, &sp,exp(sp.ln_k[i]),z, &psout_l,&ic);\n fprintf(f,\"%e %e\\n\",exp(sp.ln_k[i]),psout_l);\n }\n fclose(f);\n if(s) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: write_power_class_z(): Error writing CLASS power spectrum\\n\");\n }\n\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n}\n\n\ntypedef struct {\n double rsound;\n double zeq;\n double keq;\n double zdrag;\n double kSilk;\n double rsound_approx;\n double th2p7;\n double alphac;\n double alphab;\n double betac;\n double betab;\n double bnode;\n} eh_struct;\n\nstatic eh_struct *eh_struct_new(ccl_parameters *params)\n{\n //////\n // Computes Eisenstein & Hu parameters for\n // P_k and r_sound\n // see astro-ph/9709112 for the relevant equations\n double OMh2,OBh2;\n double th2p7;\n eh_struct *eh=malloc(sizeof(eh_struct));\n if(eh==NULL)\n return NULL;\n\n OMh2=params->Omega_m*params->h*params->h; //Cosmo params scaled by h^2\n OBh2=params->Omega_b*params->h*params->h;\n th2p7=params->T_CMB/2.7; //This is Theta_{2.7} in E&Hu notation\n eh->th2p7=th2p7; //This is Theta_{2.7} in E&Hu notation\n eh->zeq=2.5E4*OMh2/pow(th2p7,4);// Eq 2\n eh->keq=0.0746*OMh2/(params->h*th2p7*th2p7);//Eq. 3\n\n //These group corresponds to Eq. 4\n double b1,b2;\n b1=0.313*pow(OMh2,-0.419)*(1+0.607*pow(OMh2,0.674));\n b2=0.238*pow(OMh2,0.223);\n eh->zdrag=1291*pow(OMh2,0.251)*(1+b1*pow(OBh2,b2))/(1+0.659*pow(OMh2,0.828)); \n\n //These are the baryon-to-photon ratios\n //at equality (Req) and drag (Rd) epochs\n //Eq. 5\n double Req,Rd;\n Req=31.5*OBh2*1000./(eh->zeq*pow(th2p7,4));\n Rd=31.5*OBh2*1000./((1+eh->zdrag)*pow(th2p7,4));\n eh->rsound=2/(3*eh->keq)*sqrt(6/Req)*\n log((sqrt(1+Rd)+sqrt(Rd+Req))/(1+sqrt(Req)));\n\n //This is Eq. 7 (but in h/Mpc)\n eh->kSilk=1.6*pow(OBh2,0.52)*pow(OMh2,0.73)*(1+pow(10.4*OMh2,-0.95))/params->h; \n\n //These are Eqs. 11\n double a1,a2,b_frac;\n a1=pow(46.9*OMh2,0.670)*(1+pow(32.1*OMh2,-0.532));\n a2=pow(12.0*OMh2,0.424)*(1+pow(45.0*OMh2,-0.582));\n b_frac=OBh2/OMh2;\n eh->alphac=pow(a1,-b_frac)*pow(a2,-b_frac*b_frac*b_frac);\n\n //These are Eqs. 12\n double bb1,bb2;\n bb1=0.944/(1+pow(458*OMh2,-0.708));\n bb2=pow(0.395*OMh2,-0.0266);\n eh->betac=1/(1+bb1*(pow(1-b_frac,bb2)-1));\n\n double y=eh->zeq/(1+eh->zdrag);\n double sqy=sqrt(1+y);\n double gy=y*(-6*sqy+(2+3*y)*log((sqy+1)/(sqy-1))); //Eq 15\n //Baryon suppression Eq. 14\n eh->alphab=2.07*eh->keq*eh->rsound*pow(1+Rd,-0.75)*gy; \n\n //Baryon envelope shift Eq. 24\n eh->betab=0.5+b_frac+(3-2*b_frac)*sqrt(pow(17.2*OMh2,2)+1);\n\n //Node shift parameter Eq. 23\n eh->bnode=8.41*pow(OMh2,0.435);\n\n //Approx for the sound horizon, Eq. 26\n eh->rsound_approx=params->h*44.5*log(9.83/OMh2)/\n sqrt(1+10*pow(OBh2,0.75));\n \n return eh;\n}\n\nstatic double tkEH_0(double keq,double k,double a,double b)\n{\n //////\n // Eisentstein & Hu's Tk_0\n // see astro-ph/9709112 for the relevant equations\n double q=k/(13.41*keq); //Eq 10\n double c=14.2/a+386./(1+69.9*pow(q,1.08)); //Eq 20\n double l=log(M_E+1.8*b*q); //Change of var for Eq 19\n return l/(l+c*q*q); //Returns Eq 19\n}\n\nstatic double tkEH_c(eh_struct *eh,double k)\n{\n //////\n // Eisenstein & Hu's Tk_c\n // see astro-ph/9709112 for the relevant equations\n double f=1/(1+pow(k*eh->rsound/5.4,4)); //Eq 18\n return f*tkEH_0(eh->keq,k,1,eh->betac)+ \n (1-f)*tkEH_0(eh->keq,k,eh->alphac,eh->betac); //Returns Eq 17\n}\n\nstatic double jbes0(double x)\n{\n double jl;\n double ax2=x*x;\n\n if(ax2<1e-4) jl=1-ax2*(1-ax2/20.)/6.;\n else jl=sin(x)/x;\n\n return jl;\n}\n\nstatic double tkEH_b(eh_struct *eh,double k)\n{\n //////\n // Eisenstein & Hu's Tk_b (Eq 21)\n // see astro-ph/9709112 for the relevant equations\n double x_bessel,part1,part2,jbes;\n double x=k*eh->rsound;\n\n //First term of Eq. 21\n if(k==0) x_bessel=0;\n else {\n x_bessel=x*pow(1+eh->bnode*eh->bnode*eh->bnode/(x*x*x),-1./3.);\n }\n\n part1=tkEH_0(eh->keq,k,1,1)/(1+pow(x/5.2,2)); \n\n //Second term of Eq. 21\n if(k==0)\n part2=0;\n else\n part2=eh->alphab/(1+pow(eh->betab/x,3))*exp(-pow(k/eh->kSilk,1.4));\n\n return jbes0(x_bessel)*(part1+part2);\n}\n\nstatic double tsqr_EH(ccl_parameters *params,eh_struct * eh,double k,int wiggled)\n{\n //////\n // Eisenstein & Hu's Tk_c\n // see astro-ph/9709112 for the relevant equations\n // Notice the last parameter in eh_power controls\n // whether to introduce wiggles (BAO) in the power spectrum.\n // We do this by default when obtaining the power spectrum.\n double tk;\n double b_frac=params->Omega_b/params->Omega_m;\n if(wiggled)\n //Case with baryons (Eq 8)\n tk=b_frac*tkEH_b(eh,k)+(1-b_frac)*tkEH_c(eh,k);\n else {\n //Zero baryon case (sec 4.2)\n double OMh2=params->Omega_m*params->h*params->h;\n // Compute Eq. 31\n double alpha_gamma=1-0.328*log(431*OMh2)*b_frac+0.38*log(22.3*OMh2)*b_frac*b_frac;\n // Compute Eq. 30\n double gamma_eff=params->Omega_m*params->h*(alpha_gamma+(1-alpha_gamma)/\n\t\t\t\t\t\t(1+pow(0.43*k*eh->rsound_approx,4)));\n // Compute Eq. 28 (assume k in h/Mpc)\n double q=k*eh->th2p7*eh->th2p7/gamma_eff;\n // Compute Eqs. 29\n double l0=log(2*M_E+1.8*q);\n double c0=14.2+731/(1+62.5*q);\n tk=l0/(l0+c0*q*q); //T_0 of Eq. 29\n }\n\n return tk*tk; //Return T_0^2\n}\n\nstatic double eh_power(ccl_parameters *params,eh_struct *eh,double k,int wiggled)\n{\n //Wavenumber in units of Mpc^-1\n double kinvh=k/params->h; //Changed to h/Mpc\n return pow(k,params->n_s)*tsqr_EH(params,eh,kinvh,wiggled);\n}\nstatic void ccl_cosmology_compute_power_eh(ccl_cosmology * cosmo, int * status)\n{\n //These are the limits of the splining range\n cosmo->data.k_min_lin = ccl_splines->K_MIN;\n cosmo->data.k_min_nl = ccl_splines->K_MIN;\n cosmo->data.k_max_lin = ccl_splines->K_MAX;\n cosmo->data.k_max_nl = ccl_splines->K_MAX;\n double kmin = cosmo->data.k_min_lin;\n double kmax = ccl_splines->K_MAX;\n\n // Compute nk from number of decades and N_K = # k per decade\n double ndecades = log10(kmax) - log10(kmin);\n int nk = (int)ceil(ndecades*ccl_splines->N_K);\n\n // Compute na using predefined spline spacing\n double amin = ccl_splines->A_SPLINE_MINLOG_PK;\n double amax = ccl_splines->A_SPLINE_MAX;\n int na = ccl_splines->A_SPLINE_NA_PK + ccl_splines->A_SPLINE_NLOG_PK - 1;\n\n // Exit if sigma8 wasn't specified\n if (isnan(cosmo->params.sigma8)) {\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_eh(): sigma8 was not set, but is required for E&H method\\n\");\n return;\n }\n\n // New struct for EH parameters\n eh_struct *eh = eh_struct_new(&(cosmo->params));\n if (eh == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_eh(): memory allocation error\\n\");\n return;\n }\n\n // Build grids in k and a that P(k, a) will be evaluated on\n // NB: The x array is initially k, but will later be overwritten with log(k)\n double * x = ccl_log_spacing(kmin, kmax, nk);\n double * y = malloc(sizeof(double)*nk);\n double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK,\n amax, ccl_splines->A_SPLINE_NLOG_PK,\n ccl_splines->A_SPLINE_NA_PK);\n double * y2d = malloc(nk * na * sizeof(double));\n if (a==NULL || y==NULL || x==NULL || y2d==NULL) {\n free(eh);free(x);free(y);\n free(a);free(y2d);\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_eh(): memory allocation error\\n\");\n return;\n }\n\n // Calculate P(k) on k grid. After this loop, x will contain log(k) and y\n // will contain log(pk) [which has not yet been normalized]\n // Notice the last parameter in eh_power controls\n // whether to introduce wiggles (BAO) in the power spectrum.\n // We do this by default.\n for (int i=0; i<nk; i++) {\n y[i] = log(eh_power(&cosmo->params, eh, x[i], 1));\n x[i] = log(x[i]);\n }\n\n // Apply growth factor, D(a), to P(k) and store in 2D (k, a) array\n double gfac, g2;\n gsl_spline2d *log_power_lin = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na);\n for (int j = 0; j < na; j++) {\n gfac = ccl_growth_factor(cosmo, a[j], status); \n g2 = 2.*log(gfac);\n for (int i=0; i<nk; i++) {\n y2d[j*nk+i] = y[i]+g2;\n } // end loop over k\n } // end loop over a\n\n // Check that ccl_growth_factor didn't fail\n if (*status) {\n free(eh); free(x); free(y); free(a); free(y2d);\n gsl_spline2d_free(log_power_lin);\n return;\n }\n\n // Initialize a 2D spline over P(k, a) [which is still unnormalized by sigma8]\n int splinstatus = gsl_spline2d_init(log_power_lin, x, a, y2d,nk,na);\n if (splinstatus) {\n free(eh); free(x); free(y); free(a); free(y2d);\n gsl_spline2d_free(log_power_lin);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_eh(): Error creating log_power_lin spline\\n\");\n return;\n }\n\n // Calculate sigma8 for the unnormalized P(k), using the standard\n // ccl_sigma8() function\n cosmo->data.p_lin = log_power_lin;\n cosmo->computed_power = true; // Temporarily set this to true\n double sigma8 = ccl_sigma8(cosmo, status);\n cosmo->computed_power = false;\n\n // Check that ccl_sigma8 didn't fail\n if (*status) {\n free(eh); free(x); free(y); free(a); free(y2d);\n gsl_spline2d_free(log_power_lin);\n return;\n }\n\n // Calculate normalization factor using computed value of sigma8, then\n // recompute P(k, a) using this normalization\n double log_normalization_factor = 2*(log(cosmo->params.sigma8) - log(sigma8));\n for (int i=0; i < nk; i++) {\n y[i] += log_normalization_factor;\n }\n for (int j = 0; j < na; j++) {\n gfac = ccl_growth_factor(cosmo, a[j], status);\n g2 = 2.*log(gfac);\n for (int i=0; i<nk; i++) {\n y2d[j*nk+i] = y[i]+g2; // Replace previous values\n } // end k loop\n } // end a loop\n\n splinstatus = gsl_spline2d_init(log_power_lin, x, a, y2d, nk, na);\n if (splinstatus) {\n free(eh); free(x); free(y); free(a); free(y2d);\n gsl_spline2d_free(log_power_lin);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_eh(): Error creating log_power_lin spline\\n\");\n return;\n }\n else\n cosmo->data.p_lin = log_power_lin;\n\n // Allocate a 2D spline for the nonlinear P(k) [which is just a copy of the\n // linear one for E&H]\n gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PNL_SPLINE_TYPE, nk, na);\n splinstatus = gsl_spline2d_init(log_power_nl, x, a, y2d, nk, na);\n\n if (splinstatus) {\n free(eh); free(x); free(y); free(a); free(y2d);\n gsl_spline2d_free(log_power_lin);\n gsl_spline2d_free(log_power_nl);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_eh(): Error creating log_power_nl spline\\n\");\n return;\n }\n else\n cosmo->data.p_nl = log_power_nl;\n\n // Free temporary arrays\n free(eh); free(x); free(y); free(a); free(y2d);\n}\n\n/*------ ROUTINE: tsqr_BBKS -----\nINPUT: ccl_parameters and k wavenumber in 1/Mpc\nTASK: provide the square of the BBKS transfer function with baryonic correction\nNOTE: Bardeen et al. (1986) as implemented in Sugiyama (1995) \n*/\n\nstatic double tsqr_BBKS(ccl_parameters * params, double k)\n{\n double q = k/(params->Omega_m*params->h*params->h*exp(-params->Omega_b*(1.0+pow(2.*params->h,.5)/params->Omega_m)));\n return pow(log(1.+2.34*q)/(2.34*q),2.0)/pow(1.+3.89*q+pow(16.1*q,2.0)+pow(5.46*q,3.0)+pow(6.71*q,4.0),0.5);\n}\n\n/*------ ROUTINE: bbks_power -----\nINPUT: ccl_parameters and k wavenumber in 1/Mpc\nTASK: provide the BBKS power spectrum with baryonic correction at single k\n*/\n\n//Calculate Normalization see Cosmology Notes 8.105 (TODO: whose comment is this?)\nstatic double bbks_power(ccl_parameters * params, double k)\n{\n return pow(k,params->n_s)*tsqr_BBKS(params, k);\n}\n\n/*------ ROUTINE: ccl_cosmology_compute_bbks_power -----\nINPUT: cosmology\nTASK: provide spline for the BBKS power spectrum with baryonic correction\n*/\n\nstatic void ccl_cosmology_compute_power_bbks(ccl_cosmology * cosmo, int * status)\n{\n //These are the limits of the splining range\n cosmo->data.k_min_lin=ccl_splines->K_MIN;\n cosmo->data.k_min_nl=ccl_splines->K_MIN;\n cosmo->data.k_max_lin=ccl_splines->K_MAX;\n cosmo->data.k_max_nl=ccl_splines->K_MAX;\n double kmin = cosmo->data.k_min_lin;\n double kmax = ccl_splines->K_MAX;\n //Compute nk from number of decades and N_K = # k per decade\n double ndecades = log10(kmax) - log10(kmin);\n int nk = (int)ceil(ndecades*ccl_splines->N_K);\n double amin = ccl_splines->A_SPLINE_MINLOG_PK;\n double amax = ccl_splines->A_SPLINE_MAX;\n int na = ccl_splines->A_SPLINE_NA_PK+ccl_splines->A_SPLINE_NLOG_PK-1;\n\n // Exit if sigma8 wasn't specified\n if (isnan(cosmo->params.sigma8)) {\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_bbks(): sigma8 not set, required for BBKS\\n\");\n return; //Return without anything to free\n }\n\n // The x array is initially k, but will later\n // be overwritten with log(k)\n double * x = ccl_log_spacing(kmin, kmax, nk);\n double * y = malloc(sizeof(double)*nk);\n double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK);\n double * y2d = malloc(nk * na * sizeof(double)); \n \n //If error, store status, we will free later\n if (a==NULL||y==NULL|| x==NULL || y2d==0) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_bbks(): memory allocation error\\n\");\n } \n\n //Status flags\n int splinstatus=0;\n \n if(!*status){\n \n // After this loop x will contain log(k)\n for (int i=0; i<nk; i++) {\n y[i] = log(bbks_power(&cosmo->params, x[i]));\n x[i] = log(x[i]);\n }\n \n for (int j = 0; j < na; j++) {\n double gfac = ccl_growth_factor(cosmo,a[j], status);\n double g2 = 2.*log(gfac);\n for (int i=0; i<nk; i++) {\n\ty2d[j*nk+i] = y[i]+g2;\n }\n }\n }\n \n if(!*status){\n \n // Initialize a 2D spline over P(k, a) [which is still unnormalized by sigma8]\n gsl_spline2d * log_power_lin_unnorm = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na);\n splinstatus = gsl_spline2d_init(log_power_lin_unnorm, x, a, y2d,nk,na);\n\n //If not, proceed\n if (!splinstatus) { \n cosmo->data.p_lin=log_power_lin_unnorm;\n cosmo->computed_power=true;\n } else {\n gsl_spline2d_free(log_power_lin_unnorm);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo,\"ccl_power.c: ccl_cosmology_compute_power_bbks(): Error creating log_power_lin spline\\n\");\n }\n }\n\n if(*status){\n free(x); free(y); free(a); free(y2d);\n return;\n }\n\n // Calculate sigma8 for the unnormalized P(k), using the standard\n // ccl_sigma8() function\n double sigma8 = ccl_sigma8(cosmo,status);\n cosmo->computed_power=false;\n\n // Check that ccl_sigma8 didn't fail\n if (!*status) {\n \n // Calculate normalization factor using computed value of sigma8, then\n // recompute P(k, a) using this normalization\n double log_normalization_factor = 2*(log(cosmo->params.sigma8) - log(sigma8));\n for (int i=0; i<nk; i++) {\n y[i] += log_normalization_factor;\n }\n for (int j = 0; j < na; j++) {\n double gfac = ccl_growth_factor(cosmo,a[j], status);\n double g2 = 2.*log(gfac);\n for (int i=0; i<nk; i++) {\n\ty2d[j*nk+i] = y[i]+g2;\n }\n }\n }\n\n //Check growth didn't fail\n if (!*status) {\n \n gsl_spline2d * log_power_lin = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na);\n splinstatus = gsl_spline2d_init(log_power_lin, x, a, y2d,nk,na);\n\n if (!splinstatus) {\n cosmo->data.p_lin=log_power_lin;\n } else {\n gsl_spline2d_free(log_power_lin);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo,\"ccl_power.c: ccl_cosmology_compute_power_bbks(): Error creating log_power_lin spline\\n\");\n }\n }\n\n if(!*status){\n // Allocate a 2D spline for the nonlinear P(k)\n //[which is just a copy of the linear one for BBKS]\n gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PNL_SPLINE_TYPE, nk,na);\n splinstatus = gsl_spline2d_init(log_power_nl, x, a, y2d,nk,na);\n if (!splinstatus) {\n cosmo->data.p_nl = log_power_nl;\n } else {\n gsl_spline2d_free(log_power_nl);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_bbks(): Error creating log_power_nl spline\\n\");\n }\n }\n\n free(x); free(y); free(a); free(y2d);\n return;\n}\n\n\n\n/*------ ROUTINE: ccl_cosmology_compute_power_emu -----\nINPUT: cosmology\nTASK: provide spline for the emulated power spectrum from Cosmic EMU\n*/\n\nstatic void ccl_cosmology_compute_power_emu(ccl_cosmology * cosmo, int * status)\n{\n\n struct precision pr; // for precision parameters\n struct background ba; // for cosmological background\n struct thermo th; // for thermodynamics\n struct perturbs pt; // for source functions\n struct transfers tr; // for transfer functions\n struct primordial pm; // for primordial spectra\n struct spectra sp; // for output spectra\n struct nonlinear nl; // for non-linear spectra\n struct lensing le;\n struct output op;\n struct file_content fc;\n\n double Omeganuh2_eq;\n double w0wacomb = -cosmo->params.w0 - cosmo->params.wa;\n \n ErrorMsg errmsg; // for error messages\n // generate file_content structure\n // Configuration parameters will be passed through this structure,\n // to avoid writing and reading .ini files for every call\n int parser_length = 20;\n int init_arr[7]={0,0,0,0,0,0,0};\n\n //Check initialization\n if (parser_init(&fc,parser_length,\"none\",errmsg) == _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): parser init error:%s\\n\", errmsg);\n }\n\n // Check ranges to see if the cosmology is valid\n if((cosmo->params.h<0.55) || (cosmo->params.h>0.85)){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): h is outside allowed range\\n\");\n }\n if(w0wacomb<8.1e-3){ //0.3^4\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): w0 and wa do not satisfy the emulator bound\\n\");\n }\n if(cosmo->params.Omega_n_mass*cosmo->params.h*cosmo->params.h>0.01){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): Omega_nu does not satisfy the emulator bound\\n\");\n }\n \n // Check to see if sigma8 was defined\n if(isnan(cosmo->params.sigma8)){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): sigma8 is not defined; specify sigma8 instead of A_s\\n\");\n }\n\n //If one of the previous test was unsuccessful, quit:\n if(*status) return;\n\n // Check if the cosmology has been set up with equal neutrino masses for the emulator\n // If not, check if the user has forced redistribution of masses and if so do this.\n if(cosmo->params.N_nu_mass>0) {\n if (cosmo->config.emulator_neutrinos_method == ccl_emu_strict){\n if (cosmo->params.N_nu_mass==3){\n\t//double diff1 = pow((cosmo->params.mnu[0] - cosmo->params.mnu[1]) * (cosmo->params.mnu[0] - cosmo->params.mnu[1]), 0.5);\n\t//double diff2 = pow((cosmo->params.mnu[1] - cosmo->params.mnu[2]) * (cosmo->params.mnu[1] - cosmo->params.mnu[2]), 0.5);\n\t//double diff3 = pow((cosmo->params.mnu[2] - cosmo->params.mnu[0]) * (cosmo->params.mnu[2] - cosmo->params.mnu[0]), 0.5);\n\t//if (diff1>1e-12 || diff2>1e-12 || diff3>1e-12){\n\tif (cosmo->params.mnu[0] != cosmo->params.mnu[1] || cosmo->params.mnu[0] != cosmo->params.mnu[2] || cosmo->params.mnu[1] != cosmo->params.mnu[2]){\n\t *status = CCL_ERROR_INCONSISTENT;\n\t ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): In the default configuration, you must pass a list of 3 equal neutrino masses or pass a sum and set mnu_type = ccl_mnu_sum_equal. If you wish to over-ride this, set config->emulator_neutrinos_method = 'ccl_emu_equalize'. This will force the neutrinos to be of equal mass but will result in internal inconsistencies.\\n\");\n\t}\n } else if (cosmo->params.N_nu_mass!=3){\n\t*status = CCL_ERROR_INCONSISTENT;\n\tccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): In the default configuration, you must pass a list of 3 equal neutrino masses or pass a sum and set mnu_type = ccl_mnu_sum_equal. If you wish to over-ride this, set config->emulator_neutrinos_method = 'ccl_emu_equalize'. This will force the neutrinos to be of equal mass but will result in internal inconsistencies.\\n\");\n }\n } else if (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize){\n // Reset the masses to equal\n double mnu_eq[3] = {cosmo->params.sum_nu_masses / 3., cosmo->params.sum_nu_masses / 3., cosmo->params.sum_nu_masses / 3.};\n Omeganuh2_eq = ccl_Omeganuh2(1.0, 3, mnu_eq, cosmo->params.T_CMB, cosmo->data.accelerator, status);\n }\n } else {\n if(fabs(cosmo->params.N_nu_rel - 3.04)>1.e-6){\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): Set Neff = 3.04 for cosmic emulator predictions in absence of massive neutrinos.\\n\");\n }\n }\n\n if(!*status){\n // Prepare to run CLASS for linear scales\n ccl_fill_class_parameters(cosmo,&fc,parser_length, status);\n }\n \n if (!*status){\n ccl_run_class(cosmo, &fc,&pr,&ba,&th,&pt,&tr,&pm,&sp,&nl,&le,&op,init_arr,status);\n }\n\n if (*status){\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n if (parser_free(&fc)== _FAILURE_) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): Error freeing CLASS parser\\n\");\n }\n return;\n }\n \n //These are the limits of the splining range\n cosmo->data.k_min_lin=2*exp(sp.ln_k[0]);\n cosmo->data.k_max_lin=ccl_splines->K_MAX_SPLINE;\n //CLASS calculations done - now allocate CCL splines\n double kmin = cosmo->data.k_min_lin;\n double kmax = ccl_splines->K_MAX_SPLINE;\n //Compute nk from number of decades and N_K = # k per decade\n double ndecades = log10(kmax) - log10(kmin);\n int nk = (int)ceil(ndecades*ccl_splines->N_K);\n double amin = ccl_splines->A_SPLINE_MINLOG_PK;\n double amax = ccl_splines->A_SPLINE_MAX;\n int na = ccl_splines->A_SPLINE_NA_PK+ccl_splines->A_SPLINE_NLOG_PK-1;\n\n // The x array is initially k, but will later\n // be overwritten with log(k)\n double * x = ccl_log_spacing(kmin, kmax, nk);\n double * a = ccl_linlog_spacing(amin, ccl_splines->A_SPLINE_MIN_PK, amax, ccl_splines->A_SPLINE_NLOG_PK, ccl_splines->A_SPLINE_NA_PK);\n double * y2d_lin = malloc(nk * na * sizeof(double));\n if (a==NULL|| x==NULL || y2d_lin==NULL) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_class(): memory allocation error\\n\");\n }\n \n if(!*status){\n // After this loop x will contain log(k), y will contain log(P_nl), z will contain log(P_lin)\n // all in Mpc, not Mpc/h units!\n double psout_l,ic;\n int s=0;\n for (int i=0; i<nk; i++) {\n for (int j = 0; j < na; j++) {\n\t//The 2D interpolation routines access the function values y_{k_ia_j} with the following ordering:\n\t//y_ij = y2d[j*N_k + i]\n\t//with i = 0,...,N_k-1 and j = 0,...,N_a-1.\n\ts |= spectra_pk_at_k_and_z(&ba, &pm, &sp,x[i],1./a[j]-1., &psout_l,&ic);\n\ty2d_lin[j*nk+i] = log(psout_l);\n }\n x[i] = log(x[i]);\n }\n if(s) {\n *status = CCL_ERROR_CLASS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): Error computing CLASS power spectrum\\n\");\n }\n }\n\n if(!*status){\n \n gsl_spline2d * log_power = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, nk,na);\n int pwstatus = gsl_spline2d_init(log_power, x, a, y2d_lin,nk,na);\n if (!pwstatus) {\n cosmo->data.p_lin = log_power;\n } else {\n gsl_spline2d_free(log_power);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): Error creating log_power spline\\n\");\n }\n }\n\n if(*status){ //Linear power spectrum failed, so quit.\n free(x);\n free(a);\n free(y2d_lin);\n ccl_free_class_structs(cosmo, &ba,&th,&pt,&tr,&pm,&sp,&nl,&le,init_arr,status);\n return;\n }\n \n //Now start the NL computation with the emulator\n //These are the limits of the splining range\n cosmo->data.k_min_nl=K_MIN_EMU;\n cosmo->data.k_max_nl=K_MAX_EMU;\n amin = A_MIN_EMU; //limit of the emulator\n amax = ccl_splines->A_SPLINE_MAX;\n na = ccl_splines->A_SPLINE_NA_PK;\n // The x array is initially k, but will later\n // be overwritten with log(k)\n double * logx= malloc(NK_EMU*sizeof(double));\n double * y;\n double * xstar = malloc(9 * sizeof(double));\n double * aemu = ccl_linear_spacing(amin,amax, na);\n double * y2d = malloc(NK_EMU * na * sizeof(double));\n if (aemu==NULL || y2d==NULL || logx==NULL || xstar==NULL){\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): memory allocation error\\n\");\n }\n\n if(!*status){\n \n //For each redshift:\n for (int j = 0; j < na; j++){\n\n //Turn cosmology into xstar:\n xstar[0] = (cosmo->params.Omega_c+cosmo->params.Omega_b)*cosmo->params.h*cosmo->params.h;\n xstar[1] = cosmo->params.Omega_b*cosmo->params.h*cosmo->params.h;\n xstar[2] = cosmo->params.sigma8;\n xstar[3] = cosmo->params.h;\n xstar[4] = cosmo->params.n_s;\n xstar[5] = cosmo->params.w0;\n xstar[6] = cosmo->params.wa;\n if ((cosmo->params.N_nu_mass>0) && (cosmo->config.emulator_neutrinos_method == ccl_emu_equalize)){\n\txstar[7] = Omeganuh2_eq;\n } else { \n xstar[7] = cosmo->params.Omega_n_mass*cosmo->params.h*cosmo->params.h;\n }\n xstar[8] = 1./aemu[j]-1;\n //Need to have this here because otherwise overwritten by emu in each loop\n\n //Call emulator at this redshift\n ccl_pkemu(xstar,&y, status, cosmo);\n if (y == NULL){\n\t*status = CCL_ERROR_MEMORY;\n\tccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): Error obtaining emulator predictions\\n\");\n }\n for (int i=0; i<NK_EMU; i++){\n\tlogx[i] = log(mode[i]);\n\ty2d[j*NK_EMU+i] = log(y[i]);\n }\n }\n }\n\n if(!*status){\n\n gsl_spline2d * log_power_nl = gsl_spline2d_alloc(PLIN_SPLINE_TYPE, NK_EMU,na);\n int splinstatus = gsl_spline2d_init(log_power_nl, logx, aemu, y2d,NK_EMU,na);\n //Note the minimum k of the spline is different from the linear one.\n\n if (!splinstatus){\n cosmo->data.p_nl = log_power_nl;\n } else {\n gsl_spline2d_free(log_power_nl);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power_emu(): Error creating log_power spline\\n\");\n }\n }\n\n free(x); free(a); free(y);\n free(xstar); free(logx); free(aemu);\n free(y2d_lin); free(y2d);\n}\n\n\n\n/*------ ROUTINE: ccl_cosmology_compute_power -----\nINPUT: ccl_cosmology * cosmo\nTASK: compute power spectrum\n*/\nvoid ccl_cosmology_compute_power(ccl_cosmology * cosmo, int * status)\n{\n\n if (cosmo->computed_power) return;\n switch(cosmo->config.transfer_function_method){\n case ccl_bbks:\n\t ccl_cosmology_compute_power_bbks(cosmo,status);\n\t break;\n case ccl_eisenstein_hu:\n\t ccl_cosmology_compute_power_eh(cosmo,status);\n\t break;\n case ccl_boltzmann_class:\n\t ccl_cosmology_compute_power_class(cosmo,status);\n\t break;\n case ccl_emulator:\n\t ccl_cosmology_compute_power_emu(cosmo,status);\n\t break;\n default:\n\t *status = CCL_ERROR_INCONSISTENT;\n\t ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_cosmology_compute_power(): Unknown or non-implemented transfer function method: %d \\n\", cosmo->config.transfer_function_method);\n }\n\n ccl_check_status(cosmo,status);\n if (*status==0){\n cosmo->computed_power = true;\n }\n return;\n}\n\n\n/*------ ROUTINE: ccl_power_extrapol_highk -----\nINPUT: ccl_cosmology * cosmo, a, k [1/Mpc]\nTASK: extrapolate power spectrum at high k\n*/\nstatic double ccl_power_extrapol_highk(ccl_cosmology * cosmo, double k, double a,\n\t\t\t\t gsl_spline2d * powerspl, double kmax_spline, int * status)\n{\n double log_p_1;\n double deltak=1e-2; //step for numerical derivative;\n double deriv_pk_kmid,deriv2_pk_kmid;\n double lkmid;\n double lpk_kmid;\n\n lkmid = log(kmax_spline)-2*deltak;\n\n int gslstatus = gsl_spline2d_eval_e(powerspl, lkmid,a,NULL ,NULL ,&lpk_kmid);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_power_extrapol_highk():\");\n *status = CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_power_extrapol_highk(): Spline evaluation error\\n\");\n return NAN;\n }\n //GSL derivatives\n gslstatus = gsl_spline2d_eval_deriv_x_e (powerspl, lkmid, a, NULL,NULL,&deriv_pk_kmid);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_power_extrapol_highk():\");\n *status = CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_power_extrapol_highk(): Spline evaluation error\\n\");\n return NAN;\n }\n gslstatus = gsl_spline2d_eval_deriv_xx_e (powerspl, lkmid, a, NULL,NULL,&deriv2_pk_kmid);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_power_extrapol_highk():\");\n *status = CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_power_extrapol_highk(): Spline evaluation error\\n\");\n return NAN;\n }\n log_p_1=lpk_kmid+deriv_pk_kmid*(log(k)-lkmid)+deriv2_pk_kmid/2.*(log(k)-lkmid)*(log(k)-lkmid);\n\n return log_p_1;\n\n}\n\n/*------ ROUTINE: ccl_power_extrapol_lowk -----\nINPUT: ccl_cosmology * cosmo, a, k [1/Mpc]\nTASK: extrapolate power spectrum at low k\n*/\nstatic double ccl_power_extrapol_lowk(ccl_cosmology * cosmo, double k, double a,\n\t\t\t\t gsl_spline2d * powerspl, double kmin_spline, int * status)\n{\n double log_p_1;\n double deltak=1e-2; //safety step\n double lkmin=log(kmin_spline)+deltak;\n double lpk_kmin;\n int gslstatus = gsl_spline2d_eval_e(powerspl,lkmin,a,NULL,NULL,&lpk_kmin);\n\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_power_extrapol_lowk():\");\n *status=CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo,\"ccl_power.c: ccl_power_extrapol_lowk(): Spline evaluation error\\n\");\n return NAN;\n }\n\n return lpk_kmin+cosmo->params.n_s*(log(k)-lkmin);\n}\n\n\n/*------ ROUTINE: ccl_linear_matter_power -----\nINPUT: ccl_cosmology * cosmo, k [1/Mpc],a\nTASK: compute the linear power spectrum at a given redshift\n by rescaling using the growth function\n*/\n\ndouble ccl_linear_matter_power(ccl_cosmology * cosmo, double k, double a, int * status)\n\n{\n if ((cosmo->config.transfer_function_method == ccl_emulator) && (a<A_MIN_EMU)){\n *status = CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: the cosmic emulator cannot be used above a=%f\\n\",A_MIN_EMU);\n return NAN;\n }\n\n if (!cosmo->computed_power) ccl_cosmology_compute_power(cosmo, status);\n // Return if compilation failed\n //if (cosmo->data.p_lin == NULL) return NAN;\n if (!cosmo->computed_power) return NAN;\n\n double log_p_1;\n int gslstatus;\n\n if(a<ccl_splines->A_SPLINE_MINLOG_PK) { //Extrapolate linearly at high redshift\n double pk0=ccl_linear_matter_power(cosmo,k,ccl_splines->A_SPLINE_MINLOG_PK,status);\n double gf=ccl_growth_factor(cosmo,a,status)/ccl_growth_factor(cosmo,ccl_splines->A_SPLINE_MINLOG_PK,status);\n\n return pk0*gf*gf;\n }\n if (*status!=CCL_ERROR_INCONSISTENT){\n if(k<=cosmo->data.k_min_lin) {\n log_p_1=ccl_power_extrapol_lowk(cosmo,k,a,cosmo->data.p_lin,cosmo->data.k_min_lin,status);\n\n return exp(log_p_1);\n }\n else if(k<cosmo->data.k_max_lin){\n gslstatus = gsl_spline2d_eval_e(cosmo->data.p_lin, log(k), a,NULL,NULL,&log_p_1);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_linear_matter_power():\");\n *status = CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_linear_matter_power(): Spline evaluation error\\n\");\n return NAN;\n }\n else {\n return exp(log_p_1);\n }\n }\n else { //Extrapolate using log derivative\n log_p_1 = ccl_power_extrapol_highk(cosmo,k,a,cosmo->data.p_lin,cosmo->data.k_max_lin,status);\n return exp(log_p_1);\n }\n }\n\n return exp(log_p_1);\n}\n\n\n/*------ ROUTINE: ccl_nonlin_matter_power -----\nINPUT: ccl_cosmology * cosmo, a, k [1/Mpc]\nTASK: compute the nonlinear power spectrum at a given redshift\n*/\n\ndouble ccl_nonlin_matter_power(ccl_cosmology * cosmo, double k, double a, int *status)\n{\n double log_p_1, pk;\n\n switch(cosmo->config.matter_power_spectrum_method) {\n\n //If the matter PS specified was linear, then do the linear compuation\n case ccl_linear:\n return ccl_linear_matter_power(cosmo,k,a,status);\n\n case ccl_halofit:\n if (!cosmo->computed_power)\n ccl_cosmology_compute_power(cosmo, status);\n if (cosmo->data.p_nl == NULL) return NAN; // Return if computation failed\n\n if(a<ccl_splines->A_SPLINE_MINLOG_PK) { //Extrapolate linearly at high redshift\n double pk0=ccl_nonlin_matter_power(cosmo,k,ccl_splines->A_SPLINE_MINLOG_PK,status);\n double gf=ccl_growth_factor(cosmo,a,status)/ccl_growth_factor(cosmo,ccl_splines->A_SPLINE_MINLOG_PK,status);\n return pk0*gf*gf;\n }\n\t\tbreak;\n\n case ccl_emu:\n if ((cosmo->config.transfer_function_method == ccl_emulator) && (a<A_MIN_EMU)){\n *status = CCL_ERROR_EMULATOR_BOUND;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: the cosmic emulator cannot be used above z=2\\n\");\n return NAN;\n }\n\n // Compute power spectrum if needed; return if computation failed\n if (!cosmo->computed_power){\n ccl_cosmology_compute_power(cosmo,status);\n }\n if (cosmo->data.p_nl == NULL) return NAN;\n\t\tbreak;\n\n default:\n ccl_raise_warning(\n\t\t\tCCL_ERROR_NOT_IMPLEMENTED,\n \"config.matter_power_spectrum_method = %d not yet supported \"\n\t\t\t\"continuing with linear power spectrum\\n\", cosmo->config.matter_power_spectrum_method);\n cosmo->config.matter_power_spectrum_method=ccl_linear;\n return ccl_linear_matter_power(cosmo,k,a,status);\n } // end switch\n\n // if we get here, try to evaluate the power spectrum\n // we need to account for bounds below and above\n if (k <= cosmo->data.k_min_nl) {\n // we assume no baryonic effects below k_min_nl\n log_p_1 = ccl_power_extrapol_lowk(cosmo, k, a, cosmo->data.p_nl, cosmo->data.k_min_nl, status);\n return exp(log_p_1);\n }\n\n if (k < cosmo->data.k_max_nl) {\n int gslstatus = gsl_spline2d_eval_e(cosmo->data.p_nl, log(k), a, NULL ,NULL, &log_p_1);\n if (gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_nonlin_matter_power():\");\n *status = CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_nonlin_matter_power(): Spline evaluation error\\n\");\n return NAN;\n } else {\n pk = exp(log_p_1);\n }\n } else {\n // Extrapolate NL regime using log derivative\n log_p_1 = ccl_power_extrapol_highk(cosmo, k, a, cosmo->data.p_nl, cosmo->data.k_max_nl, status);\n pk = exp(log_p_1);\n }\n\n\t// Add baryonic correction\n if (cosmo->config.baryons_power_spectrum_method == ccl_bcm) {\n int pwstatus = 0;\n double fbcm = ccl_bcm_model_fka(cosmo, k, a, &pwstatus);\n pk *= fbcm;\n if (pwstatus) {\n *status = CCL_ERROR_SPLINE_EV;\n ccl_cosmology_set_status_message(cosmo, \"ccl_power.c: ccl_nonlin_matter_power(): Error in BCM correction\\n\");\n return NAN;\n }\n }\n\n return pk;\n}\n\n// Params for sigma(R) integrand\ntypedef struct {\n ccl_cosmology *cosmo;\n double R;\n int* status;\n} SigmaR_pars;\n\ntypedef struct {\n ccl_cosmology *cosmo;\n double R;\n int* status;\n} SigmaV_pars;\n\n/* --------- ROUTINE: w_tophat ---------\nINPUT: kR, ususally a wavenumber multiplied by a smoothing radius\nTASK: Output W(x)=[sin(x)-x*cos(x)]*(3/x)^3\n*/\nstatic double w_tophat(double kR)\n{\n double w;\n double kR2 = kR*kR;\n\n // This is the Maclaurin expansion of W(x)=[sin(x)-xcos(x)]*(3/x)**3 to O(x^7), with x=kR.\n // Necessary numerically because at low x W(x) relies on the fine cancellation of two terms\n if(kR<0.1) {\n w = 1. + kR2*(-0.1 +\n\t\t kR2*(0.003561429 +\n\t\t\tkR2*(-6.61376e-5 +\n\t\t\t kR2*(7.51563e-7))));\n /*w =1.-0.1*kR*kR+0.003571429*kR*kR*kR*kR\n -6.61376E-5*kR*kR*kR*kR*kR*kR\n +7.51563E-7*kR*kR*kR*kR*kR*kR*kR*kR;*/\n }\n else\n w = 3.*(sin(kR) - kR*cos(kR))/(kR2*kR);\n return w;\n}\n\n// Integrand for sigmaR integral\nstatic double sigmaR_integrand(double lk,void *params)\n{\n SigmaR_pars *par=(SigmaR_pars *)params;\n\n double k=pow(10.,lk);\n double pk=ccl_linear_matter_power(par->cosmo,k, 1.,par->status);\n double kR=k*par->R;\n double w = w_tophat(kR);\n\n return pk*k*k*k*w*w;\n}\n\n// Integrand for sigmaV integral\nstatic double sigmaV_integrand(double lk,void *params)\n{\n SigmaV_pars *par=(SigmaV_pars *)params;\n\n double k=pow(10.,lk);\n double pk=ccl_linear_matter_power(par->cosmo,k, 1.,par->status);\n double kR=k*par->R;\n double w = w_tophat(kR);\n\n return pk*k*w*w/3.0;\n}\n\n/* --------- ROUTINE: ccl_sigmaR ---------\nINPUT: cosmology, comoving smoothing radius, scale factor\nTASK: compute sigmaR, the variance in the *linear* density field\nsmoothed with a tophat filter of comoving size R\n*/\ndouble ccl_sigmaR(ccl_cosmology *cosmo,double R,double a,int *status)\n{\n SigmaR_pars par;\n par.status = status;\n\n par.cosmo=cosmo;\n par.R=R;\n gsl_integration_cquad_workspace *workspace=gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n gsl_function F;\n F.function=&sigmaR_integrand;\n F.params=∥\n double sigma_R;\n int gslstatus = gsl_integration_cquad(&F, log10(ccl_splines->K_MIN), log10(ccl_splines->K_MAX),\n\t\t\t\t 0.0, ccl_gsl->INTEGRATION_SIGMAR_EPSREL,\n workspace,&sigma_R,NULL,NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_sigmaR():\");\n *status |= gslstatus;\n }\n\n gsl_integration_cquad_workspace_free(workspace);\n\n return sqrt(sigma_R*M_LN10/(2*M_PI*M_PI))*ccl_growth_factor(cosmo, a, status);\n}\n\n/* --------- ROUTINE: ccl_sigmaV ---------\nINPUT: cosmology, comoving smoothing radius, scale factor\nTASK: compute sigmaV, the variance in the *linear* displacement field\nsmoothed with a tophat filter of comoving size R\nThe linear displacement field is the gradient of the linear density field\n*/\ndouble ccl_sigmaV(ccl_cosmology *cosmo,double R,double a,int *status)\n{\n SigmaV_pars par;\n par.status = status;\n\n par.cosmo=cosmo;\n par.R=R;\n gsl_integration_cquad_workspace *workspace=gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n gsl_function F;\n F.function=&sigmaV_integrand;\n F.params=∥\n double sigma_V;\n\tint gslstatus = gsl_integration_cquad(&F, log10(ccl_splines->K_MIN), log10(ccl_splines->K_MAX),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0.0, ccl_gsl->INTEGRATION_SIGMAR_EPSREL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tworkspace,&sigma_V,NULL,NULL);\n\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_power.c: ccl_sigmaV():\");\n *status |= gslstatus;\n }\n\n gsl_integration_cquad_workspace_free(workspace);\n\n return sqrt(sigma_V*M_LN10/(2*M_PI*M_PI))*ccl_growth_factor(cosmo, a, status);\n}\n\n/* --------- ROUTINE: ccl_sigma8 ---------\nINPUT: cosmology\nTASK: compute sigma8, the variance in the *linear* density field at a=1\nsmoothed with a tophat filter of comoving size 8 Mpc/h\n*/\ndouble ccl_sigma8(ccl_cosmology *cosmo, int *status)\n{\n return ccl_sigmaR(cosmo,8/cosmo->params.h, 1.,status);\n}\n", "meta": {"hexsha": "dc94d25ad58a1729b94c81c6c1638c3c9b2caaeb", "size": 61392, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_power.c", "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_power.c", "max_issues_repo_name": "vrastil/CCL", "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_power.c", "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4705221786, "max_line_length": 412, "alphanum_fraction": 0.6798442794, "num_tokens": 19808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.22270014914315836, "lm_q1q2_score": 0.12089573412686153}}
{"text": "/*--------------------------------------------------------------------\n * $Id$\n * \n * This file is part of libRadtran.\n * Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,\n * Claudia Emde, Robert Buras\n *\n * ######### Contact info: http://www.libradtran.org #########\n *\n * This program is free software; you can redistribute it and/or \n * modify it under the terms of the GNU General Public License \n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version. \n * \n * This program is distributed in the hope that it will be useful, \n * but WITHOUT ANY WARRANTY; without even the implied warranty of \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * GNU General Public License for more details. \n * \n * You should have received a copy of the GNU General Public License \n * along with this program; if not, write to the Free Software \n * Foundation, Inc., 59 Temple Place - Suite 330, \n * Boston, MA 02111-1307, USA.\n *--------------------------------------------------------------------*/\n\n/* 03.04.2002: Fixed problem with finding correct grid cell for direct beam, AKy. */\n\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifndef _AIX\n#include <getopt.h>\n#else\n#include <unistd.h>\n#endif\n\n#if HAVE_LIBGSL\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_vegas.h>\n#endif\n\n#include \"ascii.h\"\n\n#define PROGRAM \"angres\"\n#define VERSION \"0.3\"\n#define DATE \"3 Feb, 2003\"\n\n#define DIM_ANG_INT 2 /* Integration to be made over 2 dimensions */\n\n#ifndef PI\n#define PI 3.14159265358979323846264338327\n#endif\n\ntypedef struct {\n int nphi;\n int numu;\n double* umu;\n double* phi;\n double** prod;\n} mcinput;\n\n/*************************************************************/\n/* print usage information */\n/*************************************************************/\n\n/*\n Documentation in latex for the User's Guide. Extracted by sdoc2.awk \n and input in the doc/tools.tex.\n*/\n/*\n <lpdoc>\n\n\\subsection{Angular response and tilted surfaces - \\codeidx{angres}}\nThe \\code{angres} tool takes a precalculated radiance field and integrates \nit over a given angular area using any angular response. Typical usages of\n\\code{angres} are calculation of radiation on tilted surfaces and estimation \nof effects of imperfect angular response functions.\n\nThe \\code{angres} tool is invoked as follows:\n\\begin{Verbatim}[fontsize=\\footnotesize]\n angres angres_file raddis_file\n\\end{Verbatim}\nThe two required input files will be read by the \\code{angres} tool.\n\\begin{description}\n\\item[angres\\_file] is a two column file with the first column holding\n the angle and the second column the angular response, e.g. a\n measured cosine response. To generate standard angular response \n function see the \\code{make\\_angres\\_func} tool.\n\n\\item[raddis\\_file] holds the radiance distribution as output from uvspec\n with the disort solvers for one single wavelength.\n\\end{description}\nAfter reading the two input files the angular response will be tilted\nand rotated if specified with the \\code{-t} and \\code{-r} options respectively. Finally\nthe product of the resulting angular response and radiance distribution\nfield are integrated using Monte Carlo methods to yield the effective\nresponse. The integration is done for the diffuse radiation field only. To\ninclude the direct contribution the -s and -z options must be set to give\nthe direction of the sun.\n\nOutput is 3 numbers:\n\\begin{enumerate}\n\\item The integral of the diffuse radiation field times angular response.\n\\item Estimated absolute error of the above integral.\n\\item The integral of the diffuse+direct radiation field times angular response\n (requires that \\code{-s} and \\code{-z} are specified, otherwise same as first number\n\\end{enumerate}\n\nThe angles in the \\file{angres\\_file} must be in radians if not\nthe \\code{-a} option is used. The \\file{raddis\\_file} must contain\noutput from \\code{uvspec} run for one single wavelength with one of\nthe disort solvers and with \\code{phi} and \\code{umu} set.\nNote that the angles in the \\file{angres\\_file} must follow the same\nconventions as for the disort algorithm. This is different from\nthat typically used when reporting measurements of the angular response.\n\nThe \\code{angres} tool accepts the following command line options:\n\n\\begin{description}\n\\item[-h] show this page.\n\\item[-c] number of random points used for Monte Carlo integration.\n\\item[-i] The diffuse radiation is assumed to be isotropic.\n\\item[-a] angular response angle given in degrees and not cosine of angle.\n\\item[-r] rotation angle in degrees.\n\\item[-t] tilt angle in degrees.\n\\item[-s] solar zenith angle in degrees.\n\\item[-z] solar azimuth angle in degrees.\n\\item[-p] pgm files are made of the angular response before\n and after tilt and rotate.\n\\end{description}\n\nSample \\code{angres} input and output files are found in the \\file{examples} directory.\nThe following\n\\begin{Verbatim}[fontsize=\\footnotesize]\n angres examples/ANGRES_1_ANG.DAT \\\n examples/ANGRES_RADDIS_1.DAT -a -t -r 0 -s 32 -z 0\n\\end{Verbatim}\ncalculates the radiation on a horisontal surface given the angular response \nin \\file{examples/ANGRES_1_ANG.DAT}. The input used to calculate the radiance file is\ngiven in the start of \\file{examples/ANGRES_RADDIS_1.DAT}.\n\nAn example of the use of \\code{angres} together with \\code{uvspec} is given in \n\\citet[section 4.6]{mayer2005}.\n </lpdoc>\n*/\n\nstatic void print_usage (char* filename) {\n fprintf (stderr, \"%s - %s \\n\\n\", PROGRAM, VERSION);\n fprintf (stderr, \"written by Arve Kylling,\\n\");\n fprintf (stderr, \" Norwegian Institute for Air Research (NILU)\\n\");\n fprintf (stderr, \" P.O. Box 100, 2027 Kjeller, Norway\\n\");\n fprintf (stderr, \"Version %s finished %s\\n\\n\", VERSION, DATE);\n fprintf (stderr, \"Be aware that this program is a beta version! Please report any\\n\");\n fprintf (stderr, \"kind of error to the author, including the error message and the\\n\");\n fprintf (stderr, \"database being processed when the error occured. Thanks!\\n\\n\");\n\n fprintf (stderr, \"USAGE: %s [options] angres_file raddis_file \\n\\n\", filename);\n fprintf (stderr, \"%s will read the two required input files:\\n\", PROGRAM);\n fprintf (stderr, \" angres_file is a two column file with the first column holding\\n\");\n fprintf (stderr, \" the angle and the second column the angular response, e.g. a\\n\");\n fprintf (stderr, \" measured cosine response.\\n\");\n fprintf (stderr, \" raddis_file holds the radiance distribution as output from uvspec\\n\");\n fprintf (stderr, \" with the disort solvers for one single wavelength.\\n\");\n fprintf (stderr, \"After reading the two input files the angular response will be tilted\\n\");\n fprintf (stderr, \"and rotated if specified with the -t and -r options respectively. Finally\\n\");\n fprintf (stderr, \"the product of the resulting angular response and radiance distribution\\n\");\n fprintf (stderr, \"field are integrated using Monte Carlo methods to yield the effective\\n\");\n fprintf (stderr, \"response. The integration is done for the diffuse radiation field only. To\\n\");\n fprintf (stderr, \"include the direct contribution the -s and -z options must be set to give\\n\");\n fprintf (stderr, \"the direction of the sun. \\n\");\n fprintf (stderr, \"\\n\");\n fprintf (stderr, \"Output is 3 numbers:\\n\");\n fprintf (stderr, \" 1: The integral of the diffuse radiation field times angular response.\\n\");\n fprintf (stderr, \" 2: Estimated absolute error of the above integral.\\n\");\n fprintf (stderr, \" 3: The integral of the diffuse+direct radiation field times angular response\\n\");\n fprintf (stderr, \" (requires that -s and -z are specified, otherwise same as 1).\\n\");\n fprintf (stderr, \"\\n\");\n fprintf (stderr, \"The angles in the angres_file must be in radians if not\\n\");\n fprintf (stderr, \"the -a option is used. The raddis_file must contain\\n\");\n fprintf (stderr, \"output from uvspec run for one single wavelength with one of\\n\");\n fprintf (stderr, \"the disort solvers and with phi and umu set.\\n\");\n fprintf (stderr, \"Note that the angles in the angres_file must follow the same\\n\");\n fprintf (stderr, \"conventions as for the disort algorithm. This is different from\\n\");\n fprintf (stderr, \"that typically used when reporting measurements of the angular response.\\n\");\n fprintf (stderr, \"\\n\");\n fprintf (stderr, \" command line options:\\n\");\n fprintf (stderr, \" -h show this page\\n\");\n fprintf (stderr, \" -c number of random points used for Monte Carlo integration\\n\");\n fprintf (stderr, \" -i The diffuse radiation is assumed to be isotropic\\n\");\n fprintf (stderr, \" -a angular response angle given in degrees and not cosine of angle\\n\");\n fprintf (stderr, \" -r rotation angle in degrees\\n\");\n fprintf (stderr, \" -t tilt angle in degrees\\n\");\n fprintf (stderr, \" -s solar zenith angle in degrees\\n\");\n fprintf (stderr, \" -z solar azimuth angle in degrees\\n\");\n fprintf (stderr, \" -p pgm files are made of the angular response before\\n\");\n fprintf (stderr, \" and after tilt and rotate\\n\");\n}\n\nstatic int get_options (int argc,\n char** argv,\n char* programname,\n char* angresfilename,\n char* raddisfilename,\n int* pgm,\n int* dev,\n int* ang,\n size_t* calls,\n double* sza,\n double* phi0,\n double* theta_t,\n double* phi_r,\n int* incdir,\n int* isotropic) {\n int c = 0;\n\n /* default settings */\n\n /* save name of program */\n strncpy (programname, argv[0], FILENAME_MAX - 1);\n\n while ((c = getopt (argc, argv, \"ahipc:d:s:t:r:z:\")) != EOF) {\n switch (c) {\n case 'h': /* help */\n print_usage (programname);\n return (-1);\n break;\n case 'd':\n *dev = atoi (optarg);\n break;\n case 'a':\n *ang = 1;\n break;\n case 'i':\n *isotropic = 1;\n break;\n case 'p':\n *pgm = 1;\n break;\n case 'c':\n *calls = atoi (optarg);\n break;\n case 'r':\n *phi_r = atof (optarg);\n break;\n case 's':\n *sza = atof (optarg);\n *incdir = 1;\n break;\n case 'z':\n *phi0 = atof (optarg);\n *incdir = 1;\n break;\n case 't':\n *theta_t = atof (optarg);\n break;\n case '?':\n print_usage (programname);\n return (-1);\n break;\n default:\n print_usage (programname);\n return (-1);\n }\n }\n\n /* check number of remaining command line arguments */\n if (argc - optind != 2) {\n print_usage (programname);\n return -1;\n }\n\n /* save command line arguments */\n strncpy (angresfilename, argv[optind + 0], FILENAME_MAX - 1);\n strncpy (raddisfilename, argv[optind + 1], FILENAME_MAX - 1);\n\n return 0; /* if o.k. */\n}\n\ndouble**\ntilt_and_rotate (double* aangres, int nphi, double* phi, int numu, double* umu, int pgm, double theta_t, double phi_r, int dev) {\n int status = 0, i = 0, j = 0, k = 0, it = 0, jt = 0, ia = 0, ja = 0, nt;\n /* double umu_t; */\n double theta = 0, x = 0, y = 0, z = 0, xp = 0, yp = 0, zp = 0, r = 0;\n double a11, a12, a13, a21, a22, a23, a31, a32, a33;\n double rn = 0, theta_n = 0, phi_n = 0;\n double **angres = NULL, **angrestilted = NULL;\n double** angresindcnt = NULL;\n double delphirad = 0;\n FILE* pgmfile = NULL;\n\n /* allocate memory for the angular response function and the tilted and rotated one */\n status = ASCII_calloc_double (&angres, numu, nphi);\n if (status != 0) {\n fprintf (stderr, \"tilt_and_rotate: error allocating memory for angular response function\\n\");\n /* return status; */\n }\n status = ASCII_calloc_double (&angrestilted, numu, nphi);\n if (status != 0) {\n fprintf (stderr, \"tilt_and_rotate: error allocating memory for angular response function\\n\");\n /* return status; */\n }\n\n status = ASCII_calloc_double (&angresindcnt, numu, nphi);\n if (status != 0) {\n fprintf (stderr, \"tilt_and_rotate: error allocating memory for angular response function\\n\");\n /* return status; */\n }\n\n /* The read angular response is assumed to have no azimuth dependence, */\n /* hence it is the same for all phi */\n for (i = 0; i < numu; i++)\n for (j = 0; j < nphi; j++)\n angres[i][j] = aangres[i];\n\n if (pgm) {\n if ((pgmfile = fopen (\"angres_orginal.pgm\", \"w\")) == NULL) {\n fprintf (stderr, \"Error opening angres_orginal.pgm for writing\\n\");\n return NULL;\n }\n\n fprintf (pgmfile, \"P2\\n\");\n fprintf (pgmfile, \"%d %d\\n\", nphi, numu);\n fprintf (pgmfile, \"256\\n\");\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n k = (int)(angres[i][j] * 256);\n fprintf (pgmfile, \"%d\\n\", k);\n }\n }\n fclose (pgmfile);\n }\n\n if (dev == 1)\n fprintf (stdout, \"Tilt: %f Rotate: %f\\n\", theta_t, phi_r);\n /* commented out by RB, because was not used but caused compiler warnings */\n /* umu_t = cos(theta_t*PI/180.0); */\n\n /* Rotation matrix. */\n /* Eq 4-47., p. 147, Goldstein, Classical Mechanics. psi=0 for our purposes */\n\n /* a11 = cos(phi_r*PI/180.0); */\n /* a12 = -cos(theta_t*PI/180.0)*sin(phi_r*PI/180.0); */\n /* a13 = sin(theta_t*PI/180.0)*sin(phi_r*PI/180.0); */\n /* a21 = sin(phi_r*PI/180.0); */\n /* a22 = cos(theta_t*PI/180.0)*cos(phi_r*PI/180.0); */\n /* a23 = -sin(theta_t*PI/180.0)*cos(phi_r*PI/180.0); */\n /* a31 = 0; */\n /* a32 = sin(theta_t*PI/180.0); */\n /* a33 = cos(theta_t*PI/180.0); */\n\n /* First only tilt */\n a11 = 1;\n a12 = 0;\n a13 = 0;\n a21 = 0;\n a22 = cos (theta_t * PI / 180.0);\n a23 = -sin (theta_t * PI / 180.0);\n a31 = 0;\n a32 = sin (theta_t * PI / 180.0);\n a33 = cos (theta_t * PI / 180.0);\n\n if (dev == 1) {\n printf (\"a11: %7.3f, a12: %7.3f a13: %7.3f\\n\", a11, a12, a13);\n printf (\"a21: %7.3f, a22: %7.3f a23: %7.3f\\n\", a21, a22, a23);\n printf (\"a31: %7.3f, a32: %7.3f a33: %7.3f\\n\", a31, a32, a33);\n }\n if (dev == 1)\n fprintf (stdout, \"Tilt: %f Rotate: %f\\n\", theta_t, phi_r);\n\n /* First tilt the angular response */\n for (i = 0; i < numu; i++) {\n theta = acos (umu[i]);\n for (j = 0; j < nphi; j++) {\n rn = 1;\n xp = rn * cos (phi[j] * PI / 180) * sin (theta);\n yp = rn * sin (phi[j] * PI / 180) * sin (theta);\n zp = rn * cos (theta);\n if (dev == 1) {\n printf (\"\\nxp: %7.3f, yp: %7.3f zp: %7.3f theta: %7.4f phi: %5.1f r: %6.3f umu: %f\\n\",\n xp,\n yp,\n zp,\n theta,\n phi[j],\n r,\n umu[i]);\n }\n\n if (dev == 1)\n fprintf (stdout, \"Tilt: %f Rotate: %f\\n\", theta_t, phi_r);\n\n x = a11 * xp + a12 * yp + a13 * zp;\n y = a21 * xp + a22 * yp + a23 * zp;\n z = a31 * xp + a32 * yp + a33 * zp;\n\n rn = sqrt (x * x + y * y + z * z);\n if (rn > 0)\n theta_n = acos (z / rn);\n else\n theta_n = 0;\n\n if (rn > 0) {\n phi_n = acos (x / (rn * sin (theta_n)));\n } else {\n phi_n = 0;\n }\n\n if (dev == 1) {\n printf (\"x: %7.3f, y: %7.3f z: %7.3f theta: %7.4f phi: %5.1f\\n\", x, y, z, theta * 180 / PI, phi[j]);\n printf (\"rn: %7.3f, theta_n: %7.4f phi_n: %5.1f phi_r: %f\\n\", rn, theta_n * 180 / PI, phi_n * 180 / PI, phi_r);\n }\n\n if (dev == 1)\n fprintf (stdout, \"Tilt: %f Rotate: %f\\n\", theta_t, phi_r);\n\n it = 0;\n ia = 1;\n\n while ((theta_n * 180 / PI - acos (umu[ia++]) * 180 / PI) < 0 && ia < numu)\n ;\n it = ia - 1; /* This one is fun:-) */\n\n /* Make sure we get the closest grid point */\n if (fabs (acos (umu[it]) * 180 / PI - theta_n * 180 / PI) > fabs (acos (umu[it - 1]) * 180 / PI - theta_n * 180 / PI))\n it = it - 1;\n\n jt = 0;\n ja = 0;\n delphirad = fabs (phi[1] - phi[0]) * PI / 180;\n while (fabs (phi_n - phi[ja++] * PI / 180) > delphirad) {\n if (dev == 1) {\n printf (\"%d %d %d %f %f %f %f\\n\",\n j,\n ja,\n jt,\n phi_n,\n phi[ja - 1] * PI / 180,\n fabs (phi_n - phi[ja - 1] * PI / 180),\n delphirad);\n }\n }\n jt = ja - 1;\n angrestilted[i][j] = angres[it][jt];\n }\n }\n\n /* Now we rotate */\n nt = (phi_r * PI / 180) / delphirad;\n if (jt >= nphi)\n jt -= nphi;\n for (i = 0; i < numu; i++) {\n theta = acos (umu[i]);\n for (j = 0; j < nphi; j++) {\n jt = j + nt;\n if (jt >= nphi)\n jt -= nphi;\n if (dev == 1 || dev == 10)\n fprintf (stdout,\n \"%3d %3d nt: %d %3d jt: %3d %3d, nphi: %d, phi_r: %5.1f %3.1f\\n\",\n i,\n j,\n nt,\n it,\n jt,\n ja - 1,\n nphi,\n phi_r,\n angres[it][jt]);\n\n angres[i][j] = angrestilted[i][jt];\n if (dev == 1) {\n printf (\"angrestilted: %7.4f %7.4f %7.4f\\n\", acos (umu[it]) * 180 / PI, phi[jt], angrestilted[i][j]);\n }\n }\n }\n\n if (pgm) {\n\n if ((pgmfile = fopen (\"angres_tilted.pgm\", \"w\")) == NULL) {\n fprintf (stderr, \"Error opening angres_tilted.pgm for writing\\n\");\n return NULL;\n }\n\n fprintf (pgmfile, \"P2\\n\");\n fprintf (pgmfile, \"%d %d\\n\", nphi, numu);\n fprintf (pgmfile, \"256\\n\");\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n k = (int)(angres[i][j] * 256);\n fprintf (pgmfile, \"%d\\n\", k);\n }\n }\n fclose (pgmfile);\n }\n\n return angres;\n}\n\ndouble linpol (double x1, double x2, double y1, double y2, double x) {\n /* Linearly interpolate between two points to get wanted y value for x. */\n double y;\n double a = 0, b = 0;\n\n if (x2 > 0 && x1 > 0 && fabs (x2 - x1) < 0.0000001) {\n y = y1;\n } else {\n a = (y2 - y1) / (x2 - x1);\n b = y1 - a * x1;\n y = a * x + b;\n }\n return y;\n}\n\ndouble mc_func (double* k, size_t dim, void* params) {\n int i1 = 0, i2 = 0, j1 = 0, j2 = 0;\n double p1, p2, p3;\n double umu = 0, phi = 0;\n mcinput lmcinp;\n\n lmcinp = *(mcinput*)params;\n\n umu = k[0];\n phi = k[1];\n i2 = 0;\n while (umu > lmcinp.umu[i2++])\n ;\n i1 = i2 - 1;\n if (i2 == 0) {\n i2 = 1;\n i1 = 0;\n }\n if (i2 >= lmcinp.numu) {\n i2 = lmcinp.numu - 1;\n i1 = i2 - 1;\n }\n\n j2 = 0;\n while (phi > lmcinp.phi[j2++])\n ;\n j1 = j2 - 1;\n if (j2 == 0) {\n j2 = 1;\n j1 = 0;\n }\n if (j2 >= lmcinp.nphi) {\n j2 = lmcinp.nphi - 1;\n j1 = j2 - 1;\n }\n\n p1 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i1][j1], lmcinp.prod[i1][j2], phi);\n p2 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i2][j1], lmcinp.prod[i2][j2], phi);\n\n p3 = linpol (lmcinp.umu[i1], lmcinp.umu[i2], p1, p2, umu);\n\n return p3;\n}\n\ndouble mc_funciso (double* k, size_t dim, void* params) {\n int i1 = 0, i2 = 0, j1 = 0, j2 = 0;\n double p1, p2, p3;\n double umu = 0, phi = 0;\n mcinput lmcinp;\n\n lmcinp = *(mcinput*)params;\n\n umu = k[0];\n phi = k[1];\n i2 = 0;\n while (umu > lmcinp.umu[i2++])\n ;\n i1 = i2 - 1;\n if (i2 == 0) {\n i2 = 1;\n i1 = 0;\n }\n if (i2 >= lmcinp.numu) {\n i2 = lmcinp.numu - 1;\n i1 = i2 - 1;\n }\n\n j2 = 0;\n while (phi > lmcinp.phi[j2++])\n ;\n j1 = j2 - 1;\n if (j2 == 0) {\n j2 = 1;\n j1 = 0;\n }\n if (j2 >= lmcinp.nphi) {\n j2 = lmcinp.nphi - 1;\n j1 = j2 - 1;\n }\n\n p1 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i1][j1], lmcinp.prod[i1][j2], phi);\n p2 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i2][j1], lmcinp.prod[i2][j2], phi);\n\n p3 = linpol (lmcinp.umu[i1], lmcinp.umu[i2], p1, p2, umu);\n\n return p3;\n}\n\nint main (int argc, char** argv) {\n int i = 0, j = 0, k = 0, status = 0, pgm = 0, dev = 0, ang = 0, incdir = 0, isotropic = 0;\n int ia = 0, it = 0, ja = 0, jt = 0;\n double delphirad = 0, dir = 0;\n\n char programname[FILENAME_MAX] = \"\";\n char angresfilename[FILENAME_MAX] = \"\"; /* File holding angular response */\n char raddisfilename[FILENAME_MAX] = \"\"; /* File holding radiance distribution */\n\n double *phi = NULL, *rphi = NULL, *aumu = NULL, *rumu = NULL, *aangres = NULL;\n double theta_t = 0, phi_r = 0, sza = 0, phi0 = 0, max = 0;\n double dphi = 0, dtheta = 0, tmpprod = 0;\n double uavgso;\n /* commented out by RB, because was not used but caused compiler warnings */\n /* double rfldir, rfldn, flup, uavgso, uavgdn, uavgup; */\n\n int arows = 0, amin_columns = 0, amax_columns = 0; /* Angular response file */\n int rrows = 0, rmin_columns = 0, rmax_columns = 0; /* Radiance distribution file */\n int nphi = 0, numu = 0;\n\n mcinput mcinp;\n /* void *pmcinp; */\n mcinput mcinpiso;\n /* void *pmcinpiso; */\n\n double **angres = NULL, **avalue = NULL, **rvalue = NULL, **raddis = NULL, **prod = NULL;\n\n FILE* pgmfile = NULL;\n\n /* Monte Carlo integration stuff */\n double res = 0, err = 0;\n\n double xl[DIM_ANG_INT];\n double xu[DIM_ANG_INT];\n\n /* size_t calls = 10; */\n size_t calls = 5000000;\n\n#if HAVE_LIBGSL\n const gsl_rng_type* T;\n const gsl_rng_type* Tiso;\n gsl_rng* r;\n gsl_rng* riso;\n\n gsl_monte_function G = {&mc_func, DIM_ANG_INT, &mcinp};\n gsl_monte_function Giso = {&mc_funciso, DIM_ANG_INT, &mcinpiso};\n\n gsl_monte_plain_state* s = gsl_monte_plain_alloc (DIM_ANG_INT);\n gsl_monte_plain_state* siso = gsl_monte_plain_alloc (DIM_ANG_INT);\n#endif\n /* commented out by RB, because was not used but caused compiler warnings */\n /* pmcinp = &mcinp; */\n /* pmcinpiso = &mcinpiso; */\n\n /* get command line options */\n status = get_options (argc,\n argv,\n programname,\n angresfilename,\n raddisfilename,\n &pgm,\n &dev,\n &ang,\n &calls,\n &sza,\n &phi0,\n &theta_t,\n &phi_r,\n &incdir,\n &isotropic);\n\n if (status != 0)\n return status;\n\n#if !HAVE_LIBGSL\n fprintf (stderr, \"%s was built without the gsl-library. Thus NO SUPPORT\\n\", programname);\n fprintf (stderr, \"for integration of product of angular response and radiance field.\\n\");\n#endif\n\n /* read angular response file */\n status = ASCII_file2double (angresfilename, &arows, &amax_columns, &amin_columns, &avalue);\n\n if (status != 0) {\n fprintf (stderr, \"error %d reading input file %s\\n\", status, angresfilename);\n return status;\n }\n\n if (amin_columns < 2) {\n fprintf (stderr, \"error, input file must have at least two columns\\n\");\n return -1;\n }\n\n if (amin_columns != amax_columns) {\n fprintf (stderr, \" WARNING! %s is not a rectangular matrix; only the first\\n\", angresfilename);\n fprintf (stderr, \" %d columns will be used for the analysis\\n\", amin_columns);\n }\n numu = arows;\n\n /* Read radiance field file */\n status = ASCII_file2double (raddisfilename, &rrows, &rmax_columns, &rmin_columns, &rvalue);\n\n if (status != 0) {\n fprintf (stderr, \"error %d reading input file %s\\n\", status, raddisfilename);\n return status;\n }\n\n /* Get umu and phi from radiance field */\n rphi = ASCII_row (rvalue, rmax_columns, 1);\n j = 0;\n for (i = 0; i < rmax_columns; i++) {\n if (rphi[i] >= 0) {\n nphi++;\n }\n }\n phi = (double*)calloc (nphi, sizeof (double));\n j = 0;\n for (i = 0; i < nphi; i++) {\n if (rphi[i] != NAN) { /* ??? is that correct? Not even NAN == NAN ??? */\n phi[j++] = rphi[i];\n }\n }\n rumu = ASCII_column (rvalue, rrows, 0);\n for (i = 0; i < rrows - 2; i++) {\n rumu[i] = rumu[i + 2];\n } /* Shift to skip two first lines */\n rumu[rrows - 2] = NAN;\n rumu[rrows - 1] = NAN;\n\n /* allocate memory for the radiance field */\n status = ASCII_calloc_double (&raddis, numu, nphi);\n if (status != 0) {\n fprintf (stderr, \"angres: allocating memory for produce\\n\");\n return status;\n }\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n raddis[i][j] = rvalue[i + 2][j + 2];\n }\n }\n /* commented out by RB, because was not used but caused compiler warnings */\n /* rfldir = rvalue[0][1]; */\n /* rfldn = rvalue[0][2]; */\n /* flup = rvalue[0][3]; */\n uavgso = rvalue[0][4];\n /* uavgdn = rvalue[0][5]; */\n /* uavgup = rvalue[0][6]; */\n\n aumu = ASCII_column (avalue, arows, 0);\n if (ang)\n for (i = 0; i < numu; i++)\n aumu[i] = cos (aumu[i] * PI / 180);\n\n aangres = ASCII_column (avalue, arows, 1);\n\n /* compare umu with similar from angular response file, differences should be small, */\n /* otherwise interpolate angular response to radiance field. */\n for (i = 0; i < numu; i++)\n if (fabs (aumu[i] - rumu[i]) > 0.0001)\n fprintf (stderr, \"umu %f %f %f\\n\", aumu[i], rumu[i], aumu[i] - rumu[i]);\n\n /* Make diffuse radiation field isotropic */\n if (isotropic) {\n /* Integrate (angular response)*radiance over all angles */\n\n /* Upper and lower integration bounds for each dimension */\n xl[0] = aumu[0];\n xu[0] = aumu[numu - 1];\n xl[1] = phi[0] * PI / 180;\n xu[1] = phi[nphi - 1] * PI / 180;\n\n mcinpiso.nphi = nphi;\n mcinpiso.numu = numu;\n mcinpiso.phi = (double*)calloc (nphi, sizeof (double));\n mcinpiso.umu = (double*)calloc (numu, sizeof (double));\n status = ASCII_calloc_double (&mcinpiso.prod, numu, nphi);\n for (i = 0; i < nphi; i++)\n mcinpiso.phi[i] = phi[i] * PI / 180;\n for (i = 0; i < numu; i++)\n mcinpiso.umu[i] = aumu[i];\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n mcinpiso.prod[i][j] = raddis[i][j];\n }\n }\n\n#if HAVE_LIBGSL\n gsl_rng_env_setup();\n\n Tiso = gsl_rng_default;\n riso = gsl_rng_alloc (Tiso);\n\n gsl_monte_plain_integrate (&Giso, xl, xu, DIM_ANG_INT, calls, riso, siso, &res, &err);\n gsl_monte_plain_free (siso);\n#endif\n\n dphi = phi[1] - phi[0];\n dtheta = fabs (acos (aumu[1]) * 180 / PI - acos (aumu[0]) * 180 / PI);\n tmpprod = dtheta * dphi;\n\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n raddis[i][j] = res / tmpprod;\n }\n }\n }\n\n /* Tilt and rotate angular response */\n angres = tilt_and_rotate (aangres, nphi, phi, numu, aumu, pgm, theta_t, phi_r, dev);\n if (angres == NULL) {\n fprintf (stderr, \"Error calling tilt_and_rotate()\\n\");\n return -1;\n }\n\n /* Multiply angular response and radiance field */\n /* allocate memory for the product */\n\n status = ASCII_calloc_double (&prod, numu, nphi);\n if (status != 0) {\n fprintf (stderr, \"angres: error allocating memory for product\\n\");\n return status;\n }\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n prod[i][j] = angres[i][j] * raddis[i][j];\n }\n }\n\n if (pgm) {\n\n if ((pgmfile = fopen (\"prod.pgm\", \"w\")) == NULL) {\n fprintf (stderr, \"Error opening prod.pgm for writing\\n\");\n return -1;\n }\n\n fprintf (pgmfile, \"P2\\n\");\n fprintf (pgmfile, \"%d %d\\n\", nphi, numu);\n fprintf (pgmfile, \"256\\n\");\n max = -9999;\n for (i = 0; i < numu; i++)\n for (j = 0; j < nphi; j++)\n if (prod[i][j] > max)\n max = prod[i][j];\n\n for (i = 0; i < numu; i++)\n for (j = 0; j < nphi; j++) {\n k = (int)(prod[i][j] * 256 / max);\n fprintf (pgmfile, \"%d\\n\", k);\n }\n\n fclose (pgmfile);\n\n if ((pgmfile = fopen (\"raddis.pgm\", \"w\")) == NULL) {\n fprintf (stderr, \"Error opening raddis.pgm for writing\\n\");\n return -1;\n }\n\n fprintf (pgmfile, \"P2\\n\");\n fprintf (pgmfile, \"%d %d\\n\", nphi, numu);\n fprintf (pgmfile, \"256\\n\");\n max = -9999;\n for (i = 0; i < numu; i++)\n for (j = 0; j < nphi; j++)\n if (raddis[i][j] > max)\n max = raddis[i][j];\n\n for (i = 0; i < numu; i++)\n for (j = 0; j < nphi; j++) {\n k = (int)(raddis[i][j] * 256 / max);\n fprintf (pgmfile, \"%d\\n\", k);\n }\n\n fclose (pgmfile);\n }\n\n /* Find angular response for direct beam contribution */\n it = 0;\n ia = 0;\n\n while (((180 - sza) - acos (aumu[ia++]) * 180 / PI) < 0 && ia < numu)\n ;\n\n it = ia - 1; /* This one is fun:-) */\n\n /* Make sure we get the closest grid point */\n if (fabs (acos (aumu[it]) * 180 / PI - (180 - sza)) > fabs (acos (aumu[it - 1]) * 180 / PI - (180 - sza)))\n it = it - 1;\n\n jt = 0;\n ja = 0;\n delphirad = fabs (phi[1] - phi[0]) * PI / 180;\n while (fabs (phi0 - phi[ja++]) * PI / 180 > delphirad)\n ;\n\n jt = ja - 1;\n\n if (incdir) {\n dir = angres[it][jt] * uavgso * 4 * PI;\n } else {\n dir = 0;\n }\n\n ASCII_free_double (avalue, arows);\n ASCII_free_double (rvalue, rrows);\n ASCII_free_double (angres, numu);\n\n /* Integrate (angular response)*radiance over all angles */\n\n /* Upper and lower integration bounds for each dimension */\n xl[0] = aumu[0];\n xu[0] = aumu[numu - 1];\n xl[1] = phi[0] * PI / 180;\n xu[1] = phi[nphi - 1] * PI / 180;\n\n mcinp.nphi = nphi;\n mcinp.numu = numu;\n mcinp.phi = (double*)calloc (nphi, sizeof (double));\n mcinp.umu = (double*)calloc (numu, sizeof (double));\n status = ASCII_calloc_double (&mcinp.prod, numu, nphi);\n for (i = 0; i < nphi; i++)\n mcinp.phi[i] = phi[i] * PI / 180;\n for (i = 0; i < numu; i++)\n mcinp.umu[i] = aumu[i];\n for (i = 0; i < numu; i++) {\n for (j = 0; j < nphi; j++) {\n mcinp.prod[i][j] = prod[i][j];\n }\n }\n\n#if HAVE_LIBGSL\n gsl_rng_env_setup();\n\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n gsl_monte_plain_integrate (&G, xl, xu, DIM_ANG_INT, calls, r, s, &res, &err);\n gsl_monte_plain_free (s);\n#endif\n /* fprintf(stdout,\"Result: %f, error: %f\\n\", res, err); */\n fprintf (stdout, \"%f %f %f\\n\", res, err, res + dir);\n\n ASCII_free_double (raddis, numu);\n\n return 0; /* if o.k. */\n}\n", "meta": {"hexsha": "c07a94a5c6da5f25b970b06bc122afe22d3775d1", "size": 30407, "ext": "c", "lang": "C", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/angres.c", "max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/angres.c", "max_issues_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/angres.c", "max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_forks_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9737118822, "max_line_length": 129, "alphanum_fraction": 0.5642450751, "num_tokens": 9808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.23091975763650377, "lm_q1q2_score": 0.11906682597131325}}
|