{"text": "#include \"tmcoct.h\"\r\n#include \r\n\r\nconst double G_COS_0_D = 1.0 - 1.0E-14;\r\nconst double G_COS_90_D = 1.0E-7;\r\n\r\n\r\n#define STANDARDTEST 0\r\n/* testing program using fixed rnd seed. */\r\n\r\n#define PARTIALREFLECTION 1\r\n/* 1=split photon, 0=statistical reflection. */\r\n\r\n#define COSZERO (1.0-1.0E-14)\r\n/* cosine of about 1e-6 rad. */\r\n\r\n#define COS90D 1.0E-6\r\n/* cosine of about 1.57 - 1e-6 rad. */\r\n\r\nconst gsl_rng_type *T_RNG_GSL;\r\ngsl_rng *r_RNG_GSL;\r\n\r\n/***********************************************************\r\n *\tA random number generator from Numerical Recipes in C.\r\n ****/\r\n#define MBIG 1000000000\r\n#define MSEED 161803398\r\n#define MZ 0\r\n#define FAC 1.0E-9\r\n\r\n#undef MBIG\r\n#undef MSEED\r\n#undef MZ\r\n#undef FAC\r\n\r\n\r\n/***********************************************************\r\n *\tGenerate a random number between 0 and 1. Take a \r\n *\tnumber as seed the first time entering the function. \r\n *\tThe seed is limited to 1<<15. \r\n *\tWe found that when idum is too large, ran3 may return \r\n *\tnumbers beyond 0 and 1.\r\n ****/\r\ndouble RandomNum(void) {\r\n static Boolean first_time = 1;\r\n static unsigned long int idum; /* seed for ran3. */\r\n\r\n if (first_time) {\r\n T_RNG_GSL = gsl_rng_default;\r\n r_RNG_GSL = gsl_rng_alloc(T_RNG_GSL);\r\n\r\n#if STANDARDTEST /* Use fixed seed to test the program. */\r\n printf(\"*** Using seed to test. ***\\n\");\r\n printf(\"*** Remove the fixed seed after the test. ***\\n\");\r\n idum = 7923;\r\n\r\n#else\r\n idum = (unsigned long int) time(NULL) % (1 << 15);\r\n /* use 16-bit integer as the seed. */\r\n#endif\r\n printf(\"Random seed = %lu \\n\", idum);\r\n\r\n //ran3(&idum);\r\n gsl_rng_set(r_RNG_GSL, idum);\r\n\r\n first_time = 0;\r\n //idum = 1;\r\n }\r\n // TODO FIXME remove 1.0 -\r\n return (1.0 - gsl_rng_uniform(r_RNG_GSL));\r\n}\r\n\r\n/***********************************************************\r\n *\tCompute the specular reflection. \r\n *\r\n *\tIf the first layer is a turbid medium, use the Fresnel\r\n *\treflection from the boundary of the first layer as the \r\n *\tspecular reflectance.\r\n *\r\n *\tIf the first layer is glass, multiple reflections in\r\n *\tthe first layer is considered to get the specular\r\n *\treflectance.\r\n *\r\n *\tThe subroutine assumes the Layerspecs array is correctly \r\n *\tinitialized.\r\n ****/\r\ndouble Rspecular(double ni, double nt) {\r\n double r1;\r\n /* direct reflections from the 1st and 2nd layers. */\r\n double temp;\r\n temp = (ni - nt) / (ni + nt);\r\n r1 = temp * temp;\r\n return (r1);\r\n}\r\n\r\n/***********************************************************\r\n *\tInitialize a photon packet.\r\n ****/\r\nvoid LaunchPhoton(SimulationStruct *in_parm, double Rspecular, TetrahedronPhotonStruct *Photon_Ptr,\r\n TetrahedronPhotonStruct *PhotonCont_Ptr, TetrahedronStruct *TetrahedronRoot) {\r\n if (Photon_Ptr->FstBackReflectionFlag) {\r\n //Most often case for biased simulations\r\n //The photon will be re-initialized from where the bias was applied\r\n long double LikelihoodRatioTmp = Photon_Ptr->LikelihoodRatioAfterFstBias;\r\n CopyPhotonStruct(PhotonCont_Ptr, Photon_Ptr);\r\n\r\n //Apply one unbiased random scatter to the split photon\r\n Spin(regionspecs[Photon_Ptr->tetrahedron->region].g, Photon_Ptr);\r\n\r\n if (LikelihoodRatioTmp < 1)\r\n // Adjust the likelihoodRation to make the simulation unbiased\r\n Photon_Ptr->LikelihoodRatio = 1 - LikelihoodRatioTmp;\r\n else\r\n Photon_Ptr->LikelihoodRatio = 1;\r\n\r\n } else {\r\n\r\n Photon_Ptr->w = 1.0 - Rspecular;\r\n\r\n Photon_Ptr->x = in_parm->probe_x;\r\n Photon_Ptr->y = in_parm->probe_y;\r\n Photon_Ptr->z = in_parm->probe_z;\r\n\r\n Photon_Ptr->s = 0.0;\r\n Photon_Ptr->sleft = 0.0;\r\n\r\n Photon_Ptr->ux = Photon_Ptr->uy = 0.0;\r\n Photon_Ptr->uz = 1.0;\r\n Photon_Ptr->dead = 0.0;\r\n\r\n Photon_Ptr->OpticalPath = 0.0;\r\n Photon_Ptr->MaxDepth = 0.0;\r\n Photon_Ptr->LikelihoodRatio = 1.0;\r\n Photon_Ptr->LikelihoodRatioAfterFstBias = 1.0;\r\n\r\n Photon_Ptr->FstBackReflectionFlag = 0;\r\n Photon_Ptr->LocationFstBias = -1.0;\r\n Photon_Ptr->NumBackwardsSpecularReflections = 0;\r\n\r\n Photon_Ptr->LikelihoodRatioIncreaseFstBias = 0;\r\n\r\n Photon_Ptr->LikelihoodRatioIncreaseFstBias = 0;\r\n\r\n Photon_Ptr->NextTetrahedron = -1;\r\n\r\n Photon_Ptr->tetrahedron = TetrahedronRoot;\r\n }\r\n}\r\n\r\n/***********************************************************\r\n *\tChoose (sample) a new theta angle for photon propagation\r\n *\taccording to the anisotropy.\r\n *\r\n *\tIf anisotropy g is 0, then\r\n *\t\tcos(theta) = 2*rand-1.\r\n *\totherwise\r\n *\t\tsample according to the Henyey-Greenstein function.\r\n *\r\n *\tReturns the cosine of the polar deflection angle theta.\r\n ****/\r\ndouble SpinTheta(double g) {\r\n double cost;\r\n\r\n if (g == 0.0)\r\n cost = 2.0 * RandomNum() - 1.0;\r\n else {\r\n double temp = (1.0 - g * g) / (1.0 - g + 2.0 * g * RandomNum());\r\n cost = (1.0 + g * g - temp * temp) / (2.0 * g);\r\n if (cost < -1.0) cost = -1.0;\r\n else if (cost > 1.0) cost = 1.0;\r\n }\r\n return (cost);\r\n}\r\n\r\ndouble SpinThetaForwardFstBias(double g) {\r\n double cost;\r\n\r\n if (g == 0.0)\r\n cost = RandomNum();\r\n else {\r\n double RandomNumTmp = RandomNum();\r\n double temp = RandomNumTmp / (1 - g) + (1 - RandomNumTmp) / sqrt(g * g + 1);\r\n cost = (g * g + 1 - 1. / (temp * temp)) / (2 * g);\r\n if (cost < -1) cost = -1;\r\n else if (cost > 1) cost = 1;\r\n }\r\n return (cost);\r\n}\r\n\r\n/***********************************************************\r\n *\tChoose a new direction for photon propagation by \r\n *\tsampling the polar deflection angle theta and the \r\n *\tazimuthal angle psi.\r\n *\r\n *\tNote:\r\n * \ttheta: 0 - pi so sin(theta) is always positive \r\n * \tfeel free to use sqrt() for cos(theta).\r\n * \r\n * \tpsi: 0 - 2pi \r\n * \tfor 0-pi sin(psi) is + \r\n * \tfor pi-2pi sin(psi) is - \r\n ****/\r\n\r\nvoid Spin(double g,\r\n TetrahedronPhotonStruct *Photon_Ptr) {\r\n double cost, sint; /* cosine and sine of the */\r\n /* polar deflection angle theta. */\r\n double cosp, sinp; /* cosine and sine of the */\r\n /* azimuthal angle psi. */\r\n double ux = Photon_Ptr->ux;\r\n double uy = Photon_Ptr->uy;\r\n double uz = Photon_Ptr->uz;\r\n double psi;\r\n\r\n cost = SpinTheta(g);\r\n sint = sqrt(1.0 - cost * cost);\r\n /* sqrt() is faster than sin(). */\r\n\r\n psi = 2.0 * PI * RandomNum(); /* spin psi 0-2pi. */\r\n cosp = cos(psi);\r\n if (psi < PI)\r\n sinp = sqrt(1.0 - cosp * cosp);\r\n /* sqrt() is faster than sin(). */\r\n else\r\n sinp = -sqrt(1.0 - cosp * cosp);\r\n\r\n if (fabs(uz) > COSZERO) { /* normal incident. */\r\n Photon_Ptr->ux = sint * cosp;\r\n Photon_Ptr->uy = sint * sinp;\r\n Photon_Ptr->uz = cost * SIGN(uz);\r\n /* SIGN() is faster than division. */\r\n } else {\r\n /* regular incident. */\r\n double temp = sqrt(1.0 - uz * uz);\r\n Photon_Ptr->ux = sint * (ux * uz * cosp - uy * sinp)\r\n / temp + ux * cost;\r\n Photon_Ptr->uy = sint * (uy * uz * cosp + ux * sinp)\r\n / temp + uy * cost;\r\n Photon_Ptr->uz = -sint * cosp * temp + uz * cost;\r\n }\r\n\r\n}\r\n\r\nvoid SpinBias37(double g,\r\n TetrahedronPhotonStruct *Photon_Ptr,\r\n TetrahedronPhotonStruct *PhotonCont_Ptr,\r\n SimulationStruct *In_Ptr)\r\n{\r\n double g_squared = sq(g);\r\n\r\n double cost, sint; /* cosine and sine of the */\r\n /* polar deflection angle theta. */\r\n double cosp, sinp; /* cosine and sine of the */\r\n /* azimuthal angle psi. */\r\n double ux = Photon_Ptr->ux;\r\n double uy = Photon_Ptr->uy;\r\n double uz = Photon_Ptr->uz;\r\n double ux_Orig = ux;\r\n double uy_Orig = uy;\r\n double uz_Orig = uz;\r\n double psi;\r\n\r\n\r\n double BackwardBiasCoefficient = In_Ptr->BackwardBiasCoefficient;\r\n double costg;\r\n double costg1, costg2;\r\n\r\n double BiasCoefficientTmp = 0;\r\n\r\n short int ReachedTargetOpticalDepthFlag = 0;\r\n short int ThisIsFirstBackwardBiasFlag = 0;\r\n\r\n if (Photon_Ptr->z > In_Ptr->TargetDepthMin\r\n && Photon_Ptr->z < In_Ptr->TargetDepthMax\r\n && Photon_Ptr->uz > 0\r\n && !Photon_Ptr->FstBackReflectionFlag) {\r\n // The bias backwards will be applied only if the photon is going forward\r\n // The status of the photon prior to the bias will be saved\r\n\r\n CopyPhotonStruct(Photon_Ptr, PhotonCont_Ptr);\r\n ReachedTargetOpticalDepthFlag = 1;\r\n Photon_Ptr->FstBackReflectionFlag = 1; // Bias backwards only once\r\n Photon_Ptr->LocationFstBias = Photon_Ptr->z;\r\n BiasCoefficientTmp = BackwardBiasCoefficient;\r\n ThisIsFirstBackwardBiasFlag = 1;\r\n }\r\n\r\n /**********************************\r\n\t ** Biased Direction towards probe\r\n\t **********************************/\r\n double vx = In_Ptr->probe_x-Photon_Ptr->x;\r\n double vy = In_Ptr->probe_y-Photon_Ptr->y;\r\n double vz = In_Ptr->probe_z-Photon_Ptr->z;\r\n double LengthVector = sqrt(sq(vx) + sq(vy) + sq(vz));\r\n vx /= LengthVector;\r\n vy /= LengthVector;\r\n vz /= LengthVector;\r\n /*********************************/\r\n\r\n if ((Photon_Ptr->FstBackReflectionFlag\r\n || Photon_Ptr->NumBackwardsSpecularReflections > 0)\r\n && !ReachedTargetOpticalDepthFlag)\r\n {\r\n // It was biased at least once before, and is moving backwards\r\n ReachedTargetOpticalDepthFlag = 2;\r\n\r\n double NextStepSize = -log(In_Ptr->rndStepSizeInTissue) / regionspecs[Photon_Ptr->tetrahedron->region].muas;\r\n double CurrentDistanceToOrigin = sqrt(sq(Photon_Ptr->x-In_Ptr->probe_x) + sq(Photon_Ptr->y-In_Ptr->probe_y) + sq(Photon_Ptr->z-In_Ptr->probe_z));\r\n\r\n if (NextStepSize >= CurrentDistanceToOrigin\r\n && acos(-vz) <= In_Ptr->MaxCollectingAngleDeg * PI / 180) {\r\n ReachedTargetOpticalDepthFlag = 1;\r\n }\r\n\r\n BiasCoefficientTmp = BackwardBiasCoefficient;\r\n\r\n }\r\n\r\n int BiasFunctionRandomlySelected = 0;\r\n if (ReachedTargetOpticalDepthFlag) {\r\n // Photon reached target optical layer or may undergo an additional biased\r\n // scattering or unbiased scattering\r\n\r\n // BiasFunctionRandomlySelected=1 means use biased scattering and 2 means unbiased scattering\r\n if (RandomNum() <= In_Ptr->ProbabilityAdditionalBias)\r\n BiasFunctionRandomlySelected = 1;\r\n else\r\n BiasFunctionRandomlySelected = 2;\r\n\r\n if (ReachedTargetOpticalDepthFlag == 1\r\n || BiasFunctionRandomlySelected == 1) {\r\n /*************************************************************************\r\n\t\t\t** The photon is within the target depth and going forward\r\n\t\t\t** The additional biased scattering is randomly chosen\r\n\t\t\t** So the scattering is biased Henyey-Greenstein scattering\r\n\t\t\t*************************************************************************/\r\n cost = SpinThetaForwardFstBias(BiasCoefficientTmp);\r\n ux = vx;\r\n uy = vy;\r\n uz = vz;\r\n } else {\r\n /**************************************************************************************\r\n\t\t\t** The photon is within the target depth but the scattering is randomly selected is\r\n\t\t\t** unbiased scattering\r\n\t\t\t** or the photon is already going backward or it is out of target depth\r\n\t\t\t**************************************************************************************/\r\n cost = SpinTheta(g);\r\n }\r\n } else {\r\n /**************************************************************************\r\n\t\t** The photon is not within the target depth or it is not going forward\r\n\t\t** so do unbiased scattering\r\n\t\t**************************************************************************/\r\n cost = SpinTheta(g);\r\n }\r\n\r\n if (cost < -1)\r\n cost = -1;\r\n else if (cost > 1)\r\n cost = 1;\r\n\r\n sint = sqrt(1.0 - cost * cost);\r\n /* sqrt() is faster than sin(). */\r\n\r\n psi = 2.0 * PI * RandomNum(); /* spin psi 0-2pi. */\r\n cosp = cos(psi);\r\n if (psi < PI)\r\n sinp = sqrt(1.0 - cosp * cosp);\r\n /* sqrt() is faster than sin(). */\r\n else\r\n sinp = -sqrt(1.0 - cosp * cosp);\r\n\r\n if (fabs(uz) > COSZERO) { /* normal incident. */\r\n Photon_Ptr->ux = sint * cosp;\r\n Photon_Ptr->uy = sint * sinp;\r\n Photon_Ptr->uz = cost * SIGN(uz);\r\n /* SIGN() is faster than division. */\r\n } else { /* regular incident. */\r\n double temp = sqrt(1.0 - uz * uz);\r\n Photon_Ptr->ux = sint * (ux * uz * cosp - uy * sinp)\r\n / temp + ux * cost;\r\n Photon_Ptr->uy = sint * (uy * uz * cosp + ux * sinp)\r\n / temp + uy * cost;\r\n Photon_Ptr->uz = -sint * cosp * temp + uz * cost;\r\n }\r\n\r\n\r\n costg = ux_Orig * Photon_Ptr->ux\r\n + uy_Orig * Photon_Ptr->uy\r\n + uz_Orig * Photon_Ptr->uz;\r\n costg2 = costg;\r\n costg1 = vx * Photon_Ptr->ux\r\n + vy * Photon_Ptr->uy\r\n + vz * Photon_Ptr->uz;\r\n\r\n if (BiasCoefficientTmp) {\r\n double one_plus_a_squared = 1 + sq(BiasCoefficientTmp);\r\n double sqrt_one_plus_a_squared = sqrt(one_plus_a_squared);\r\n double LikelihoodRatioIncreaseFactor;\r\n if (ReachedTargetOpticalDepthFlag == 1)\r\n /****************************************************************************************\r\n\t\t\t ** Likelihood for the first Bias scattering. Equation (8) of the paper:\r\n\t\t\t ** Malektaji, Siavash, Ivan T. Lima, and Sherif S. Sherif. \"Monte Carlo simulation of\r\n\t\t\t ** optical coherence tomography for turbid media with arbitrary spatial distributions.\"\r\n\t\t\t ** Journal of biomedical optics 19.4 (2014): 046001-046001.\r\n\t\t\t ****************************************************************************************/\r\n LikelihoodRatioIncreaseFactor = ((1.0 - g_squared) * (sqrt_one_plus_a_squared - 1.0 + BiasCoefficientTmp) *\r\n sqrt(cube(one_plus_a_squared - 2.0 * BiasCoefficientTmp * cost))) /\r\n (2.0 * BiasCoefficientTmp * (1.0 - BiasCoefficientTmp) *\r\n sqrt_one_plus_a_squared * sqrt(cube(1.0 + g_squared - 2.0 * g * costg)));\r\n else {\r\n double cost1, cost2;\r\n if (BiasFunctionRandomlySelected == 1) {\r\n cost1 = cost;\r\n cost2 = costg2;\r\n } else {\r\n cost1 = costg1;\r\n cost2 = cost;\r\n }\r\n /*******************************************************************************************************\r\n\t\t\t ** The likelihood ratio of additional biased scatterings, whether the biased or the unbiased\r\n\t\t\t ** probability density function is randomly selected, is calculated according to the equation (9)\r\n\t\t\t ** of the paper:\r\n\t\t\t ** Malektaji, Siavash, Ivan T. Lima, and Sherif S. Sherif. \"Monte Carlo simulation of\r\n\t\t\t ** optical coherence tomography for turbid media with arbitrary spatial distributions.\"\r\n\t\t\t ** Journal of biomedical optics 19.4 (2014): 046001-046001.\r\n\t\t\t *******************************************************************************************************/\r\n double pdf1 = (sqrt_one_plus_a_squared * BiasCoefficientTmp * (1.0 - BiasCoefficientTmp)) /\r\n ((sqrt_one_plus_a_squared - 1.0 + BiasCoefficientTmp) *\r\n sqrt(cube(one_plus_a_squared - 2.0 * BiasCoefficientTmp * cost1)));\r\n\r\n double pdf2 = (1.0 - g_squared) / (2.0 * cube(sqrt(1.0 + g_squared - 2.0 * g * cost2)));\r\n\r\n LikelihoodRatioIncreaseFactor = pdf2 /\r\n (In_Ptr->ProbabilityAdditionalBias * pdf1 +\r\n (1.0 - In_Ptr->ProbabilityAdditionalBias) * pdf2);\r\n\r\n }\r\n\r\n Photon_Ptr->LikelihoodRatio *= LikelihoodRatioIncreaseFactor;\r\n if (ThisIsFirstBackwardBiasFlag == 1) {\r\n // In case there was a sure backward bias and that was the very first one\r\n Photon_Ptr->LikelihoodRatioAfterFstBias = Photon_Ptr->LikelihoodRatio;\r\n Photon_Ptr->LikelihoodRatioIncreaseFstBias = LikelihoodRatioIncreaseFactor;\r\n }\r\n }\r\n}\r\n\r\n/***********************************************************\r\n *\tMove the photon s away in the current layer of medium. \r\n ****/\r\nvoid Hop(TetrahedronPhotonStruct *Photon_Ptr) {\r\n double s = Photon_Ptr->s;\r\n Photon_Ptr->x += s * Photon_Ptr->ux;\r\n Photon_Ptr->y += s * Photon_Ptr->uy;\r\n Photon_Ptr->z += s * Photon_Ptr->uz;\r\n\r\n Photon_Ptr->OpticalPath += s;\r\n if (Photon_Ptr->MaxDepth < Photon_Ptr->z)\r\n Photon_Ptr->MaxDepth = Photon_Ptr->z;\r\n}\r\n/***********************************************************\r\n *\tIf uz != 0, return the photon step size in glass, \r\n *\tOtherwise, return 0.\r\n *\r\n *\tThe step size is the distance between the current \r\n *\tposition and the boundary in the photon direction.\r\n *\r\n *\tMake sure uz !=0 before calling this function.\r\n ****/\r\n\r\n/***********************************************************\r\n *\tPick a step size for a photon packet when it is in \r\n *\ttissue.\r\n *\tIf the member sleft is zero, make a new step size \r\n *\twith: -log(rnd)/(mua+mus).\r\n *\tOtherwise, pick up the leftover in sleft.\r\n *\r\n *\tLayer is the index to layer.\r\n *\tIn_Ptr is the input parameters.\r\n ****/\r\nvoid StepSizeInTissue(TetrahedronPhotonStruct *Photon_Ptr) {\r\n\r\n if (Photon_Ptr->sleft == 0.0) { /* make a new step. */\r\n double rnd;\r\n\r\n do rnd = RandomNum();\r\n while (rnd <= 0.0); /* avoid zero. */\r\n\r\n Photon_Ptr->s = -log(rnd) * regionspecs[Photon_Ptr->tetrahedron->region].rmuas;\r\n } else { /* take the leftover. */\r\n Photon_Ptr->s = Photon_Ptr->sleft * regionspecs[Photon_Ptr->tetrahedron->region].rmuas;\r\n Photon_Ptr->sleft = 0.0;\r\n }\r\n}\r\n\r\n/***********************************************************\r\n *\tCheck if the step will hit the boundary.\r\n *\tReturn 1 if hit boundary.\r\n *\tReturn 0 otherwise.\r\n *\r\n * \tIf the projected step hits the boundary, the members\r\n *\ts and sleft of Photon_Ptr are updated.\r\n ****/\r\nBoolean HitBoundary(TetrahedronPhotonStruct *Photon_Ptr) {\r\n TetrahedronStruct *tetrahedron;\r\n tetrahedron = Photon_Ptr->tetrahedron;\r\n\r\n double min_distance = 1e10;\r\n int index_of_tetrahedron_with_min_distance = -1;\r\n\r\n double cos_normals_and_photon_direction[4];\r\n double distance_from_face_in_photon_direction;\r\n double perpendicular_distance;\r\n\r\n for (int i = 0; i < 4; i++) {\r\n cos_normals_and_photon_direction[i] = (Photon_Ptr->tetrahedron->Faces[i].Nx) * Photon_Ptr->ux +\r\n (Photon_Ptr->tetrahedron->Faces[i].Ny) * Photon_Ptr->uy +\r\n (Photon_Ptr->tetrahedron->Faces[i].Nz) * Photon_Ptr->uz;\r\n }\r\n\r\n for (int i = 0; i < 4; i++) {\r\n if (cos_normals_and_photon_direction[i] < 0) {\r\n perpendicular_distance = ((Photon_Ptr->tetrahedron->Faces[i].Nx) * Photon_Ptr->x +\r\n (Photon_Ptr->tetrahedron->Faces[i].Ny) * Photon_Ptr->y +\r\n (Photon_Ptr->tetrahedron->Faces[i].Nz) * Photon_Ptr->z + Photon_Ptr->tetrahedron->Faces[i].d);\r\n distance_from_face_in_photon_direction = -perpendicular_distance / cos_normals_and_photon_direction[i];\r\n\r\n if (distance_from_face_in_photon_direction < min_distance) {\r\n min_distance = distance_from_face_in_photon_direction;\r\n index_of_tetrahedron_with_min_distance = i;\r\n Photon_Ptr->MinCos = cos_normals_and_photon_direction[i];\r\n }\r\n }\r\n }\r\n\r\n Boolean hit_boundary;\r\n if (Photon_Ptr->s > min_distance) {\r\n /* not horizontal & crossing. */\r\n\r\n Photon_Ptr->sleft = (Photon_Ptr->s - min_distance) * regionspecs[tetrahedron->region].muas;\r\n Photon_Ptr->s = min_distance;\r\n hit_boundary = 1;\r\n Photon_Ptr->NextTetrahedron = index_of_tetrahedron_with_min_distance;\r\n\r\n } else {\r\n\r\n hit_boundary = 0;\r\n Photon_Ptr->NextTetrahedron = -1;\r\n\r\n }\r\n return hit_boundary;\r\n}\r\n\r\n/***********************************************************\r\n *\tDrop photon weight inside the tissue (not glass).\r\n *\r\n * The photon is assumed not dead. \r\n *\r\n *\tThe weight drop is dw = w*mua/(mua+mus).\r\n *\r\n *\tThe dropped weight is assigned to the absorption array \r\n *\telements.\r\n ****/\r\nvoid Drop(TetrahedronPhotonStruct *Photon_Ptr) {\r\n double dwa; /* absorbed weight.*/\r\n TetrahedronStruct *tetrahedron = Photon_Ptr->tetrahedron;\r\n\r\n dwa = Photon_Ptr->w * regionspecs[tetrahedron->region].mua_muas;\r\n Photon_Ptr->w -= dwa;\r\n}\r\n\r\n/***********************************************************\r\n *\tThe photon weight is small, and the photon packet tries \r\n *\tto survive a roulette.\r\n ****/\r\nvoid Roulette(TetrahedronPhotonStruct *Photon_Ptr) {\r\n if (Photon_Ptr->w == 0.0)\r\n Photon_Ptr->dead = 1;\r\n else if (RandomNum() < CHANCE) /* survived the roulette.*/\r\n Photon_Ptr->w /= CHANCE;\r\n else\r\n Photon_Ptr->dead = 1;\r\n}\r\n\r\n/***********************************************************\r\n *\tCompute the Fresnel reflectance.\r\n *\r\n *\tMake sure that the cosine of the incident angle a1\r\n *\tis positive, and the case when the angle is greater \r\n *\tthan the critical angle is ruled out.\r\n *\r\n * \tAvoid trigonometric function operations as much as\r\n *\tpossible, because they are computation-intensive.\r\n ****/\r\ndouble\r\nRFresnel(SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, double *ux_reflected, double *uy_reflected,\r\n double *uz_reflected, double *ux_refracted, double *uy_refracted, double *uz_refracted) {\r\n\r\n double r;\r\n\r\n double cosa, sina, sinb, cosb;\r\n\r\n cosa = -(Photon_Ptr->MinCos);\r\n\r\n double ni = regionspecs[Photon_Ptr->tetrahedron->region].n;\r\n double nt;\r\n if (Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron] == NULL)\r\n nt = regionspecs[0].n;\r\n else {\r\n\r\n int next_region = Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron]->region;\r\n nt = regionspecs[next_region].n;\r\n }\r\n\r\n sina = sqrt(1.0 - cosa * cosa);\r\n sinb = ni * sina / nt;\r\n cosb = sqrt(1.0 - sinb * sinb);\r\n\r\n if (cosa > G_COS_0_D) {\r\n r = (ni - nt)\r\n / (ni + nt);\r\n r *= r;\r\n cosb = 1;\r\n } else if (cosa < G_COS_90_D) {\r\n r = 1.0;\r\n } else {\r\n sina = sqrt(1 - cosa * cosa);\r\n sinb = ni * sina / nt;\r\n if (sinb >= 1) {\r\n r = 1.0;\r\n } else {\r\n cosb = sqrt(1.0 - sinb * sinb);\r\n double cosacosb = cosa * cosb;\r\n double sinasinb = sina * sinb;\r\n double sinacosb = sina * cosb;\r\n double cosasinb = cosa * sinb;\r\n double cap = cosacosb - sinasinb;\r\n double cam = cosacosb + sinasinb;\r\n double sap = sinacosb + cosasinb;\r\n double sam = sinacosb - cosasinb;\r\n r = 0.5 * sam * sam * (cam * cam + cap * cap) / (sap * sap * cam * cam);\r\n }\r\n }\r\n\r\n double sbdivsa = ni / nt;\r\n *ux_refracted = -cosb * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nx +\r\n sbdivsa * (cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nx + Photon_Ptr->ux);\r\n *uy_refracted = -cosb * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Ny +\r\n sbdivsa * (cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Ny + Photon_Ptr->uy);\r\n *uz_refracted = -cosb * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nz +\r\n sbdivsa * (cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nz + Photon_Ptr->uz);\r\n\r\n *ux_reflected = 2 * cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nx + Photon_Ptr->ux;\r\n *uy_reflected = 2 * cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Ny + Photon_Ptr->uy;\r\n *uz_reflected = 2 * cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nz + Photon_Ptr->uz;\r\n\r\n return r;\r\n\r\n}\r\n\r\n/***********************************************************\r\n *\tRecord the photon weight exiting the first layer(uz<0), \r\n *\tno matter whether the layer is glass or not, to the \r\n *\treflection array.\r\n *\r\n *\tUpdate the photon weight as well.\r\n ***********************************************************/\r\nvoid RecordValidationR(double Refl, SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, OutStruct *Out_Ptr) {\r\n double x = Photon_Ptr->x;\r\n double y = Photon_Ptr->y;\r\n\r\n short SpatialFilterFlag = 0;\r\n if (sqrt(sq(x-In_Ptr->probe_x) + sq(y-In_Ptr->probe_y)) <\r\n In_Ptr->MaxCollectingRadius /* The position of photon should be within the radius of the probe */\r\n && acos(-Photon_Ptr->uz) < In_Ptr->MaxCollectingAngleDeg * PI / 180) {\r\n if ((In_Ptr->TypeBias == 0 || In_Ptr->TypeBias == 3))\r\n SpatialFilterFlag = 1;\r\n\r\n if ((Photon_Ptr->FstBackReflectionFlag && In_Ptr->TypeBias == 37 ||\r\n Photon_Ptr->LocationFstBias == Photon_Ptr->MaxDepth\r\n && In_Ptr->TypeBias != 37 ||\r\n Photon_Ptr->NumBackwardsSpecularReflections > 0))\r\n SpatialFilterFlag = 1;\r\n }\r\n\r\n if (SpatialFilterFlag) {\r\n\r\n In_Ptr->NumFilteredPhotons++;\r\n double FilterOpticalPath = Photon_Ptr->OpticalPath;\r\n double FilterOpticalDepth = FilterOpticalPath / 2.0;\r\n\r\n unsigned int VectorPosition = (unsigned int) (\r\n (FilterOpticalPath / 2.0 - In_Ptr->OpticalDepthShift)\r\n / (In_Ptr->CoherenceLengthSource / NUM_SUBSTEPS_RESOLUTION));\r\n\r\n int ii;\r\n for (ii = VectorPosition - NUM_SUBSTEPS_RESOLUTION / 2;\r\n ii < VectorPosition + NUM_SUBSTEPS_RESOLUTION / 2;\r\n ii++) {\r\n if (ii >= 0 && ii < In_Ptr->NumOpticalDepthLengthSteps) {\r\n short FilterClassI_Flag =\r\n Photon_Ptr->MaxDepth > (FilterOpticalDepth\r\n - In_Ptr->CoherenceLengthSource / 2.0);\r\n\r\n double tmpPhotonContribution = Photon_Ptr->w * (1.0 - Refl) * Photon_Ptr->LikelihoodRatio;\r\n if (FilterClassI_Flag) {\r\n if (ii == VectorPosition)\r\n In_Ptr->NumFilteredPhotonsClassI++;\r\n Out_Ptr->ReflectanceClassI_Sum[ii] += tmpPhotonContribution;\r\n if (Out_Ptr->ReflectanceClassI_Max[ii] < tmpPhotonContribution)\r\n Out_Ptr->ReflectanceClassI_Max[ii] = tmpPhotonContribution;\r\n Out_Ptr->ReflectanceClassI_SumSq[ii] += sq(tmpPhotonContribution);\r\n Out_Ptr->NumClassI_PhotonsFilteredInRange[ii]++;\r\n\r\n } else {\r\n if (ii == VectorPosition)\r\n In_Ptr->NumFilteredPhotonsClassII++;\r\n if (Out_Ptr->ReflectanceClassII_Max[ii] < tmpPhotonContribution)\r\n Out_Ptr->ReflectanceClassII_Max[ii] = tmpPhotonContribution;\r\n Out_Ptr->ReflectanceClassII_Sum[ii] += tmpPhotonContribution;\r\n Out_Ptr->ReflectanceClassII_SumSq[ii] += sq(tmpPhotonContribution);\r\n Out_Ptr->NumClassII_PhotonsFilteredInRange[ii]++;\r\n\r\n }\r\n }\r\n }\r\n }\r\n\r\n Photon_Ptr->w *= Refl;\r\n\r\n}\r\n\r\n/***********************************************************\r\n *\tDecide whether the photon will be transmitted or be \r\n *\treflected on the bottom boundary (uz>0) of the current \r\n *\tlayer.\r\n *\r\n *\tIf the photon is transmitted, move the photon to \r\n *\t\"layer+1\". If \"layer\" is the last layer, record the \r\n *\ttransmitted weight as transmittance. See comments for \r\n *\tCrossUpOrNot.\r\n *\r\n *\tUpdate the photon parmameters.\r\n ****/\r\nvoid CrossOrNot(SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, OutStruct *Out_Ptr) {\r\n\r\n double uz_reflected = 0, ux_reflected = 0, uy_reflected = 0; /* cosines of transmission alpha. */\r\n double uz_refracted = 0, ux_refracted = 0, uy_refracted = 0;\r\n\r\n double r = 0.0; /* reflectance */\r\n\r\n r = RFresnel(In_Ptr, Photon_Ptr, &ux_reflected, &uy_reflected, &uz_reflected, &ux_refracted, &uy_refracted,\r\n &uz_refracted);\r\n\r\n#if PARTIALREFLECTION\r\n if (Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron] == NULL && r < 1.0) { /* We use actual photon splitting if the photon is exiting the media\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ** We store the part the is exiting and the rest will be traced */\r\n Photon_Ptr->ux = ux_refracted;\r\n Photon_Ptr->uy = uy_refracted;\r\n Photon_Ptr->uz = uz_refracted;\r\n\r\n if (Photon_Ptr->uz < 0)\r\n RecordValidationR(r, In_Ptr, Photon_Ptr, Out_Ptr);\r\n else {\r\n Photon_Ptr->NumBackwardsSpecularReflections++;\r\n Photon_Ptr->w *= r;\r\n }\r\n Photon_Ptr->ux = ux_reflected;\r\n Photon_Ptr->uy = uy_reflected;\r\n Photon_Ptr->uz = uz_reflected;\r\n\r\n }\r\n /* If photon is not exiting the medium we use the statistical splitting */\r\n else if (RandomNum() > r) {/* transmitted */\r\n\r\n Photon_Ptr->tetrahedron = Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron];\r\n\r\n Photon_Ptr->ux = ux_refracted;\r\n Photon_Ptr->uy = uy_refracted;\r\n Photon_Ptr->uz = uz_refracted;\r\n\r\n Photon_Ptr->NextTetrahedron = -1;\r\n\r\n } else /* reflected. */\r\n {\r\n Photon_Ptr->NextTetrahedron = -1;\r\n\r\n if (Photon_Ptr->uz > 0)\r\n Photon_Ptr->NumBackwardsSpecularReflections++;\r\n\r\n Photon_Ptr->ux = ux_reflected;\r\n Photon_Ptr->uy = uy_reflected;\r\n Photon_Ptr->uz = uz_reflected;\r\n\r\n }\r\n#else\t/* use just statistical splitting */\r\n if(RandomNum() > r) {\t\t/* transmitted. */\r\n \r\n if(Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron]==NULL) {\r\n \r\n \r\n\r\n Photon_Ptr->ux = ux_refracted;\r\n Photon_Ptr->uy = uy_refracted;\r\n Photon_Ptr->uz = uz_refracted;\r\n\r\n if (Photon_Ptr->uz<0)\r\n RecordValidationR(0.0, In_Ptr, Photon_Ptr, Out_Ptr);\r\n\r\n Photon_Ptr->dead = 1;\r\n }\r\n else {\r\n\r\n /* Siavash Refraction Direction Cosines */\r\n Photon_Ptr->ux = ux_refracted;\r\n Photon_Ptr->uy = uy_refracted;\r\n Photon_Ptr->uz = uz_refracted;\r\n Photon_Ptr->tetrahedron=Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron];\r\n Photon_Ptr->NextTetrahedron=-1;\r\n }\r\n }\r\n else {\r\n /* reflected. */\r\n\r\n Photon_Ptr->ux = ux_reflected;\r\n Photon_Ptr->uy = uy_reflected;\r\n Photon_Ptr->uz = uz_reflected;\r\n Photon_Ptr->NextTetrahedron=-1;\r\n }\r\n#endif\r\n\r\n}\r\n\r\n/***********************************************************\r\n ****/\r\n/***********************************************************\r\n *\tMove the photon packet in glass layer.\r\n *\tHorizontal photons are killed because they will\r\n *\tnever interact with tissue again.\r\n ****/\r\n/***********************************************************\r\n *\tSet a step size, move the photon, drop some weight, \r\n *\tchoose a new photon direction for propagation. \r\n *\r\n *\tWhen a step size is long enough for the photon to \r\n *\thit an interface, this step is divided into two steps. \r\n *\tFirst, move the photon to the boundary free of \r\n *\tabsorption or scattering, then decide whether the \r\n *\tphoton is reflected or transmitted.\r\n *\tThen move the photon in the current or transmission \r\n *\tmedium with the unfinished stepsize to interaction \r\n *\tsite. If the unfinished stepsize is still too long, \r\n *\trepeat the above process. \r\n ****/\r\nvoid HopDropSpinInTissue(SimulationStruct *In_Ptr,\r\n TetrahedronPhotonStruct *Photon_Ptr,\r\n TetrahedronPhotonStruct *PhotonCont_Ptr,\r\n OutStruct *Out_Ptr) {\r\n StepSizeInTissue(Photon_Ptr);\r\n if (HitBoundary(Photon_Ptr)) {\r\n Hop(Photon_Ptr); /* move to boundary plane. */\r\n CrossOrNot(In_Ptr, Photon_Ptr, Out_Ptr);\r\n } else {\r\n Hop(Photon_Ptr);\r\n Drop(Photon_Ptr);\r\n\r\n switch (In_Ptr->TypeBias) {\r\n case 0: /* No importance sampling */\r\n Spin(regionspecs[Photon_Ptr->tetrahedron->region].g, Photon_Ptr);\r\n break;\r\n case 37: /* BOE2 Biasing by Lima et al. */\r\n SpinBias37(regionspecs[Photon_Ptr->tetrahedron->region].g, Photon_Ptr, PhotonCont_Ptr, In_Ptr);\r\n }\r\n }\r\n}\r\n\r\nvoid HopDropSpin(SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, TetrahedronPhotonStruct *PhotonCont_Ptr,\r\n OutStruct *Out_Ptr) {\r\n HopDropSpinInTissue(In_Ptr, Photon_Ptr, PhotonCont_Ptr, Out_Ptr);\r\n\r\n if (Photon_Ptr->w < WEIGHT && !Photon_Ptr->dead)\r\n Roulette(Photon_Ptr);\r\n\r\n}\r\n\r\nvoid CopyPhotonStruct(TetrahedronPhotonStruct *OrigPhoton_Ptr, TetrahedronPhotonStruct *DestPhoton_Ptr) {\r\n\r\n DestPhoton_Ptr->x = OrigPhoton_Ptr->x;\r\n DestPhoton_Ptr->y = OrigPhoton_Ptr->y;\r\n DestPhoton_Ptr->z = OrigPhoton_Ptr->z; /* Cartesian coordinates.[cm] */\r\n DestPhoton_Ptr->ux = OrigPhoton_Ptr->ux;\r\n DestPhoton_Ptr->uy = OrigPhoton_Ptr->uy;\r\n DestPhoton_Ptr->uz = OrigPhoton_Ptr->uz;/* directional cosines of a photon. */\r\n DestPhoton_Ptr->w = OrigPhoton_Ptr->w; /* weight. */\r\n DestPhoton_Ptr->dead = OrigPhoton_Ptr->dead; /* 1 if photon is terminated. */\r\n\r\n DestPhoton_Ptr->MinCos = OrigPhoton_Ptr->MinCos;\r\n DestPhoton_Ptr->tetrahedron = OrigPhoton_Ptr->tetrahedron;\r\n DestPhoton_Ptr->NextTetrahedron = OrigPhoton_Ptr->NextTetrahedron;\r\n\r\n DestPhoton_Ptr->s = OrigPhoton_Ptr->s; /* current step size. [cm]. */\r\n DestPhoton_Ptr->sleft = OrigPhoton_Ptr->sleft; /* step size left. dimensionless [-]. */\r\n\r\n DestPhoton_Ptr->OpticalPath = OrigPhoton_Ptr->OpticalPath;\r\n DestPhoton_Ptr->MaxDepth = OrigPhoton_Ptr->MaxDepth;\r\n DestPhoton_Ptr->LikelihoodRatio = OrigPhoton_Ptr->LikelihoodRatio;\r\n DestPhoton_Ptr->FstBackReflectionFlag = OrigPhoton_Ptr->FstBackReflectionFlag;\r\n DestPhoton_Ptr->LocationFstBias = OrigPhoton_Ptr->LocationFstBias;\r\n DestPhoton_Ptr->NumBackwardsSpecularReflections = OrigPhoton_Ptr->NumBackwardsSpecularReflections;\r\n\r\n}\r\n", "meta": {"hexsha": "5202e3715777766f9ca9e8432cf40a8ddef1d371", "size": 34734, "ext": "c", "lang": "C", "max_stars_repo_path": "src/tmcoct_go.c", "max_stars_repo_name": "JunyaoPu/git_OCT", "max_stars_repo_head_hexsha": "d3d9c05218f88d8428d7eea5e81f85340e9e2919", "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": "src/tmcoct_go.c", "max_issues_repo_name": "JunyaoPu/git_OCT", "max_issues_repo_head_hexsha": "d3d9c05218f88d8428d7eea5e81f85340e9e2919", "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": "src/tmcoct_go.c", "max_forks_repo_name": "JunyaoPu/git_OCT", "max_forks_repo_head_hexsha": "d3d9c05218f88d8428d7eea5e81f85340e9e2919", "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": 38.0438116101, "max_line_length": 169, "alphanum_fraction": 0.5645764957, "num_tokens": 8729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.1995380783911481}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bvh.h\"\n#include \n#include \n\nnamespace Geometrics\n{\n\ttemplate \n\tstruct Triangle\n\t{\n\t\tstatic constexpr size_t VertexCount = 3;\n\t\ttypedef std::array container_type;\n\t\tcontainer_type v;\n\n\t\ttypedef IndexType value_type;\n\t\ttypedef size_t size_type;\n\t\ttypedef ptrdiff_t difference_type;\n\t\ttypedef IndexType *pointer;\n\t\ttypedef const IndexType *const_pointer;\n\t\ttypedef IndexType& reference;\n\t\ttypedef const IndexType& const_reference;\n\n\t\ttypedef typename container_type::iterator iterator;\n\t\ttypedef typename container_type::const_iterator const_iterator;\n\n\t\ttypedef typename container_type::reverse_iterator reverse_iterator;\n\t\ttypedef typename container_type::const_reverse_iterator const_reverse_iterator;\n\n\t\tTriangle() {}\n\t\tTriangle(const IndexType &v0, const IndexType &v1, const IndexType &v2)\n\t\t{\n\t\t\tv[0] = v0; v[1] = v1; v[2] = v2;\n\t\t}\n\t\tTriangle(const IndexType *v_)\n\t\t{\n\t\t\tv[0] = v_[0]; v[1] = v_[1]; v[2] = v_[2];\n\t\t}\n\t\ttemplate explicit Triangle(const S &x)\n\t\t{\n\t\t\tv[0] = x[0]; v[1] = x[1]; v[2] = x[2];\n\t\t}\n\t\tIndexType &operator[] (int i) { return v[i]; }\n\t\tconst IndexType &operator[] (int i) const { return v[i]; }\n\t\toperator const IndexType * () const { return &(v[0]); }\n\t\toperator IndexType * () { return &(v[0]); }\n\n\t\tvoid rewind() {\n\t\t\tstd::swap(v[0], v[2]);\n\t\t}\n\n\t\tint indexof(IndexType v_) const\n\t\t{\n\t\t\treturn (v[0] == v_) ? 0 :\n\t\t\t\t(v[1] == v_) ? 1 :\n\t\t\t\t(v[2] == v_) ? 2 : -1;\n\t\t}\n\n\t\t// contrainer access\n\t\tauto begin() { return v.begin(); }\n\t\tauto end() { return v.end(); }\n\t\tauto begin() const { return v.begin(); }\n\t\tauto end() const { return v.end(); }\n\n\t\tauto rbegin() { return v.rbegin(); }\n\t\tauto rend() { return v.rend(); }\n\t\tauto rbegin() const { return v.rbegin(); }\n\t\tauto rend() const { return v.rend(); }\n\n\t\tsize_t size() const { return VertexCount; }\n\t};\n\n\tstruct submesh_data\n\t{\n\t\tuint32_t vertex_offset; // start vertices index of this geometry\n\t\tuint32_t vertex_count;\n\t\tuint32_t index_offset; // start index position of this geometry\n\t\tuint32_t index_count;\n\t};\n\n\n\t// generate per vertex normal for given triangle mesh\n\ttemplate \n\tbool generate_normal(gsl::span vertices, gsl::span> facets)\n\t{\n\t\tusing namespace DirectX::VertexTraits;\n\t\tusing namespace DirectX;\n\n\t\tif (!has_normal::value)\n\t\t\treturn false;\n\n\t\t//static_assert(has_normal::value, \"The vertex type dose not contains normal field\");\n\n\t\tstd::vector normals(vertices.size());\n\n\t\t// set zero\n\t\tstd::memset(normals.data(), 0, normals.size() * sizeof(XMVECTOR));\n\n\t\tXMVECTOR v0, v1, v2, n;\n\t\tfor (const auto& face : facets)\n\t\t{\n\t\t\tv0 = get_position(vertices[face[0]]);\n\t\t\tv1 = get_position(vertices[face[1]]);\n\t\t\tv2 = get_position(vertices[face[2]]);\n\t\t\tv1 -= v0;\n\t\t\tv2 -= v0;\n\n\t\t\tv1 = XMVector3Normalize(v1);\n\t\t\tv2 = XMVector3Normalize(v2);\n\t\t\tn = XMVector3Cross(v1, v2); // weighted normal \n\n\t\t\tnormals[face[0]] += n;\n\t\t\tnormals[face[1]] += n;\n\t\t\tnormals[face[2]] += n;\n\t\t}\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\n\t\t{\n\t\t\tn = XMVector3Normalize(normals[i]);\n\t\t\tset_normal(vertices[i], n);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t// generate per vertex tangent for given triangle mesh\n\ttemplate \n\tbool generate_tangent(gsl::span vertices, gsl::span> facets)\n\t{\n\t\tusing namespace DirectX::VertexTraits;\n\t\tusing namespace DirectX;\n\n\t\tif (!has_tangent::value)\n\t\t\treturn false;\n\t\t//static_assert(has_tangent::value, \"The vertex type dose not contains tangent field\");\n\n\t\tstd::vector tan1(vertices.size() * 2);\n\t\tXMVECTOR* tan2 = &tan1[vertices.size()];\n\t\tstd::memset(tan1.data(), 0, tan1.size() * sizeof(XMVECTOR));\n\n\t\tfor (const auto& face : facets)\n\t\t{\n\t\t\t{\n\t\t\t\tXMVECTOR v0, v1, v2, w0, w1, w2;\n\t\t\t\tv0 = get_position(vertices[face[0]]);\n\t\t\t\tw0 = get_uv(vertices[face[0]]);\n\n\t\t\t\tv1 = get_position(vertices[face[1]]);\n\t\t\t\tw1 = get_uv(vertices[face[1]]);\n\n\t\t\t\tv2 = get_position(vertices[face[2]]);\n\t\t\t\tw2 = get_uv(vertices[face[2]]);\n\t\t\t}\n\t\t\tXMFLOAT4A v_1, v_2, w_1, w_2;\n\n\t\t\tXMStoreA(v_1, v1 - v0);\n\t\t\tXMStoreA(v_2, v2 - v0);\n\t\t\tXMStoreA(w_1, w1 - w0);\n\t\t\tXMStoreA(w_2, w2 - w0);\n\n\t\t\tfloat x1 = v_1.x; float x2 = v_2.x;\n\t\t\tfloat y1 = v_1.y; float y2 = v_2.y;\n\t\t\tfloat z1 = v_1.z; float z2 = v_2.z;\n\n\t\t\tfloat s1 = w_1.x; float s2 = w_2.x;\n\t\t\tfloat t1 = w_1.y; float t2 = w_2.y;\n\n\t\t\tfloat r = 1.0F / (s1 * t2 - s2 * t1);\n\t\t\tXMVECTOR sdir = XMVectorSet(\n\t\t\t\t(t2 * x1 - t1 * x2) * r,\n\t\t\t\t(t2 * y1 - t1 * y2) * r,\n\t\t\t\t(t2 * z1 - t1 * z2) * r, .0f);\n\t\t\tXMVECTOR tdir = XMVectorSet(\n\t\t\t\t(s1 * x2 - s2 * x1) * r,\n\t\t\t\t(s1 * y2 - s2 * y1) * r,\n\t\t\t\t(s1 * z2 - s2 * z1) * r, .0f);\n\n\t\t\ttan1[face[0]] += sdir;\n\t\t\ttan1[face[1]] += sdir;\n\t\t\ttan1[face[2]] += sdir;\n\n\t\t\ttan2[face[0]] += tdir;\n\t\t\ttan2[face[1]] += tdir;\n\t\t\ttan2[face[2]] += tdir;\n\t\t}\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\n\t\t{\n\t\t\tXMVECTOR n = get_normal(vertices[i], n);\n\t\t\tXMVECTOR t = tan1[i];\n\n\t\t\t// Gram-Schmidt orthogonalize\n\t\t\tXMVECTOR nt = XMVector3Normalize(t - n * XMVector3Dot(n, t));\n\n\t\t\tXMVECTOR w = XMVectorLess(XMVector3Dot(XMVector3Cross(n, t), tan2[i]), XMVectorZero());\n\t\t\tw = XMVectorSelect(g_XMNegativeOne.v, g_XMOne.v, w);\n\n\t\t\tnt = _DXMEXT XMVectorSelect<0, 0, 0, 1>(nt, w);\n\t\t\tset_tangent(vertices[i], nt);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tnamespace Detail\n\t{\n\t\tXM_HAS_MEMBER(vertices, has_vertices);\n\t\tXM_HAS_MEMBER(indices, has_indices);\n\t}\n\n\ttemplate \n\tstruct concept_mesh_type : public std::integral_constant::value && Detail::has_indices::value> {};\n\n\ttemplate \n\tclass SubMesh : public submesh_data\n\t{\n\tpublic:\n\t\ttypedef _MeshType MeshType; // Parent MeshTypw\n\t\ttypedef typename MeshType::VertexType\tVertexType;\n\t\ttypedef typename MeshType::IndexType\tIndexType;\n\t\ttypedef typename MeshType::FaceType\t\tFaceType;\n\n\t\tstatic constexpr size_t PolygonVertex = FaceType::VertexCount;\n\n\n\t\tSubMesh(MeshType& mesh, const submesh_data& metric)\n\t\t\t: parent(mesh), submesh_data(metric)\n\t\t{\n\t\t\tvertices = gsl::span(&mesh.vertices[metric.vertex_offset], metric.vertex_count);\n\t\t\tindices = gsl::span(&mesh.indices[metric.index_offset], metric.index_count);\n\t\t}\n\n\t\tMeshType&\t\t\t\t\t\tparent;\n\t\tgsl::span\t\t\tvertices;\n\t\tgsl::span\t\t\tindices;\n\n\t\tgsl::span>\tfacets()\n\t\t{\n\t\t\treturn gsl::span(\n\t\t\t\treinterpret_cast(indices.data()),\n\t\t\t\tindices.size() / FaceType::VertexCount);\n\t\t}\n\n\t\tbool empty() const {\n\t\t\treturn vertices.empty() || indices.empty();\n\t\t}\n\n\t};\n\n\ttemplate >\n\tclass PolygonSoup\n\t{\n\tpublic:\n\t\ttypedef _VertexType VertexType;\n\t\ttypedef _IndexType\tIndexType;\n\t\ttypedef _FaceType\tFaceType;\n\n\t\tstatic constexpr size_t PolygonVertex = FaceType::VertexCount;\n\n\t\tPolygonSoup() {}\n\n\t\tbool empty() const {\n\t\t\treturn vertices.empty() || indices.empty();\n\t\t}\n\n\t\tvoid clear()\n\t\t{\n\t\t\tvertices.clear();\n\t\t\tindices.clear();\n\t\t}\n\n\t\tinline const FaceType& facet(int idx) const\n\t\t{\n\t\t\treturn reinterpret_cast(indices[idx * FaceType::VertexCount]);\n\t\t}\n\n\t\tinline FaceType& facet(int idx)\n\t\t{\n\t\t\treturn reinterpret_cast(indices[idx * FaceType::VertexCount]);\n\t\t}\n\n\t\tvoid add_facet(const FaceType& new_facet)\n\t\t{\n\t\t\tindices.insert(indices.end(), new_facet.begin(), new_facet.end());\n\t\t}\n\n\t\ttemplate \n\t\tstd::enable_if_t add_facet(_TIndecies... _indices)\n\t\t{\n\t\t\tindices.insert(indices.end(), { static_cast(_indices)... });\n\t\t}\n\n\n\t\tgsl::span facets() {\n\t\t\treturn gsl::span(\n\t\t\t\treinterpret_cast(indices.data()),\n\t\t\t\tindices.size() / FaceType::VertexCount);\n\t\t}\n\n\t\tgsl::span facets() const {\n\t\t\treturn gsl::span(\n\t\t\t\treinterpret_cast(indices.data()),\n\t\t\t\tindices.size() / FaceType::VertexCount);\n\t\t}\n\n\t\tconst VertexType& vertex(int facet, int vidx) const\n\t\t{\n\t\t\treturn this->vertices[this->indices[facet * FaceType::VertexCount + vidx]];\n\t\t}\n\n\t\tVertexType& vertex(int facet, int vidx)\n\t\t{\n\t\t\treturn this->vertices[this->indices[facet * FaceType::VertexCount + vidx]];\n\t\t}\n\n\t\t// flip all the polygons' winding and vertices' normal \n\t\tvoid flip()\n\t\t{\n\t\t\tusing namespace DirectX::VertexTraits;\n\n\t\t\tif (has_normal::value)\n\t\t\t{\n\t\t\t\tfor (auto& v : vertices)\n\t\t\t\t\tset_normal(v, -get_normal(v));\n\t\t\t}\n\n\t\t\tstatic constexpr int vc = FaceType::VertexCount;\n\t\t\tfor (int i = 0; i < indices.size() / vc; i++)\n\t\t\t\tstd::reverse(indices.begin() + i * vc, indices.begin() + (i + 1)* vc);\n\t\t}\n\n\t\tvoid generate_normal()\n\t\t{\n\t\t\tstatic_assert(PolygonVertex == 3, \"This mesh is not trigle mesh, please trianglize it first\");\n\t\t\tgenerate_normal(this->vertices, this->facets());\n\t\t}\n\n\t\tvoid generate_tangent()\n\t\t{\n\t\t\tstatic_assert(PolygonVertex == 3, \"This mesh is not trigle mesh, please trianglize it first\");\n\t\t\tgenerate_tangent(this->vertices, this->facets());\n\t\t}\n\n\t\t// applies an uniform transform to all vertices in the mesh \n\t\tvoid XM_CALLCONV transform(DirectX::FXMMATRIX M)\n\t\t{\n\t\t\tusing namespace DirectX::VertexTraits;\n\t\t\tfor (auto& v : vertices)\n\t\t\t{\n\t\t\t\tXMVECTOR p = get_position(v);\n\t\t\t\tp = _DXMEXT XMVector3TransformCoord(p, M);\n\t\t\t\tset_position(v, p);\n\n\t\t\t\tif (has_normal::value)\n\t\t\t\t{\n\t\t\t\t\tp = get_normal(v);\n\t\t\t\t\tp = _DXMEXT XMVector3TransformNormal(p, M);\n\t\t\t\t\tset_normal(v, p);\n\n\t\t\t\t\tif (has_tangent::value)\n\t\t\t\t\t{\n\t\t\t\t\t\tp = get_tangent(v);\n\t\t\t\t\t\tp = _DXMEXT XMVector3TransformNormal(p, M);\n\t\t\t\t\t\tset_tangent(v, p);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::vector> vertices;\n\t\tstd::vector\tindices;\n\t};\n\n\ttemplate \n\tint XM_CALLCONV intersect(const PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>> &Mesh, DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, std::vector* distances = nullptr)\n\t{\n\t\tusing namespace DirectX;\n\t\tusing namespace DirectX::VertexTraits;\n\t\tint count = 0;\n\t\tXMVECTOR vDir = XMVector3Normalize(Direction);\n\t\tfor (const auto& tri : Mesh.facets())\n\t\t{\n\t\t\tfloat distance;\n\n\t\t\tXMVECTOR v0 = get_position(&Mesh.vertices[tri[0]]);\n\t\t\tXMVECTOR v1 = get_position(&Mesh.vertices[tri[1]]);\n\t\t\tXMVECTOR v2 = get_position(&Mesh.vertices[tri[2]]);\n\n\t\t\tbool hr = DirectX::TriangleTests::Intersects(Origin, vDir, v0, v1, v2, distance);\n\t\t\tif (hr) {\n\t\t\t\t++count;\n\t\t\t\tif (distances) {\n\t\t\t\t\tdistances->push_back(distances);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}\n\n\ttemplate \n\tstruct MeshRayIntersectedVertex : public _TVertex\n\t{\n\t\tusing Vector3 = DirectX::Vector3;\n\n\t\tfloat\tdistance;\n\t\tVector3 barycentric;\n\t\tint\t\tfacet; // facet id\n\n\t\tinline bool operator < (const MeshRayIntersectedVertex& rhs)\n\t\t{\n\t\t\treturn this->distance < rhs.distance;\n\t\t}\n\n\t\tinline bool is_valiad() const {return facet >= 0; }\n\t\tinline operator bool() const { return is_valiad(); }\n\t};\n\n\ttemplate \n\tstruct PolygonContainmentInfo\n\t{\n\t\tstatic constexpr size_t Dim = _Dim;\n\t\tDirectX::ContainmentType containment; // overall polygon containment type\n\t\tDirectX::ContainmentType vertex_containments[Dim];\n\t\toperator DirectX::ContainmentType() const { return containment; }\n\t};\n\n\tstruct XM_ALIGNATTR aabb_t {\n\t\t::hlsl::xmvector3f min;\n\t\t::hlsl::xmvector3f max;\n\t\tmutable int\t intersected;\n\n\t\ttemplate \n\t\tstatic bool less(const aabb_t& lhs, const aabb_t & rhs)\n\t\t{\n\t\t\tusing namespace hlsl;\n\t\t\treturn hlsl::less(lhs.min, rhs.min).get();\n\t\t}\n\n\t\taabb_t operator+(const aabb_t& rhs) const\n\t\t{\n\t\t\tconst aabb_t& lhs = *this;\n\t\t\tusing namespace ::hlsl;\n\t\t\taabb_t ret{ ::hlsl::min(lhs.min,rhs.min),::hlsl::max(lhs.max,rhs.max) };\n\t\t\treturn ret;\n\t\t}\n\n\t\t// Convert min-max representation of this box to center-extent representation\n\t\tDirectX::BoundingBox get_dxbox() const\n\t\t{\n\t\t\tconst float epsilon = 1e-3;\n\t\t\tusing namespace ::hlsl;\n\t\t\tauto& aabb = *this;\n\t\t\tDirectX::BoundingBox box;\n\t\t\txmvector3f extent = (aabb.max - aabb.min) * 0.5f;\n\t\t\textent = ::hlsl::max(extent, xmfloat(epsilon));\n\t\t\tbox.Center << (aabb.max + aabb.min) * 0.5f;\n\t\t\tbox.Extents << extent;\n\t\t\treturn box;\n\t\t}\n\n\t\toperator DirectX::BoundingBox() const { return get_dxbox(); }\n\t};\n\n\t// A struct stores fixed size polygon (position only)\n\ttemplate \n\tstruct PlainPolygon {\n\t\thlsl::xmvector3f v[_Size];\n\t};\n\n\t/// \n\t/// Basic triangle mesh, each index represent an edge, which is the edge oppsite to the vertex in it's owner triangle\n\t/// \n\ttemplate \n\tclass TriangleMesh : public PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>>\n\t{\n\tpublic:\n\t\tstatic const size_t VertexCount = FaceType::VertexCount;\n\t\tusing triangle_handle = IndexType;\n\t\tusing PlainTriangle = PlainPolygon<3>;\n\t\tusing ContainmentType = DirectX::ContainmentType;\n\t\tusing BaseType = PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>>;\n\t\tusing BaseType::PolygonVertex;\n\t\tusing typename BaseType::VertexType;\n\t\tusing typename BaseType::IndexType;\n\t\tusing IntersectionVertex = MeshRayIntersectedVertex<_VertexType>;\n\n\tpublic:\n\t\t// edge's reverse edge\n\t\t// stores the adjacent edges of a edge in a triangle\n\t\tstd::vector\trevedges;\n\t\tDirectX::BoundingBox\taabb;\n\t\tDirectX::BoundingOrientedBox obb;\n\n\t\tPlainTriangle XM_CALLCONV get_triangle_position(IndexType fid) const\n\t\t{\n\t\t\tusing namespace DirectX::VertexTraits;\n\t\t\tusing namespace hlsl;\n\t\t\tauto f = this->indices.begin() + fid * 3;\n\t\t\tPlainTriangle tri = {\n\t\t\txmvector3f(get_position(this->vertices[f[0]]))\n\t\t\t,xmvector3f(get_position(this->vertices[f[1]]))\n\t\t\t,xmvector3f(get_position(this->vertices[f[2]])) };\n\t\t\treturn tri;\n\t\t}\n\n#define _EXPANDTRI(tri) tri.v[0].v, tri.v[1].v, tri.v[2].v\n\n\t\taabb_t XM_CALLCONV get_triangle_aabb(triangle_handle t) const\n\t\t{\n\t\t\tusing namespace hlsl;\n\t\t\tPlainTriangle tri = get_triangle_position(t);\n\t\t\txmvector3f vmax = hlsl::max(tri.v[0], tri.v[1]);\n\t\t\tvmax = hlsl::max(vmax, tri.v[2]);\n\t\t\txmvector3f vmin = hlsl::min(tri.v[0], tri.v[1]);\n\t\t\tvmin = hlsl::min(vmin, tri.v[2]);\n\t\t\taabb_t ret;\n\t\t\tret.min = vmin;\n\t\t\tret.max = vmax;\n\t\t\tret.intersected = true;\n\t\t\treturn ret;\n\t\t}\n\n\t\tusing triangle_bvh_t = kd_bvh;\n\t\ttriangle_bvh_t\t\t\t\ttriangle_bvh;\n\n\t\tusing vertex_bvh_t = kd_bvh<::hlsl::xmvector3f, float, 3, aabb_t>;\n\t\tvertex_bvh_t\t\t\t\tvertex_bvh;\n\t\t// An Lookup table to find the 'Ienditification' of a vertex\n\t\t// Make sense when multiple vertex shares the same spatial location but have different index\n\t\tstd::vector\t\tvertex_id;\n\n\t\tTriangleMesh() : triangle_bvh([this](const triangle_handle& t) {\n\t\t\treturn this->get_triangle_aabb(t);\n\t\t}) {}\n\n\t\t// vertex's first adjacant edge\n\t\t// std::vector vedges;\n\n\t\tunion EdgeType\n\t\t{\n\t\t\t_IndexType v[2];\n\t\t\tstruct {\n\t\t\t\t_IndexType v0, v1;\n\t\t\t};\n\t\t};\n\n\t\tinline EdgeType edge(int facet, int edge) const\n\t\t{\n\t\t\tEdgeType e;\n\t\t\tauto& tri = this->facet(facet);\n\t\t\tswitch (edge)\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\te.v0 = tri[1];\n\t\t\t\te.v1 = tri[2];\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\te.v0 = tri[2];\n\t\t\t\te.v1 = tri[0];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\te.v0 = tri[0];\n\t\t\t\te.v1 = tri[1];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\te.v0 = -1;\n\t\t\t\te.v1 = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t}\n\n\t\tinline EdgeType edge(int eid) const\n\t\t{\n\t\t\treturn edge(eid / VertexCount, eid % VertexCount);\n\t\t}\n\n\t\tinline int adjacentFacet(int facet, int edge) const\n\t\t{\n\t\t\treturn revedges[facet * VertexCount + edge] / VertexCount;\n\t\t}\n\n\t\tinline int adjacentFacet(int eid) const\n\t\t{\n\t\t\treturn revedges[eid] / VertexCount;\n\t\t}\n\n\t\tvoid build_reverse_edges()\n\t\t{\n\t\t\t// intialize all adjacant edges to -1\n\t\t\trevedges.resize(this->indices.size(), -1);\n\t\t\t_IndexType vsize = this->vertices.size();\n\t\t\tint esize = this->indices.size();\n\t\t\tint fsize = this->indices.size() / VertexCount;\n\n\t\t\tusing hash_type = uint64_t;\n\t\t\t// make sure int for hash is enough\n\t\t\tassert(vsize*vsize < std::numeric_limits::max());\n\t\t\tstd::unordered_map edges(esize * 2);\n\t\t\t// max items inside this table should be less than (esize / 2)\n\n\t\t\tfor (_IndexType fid = 0; fid < fsize; fid++)\n\t\t\t{\n\t\t\t\tfor (_IndexType i = 0; i < VertexCount; i++)\n\t\t\t\t{\n\t\t\t\t\t_IndexType eid = i + fid * VertexCount;\n\t\t\t\t\tauto e = this->edge(fid, i);\n\t\t\t\t\te.v0 = vertex_id[e.v0];\n\t\t\t\t\te.v1 = vertex_id[e.v1];\n\n\t\t\t\t\thash_type ehash = e.v0 * vsize + e.v1;\n\t\t\t\t\thash_type revehash = e.v0 + e.v1 * vsize;\n\n\t\t\t\t\tauto revItr = edges.find(revehash);\n\t\t\t\t\tif (revItr == edges.end())\n\t\t\t\t\t\tedges[ehash] = eid;\n\t\t\t\t\telse // find reversed edge, remove from edges map\n\t\t\t\t\t{\n\t\t\t\t\t\tauto revEid = revItr->second;\n\t\t\t\t\t\trevedges[eid] = revEid;\n\t\t\t\t\t\trevedges[revEid] = eid;\n\t\t\t\t\t\tauto reve = this->edge(revEid);\n\t\t\t\t\t\treve.v0 = vertex_id[reve.v0];\n\t\t\t\t\t\treve.v1 = vertex_id[reve.v1];\n\t\t\t\t\t\tassert(reve.v0 == e.v1 && reve.v1 == e.v0);\n\t\t\t\t\t\tedges.erase(revItr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// build the adjacent map so we can access all the 1 rings\n\t\tvoid build()\n\t\t{\n\t\t\tint vsize = this->vertices.size();\n\t\t\tint esize = this->indices.size();\n\t\t\tint fsize = this->indices.size() / VertexCount;\n\n\t\t\t// rebuild the triangle-bvh\n\t\t\ttriangle_bvh.resize(fsize);\n\t\t\tstd::iota(triangle_bvh.begin(), triangle_bvh.end(), 0);\n\t\t\ttriangle_bvh.rebuild();\n\n\t\t\t// build the vertex-bvh\n\t\t\tconst aabb_t& bb = this->triangle_bvh.get_volumn(this->triangle_bvh.root());\n\t\t\t::hlsl::xmvector3f voxel_ext(1e-4f);\n\n\t\t\tvertex_bvh.set_volumn_getter([voxel_ext](const ::hlsl::xmvector3f v) {\n\t\t\t\treturn aabb_t{ v - voxel_ext , v + voxel_ext, 0 };\n\t\t\t});\n\t\t\tvertex_bvh.resize(vsize);\n\t\t\tfor (int i = 0; i < vsize; i++)\n\t\t\t\tvertex_bvh[i] = ::hlsl::xmvector3f(::DirectX::VertexTraits::get_position(this->vertices[i]));\n\t\t\tvertex_bvh.rebuild();\n\n\t\t\tvertex_id.resize(vsize);\n\t\t\tstd::iota(vertex_id.begin(), vertex_id.end(), 0);\n\t\t\tstd::unordered_map vids(vsize);\n\n\t\t\t// Use 20-bits to hash a float component, plus 1 bit signbit\n\t\t\t// Generate a total 63-bits\n\t\t\tauto hash_position = [](const ::hlsl::xmvector3f vp) -> uint64_t{\n\t\t\t\tauto vf = vp * 3e4f; // 30 * 3e4 = 9e5 < 1e6 = 2^20\n\t\t\t\tauto vi = vf.cast();\n\t\t\t\tuint32_t signbits32 = ::hlsl::detail::move_mask(vi);\n\t\t\t\tuint64_t signbits = signbits32;\n\t\t\t\tvi &= ::hlsl::xmuint((1ULL << 20ULL) - 1ULL);\n\t\t\t\tuint32_t vis32[3];\n\t\t\t\tvis32 << vi;\n\t\t\t\tuint64_t vis[3] = { vis32[0], vis32[1], vis32[2]};\n\t\t\t\tuint64_t vhash = ((signbits&7) << 60ULL) | (vis[0] << 40ULL) | (vis[1] << 20ULL) | (vis[2]);\n\t\t\t\treturn vhash;\n\t\t\t};\n\n\t\t\tfor (int i = 0; i < vsize; i++)\n\t\t\t{\n\t\t\t\tauto vp = *vertex_bvh.get_object(i);\n\t\t\t\tstd::pair p = { hash_position(vp), i };\n\t\t\t\tauto rib = vids.insert(p);\n\t\t\t\tIndexType vid = rib.first->second;\n\t\t\t\tif (!rib.second && vid != i)\n\t\t\t\t{\n\t\t\t\t\t// query-merge-set merge algorithm\n\t\t\t\t\tint root = vid;\n\t\t\t\t\t// find the ultimate parent (root)\n\t\t\t\t\twhile (vertex_id[root] != root) root = vertex_id[root];\n\n\t\t\t\t\twhile (vid != root)\n\t\t\t\t\t{\n\t\t\t\t\t\tint cvid = vid;\n\t\t\t\t\t\tvid = vertex_id[vid];\n\t\t\t\t\t\tvertex_id[cvid] = root;\n\t\t\t\t\t}\n\t\t\t\t\tvertex_id[i] = root;\n\t\t\t\t\t//if (vid != i)\n\t\t\t\t\t//\tstd::cout << \"Glued vertex pair (\" << i << ',' << vid << ')' << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuild_reverse_edges();\n\n\n\t\t\t//for (int fid = 0; fid < this->indices.size() / 3; ++fid)\n\t\t\t//{\n\t\t\t//\tauto tri = this->facet(fid);\n\t\t\t//\tusing namespace DirectX::VertexTraits;\n\t\t\t//\tDirectX::XMVECTOR v0 = get_position(this->vertices[tri[0]]);\n\t\t\t//\tDirectX::XMVECTOR v1 = get_position(this->vertices[tri[1]]);\n\t\t\t//\tDirectX::XMVECTOR v2 = get_position(this->vertices[tri[2]]);\n\t\t\t//\tauto&& vol = triangle_bvh.get_volumn(fid);\n\t\t\t//\tbool cond = true;\n\t\t\t//\tassert(DirectX::XMVector3LessOrEqual(v0, vol.max.v));\n\t\t\t//\tassert(DirectX::XMVector3LessOrEqual(v1, vol.max.v));\n\t\t\t//\tassert(DirectX::XMVector3LessOrEqual(v2, vol.max.v));\n\t\t\t//\tassert(DirectX::XMVector3LessOrEqual(vol.min.v, v0));\n\t\t\t//\tassert(DirectX::XMVector3LessOrEqual(vol.min.v, v1));\n\t\t\t//\tassert(DirectX::XMVector3LessOrEqual(vol.min.v, v2));\n\t\t\t//}\n\t\t}\n\n\t\t// generate a persoude vertex from the interpolation of the trianlge\n\t\tVertexType persudo_vertex(int fid, DirectX::FXMVECTOR baycentric) const\n\t\t{\n\t\t\tconst auto& tri = this->facet(fid);\n\n\t\t\tconst VertexType& v0 = this->vertices[tri[0]];\n\t\t\tconst VertexType& v1 = this->vertices[tri[1]];\n\t\t\tconst VertexType& v2 = this->vertices[tri[2]];\n\n\t\t\tusing namespace DirectX::VertexTraits;\n\t\t\treturn interpolate_vertex(baycentric, v0, v1, v2);\n\t\t}\n\n\t\tprotected:\n\t\t\tIntersectionVertex XM_CALLCONV get_ray_intersected_vertex(DirectX::FXMVECTOR vOri, DirectX::FXMVECTOR vDir, IndexType fid) const\n\t\t\t{\n\t\t\t\tusing DirectX::XMVECTOR;\n\t\t\t\tIntersectionVertex info;\n\t\t\t\tfloat distance = .0f;\n\t\t\t\tinfo.facet = -1;\n\t\t\t\tPlainTriangle tri = this->get_triangle_position(fid);\n\t\t\t\tbool hr = DirectX::TriangleTests::Intersects(vOri, vDir, _EXPANDTRI(tri), distance);\n\t\t\t\tif (!hr) return info; // No intersection, return with info.facet == -1\n\t\t\t\t// Fill the persudo-vertex\n\t\t\t\tXMVECTOR pos = distance * vDir + vOri;\n\t\t\t\tXMVECTOR baryc = DirectX::TriangleTests::BarycentricCoordinate(pos, _EXPANDTRI(tri));\n\t\t\t\tinfo.barycentric = baryc;\n\t\t\t\tinfo.facet = fid;\n\t\t\t\tinfo.distance = distance;\n\t\t\t\t(VertexType&)info = this->persudo_vertex(fid, baryc);\n\t\t\t\treturn info;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tinline static void push_back_output_itr(nullptr_t itr, _Ty&& element)\n\t\t\t{\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tinline static std::enable_if_t::value> \n\t\t\t\tpush_back_output_itr(_OutItr& itr, _Ty&& element)\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_same,std::decay_t<_Ty>>::value,\"Output Iterator's Type is not expected\");\n\t\t\t\t*(itr++) = element;\n\t\t\t}\n\n\t\tpublic:\n\n\t\tIntersectionVertex XM_CALLCONV first_intersect(DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction) const\n\t\t{\n\t\t\tusing namespace DirectX;\n\t\t\tassert(this->triangle_bvh.valiad() && \"This triangle mesh is modified but not rebuild\");\n\n\t\t\tXMVECTOR vOri = Origin;\n\t\t\tXMVECTOR vDir = XMVector3Normalize(Direction);\n\t\t\tauto ray_aabb_inter = [vOri, vDir](const aabb_t& aabb) -> float\n\t\t\t{\n\t\t\t\tfloat f;\n\t\t\t\tauto box = aabb.get_dxbox();\n\t\t\t\tbool succ = box.Intersects(vOri, vDir, f);\n\t\t\t\taabb.intersected = succ;\n\t\t\t\treturn succ ? f : -1.0f;\n\t\t\t};\n\t\t\tauto ray_triangle_inter = [this, vOri, vDir](const int fid) -> float\n\t\t\t{\n\t\t\t\tPlainTriangle tri = this->get_triangle_position(fid);\n\t\t\t\tfloat f;\n\t\t\t\tbool succ = DirectX::TriangleTests::Intersects(vOri, vDir, _EXPANDTRI(tri), f);\n\t\t\t\treturn succ ? f : -1.0f;\n\t\t\t};\n\n\t\t\t//std::cout << counter << std::endl;\n\t\t\tauto pfid = find_first_of(this->triangle_bvh, ray_triangle_inter, ray_aabb_inter);\n\t\t\tIntersectionVertex info;\n\t\t\tinfo.facet = -1;\n\t\t\tif (pfid)\n\t\t\t\tinfo = get_ray_intersected_vertex(vOri, vDir, *pfid);\n\t\t\treturn info;\n\t\t}\n\n\t\t// Ray intersection test with advanced infomation\n\t\ttemplate \n\t\tint XM_CALLCONV all_intersections(DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, _TOutItr outItr) const\n\t\t{\n\t\t\tusing namespace DirectX;\n\t\t\tassert(this->triangle_bvh.valiad() && \"This triangle mesh is modified but not rebuild\");\n\n\t\t\tsize_t count = 0;\n\t\t\tXMVECTOR vOri = Origin;\n\t\t\tXMVECTOR vDir = XMVector3Normalize(Direction);\n\n\t\t\tstruct XM_ALIGNATTR ray_aabb_intersector {\n\t\t\t\tDirectX::XMVECTOR origin;\n\t\t\t\tDirectX::XMVECTOR direction;\n\t\t\t\tbool XM_CALLCONV operator ()(const aabb_t& aabb) const\n\t\t\t\t{\n\t\t\t\t\tfloat f;\n\t\t\t\t\tauto box = aabb.get_dxbox();\n\t\t\t\t\tbool succ = box.Intersects(origin, direction, f);\n\t\t\t\t\taabb.intersected = succ;\n\t\t\t\t\treturn succ;\n\t\t\t\t}\n\t\t\t} intersector{ vOri , vDir };\n\n\t\t\tfor (auto triangles = find_all_of(triangle_bvh, intersector);\n\t\t\t\ttriangles;\n\t\t\t\t++triangles)\n\t\t\t{\n\t\t\t\tint fid = *triangles;\n\t\t\t\tIntersectionVertex info = get_ray_intersected_vertex(vOri, vDir, fid);\n\t\t\t\tif (info.is_valiad()) {\n\t\t\t\t\t++count;\n\t\t\t\t\tpush_back_output_itr(outItr, std::move(info));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn count;\n\t\t}\n\n\t\ttemplate \n\t\tvoid find_adjacant_facets_of(IndexType facet_id, _TPred&& pred, _TContainer& result_map) const\n\t\t{\n\t\t\tauto containment = pred(facet_id);\n\t\t\tresult_map.insert(std::make_pair(facet_id, containment));\n\t\t\tif (!containment) return;\n\t\t\tfor (int e = 0; e < PolygonVertex; e++)\n\t\t\t{\n\t\t\t\tint eid = facet_id * PolygonVertex + e;\n\t\t\t\tauto rev_edge = this->revedges[eid];\n\t\t\t\tauto adj_face = rev_edge / PolygonVertex;\n\t\t\t\t// if not visited yet\n\t\t\t\tif (rev_edge != -1 && result_map.find(adj_face) == result_map.end())\n\t\t\t\t\tthis->find_adjacant_facets_of(adj_face, pred, result_map);\n\t\t\t}\n\t\t}\n\n\n\t};\n\n\tnamespace Internal\n\t{\n#ifndef min\n\t\ttemplate \n\t\tinline T clamp(T value, T minV, T maxV)\n\t\t{\n\t\t\treturn std::max(std::min(value, maxV), minV);\n\t\t}\n#else\n\t\ttemplate \n\t\tinline T clamp(T value, T minV, T maxV)\n\t\t{\n\t\t\treturn max(min(value, maxV), minV);\n\t\t}\n#endif\n\t}\n\n\t/// \n\t/// Compute the closest projection point from P0 to triangle(V0,V1,V2).\n\t/// \n\t/// The p0.\n\t/// The v0.\n\t/// The v1.\n\t/// The v2.\n\t/// \n\tinline DirectX::XMVECTOR XM_CALLCONV Projection(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)\n\t{\n\t\tusing namespace DirectX;\n\t\tusing namespace Geometrics::Internal;\n\t\tXMVECTOR edge0 = V1 - V0;\n\t\tXMVECTOR edge1 = V2 - V0;\n\t\tXMVECTOR p0 = V0 - P0;\n\n\t\t//XMVectorBaryCentric();\n\n\t\tfloat a = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge0));\n\t\tfloat b = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, edge1));\n\t\tfloat c = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge1));\n\t\tfloat d = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, p0));\n\t\tfloat e = XMVectorGetX(_DXMEXT XMVector3Dot(edge1, p0));\n\n\t\tfloat det = a*c - b*b;\n\t\tfloat s = b*e - c*d;\n\t\tfloat t = b*d - a*e;\n\n\t\tif (s + t < det)\n\t\t{\n\t\t\tif (s < 0.f)\n\t\t\t{\n\t\t\t\tif (t < 0.f)\n\t\t\t\t{\n\t\t\t\t\tif (d < 0.f)\n\t\t\t\t\t{\n\t\t\t\t\t\ts = clamp(-d / a, 0.f, 1.f);\n\t\t\t\t\t\tt = 0.f;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ts = 0.f;\n\t\t\t\t\t\tt = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts = 0.f;\n\t\t\t\t\tt = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (t < 0.f)\n\t\t\t{\n\t\t\t\ts = clamp(-d / a, 0.f, 1.f);\n\t\t\t\tt = 0.f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat invDet = 1.f / det;\n\t\t\t\ts *= invDet;\n\t\t\t\tt *= invDet;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (s < 0.f)\n\t\t\t{\n\t\t\t\tfloat tmp0 = b + d;\n\t\t\t\tfloat tmp1 = c + e;\n\t\t\t\tif (tmp1 > tmp0)\n\t\t\t\t{\n\t\t\t\t\tfloat numer = tmp1 - tmp0;\n\t\t\t\t\tfloat denom = a - 2 * b + c;\n\t\t\t\t\ts = clamp(numer / denom, 0.f, 1.f);\n\t\t\t\t\tt = 1 - s;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tt = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t\ts = 0.f;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (t < 0.f)\n\t\t\t{\n\t\t\t\tif (a + d > b + e)\n\t\t\t\t{\n\t\t\t\t\tfloat numer = c + e - b - d;\n\t\t\t\t\tfloat denom = a - 2 * b + c;\n\t\t\t\t\ts = clamp(numer / denom, 0.f, 1.f);\n\t\t\t\t\tt = 1 - s;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t\tt = 0.f;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat numer = c + e - b - d;\n\t\t\t\tfloat denom = a - 2 * b + c;\n\t\t\t\ts = clamp(numer / denom, 0.f, 1.f);\n\t\t\t\tt = 1.f - s;\n\t\t\t}\n\t\t}\n\n\t\treturn V0 + s * edge0 + t * edge1;\n\t}\n\n\tinline float XM_CALLCONV Distance(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)\n\t{\n\t\tusing namespace DirectX;\n\t\tXMVECTOR vProj = Projection(P0, V0, V1, V2);\n\t\tvProj -= P0;\n\t\treturn XMVectorGetX(_DXMEXT XMVector3Length(vProj));\n\t}\n\n\ttemplate \n\tinline float XM_CALLCONV Distance(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)\n\t{\n\t\tusing namespace DirectX;\n\t\tfloat minDis = numeric_limits::max();\n\t\tfor (const auto& tri : Mesh.facets())\n\t\t{\n\t\t\tfloat dis;\n\n\t\t\tXMVECTOR v0 = XMLoadFloat3(&Mesh.vertices[tri[0]].position);\n\t\t\tXMVECTOR v1 = XMLoadFloat3(&Mesh.vertices[tri[1]].position);\n\t\t\tXMVECTOR v2 = XMLoadFloat3(&Mesh.vertices[tri[2]].position);\n\n\t\t\tdis = Distance(Point, v0, v1, v2);\n\t\t\tif (dis < minDis) minDis = dis;\n\t\t\t//minDis = std::min(dis,minDis);\n\t\t}\n\n\t\t//XMVECTOR vDis = XMVectorReplicate(numeric_limits::max());\n\t\t//for (const auto& vertex : Mesh.vertices)\n\t\t//{\n\t\t//\tXMVECTOR vPos = XMLoadFloat3(&vertex.position);\n\t\t//\tvPos -= Point;\n\t\t//\tXMVECTOR dis = XMVector3Length(vPos);\n\t\t//\tvDis = XMVectorMin(vDis,dis);\n\t\t//}\n\n\t\t//float minDisV = XMVectorGetX(vDis);\n\t\t//assert(minDisV >= minDis);\n\t\treturn minDis;\n\t\t//return XMVectorGetX(minDis);\n\t}\n\n\n\ttemplate \n\tbool XM_CALLCONV Inside(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)\n\t{\n\t\tXMFLOAT3A Direction;\n\t\tDirection.x = (float)std::rand() / (RAND_MAX + 1);\n\t\tDirection.y = (float)std::rand() / (RAND_MAX + 1);\n\t\tDirection.z = (float)std::rand() / (RAND_MAX + 1);\n\t\tXMVECTOR vDir = XMLoadFloat3A(&Direction);\n\t\tauto count = intersect(Mesh, Point, vDir, nullptr);\n\t\treturn count & 1; //count % 2\n\t}\n\n\n\n}", "meta": {"hexsha": "d5444e3383ae3a2d48466c23320ad465ca048731", "size": 29182, "ext": "h", "lang": "C", "max_stars_repo_path": "Geometrics/TriangleMesh.h", "max_stars_repo_name": "ArcEarth/SrInspection", "max_stars_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "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": "Geometrics/TriangleMesh.h", "max_issues_repo_name": "ArcEarth/SrInspection", "max_issues_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "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": "Geometrics/TriangleMesh.h", "max_forks_repo_name": "ArcEarth/SrInspection", "max_forks_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9", "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": 27.8188751192, "max_line_length": 196, "alphanum_fraction": 0.6517373724, "num_tokens": 9244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}} {"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (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, Boston, MA 02111-1307 USA\n *\n */\n\n/* This file was automatically generated --- DO NOT EDIT */\n/* Generated on Sun Nov 7 20:43:56 EST 1999 */\n\n#include \n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -real2hc 13 */\n\n/*\n * This function contains 76 FP additions, 34 FP multiplications,\n * (or, 57 additions, 15 multiplications, 19 fused multiply/add),\n * 34 stack variables, and 26 memory accesses\n */\nstatic const fftw_real K083333333 = FFTW_KONST(+0.083333333333333333333333333333333333333333333);\nstatic const fftw_real K075902986 = FFTW_KONST(+0.075902986037193865983102897245103540356428373);\nstatic const fftw_real K251768516 = FFTW_KONST(+0.251768516431883313623436926934233488546674281);\nstatic const fftw_real K503537032 = FFTW_KONST(+0.503537032863766627246873853868466977093348562);\nstatic const fftw_real K113854479 = FFTW_KONST(+0.113854479055790798974654345867655310534642560);\nstatic const fftw_real K265966249 = FFTW_KONST(+0.265966249214837287587521063842185948798330267);\nstatic const fftw_real K387390585 = FFTW_KONST(+0.387390585467617292130675966426762851778775217);\nstatic const fftw_real K300462606 = FFTW_KONST(+0.300462606288665774426601772289207995520941381);\nstatic const fftw_real K258260390 = FFTW_KONST(+0.258260390311744861420450644284508567852516811);\nstatic const fftw_real K132983124 = FFTW_KONST(+0.132983124607418643793760531921092974399165133);\nstatic const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);\nstatic const fftw_real K1_732050807 = FFTW_KONST(+1.732050807568877293527446341505872366942805254);\nstatic const fftw_real K156891391 = FFTW_KONST(+0.156891391051584611046832726756003269660212636);\nstatic const fftw_real K256247671 = FFTW_KONST(+0.256247671582936600958684654061725059144125175);\nstatic const fftw_real K011599105 = FFTW_KONST(+0.011599105605768290721655456654083252189827041);\nstatic const fftw_real K300238635 = FFTW_KONST(+0.300238635966332641462884626667381504676006424);\nstatic const fftw_real K174138601 = FFTW_KONST(+0.174138601152135905005660794929264742616964676);\nstatic const fftw_real K575140729 = FFTW_KONST(+0.575140729474003121368385547455453388461001608);\nstatic const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627);\nstatic const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000);\n\n/*\n * Generator Id's : \n * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $\n * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $\n * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $\n */\n\nvoid fftw_real2hc_13(const fftw_real *input, fftw_real *real_output, fftw_real *imag_output, int istride, int real_ostride, int imag_ostride)\n{\n fftw_real tmp65;\n fftw_real tmp11;\n fftw_real tmp28;\n fftw_real tmp37;\n fftw_real tmp51;\n fftw_real tmp62;\n fftw_real tmp22;\n fftw_real tmp58;\n fftw_real tmp59;\n fftw_real tmp66;\n fftw_real tmp56;\n fftw_real tmp63;\n fftw_real tmp35;\n fftw_real tmp38;\n ASSERT_ALIGNED_DOUBLE;\n tmp65 = input[0];\n {\n\t fftw_real tmp3;\n\t fftw_real tmp53;\n\t fftw_real tmp21;\n\t fftw_real tmp30;\n\t fftw_real tmp26;\n\t fftw_real tmp16;\n\t fftw_real tmp29;\n\t fftw_real tmp25;\n\t fftw_real tmp6;\n\t fftw_real tmp32;\n\t fftw_real tmp9;\n\t fftw_real tmp33;\n\t fftw_real tmp10;\n\t fftw_real tmp54;\n\t fftw_real tmp1;\n\t fftw_real tmp2;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp1 = input[8 * istride];\n\t tmp2 = input[5 * istride];\n\t tmp3 = tmp1 - tmp2;\n\t tmp53 = tmp1 + tmp2;\n\t {\n\t fftw_real tmp17;\n\t fftw_real tmp18;\n\t fftw_real tmp19;\n\t fftw_real tmp20;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp17 = input[12 * istride];\n\t tmp18 = input[4 * istride];\n\t tmp19 = input[10 * istride];\n\t tmp20 = tmp18 + tmp19;\n\t tmp21 = tmp17 + tmp20;\n\t tmp30 = tmp17 - (K500000000 * tmp20);\n\t tmp26 = tmp18 - tmp19;\n\t }\n\t {\n\t fftw_real tmp12;\n\t fftw_real tmp13;\n\t fftw_real tmp14;\n\t fftw_real tmp15;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp12 = input[istride];\n\t tmp13 = input[3 * istride];\n\t tmp14 = input[9 * istride];\n\t tmp15 = tmp13 + tmp14;\n\t tmp16 = tmp12 + tmp15;\n\t tmp29 = tmp12 - (K500000000 * tmp15);\n\t tmp25 = tmp13 - tmp14;\n\t }\n\t {\n\t fftw_real tmp4;\n\t fftw_real tmp5;\n\t fftw_real tmp7;\n\t fftw_real tmp8;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp4 = input[6 * istride];\n\t tmp5 = input[11 * istride];\n\t tmp6 = tmp4 - tmp5;\n\t tmp32 = tmp4 + tmp5;\n\t tmp7 = input[2 * istride];\n\t tmp8 = input[7 * istride];\n\t tmp9 = tmp7 - tmp8;\n\t tmp33 = tmp7 + tmp8;\n\t }\n\t tmp10 = tmp6 + tmp9;\n\t tmp54 = tmp32 + tmp33;\n\t tmp11 = tmp3 - tmp10;\n\t {\n\t fftw_real tmp24;\n\t fftw_real tmp27;\n\t fftw_real tmp49;\n\t fftw_real tmp50;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp24 = tmp3 + (K500000000 * tmp10);\n\t tmp27 = K866025403 * (tmp25 + tmp26);\n\t tmp28 = tmp24 - tmp27;\n\t tmp37 = tmp27 + tmp24;\n\t tmp49 = tmp9 - tmp6;\n\t tmp50 = tmp25 - tmp26;\n\t tmp51 = tmp49 - tmp50;\n\t tmp62 = tmp50 + tmp49;\n\t }\n\t tmp22 = tmp16 - tmp21;\n\t tmp58 = tmp16 + tmp21;\n\t tmp59 = tmp53 + tmp54;\n\t tmp66 = tmp58 + tmp59;\n\t {\n\t fftw_real tmp52;\n\t fftw_real tmp55;\n\t fftw_real tmp31;\n\t fftw_real tmp34;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp52 = tmp29 + tmp30;\n\t tmp55 = tmp53 - (K500000000 * tmp54);\n\t tmp56 = tmp52 - tmp55;\n\t tmp63 = tmp52 + tmp55;\n\t tmp31 = tmp29 - tmp30;\n\t tmp34 = K866025403 * (tmp32 - tmp33);\n\t tmp35 = tmp31 + tmp34;\n\t tmp38 = tmp31 - tmp34;\n\t }\n }\n real_output[0] = tmp65 + tmp66;\n {\n\t fftw_real tmp23;\n\t fftw_real tmp45;\n\t fftw_real tmp40;\n\t fftw_real tmp48;\n\t fftw_real tmp44;\n\t fftw_real tmp46;\n\t fftw_real tmp41;\n\t fftw_real tmp47;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp23 = (K575140729 * tmp11) - (K174138601 * tmp22);\n\t tmp45 = (K575140729 * tmp22) + (K174138601 * tmp11);\n\t {\n\t fftw_real tmp36;\n\t fftw_real tmp39;\n\t fftw_real tmp42;\n\t fftw_real tmp43;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp36 = (K300238635 * tmp28) + (K011599105 * tmp35);\n\t tmp39 = (K256247671 * tmp37) + (K156891391 * tmp38);\n\t tmp40 = tmp36 - tmp39;\n\t tmp48 = K1_732050807 * (tmp39 + tmp36);\n\t tmp42 = (K300238635 * tmp35) - (K011599105 * tmp28);\n\t tmp43 = (K156891391 * tmp37) - (K256247671 * tmp38);\n\t tmp44 = K1_732050807 * (tmp42 - tmp43);\n\t tmp46 = tmp43 + tmp42;\n\t }\n\t imag_output[imag_ostride] = tmp23 + (K2_000000000 * tmp40);\n\t tmp41 = tmp23 - tmp40;\n\t imag_output[3 * imag_ostride] = tmp41 - tmp44;\n\t imag_output[4 * imag_ostride] = -(tmp41 + tmp44);\n\t imag_output[5 * imag_ostride] = -(tmp45 + (K2_000000000 * tmp46));\n\t tmp47 = tmp46 - tmp45;\n\t imag_output[2 * imag_ostride] = tmp47 - tmp48;\n\t imag_output[6 * imag_ostride] = tmp48 + tmp47;\n }\n {\n\t fftw_real tmp61;\n\t fftw_real tmp70;\n\t fftw_real tmp74;\n\t fftw_real tmp76;\n\t fftw_real tmp68;\n\t fftw_real tmp69;\n\t fftw_real tmp57;\n\t fftw_real tmp60;\n\t fftw_real tmp71;\n\t fftw_real tmp75;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp57 = (K132983124 * tmp51) + (K258260390 * tmp56);\n\t tmp60 = K300462606 * (tmp58 - tmp59);\n\t tmp61 = (K2_000000000 * tmp57) + tmp60;\n\t tmp70 = tmp60 - tmp57;\n\t {\n\t fftw_real tmp72;\n\t fftw_real tmp73;\n\t fftw_real tmp64;\n\t fftw_real tmp67;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp72 = (K387390585 * tmp51) - (K265966249 * tmp56);\n\t tmp73 = (K113854479 * tmp62) - (K503537032 * tmp63);\n\t tmp74 = tmp72 + tmp73;\n\t tmp76 = tmp73 - tmp72;\n\t tmp64 = (K251768516 * tmp62) + (K075902986 * tmp63);\n\t tmp67 = tmp65 - (K083333333 * tmp66);\n\t tmp68 = (K2_000000000 * tmp64) + tmp67;\n\t tmp69 = tmp67 - tmp64;\n\t }\n\t real_output[real_ostride] = tmp61 + tmp68;\n\t real_output[5 * real_ostride] = tmp68 - tmp61;\n\t tmp71 = tmp69 - tmp70;\n\t real_output[2 * real_ostride] = tmp71 - tmp74;\n\t real_output[6 * real_ostride] = tmp74 + tmp71;\n\t tmp75 = tmp70 + tmp69;\n\t real_output[3 * real_ostride] = tmp75 - tmp76;\n\t real_output[4 * real_ostride] = tmp76 + tmp75;\n }\n}\n\nfftw_codelet_desc fftw_real2hc_13_desc =\n{\n \"fftw_real2hc_13\",\n (void (*)()) fftw_real2hc_13,\n 13,\n FFTW_FORWARD,\n FFTW_REAL2HC,\n 288,\n 0,\n (const int *) 0,\n};\n", "meta": {"hexsha": "538e149c6167b5523eae4638563d7cffd2dc311d", "size": 9294, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_13.c", "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_13.c", "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "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": "original/lib/fftw-2.1.3/rfftw/frc_13.c", "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "avg_line_length": 34.1691176471, "max_line_length": 141, "alphanum_fraction": 0.6665590704, "num_tokens": 3053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.19474761639592367}} {"text": "/* Copyright (C) 2021 Atsushi Togo */\n/* All rights reserved. */\n\n/* This file is part of phonopy. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions */\n/* are met: */\n\n/* * Redistributions of source code must retain the above copyright */\n/* notice, this list of conditions and the following disclaimer. */\n\n/* * Redistributions in binary form must reproduce the above copyright */\n/* notice, this list of conditions and the following disclaimer in */\n/* the documentation and/or other materials provided with the */\n/* distribution. */\n\n/* * Neither the name of the phonopy project nor the names of its */\n/* contributors may be used to endorse or promote products derived */\n/* from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */\n/* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */\n/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */\n/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */\n/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */\n/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */\n/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */\n/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */\n/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */\n/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */\n/* POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef __phono3py_H__\n#define __phono3py_H__\n\n#ifdef MKL_LAPACKE\n#include \n#else\n#include \n#endif\n#include \"phonoc_array.h\"\n\nlong ph3py_get_interaction(Darray *fc3_normal_squared,\n const char *g_zero,\n const Darray *frequencies,\n const lapack_complex_double *eigenvectors,\n const long (*triplets)[3],\n const long num_triplets,\n const long (*bz_grid_addresses)[3],\n const long D_diag[3],\n const long Q[3][3],\n const double *fc3,\n const long is_compact_fc3,\n const double (*svecs)[3],\n const long multi_dims[2],\n const long (*multi)[2],\n const double *masses,\n const long *p2s_map,\n const long *s2p_map,\n const long *band_indices,\n const long symmetrize_fc3_q,\n const double cutoff_frequency);\nlong ph3py_get_pp_collision(double *imag_self_energy,\n const long relative_grid_address[24][4][3], /* thm */\n const double *frequencies,\n const lapack_complex_double *eigenvectors,\n const long (*triplets)[3],\n const long num_triplets,\n const long *triplet_weights,\n const long (*bz_grid_addresses)[3], /* thm */\n const long *bz_map, /* thm */\n const long bz_grid_type,\n const long D_diag[3],\n const long Q[3][3],\n const double *fc3,\n const long is_compact_fc3,\n const double (*svecs)[3],\n const long multi_dims[2],\n const long (*multi)[2],\n const double *masses,\n const long *p2s_map,\n const long *s2p_map,\n const Larray *band_indices,\n const Darray *temperatures,\n const long is_NU,\n const long symmetrize_fc3_q,\n const double cutoff_frequency);\nlong ph3py_get_pp_collision_with_sigma(\n double *imag_self_energy,\n const double sigma,\n const double sigma_cutoff,\n const double *frequencies,\n const lapack_complex_double *eigenvectors,\n const long (*triplets)[3],\n const long num_triplets,\n const long *triplet_weights,\n const long (*bz_grid_addresses)[3],\n const long D_diag[3],\n const long Q[3][3],\n const double *fc3,\n const long is_compact_fc3,\n const double (*svecs)[3],\n const long multi_dims[2],\n const long (*multi)[2],\n const double *masses,\n const long *p2s_map,\n const long *s2p_map,\n const Larray *band_indices,\n const Darray *temperatures,\n const long is_NU,\n const long symmetrize_fc3_q,\n const double cutoff_frequency);\nvoid ph3py_get_imag_self_energy_at_bands_with_g(\n double *imag_self_energy,\n const Darray *fc3_normal_squared,\n const double *frequencies,\n const long (*triplets)[3],\n const long *triplet_weights,\n const double *g,\n const char *g_zero,\n const double temperature,\n const double cutoff_frequency,\n const long num_frequency_points,\n const long frequency_point_index);\nvoid ph3py_get_detailed_imag_self_energy_at_bands_with_g(\n double *detailed_imag_self_energy,\n double *imag_self_energy_N,\n double *imag_self_energy_U,\n const Darray *fc3_normal_squared,\n const double *frequencies,\n const long (*triplets)[3],\n const long *triplet_weights,\n const long (*bz_grid_addresses)[3],\n const double *g,\n const char *g_zero,\n const double temperature,\n const double cutoff_frequency);\nvoid ph3py_get_real_self_energy_at_bands(double *real_self_energy,\n const Darray *fc3_normal_squared,\n const long *band_indices,\n const double *frequencies,\n const long (*triplets)[3],\n const long *triplet_weights,\n const double epsilon,\n const double temperature,\n const double unit_conversion_factor,\n const double cutoff_frequency);\nvoid ph3py_get_real_self_energy_at_frequency_point(\n double *real_self_energy,\n const double frequency_point,\n const Darray *fc3_normal_squared,\n const long *band_indices,\n const double *frequencies,\n const long (*triplets)[3],\n const long *triplet_weights,\n const double epsilon,\n const double temperature,\n const double unit_conversion_factor,\n const double cutoff_frequency);\nvoid ph3py_get_collision_matrix(double *collision_matrix,\n const Darray *fc3_normal_squared,\n const double *frequencies,\n const long (*triplets)[3],\n const long *triplets_map,\n const long *map_q,\n const long *rotated_grid_points,\n const double *rotations_cartesian,\n const double *g,\n const long num_ir_gp,\n const long num_gp,\n const long num_rot,\n const double temperature,\n const double unit_conversion_factor,\n const double cutoff_frequency);\nvoid ph3py_get_reducible_collision_matrix(double *collision_matrix,\n const Darray *fc3_normal_squared,\n const double *frequencies,\n const long (*triplets)[3],\n const long *triplets_map,\n const long *map_q,\n const double *g,\n const long num_gp,\n const double temperature,\n const double unit_conversion_factor,\n const double cutoff_frequency);\nvoid ph3py_get_isotope_scattering_strength(\n double *gamma,\n const long grid_point,\n const double *mass_variances,\n const double *frequencies,\n const lapack_complex_double *eigenvectors,\n const long num_grid_points,\n const long *band_indices,\n const long num_band,\n const long num_band0,\n const double sigma,\n const double cutoff_frequency);\nvoid ph3py_get_thm_isotope_scattering_strength(\n double *gamma,\n const long grid_point,\n const long *ir_grid_points,\n const long *weights,\n const double *mass_variances,\n const double *frequencies,\n const lapack_complex_double *eigenvectors,\n const long num_ir_grid_points,\n const long *band_indices,\n const long num_band,\n const long num_band0,\n const double *integration_weights,\n const double cutoff_frequency);\nvoid ph3py_distribute_fc3(double *fc3,\n const long target,\n const long source,\n const long *atom_mapping,\n const long num_atom,\n const double *rot_cart);\nvoid ph3py_rotate_delta_fc2(double (*fc3)[3][3][3],\n const double (*delta_fc2s)[3][3],\n const double *inv_U,\n const double (*site_sym_cart)[3][3],\n const long *rot_map_syms,\n const long num_atom,\n const long num_site_sym,\n const long num_disp);\nvoid ph3py_get_permutation_symmetry_fc3(double *fc3, const long num_atom);\nvoid ph3py_get_permutation_symmetry_compact_fc3(double *fc3,\n const long p2s[],\n const long s2pp[],\n const long nsym_list[],\n const long perms[],\n const long n_satom,\n const long n_patom);\nvoid ph3py_transpose_compact_fc3(double *fc3,\n const long p2s[],\n const long s2pp[],\n const long nsym_list[],\n const long perms[],\n const long n_satom,\n const long n_patom,\n const long t_type);\nlong ph3py_get_triplets_reciprocal_mesh_at_q(long *map_triplets,\n long *map_q,\n const long grid_point,\n const long mesh[3],\n const long is_time_reversal,\n const long num_rot,\n const long (*rec_rotations)[3][3],\n const long swappable);\nlong ph3py_get_BZ_triplets_at_q(long (*triplets)[3],\n const long grid_point,\n const long (*bz_grid_addresses)[3],\n const long *bz_map,\n const long *map_triplets,\n const long num_map_triplets,\n const long D_diag[3],\n const long Q[3][3],\n const long bz_grid_type);\nlong ph3py_get_integration_weight(double *iw,\n char *iw_zero,\n const double *frequency_points,\n const long num_band0,\n const long relative_grid_address[24][4][3],\n const long mesh[3],\n const long (*triplets)[3],\n const long num_triplets,\n const long (*bz_grid_addresses)[3],\n const long *bz_map,\n const long bz_grid_type,\n const double *frequencies1,\n const long num_band1,\n const double *frequencies2,\n const long num_band2,\n const long tp_type,\n const long openmp_per_triplets,\n const long openmp_per_bands);\nvoid ph3py_get_integration_weight_with_sigma(double *iw,\n char *iw_zero,\n const double sigma,\n const double sigma_cutoff,\n const double *frequency_points,\n const long num_band0,\n const long (*triplets)[3],\n const long num_triplets,\n const double *frequencies,\n const long num_band,\n const long tp_type);\nlong ph3py_get_grid_index_from_address(const long address[3],\n const long mesh[3]);\nvoid ph3py_get_gr_grid_addresses(long gr_grid_addresses[][3],\n const long D_diag[3]);\nlong ph3py_get_reciprocal_rotations(long rec_rotations[48][3][3],\n const long (*rotations)[3][3],\n const long num_rot,\n const long is_time_reversal);\nlong ph3py_transform_rotations(long (*transformed_rots)[3][3],\n const long (*rotations)[3][3],\n const long num_rot,\n const long D_diag[3],\n const long Q[3][3]);\nlong ph3py_get_snf3x3(long D_diag[3],\n long P[3][3],\n long Q[3][3],\n const long A[3][3]);\nlong ph3py_transform_rotations(long (*transformed_rots)[3][3],\n const long (*rotations)[3][3],\n const long num_rot,\n const long D_diag[3],\n const long Q[3][3]);\nlong ph3py_get_ir_grid_map(long *ir_grid_map,\n const long D_diag[3],\n const long PS[3],\n const long (*grg_rotations)[3][3],\n const long num_rot);\nlong ph3py_get_bz_grid_addresses(long (*bz_grid_addresses)[3],\n long *bz_map,\n long *bzg2grg,\n const long D_diag[3],\n const long Q[3][3],\n const long PS[3],\n const double rec_lattice[3][3],\n const long type);\nlong ph3py_rotate_bz_grid_index(const long bz_grid_index,\n const long rotation[3][3],\n const long (*bz_grid_addresses)[3],\n const long *bz_map,\n const long D_diag[3],\n const long PS[3],\n const long bz_grid_type);\nvoid ph3py_symmetrize_collision_matrix(double *collision_matrix,\n const long num_column,\n const long num_temp,\n const long num_sigma);\nvoid ph3py_expand_collision_matrix(double *collision_matrix,\n const long *rot_grid_points,\n const long *ir_grid_points,\n const long num_ir_gp,\n const long num_grid_points,\n const long num_rot,\n const long num_sigma,\n const long num_temp,\n const long num_band);\nlong ph3py_get_neighboring_gird_points(long *relative_grid_points,\n const long *grid_points,\n const long (*relative_grid_address)[3],\n const long mesh[3],\n const long (*bz_grid_addresses)[3],\n const long *bz_map,\n const long bz_grid_type,\n const long num_grid_points,\n const long num_relative_grid_address);\nlong ph3py_get_thm_integration_weights_at_grid_points(\n double *iw,\n const double *frequency_points,\n const long num_band0,\n const long num_band,\n const long num_gp,\n const long (*relative_grid_address)[4][3],\n const long D_diag[3],\n const long *grid_points,\n const long (*bz_grid_addresses)[3],\n const long *bz_map,\n const long bz_grid_type,\n const double *frequencies,\n const long *gp2irgp_map,\n const char function);\n\n#endif\n", "meta": {"hexsha": "fc0e6e2f89c0983eee5b7674d3493cf06b2e51d5", "size": 18174, "ext": "h", "lang": "C", "max_stars_repo_path": "c/phono3py.h", "max_stars_repo_name": "phonopy/phono3py", "max_stars_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T09:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:37:21.000Z", "max_issues_repo_path": "c/phono3py.h", "max_issues_repo_name": "phonopy/phono3py", "max_issues_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2020-05-02T22:11:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:35:12.000Z", "max_forks_repo_path": "c/phono3py.h", "max_forks_repo_name": "phonopy/phono3py", "max_forks_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-06-06T21:20:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T10:24:13.000Z", "avg_line_length": 48.9865229111, "max_line_length": 81, "alphanum_fraction": 0.4869593925, "num_tokens": 3113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.2942149845400438, "lm_q1q2_score": 0.19371629080460473}} {"text": "/* -*- linux-c -*- */\n/* sigma_binsingle.c\n\n Copyright (C) 2002-2004 John M. Fregeau\n \n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (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, Boston, MA 02111-1307 USA\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"fewbody.h\"\n#include \"sigma_binsingle.h\"\n\n/* print the usage */\nvoid print_usage(FILE *stream)\n{\n\tfprintf(stream, \"USAGE:\\n\");\n\tfprintf(stream, \" sigma_binsingle [options...]\\n\");\n\tfprintf(stream, \"\\n\");\n\tfprintf(stream, \"OPTIONS:\\n\");\n\tfprintf(stream, \" -m --m0 : set mass of single star [%.6g]\\n\", FB_M0/FB_CONST_MSUN);\n\tfprintf(stream, \" -n --m10 : set mass of star 0 of binary [%.6g]\\n\", FB_M10/FB_CONST_MSUN);\n\tfprintf(stream, \" -o --m11 : set mass of star 1 of binary [%.6g]\\n\", FB_M11/FB_CONST_MSUN);\n\tfprintf(stream, \" -r --r0 : set radius of single star [%.6g]\\n\", FB_R0/FB_CONST_RSUN);\n\tfprintf(stream, \" -g --r10 : set radius of star 0 of binary [%.6g]\\n\", FB_R10/FB_CONST_RSUN);\n\tfprintf(stream, \" -i --r11 : set radius of star 1 of binary [%.6g]\\n\", FB_R11/FB_CONST_RSUN);\n\tfprintf(stream, \" -a --a1 : set semimajor axis of binary [%.6g]\\n\", FB_A1/FB_CONST_AU);\n\tfprintf(stream, \" -e --e1 : set eccentricity of binary 0 [%.6g]\\n\", FB_E1);\n\tfprintf(stream, \" -v --vinf : set velocity at infinity [%.6g]\\n\", FB_VINF);\n\tfprintf(stream, \" -P --precision : set fractional precision on cross\\n\");\n\tfprintf(stream, \" section [%.6g]\\n\", FB_PRECISION);\n\tfprintf(stream, \" -t --tstop : set stopping time [%.6g]\\n\", FB_TSTOP);\n\tfprintf(stream, \" -D --dt
: set approximate output dt [%.6g]\\n\", FB_DT);\n\tfprintf(stream, \" -c --tcpustop : set cpu stopping time [%.6g]\\n\", FB_TCPUSTOP);\n\tfprintf(stream, \" -A --absacc : set integrator's absolute accuracy [%.6g]\\n\", FB_ABSACC);\n\tfprintf(stream, \" -R --relacc : set integrator's relative accuracy [%.6g]\\n\", FB_RELACC);\n\tfprintf(stream, \" -N --ncount : set number of integration steps between calls\\n\");\n\tfprintf(stream, \" to fb_classify() [%d]\\n\", FB_NCOUNT);\n\tfprintf(stream, \" -z --tidaltol : set tidal tolerance [%.6g]\\n\", FB_TIDALTOL);\n\tfprintf(stream, \" -x --fexp : set expansion factor of merger product [%.6g]\\n\", FB_FEXP);\n\tfprintf(stream, \" -k --ks : turn K-S regularization on or off [%d]\\n\", FB_KS);\n\tfprintf(stream, \" -s --seed : set random seed [%ld]\\n\", FB_SEED);\n\tfprintf(stream, \" -d --debug : turn on debugging\\n\");\n\tfprintf(stream, \" -V --version : print version info\\n\");\n\tfprintf(stream, \" -h --help : display this help text\\n\");\n}\n\n/* calculate the units used */\nint calc_units(fb_obj_t *obj[2], fb_units_t *units)\n{\n\tunits->v = sqrt(FB_CONST_G*(obj[0]->m + obj[1]->m)/(obj[0]->m * obj[1]->m) * \\\n\t\t\t(obj[1]->obj[0]->m * obj[1]->obj[1]->m / obj[1]->a));\n\tunits->l = obj[1]->a;\n\tunits->t = units->l / units->v;\n\tunits->m = units->l * fb_sqr(units->v) / FB_CONST_G;\n\tunits->E = units->m * fb_sqr(units->v);\n\t\n\treturn(0);\n}\n\n/* the main attraction */\nint main(int argc, char *argv[])\n{\n\tint i, j, k, res, err, sid, bid, precisionmet=0;\n\tlong l, nb;\n\tunsigned long int seed;\n\tdouble m0, m10, m11, r0, r10, r11, a1, e1, precision;\n\tdouble rtid, vinf, rperi, b, b0, bmin, bmax, db, bxlast, t, vc;\n\tfb_sigma_t sigmacurr[11], sigmaprev[11];\n\tchar outcome[11][FB_MAX_STRING_LENGTH];\n\t/* char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH]; */\n\tfb_hier_t hier;\n\tfb_input_t input;\n\tfb_ret_t retval;\n\tfb_units_t units;\n\tgsl_rng *rng;\n\tconst gsl_rng_type *rng_type=gsl_rng_mt19937;\n\tconst char *short_opts = \"m:n:o:r:g:i:a:e:v:P:t:D:c:A:R:N:z:x:k:s:dVh\";\n\tconst struct option long_opts[] = {\n\t\t{\"m0\", required_argument, NULL, 'm'},\n\t\t{\"m10\", required_argument, NULL, 'n'},\n\t\t{\"m11\", required_argument, NULL, 'o'},\n\t\t{\"r0\", required_argument, NULL, 'r'},\n\t\t{\"r10\", required_argument, NULL, 'g'},\n\t\t{\"r11\", required_argument, NULL, 'i'},\n\t\t{\"a1\", required_argument, NULL, 'a'},\n\t\t{\"e1\", required_argument, NULL, 'e'},\n\t\t{\"vinf\", required_argument, NULL, 'v'},\n\t\t{\"precision\", required_argument, NULL, 'P'},\n\t\t{\"tstop\", required_argument, NULL, 't'},\n\t\t{\"dt\", required_argument, NULL, 'D'},\n\t\t{\"tcpustop\", required_argument, NULL, 'c'},\n\t\t{\"absacc\", required_argument, NULL, 'A'},\n\t\t{\"relacc\", required_argument, NULL, 'R'},\n\t\t{\"ncount\", required_argument, NULL, 'N'},\n\t\t{\"tidaltol\", required_argument, NULL, 'z'},\n\t\t{\"fexp\", required_argument, NULL, 'x'},\n\t\t{\"ks\", required_argument, NULL, 'k'},\n\t\t{\"seed\", required_argument, NULL, 's'},\n\t\t{\"debug\", no_argument, NULL, 'd'},\n\t\t{\"version\", no_argument, NULL, 'V'},\n\t\t{\"help\", no_argument, NULL, 'h'},\n\t\t{NULL, 0, NULL, 0}\n\t};\n\n\t/* set parameters to default values */\n\tm0 = FB_M0;\n\tm10 = FB_M10;\n\tm11 = FB_M11;\n\tr0 = FB_R0;\n\tr10 = FB_R10;\n\tr11 = FB_R11;\n\ta1 = FB_A1;\n\te1 = FB_E1;\n\tvinf = FB_VINF;\n\tprecision = 1.0e-2;\n\tinput.ks = FB_KS;\n\tinput.tstop = FB_TSTOP;\n\tinput.Dflag = 0;\n\tinput.dt = FB_DT;\n\tinput.tcpustop = FB_TCPUSTOP;\n\tinput.absacc = FB_ABSACC;\n\tinput.relacc = FB_RELACC;\n\tinput.ncount = FB_NCOUNT;\n\tinput.tidaltol = FB_TIDALTOL;\n\tinput.fexp = FB_FEXP;\n\tseed = FB_SEED;\n\tfb_debug = FB_DEBUG;\n\t\n\twhile ((i = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {\n\t\tswitch (i) {\n\t\tcase 'm':\n\t\t\tm0 = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tm10 = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\tm11 = atof(optarg) * FB_CONST_MSUN;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tr0 = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\tr10 = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tr11 = atof(optarg) * FB_CONST_RSUN;\n\t\t\tbreak;\n\t\tcase 'a':\n\t\t\ta1 = atof(optarg) * FB_CONST_AU;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\te1 = atof(optarg);\n\t\t\tif (e1 >= 1.0) {\n\t\t\t\tfprintf(stderr, \"e0 must be less than 1\\n\");\n\t\t\t\treturn(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tvinf = atof(optarg);\n\t\t\tif (vinf < 0.0) {\n\t\t\t\tfprintf(stderr, \"vinf must be non-negative\\n\");\n\t\t\t\treturn(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'P':\n\t\t\tprecision = atof(optarg);\n\t\t\tif (precision <= 0.0) {\n\t\t\t\tfprintf(stderr, \"precision must be > 0\\n\");\n\t\t\t\treturn(1);\n\t\t\t} else if (precision > 1.0) {\n\t\t\t\tfprintf(stderr, \"precision must be < 1\\n\");\n\t\t\t\treturn(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tinput.tstop = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'D':\n\t\t\tinput.Dflag = 1;\n\t\t\tinput.dt = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tinput.tcpustop = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'A':\n\t\t\tinput.absacc = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\tinput.relacc = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'N':\n\t\t\tinput.ncount = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\tinput.tidaltol = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\tinput.fexp = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\tinput.ks = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tseed = atol(optarg);\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tfb_debug = 1;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tfb_print_version(stdout);\n\t\t\treturn(0);\n\t\tcase 'h':\n\t\t\tfb_print_version(stdout);\n\t\t\tfprintf(stdout, \"\\n\");\n\t\t\tprint_usage(stdout);\n\t\t\treturn(0);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t/* check to make sure there was nothing crazy on the command line */\n\tif (optind < argc) {\n\t\tprint_usage(stdout);\n\t\treturn(1);\n\t}\n\n\t/* initialize a few things for integrator */\n\thier.nstarinit = 3;\n\tfb_malloc_hier(&hier);\n\n\t/* initialize GSL rng */\n\tgsl_rng_env_setup();\n\trng = gsl_rng_alloc(rng_type);\n\tgsl_rng_set(rng, seed);\n\n\t/* zero everything out before summing */\n\tfor (i=0; i<11; i++) {\n\t\tsigmacurr[i].sigma_r = 0.0;\n\t\tsigmacurr[i].dsigma2_r_minus = 0.0;\n\t\tsigmacurr[i].dsigma2_r_plus = 0.0;\n\t\tsigmacurr[i].sigma_nr = 0.0;\n\t\tsigmacurr[i].dsigma2_nr_minus = 0.0;\n\t\tsigmacurr[i].dsigma2_nr_plus = 0.0;\n\t\tsigmaprev[i].sigma_r = 0.0;\n\t\tsigmaprev[i].dsigma2_r_minus = 0.0;\n\t\tsigmaprev[i].dsigma2_r_plus = 0.0;\n\t\tsigmaprev[i].sigma_nr = 0.0;\n\t\tsigmaprev[i].dsigma2_nr_minus = 0.0;\n\t\tsigmaprev[i].dsigma2_nr_plus = 0.0;\n\t}\n\t/* loop through and calcluate cross sections */\n\tnb = (long) (1.0/precision);\n\twhile (!precisionmet) {\n\t\t/* select b0 that gives r_p=2a */\n\t\tvc = sqrt(FB_CONST_G * (m0+m10+m11) / (m0*(m10+m11)) * (m10*m11/a1));\n\t\trperi = 2.0 * a1;\n\t\t/* b0 is in code units here (vinf is in units of vc) */\n\t\tb0 = sqrt(fb_sqr(rperi) + 2.0 * FB_CONST_G * (m0+m10+m11) * rperi / fb_sqr(vinf*vc)) / a1;\n\t\tdb = b0/((double) nb);\n\t\tbxlast = GSL_POSINF;\n\n\t\tl = 0;\n\t\tbmin = ((double) l) * db;\n\t\tbmax = bmin + db;\n\t\twhile (bmax <= b0 || bmax <= 2.0*bxlast) {\n\t\t\tbmin = ((double) l) * db;\n\t\t\tbmax = bmin + db;\n\t\t\t/* choose b uniformly in area from bmin to bmax */\n\t\t\tb = sqrt(gsl_rng_uniform(rng) * (fb_sqr(bmax)-fb_sqr(bmin)) + fb_sqr(bmin));\n\t\t\t\n\t\t\t/* do scattering experiment */\n\t\t\t/* initialize a few things for integrator */\n\t\t\tt = 0.0;\n\t\t\thier.nstar = 3;\n\t\t\tfb_init_hier(&hier);\n\t\t\t\n\t\t\t/* create binary */\n\t\t\thier.hier[hier.hi[2]+0].obj[0] = &(hier.hier[hier.hi[1]+1]);\n\t\t\thier.hier[hier.hi[2]+0].obj[1] = &(hier.hier[hier.hi[1]+2]);\n\t\t\thier.hier[hier.hi[2]+0].t = t;\n\t\t\t\n\t\t\t/* give the objects some properties */\n\t\t\tfor (j=0; jm + hier.obj[1]->m) / (hier.obj[1]->m * input.tidaltol), 1.0/3.0) * \n\t\t\t\thier.obj[1]->a * (1.0 + hier.obj[1]->e);\n\t\t\tfb_init_scattering(hier.obj[0], hier.obj[1], vinf, b, rtid);\n\t\t\t\n\t\t\t/* trickle down the binary properties, then back up */\n\t\t\tfb_randorient(&(hier.hier[hier.hi[2]+0]), rng);\n\t\t\tfb_downsync(&(hier.hier[hier.hi[2]+0]), t);\n\t\t\t/* fb_upsync(&(hier.hier[hier.hi[2]+0]), t); */\n\t\t\t\n\t\t\t/* call fewbody! */\n\t\t\tretval = fewbody(input, &hier, &t);\n\n\t\t\tk = -1;\n\t\t\tres = 0;\n\t\t\terr = 0;\n\n\t\t\t/* analyze outcome */\n\t\t\tif (retval.retval == 1 && \n\t\t\t FB_MIN(fabs(retval.DeltaEfrac), fabs(retval.DeltaE)) <= 1.0e-4 &&\n\t\t\t FB_MIN(fabs(retval.DeltaLfrac), fabs(retval.DeltaL)) <= 1.0e-4) {\n\t\t\t\t/* check for resonance */\n\t\t\t\tif (retval.Nosc >= 1) {\n\t\t\t\t\tres = 1;\n\t\t\t\t} else {\n\t\t\t\t\tres = 0;\n\t\t\t\t}\n\t\t\t\t/* classify outcome */\n\t\t\t\tif (hier.nstar == 3) {\n\t\t\t\t\tif (hier.nobj == 1) {\n\t\t\t\t\t\t/* triples physically forbidden */\n\t\t\t\t\t\terr = 1;\n\t\t\t\t\t} else if (hier.nobj == 2) {\n\t\t\t\t\t\tif (fb_n_hier(hier.obj[0])==2) {\n\t\t\t\t\t\t\tbid = 0;\n\t\t\t\t\t\t\tsid = 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbid = 1;\n\t\t\t\t\t\t\tsid = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (hier.obj[sid]->id[0] == 0) {\n\t\t\t\t\t\t\tk = 0;\n\t\t\t\t\t\t} else if (hier.obj[sid]->id[0] == 1) {\n\t\t\t\t\t\t\tk = 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tk = 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else { /* hier.nobj == 3 */\n\t\t\t\t\t\tk = 3;\n\t\t\t\t\t}\n } else if (hier.nstar == 2) {\n\t\t\t\t\tif (hier.nobj == 1) {\n\t\t\t\t\t\tif ((hier.obj[0]->obj[0]->ncoll==1 && hier.obj[0]->obj[0]->id[0]==0) ||\n\t\t\t\t\t\t (hier.obj[0]->obj[1]->ncoll==1 && hier.obj[0]->obj[1]->id[0]==0)) {\n\t\t\t\t\t\t\tk = 4;\n\t\t\t\t\t\t} else if ((hier.obj[0]->obj[0]->ncoll==1 && hier.obj[0]->obj[0]->id[0]==1) ||\n\t\t\t\t\t\t\t (hier.obj[0]->obj[1]->ncoll==1 && hier.obj[0]->obj[1]->id[0]==1)) {\n\t\t\t\t\t\t\tk = 5;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tk = 6;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else { /* hier.nobj == 2 */\n\t\t\t\t\t\tif ((hier.obj[0]->ncoll==1 && hier.obj[0]->id[0]==0) ||\n\t\t\t\t\t\t (hier.obj[1]->ncoll==1 && hier.obj[1]->id[0]==0)) {\n\t\t\t\t\t\t\tk = 7;\n\t\t\t\t\t\t} else if ((hier.obj[0]->ncoll==1 && hier.obj[0]->id[0]==1) ||\n\t\t\t\t\t\t\t (hier.obj[1]->ncoll==1 && hier.obj[1]->id[0]==1)) {\n\t\t\t\t\t\t\tk = 8;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tk = 9;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (hier.nstar == 1) {\n\t\t\t\t\tk = 10;\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"ERROR: hier.nstar!=1,2,3!\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n } else { /* bad outcome */\n\t\t\t\terr = 1;\n\t\t\t}\n\n\t\t\t/* tally up cross sections */\n\t\t\tif (!err) {\n\t\t\t\tfor (i=0; i<11; i++) {\n\t\t\t\t\tif (i==k) {\n\t\t\t\t\t\tif (res) {\n\t\t\t\t\t\t\tsigmacurr[i].sigma_r += FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin));\n\t\t\t\t\t\t\tsigmacurr[i].dsigma2_r_minus += fb_sqr(0.1587 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t\t\t\tsigmacurr[i].dsigma2_nr_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsigmacurr[i].sigma_nr += FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin));\n\t\t\t\t\t\t\tsigmacurr[i].dsigma2_nr_minus += fb_sqr(0.1587 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\t\n\t\t\t\t\t\t\tsigmacurr[i].dsigma2_r_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsigmacurr[i].dsigma2_r_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t\t\tsigmacurr[i].dsigma2_nr_plus += fb_sqr(0.8413/21.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (i=0; i<11; i++) {\n\t\t\t\t\tsigmacurr[i].dsigma2_r_plus += fb_sqr(0.8413/22.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t\tsigmacurr[i].dsigma2_nr_plus += fb_sqr(0.8413/22.0 * FB_CONST_PI * (fb_sqr(bmax)-fb_sqr(bmin)));\n\t\t\t\t}\t\n\t\t\t}\n\t\t\t\n\t\t\t/* if the outcome was not a weak flyby, then record last impact parameter */\n\t\t\tif (!err && (k!=0 || (k==0 && res))) {\n\t\t\t\tbxlast = bmax;\n\t\t\t}\n\t\t\t\n\t\t\t/*\n\t\t\tfprintf(stderr, \"outcome: retval=%d %s (%s)\\n\", retval.retval, \n\t\t\t\tfb_sprint_hier(hier, string1), fb_sprint_hier_hr(hier, string2));\n\t\t\tfprintf(stderr, \" DeltaL/L0=%.6g DeltaL=%.6g\\n\", retval.DeltaLfrac, retval.DeltaL);\n\t\t\tfprintf(stderr, \" DeltaE/E0=%.6g DeltaE=%.6g\\n\", retval.DeltaEfrac, retval.DeltaE);\n\t\t\tfprintf(stderr, \" l=%ld b0=%g bmin=%g bmax=%g bxlast=%g k=%d res=%d err=%d\\n\", l, b0, bmin, bmax, bxlast, k, res, err);\n\t\t\t*/\n\n\t\t\tl++;\n\t\t}\n\t\t\n\t\t/* add current and previous sigmas, and transfer current to previous */\n\t\t\n\t\t/* increase resolution geometrically */\n\t\tnb *= 2;\n\t\t\n\t\tprecisionmet = 1;\n\t}\n\n\tsnprintf(outcome[0], FB_MAX_STRING_LENGTH, \"[1 2] 0 (preservation)\");\n\tsnprintf(outcome[1], FB_MAX_STRING_LENGTH, \"[0 2] 1 (exchange_1)\");\n\tsnprintf(outcome[2], FB_MAX_STRING_LENGTH, \"[0 1] 2 (exchange_2)\");\n\tsnprintf(outcome[3], FB_MAX_STRING_LENGTH, \"0 1 2 (ionization)\");\n\tsnprintf(outcome[4], FB_MAX_STRING_LENGTH, \"[1:2 0] (merger_binary_12)\");\n\tsnprintf(outcome[5], FB_MAX_STRING_LENGTH, \"[0:2 1] (merger_binary_02)\");\n\tsnprintf(outcome[6], FB_MAX_STRING_LENGTH, \"[0:1 2] (merger_binary_01)\");\n\tsnprintf(outcome[7], FB_MAX_STRING_LENGTH, \"1:2 0 (merger_12)\");\n\tsnprintf(outcome[8], FB_MAX_STRING_LENGTH, \"0:2 1 (merger_02)\");\n\tsnprintf(outcome[9], FB_MAX_STRING_LENGTH, \"0:1 2 (merger_01)\");\n\tsnprintf(outcome[10], FB_MAX_STRING_LENGTH, \"0:1:2 (triple_merger)\");\n\n\t/* precision has now been met, so print out results */\n\tfprintf(stdout, \"outcome sigma_r dsigma_r_minus dsigma_r_plus sigma_nr dsigma_nr_minus dsigma_nr_plus\\n\");\n\tfor (i=0; i<11; i++) {\n\t\tfprintf(stdout, \"%27s %6.6g %6.6g %6.6g %6.6g %6.6g %6.6g\\n\", outcome[i], \n\t\t\tsigmacurr[i].sigma_r/FB_CONST_PI, \n\t\t\tsqrt(sigmacurr[i].dsigma2_r_minus)/FB_CONST_PI, \n\t\t\tsqrt(sigmacurr[i].dsigma2_r_plus)/FB_CONST_PI,\n\t\t\tsigmacurr[i].sigma_nr/FB_CONST_PI, \n\t\t\tsqrt(sigmacurr[i].dsigma2_nr_minus)/FB_CONST_PI, \n\t\t\tsqrt(sigmacurr[i].dsigma2_nr_plus)/FB_CONST_PI);\n\t}\n\n\t/* free GSL stuff */\n\tgsl_rng_free(rng);\n\n\t/* free our own stuff */\n\tfb_free_hier(hier);\n\n\t/* done! */\n\treturn(0);\n}\n", "meta": {"hexsha": "87d3c1d3a3c92e8c97f9e4383ed1967c7bf954ac", "size": 16902, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/sigma_binsingle.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-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": "ext/fewbod/fewbody-0.26/sigma_binsingle.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/sigma_binsingle.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6023856859, "max_line_length": 123, "alphanum_fraction": 0.5908176547, "num_tokens": 6034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19188052770221994}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core_allvars_grid.h\"\n#include \"core_proto_grid.h\"\n\n\n\nint32_t init(void)\n{\n int32_t i, status;\n\n sum_photons = 0.0; \n\n random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n gsl_rng_set(random_generator, 42);\t // start-up seed \n\n set_units(); // Change units to code units where necessary.\n srand((unsigned) time(NULL));\n\n read_snap_list(); // Read the snapshots required.\n\n for(i = 0; i < Snaplistlen; i++)\n {\n ZZ[i] = 1 / AA[i] - 1; // Redshift array.\n Age[i] = time_to_present(ZZ[i]); // Age array.\n }\n\n \n if (fescPrescription == 0)\n {\n printf(\"\\n\\nUsing a constant escape fraction of %.4f\\n\", fesc); \n }\n else if (fescPrescription == 1)\n {\n fprintf(stderr, \"\\n\\nDeprecated! Use a new one!\\n\");\n return EXIT_FAILURE;\n } \n else if (fescPrescription == 2)\n {\n printf(\"\\n\\nUsing an fesc prescription that scales with halo mass.\\n\\n\");\n determine_fesc_constants();\n }\n else if (fescPrescription == 3)\n {\n printf(\"\\n\\nUsing an fesc prescription that scales with the fraction of ejected mass in the galaxy.\\n\");\n printf(\"\\nThis takes the form A*fej + B with A = %.4e and B = %.4e\\n\", alpha, beta); \n }\n else if (fescPrescription == 4)\n {\n printf(\"\\n\\nUsing an fesc prescription that depends upon quasar activity.\\n\");\n printf(\"\\nFor a galaxy that had a quasar event within %.2f dynamical times go the escape fraction will be %.2f. Otherwise it will have a constant value of %.2f\\n\", N_dyntime, quasar_boosted, quasar_baseline);\n }\n else if (fescPrescription == 5)\n {\n printf(\"\\n\\nUsing Anne's functional form for an escape fraction that decreases for increasing halo mass.\\n\");\n XASSERT(fesc_low > fesc_high, \"Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 5), we require fesc_low > fesc_high\\n\", fesc_low, fesc_high);\n }\n else if (fescPrescription == 6)\n {\n printf(\"\\n\\nUsing Anne's functional form for an escape fraction that increases for increasing halo mass.\\n\");\n XASSERT(fesc_low < fesc_high, \"Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 6), we require fesc_low < fesc_high\\n\", fesc_low, fesc_high);\n }\n else if (fescPrescription == 7)\n {\n printf(\"\\n\\nUsing an fesc prescription that scales as a power law with the fraction of ejected gas.\\n\");\n determine_fesc_constants();\n } \n else\n {\n printf(\"\\n\\nOnly escape fraction prescriptions 0 to 6 (exlucding 1) are permitted.\\n\");\n return EXIT_FAILURE;\n }\n\n Grid = malloc(sizeof(struct GRID_STRUCT));\n if (Grid == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the high level grid structure\\n\");\n return EXIT_FAILURE;\n }\n\n status = init_grid(Grid);\n if (status == EXIT_FAILURE)\n {\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n\n\n QuasarEventsAbovePartCut = 0;\n QuasarEventsBelowPartCut = 0;\n\n}\n\n\nint32_t init_grid(struct GRID_STRUCT *grid)\n{\n\n#define ALLOCATE_GRID_MEMORY(name, length) \\\n{ \\\n name = calloc(length, sizeof(*(name))); \\\n if (name == NULL) \\\n { \\\n fprintf(stderr, \"Out of memory allocating %ld bytes, could not allocate\"#name\".\\n\", sizeof(*(name)* length)); \\\n return EXIT_FAILURE; \\\n } \\\n}\n\n int32_t i;\n uint64_t cell_idx;\n\n if (grid == NULL)\n {\n fprintf(stderr, \"init_grid was called with a GRID_STRUCT pointer that has not been initialized\\n\");\n return EXIT_FAILURE;\n } \n\n \n grid->GridSize = GridSize;\n grid->NumCellsTotal = CUBE(GridSize);\n \n grid->NumGrids = NGrid; \n\n grid->GridProperties = malloc(sizeof(struct GRID_PROPERTIES_STRUCT) * grid->NumGrids);\n if (grid->GridProperties == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the grid properties struct\\n\");\n return EXIT_FAILURE;\n }\n\n for (i = 0; i < grid->NumGrids; ++i)\n {\n#ifdef MPI\n printf(\"Allocating grid %d on Task %d.\\n\", i, ThisTask);\n#endif\n\n /* For now the self-consistent model only using the number of ionizing photons. */\n /* Also use the number of galaxies for sanity check. */\n \n ALLOCATE_GRID_MEMORY(grid->GridProperties[i].Nion_HI, grid->NumCellsTotal);\n ALLOCATE_GRID_MEMORY(grid->GridProperties[i].GalCount, grid->NumCellsTotal);\n\n if (self_consistent == 0)\n {\n ALLOCATE_GRID_MEMORY(grid->GridProperties[i].SFR, grid->NumCellsTotal);\n ALLOCATE_GRID_MEMORY(grid->GridProperties[i].StellarMass, grid->NumCellsTotal);\n ALLOCATE_GRID_MEMORY(grid->GridProperties[i].Nion_HeI, grid->NumCellsTotal);\n ALLOCATE_GRID_MEMORY(grid->GridProperties[i].Nion_HeII, grid->NumCellsTotal);\n\n }\n\n // All the memory has been allocated for the inner grid.\n // Now let's initialize the values.\n\n for (cell_idx = 0; cell_idx < Grid->NumCellsTotal; ++cell_idx)\n {\n grid->GridProperties[i].Nion_HI[cell_idx] = 0.0; \n grid->GridProperties[i].GalCount[cell_idx] = 0; \n\n if (self_consistent == 0)\n {\n grid->GridProperties[i].SFR[cell_idx] = 0.0; \n grid->GridProperties[i].StellarMass[cell_idx] = 0.0; \n grid->GridProperties[i].Nion_HeI[cell_idx] = 0.0; \n grid->GridProperties[i].Nion_HeII[cell_idx] = 0.0; \n \n }\n } \n\n } \n \n printf(\"All grids have been initialized\\n\");\n return EXIT_SUCCESS; \n}\n\nint32_t free_grid(void)\n{\n\n int32_t i;\n\n for (i = 0; i < Grid->NumGrids; ++i)\n {\n free(Grid->GridProperties[i].Nion_HI);\n free(Grid->GridProperties[i].GalCount);\n\n if (self_consistent == 0)\n {\n free(Grid->GridProperties[i].Nion_HeII);\n free(Grid->GridProperties[i].Nion_HeI);\n free(Grid->GridProperties[i].StellarMass);\n free(Grid->GridProperties[i].SFR);\n }\n }\n\n free(Grid->GridProperties);\n free(Grid);\n\n return EXIT_SUCCESS;\n\n}\n\n\nvoid set_units(void)\n{\n\n UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;\n UnitTime_in_Megayears = UnitTime_in_s / SEC_PER_MEGAYEAR;\n G = GRAVITY / pow(UnitLength_in_cm, 3) * UnitMass_in_g * pow(UnitTime_in_s, 2);\n UnitDensity_in_cgs = UnitMass_in_g / pow(UnitLength_in_cm, 3);\n UnitPressure_in_cgs = UnitMass_in_g / UnitLength_in_cm / pow(UnitTime_in_s, 2);\n UnitCoolingRate_in_cgs = UnitPressure_in_cgs / UnitTime_in_s;\n UnitEnergy_in_cgs = UnitMass_in_g * pow(UnitLength_in_cm, 2) / pow(UnitTime_in_s, 2);\n\n // convert some physical input parameters to internal units \n Hubble = HUBBLE * UnitTime_in_s;\n\n // compute a few quantitites \n RhoCrit = 3 * Hubble * Hubble / (8 * M_PI * G);\n\n}\n\nvoid read_snap_list(void)\n{\n FILE *fd;\n char fname[MAXLEN];\n\n snprintf(fname, MAXLEN, \"%s\", FileWithSnapList);\n\n if(!(fd = fopen(fname, \"r\")))\n {\n printf(\"can't read output list in file '%s'\\n\", fname);\n ABORT(0);\n }\n\n Snaplistlen = 0;\n do\n {\n if(fscanf(fd, \" %lg \", &AA[Snaplistlen]) == 1)\n Snaplistlen++;\n else\n break;\n }\n while(Snaplistlen < MAXSNAPS);\n\n fclose(fd);\n\n#ifdef MPI\n if(ThisTask == 0)\n#endif\n printf(\"found %d defined times in snaplist\\n\", Snaplistlen);\n}\n\ndouble time_to_present(double z)\n{\n#define WORKSIZE 1000\n gsl_function F;\n gsl_integration_workspace *workspace;\n double time, result, abserr;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n F.function = &integrand_time_to_present;\n\n gsl_integration_qag(&F, 1.0 / (z + 1), 1.0, 1.0 / Hubble,\n 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);\n\n time = 1 / Hubble * result;\n\n gsl_integration_workspace_free(workspace);\n\n // return time to present as a function of redshift \n return time;\n}\n\n\n\ndouble integrand_time_to_present(double a, void *param)\n{\n return 1 / sqrt(Omega / a + (1 - Omega - OmegaLambda) + OmegaLambda * a * a);\n}\n\nvoid determine_fesc_constants(void)\n{\n\n double A, B, log_A;\n\n log_A = (log10(fesc_high) - (log10(fesc_low)*log10(MH_high)/log10(MH_low))) * pow(1 - (log10(MH_high) / log10(MH_low)), -1);\n B = (log10(fesc_low) - log_A) / log10(MH_low);\n A = pow(10, log_A);\n\n alpha = A;\n beta = B;\n\n printf(\"Fixing the points (%.4e, %.2f) and (%.4e, %.2f)\\n\", MH_low, fesc_low, MH_high, fesc_high);\n printf(\"This gives a power law with constants A = %.4e, B = %.4e\\n\", alpha, beta);\n\n \n}\n/*\nvoid estimate_grid_memory(void)\n{\n\n if (Verbose == 1)\n {\n printf(\"The size of the Grid Struct (that contains all the pointers) is %lu bytes\\nEach grid cell has a struct, in addition to data that the pointers point to.\\n\", sizeof(struct GRID));\n printf(\"The total memory taken up by the Grid will be the sizeof a grid cell (%lu bytes) times the number of grid cells (%d) times the number of output snapshots (%d) times 2 because we need memory for both the pointers for the grid and the actual numbers themselves.\\n\", sizeof(struct GRID), CUBE(GridSize), NGrid);\n }\n\n printf(\"Approximate total memory for the grid ===== %lu mb\\n\", sizeof(struct GRID)*CUBE(GridSize)*NGrid*2/1024/1024);\n\n}\n\nvoid estimate_gal_memory(int NtotGals)\n{\n if (Verbose == 1)\n {\n printf(\"The size of the Galaxy struct is %lu bytes and the size of the GalaxyGrid struct (that contains all the pointers for the SnapShot history) is %lu\\n\", sizeof(struct GALAXY_INPUT), sizeof(struct GALAXY_GRID));\n printf(\"The total memory taken up by this file of galaxies will be the sizeof the galaxy input (%lu bytes) times the number of galaxies (%d) plus the sizeof the galaxygrid (%lu bytes) times the number of snapshots in the simulation (%d) times the number of galaxies (%d)\\n\", sizeof(struct GALAXY_INPUT), NtotGals, sizeof(struct GALAXY_GRID), LastSnapShotNr, NtotGals); \n }\n\n printf(\"Approximate memory occupied for this file of galaxies ===== %lu mb\\n\", (sizeof(struct GALAXY_INPUT)*NtotGals + sizeof(struct GALAXY_GRID)*NtotGals*LastSnapShotNr)/1024/1024);\n\n}\n*/\n", "meta": {"hexsha": "476354e6515b61ea7a5267346aeaf1fcebdd16da", "size": 10055, "ext": "c", "lang": "C", "max_stars_repo_path": "gridding/core_init_grid.c", "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_issues_repo_path": "gridding/core_init_grid.c", "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_forks_repo_path": "gridding/core_init_grid.c", "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "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": 30.1047904192, "max_line_length": 373, "alphanum_fraction": 0.670810542, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.19056183150960393}} {"text": "/**\n *\n * @file pcunmqr_blgtrd.c\n *\n * PLASMA auxiliary routines\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Azzam Haidar\n * @date 2011-05-15\n * @generated c Tue Jan 7 11:45:13 2014\n *\n **/\n#include \n#include \n#include \"common.h\"\n#undef REAL\n#define COMPLEX\n\n#define E(_m, _n) (E + (_m) + LDE * (_n) )\n#define V(_m) (V + (_m))\n#define T(_m) (T + (_m))\n#define TAU(_m) (TAU + (_m))\n/***************************************************************************\n * Parallel apply Q2 from bulgechasing matrices - static scheduling\n * Lower case is treated\n **/\n /*\n * side == PlasmaLeft:\n * meaning apply E = Q*E = (q_1*q_2*.....*q_n) * E ==> so\n * traverse Vs in reverse order (forward) from q_n to q_1 Also\n * E is splitten by block of col over cores because each apply\n * consist in a block of row (horizontal block)\n */\n /*\n * side == PlasmaRight:\n * meaning apply E = E*Q = E * (q_1*q_2*.....*q_n) ==> so\n * traverse Vs in normal order (forward) from q_1 to q_n Also\n * E is splitten by block of row over core because each apply\n * consist in a block of col (vertical block)\n */\n/***************************************************************************/\nvoid plasma_pcunmqr_blgtrd(plasma_context_t *plasma)\n{\n int my_core_id = PLASMA_RANK;\n int cores_num = plasma->world_size;\n\n /*===========================*/\n int N, NB, NE, LDE, Vblksiz, WANTZ;\n PLASMA_enum side;\n PLASMA_enum trans;\n PLASMA_Complex32_t *V;\n PLASMA_Complex32_t *T;\n PLASMA_Complex32_t *TAU;\n PLASMA_Complex32_t *E;\n PLASMA_sequence *sequence;\n PLASMA_request *request;\n\n /*===========================\n * local variables\n *===========================*/\n PLASMA_Complex32_t *WORK;\n int LDT, LDV;\n int Vm, Vn, mt, nt;\n int myrow, mycol, blkj, blki;\n int firstrow, nbcolinvolvd;\n int blkid, vpos, taupos, tpos;\n int chunkid, nbchunk, colpercore, corest, corelen, len, col;\n int coreid, allcoresnb, maxrequiredcores;\n int lchunkid, rchunkid, halfchunk, nbportion, sw;\n int LWORK;\n int standalonework = 0 ;\n int versionL, versionR;\n\n\n plasma_unpack_args_14(side, trans, N, NB, NE, Vblksiz, WANTZ, V, T, TAU, E, LDE, sequence, request);\n if (sequence->status != PLASMA_SUCCESS)\n return;\n\n /* Quick return */\n if ( N == 0 ) {\n return;\n }\n if ( NB == 0 ) {\n return;\n }\n if ( NE == 0 ) {\n return;\n }\n /* ==========================================\n * some infor for developer\n * Initialisation and checking nb of cores\n * ==========================================*/\n /* we have to 2 algo for left (113 114) and 2 algo for right (91 92)\n * which correspond to versionL versionR.\n * They ae very similar (detail explained in tech report and matlab code)\n * however version 114 and 92 improve locality.\n * while version 113 is used in case WNATZ=1 (construct Q2) which allow\n * the construction to be done in an optimized way taking into\n * consideration that the matrix is Identity so making less flops.\n *\n */\n versionL = 113;\n versionR = 92;\n LDT = Vblksiz;\n LDV = NB+Vblksiz-1;\n /* use colpercore = N/cores_num; :if i want to split E into\n * cores_num chunk so I will have large chunk for each core.\n * However I prefer to split E into chunk of small size where\n * I guarantee that blas3 occur and the size of chunk remain into\n * cache, I think it is better. than I will have different chunk of\n * small size per core and i will do each chunk till the end and\n * then move to the second one for data locality\n *\n * version v1: for each chunck it apply all the V's then move to\n * the other chunck. the locality here inside each\n * chunck meaning that thread \"t\" apply V_k then move\n * to V_k+1 which overlap with V_k meaning that the\n * E_k+1 overlap with E_k. so here is the\n * locality however thread t had to read V_k+1 and\n * T_k+1 at each apply. note that all thread if they\n * run at same speed they might reading the same V_k\n * and T_k at the same time.\n *\n * version v2: for each V_k and T_k thread t apply those V_k and\n * T_k to E_k for all its chunck, then move to V_k+1\n * T_k+1 and apply them to E_k+1 on all the chunck,\n * and so on. the difference is that, thread keep V_k\n * and T_K while move over the E_k.\n * both version look like similar in perf.\n *\n * THIS IS v1 CODE\n * */\n\n if(WANTZ==1)\n colpercore = plasma_ceildiv(NE,2*cores_num);\n else\n colpercore = plasma_ceildiv(NE,cores_num);\n\n if(colpercore>1000)\n colpercore = plasma_ceildiv(colpercore,10);\n else if(colpercore>800)\n colpercore = plasma_ceildiv(colpercore,8);\n else if(colpercore>600)\n colpercore = plasma_ceildiv(colpercore,6);\n else if(colpercore>400)\n colpercore = plasma_ceildiv(colpercore,4);\n else if(colpercore>200)\n colpercore = plasma_ceildiv(colpercore,2);\n if(colpercore>200)\n colpercore=120;\n if(colpercore<30)\n colpercore=32;\n /*colpercore = N make the code sequential running on thread=0;*/\n nbchunk = plasma_ceildiv(NE, colpercore);\n allcoresnb = cores_num;\n maxrequiredcores = nbchunk;\n if( maxrequiredcores < 1 )\n maxrequiredcores = 1;\n if(allcoresnb > maxrequiredcores)\n allcoresnb = maxrequiredcores;\n\n#if defined (ENABLE_DEBUG)\n if(my_core_id==0)\n printf(\" APPLY Q_v1 parallel with threads %d nbchunk %d colpercore %d N %d NB %d Vblksiz %d SIDE %c TRANS %c versionL %d versionR %d WANTZ %d \\n\",\n cores_num,nbchunk,colpercore,N,NB,Vblksiz,lapack_const(side),lapack_const(trans),versionL,versionR,WANTZ);\n#endif\n /* =========================================\n * case NB = 1 special case.\n * just make the element real for complex\n * =========================================\n */\n if ( NB == 1 ) {\n /* NOTE in CASE USED STANDALONE FUNCTION\n * In COMPLEX matrix Z need to be scaled by the TAU\n * generated during the make off-diagonal elements real\n */\n /*\n * In case where the first stage has been done we are sure\n * that all element of E are real so no need to go through\n * NB=1. However in case where this function need to be used\n * for only band matrices meaning only stage2 has been called\n * then it require to make all off-diagonal elements real and\n * so remove the return from here and from the bulgechasing\n * function\n */\n if(WANTZ==1){\n PLASMA_Complex32_t zone = 1.0;\n memset(E, 0, LDE*N*sizeof(PLASMA_Complex32_t));\n for(sw=0; sw1 main code\n * =========================================\n */\n LWORK = 2*colpercore*max(Vblksiz,64);\n WORK = (PLASMA_Complex32_t*) plasma_private_alloc(plasma, LWORK, PlasmaComplexFloat);\n /* WANTZ = 1 meaning E is IDENTITY so form Q using optimized update.\n * So we use the reverse order from small q to large one,\n * so from q_n to q_1 so Left update to Identity.\n * Use version 113 because in 114 we need to update the whole matrix and not in icreasing order.\n * WANTZ = 2 meaning E is a full matrix and need to be updated from Left or Right so use normal update\n * */\n if ( WANTZ==1 ) {\n versionL = 113;\n halfchunk = plasma_ceildiv(nbchunk,2);\n for (lchunkid = 0; lchunkid=0; blkj--) {\n /* the index of the first row on the top of block (blkj) */\n firstrow = blkj * Vblksiz + 1;\n /*find the number of tile for this block */\n if( blkj == nt-1 )\n mt = plasma_ceildiv( N - firstrow, NB);\n else\n mt = plasma_ceildiv( N - (firstrow+1), NB);\n /*loop over the tiles find the size of the Vs and apply it */\n for (blki=mt; blki>0; blki--) {\n /*calculate the size of each losange of Vs= (Vm,Vn)*/\n myrow = firstrow + (mt-blki)*NB;\n mycol = blkj*Vblksiz;\n Vm = min( NB+Vblksiz-1, N-myrow);\n if( ( blkj == nt-1 ) && ( blki == mt ) ){\n Vn = min (Vblksiz, Vm);\n } else {\n Vn = min (Vblksiz, Vm-1);\n }\n /*calculate the pointer to the Vs and the Ts.\n * Note that Vs and Ts have special storage done\n * by the bulgechasing function*/\n findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid);\n if((Vm>0)&&(Vn>0)){\n col = max(mycol,corest);\n len = corelen - (col-corest);\n if(side==PlasmaLeft){\n if( len > 0 )\n CORE_clarfb_gemm(\n side, trans,\n PlasmaForward, PlasmaColumnwise,\n Vm, len, Vn, V(vpos), LDV, T(tpos), LDT, E(myrow,col), LDE, WORK, len);\n }\n else{\n if( len > 0 )\n CORE_clarfb_gemm(\n side, trans,\n PlasmaForward, PlasmaColumnwise,\n len, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(col, myrow), LDE, WORK, len);\n }\n }\n }\n }\n } /* END my_core_id=coreid */\n } /* END of sw */\n } /* END loop over the chunk */\n } /* END if WANTZ=1 */\n else{\n /*\n * WANTZ != 1\n */\n for (chunkid = 0; chunkid=0; blkj--) {\n /* the index of the first row on the top of block (blkj) */\n firstrow = blkj * Vblksiz + 1;\n /*find the number of tile for this block */\n if( blkj == nt-1 )\n mt = plasma_ceildiv( N - firstrow, NB);\n else\n mt = plasma_ceildiv( N - (firstrow+1), NB);\n /*loop over the tiles find the size of the Vs and apply it */\n for (blki=mt; blki>0; blki--) {\n /*calculate the size of each losange of Vs= (Vm,Vn)*/\n myrow = firstrow + (mt-blki)*NB;\n mycol = blkj*Vblksiz;\n Vm = min( NB+Vblksiz-1, N-myrow);\n if( ( blkj == nt-1 ) && ( blki == mt ) ){\n Vn = min (Vblksiz, Vm);\n } else {\n Vn = min (Vblksiz, Vm-1);\n }\n /*calculate the pointer to the Vs and the Ts.\n * Note that Vs and Ts have special storage done\n * by the bulgechasing function*/\n findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid);\n if((Vm>0)&&(Vn>0)){\n if( side == PlasmaLeft ){\n CORE_clarfb_gemm(\n PlasmaLeft, trans,\n PlasmaForward, PlasmaColumnwise,\n Vm, corelen, Vn, V(vpos), LDV, T(tpos), LDT, E(myrow,corest), LDE, WORK, corelen);\n\n }else{\n CORE_clarfb_gemm(\n PlasmaRight, trans,\n PlasmaForward, PlasmaColumnwise,\n corelen, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(corest, myrow), LDE, WORK, corelen);\n }\n }\n }\n }\n }\n /*\n * Version 114:\n * loop over the block_row (mt) and for each find diagonally the\n * number of tiles (nt) in this block_row. then loop over nt, find\n * the size of the V's(Vm,Vn) and apply it to the corresponding\n * portion of E.\n */\n else {\n mt = plasma_ceildiv((N-1),NB);\n for (blki = mt; blki>0; blki--) {\n /* nbcolinvolvd = number of column corresponding to this block_row (blki) */\n nbcolinvolvd = min(N-1, blki*NB);\n /*find the number of tile for this block (diagonal row of tiles) */\n nt = plasma_ceildiv(nbcolinvolvd,Vblksiz);\n /*loop over the tiles find the size of the Vs and apply it */\n for (blkj = nt-1; blkj>=0; blkj--) {\n /* the index of the first row of the first col meaning\n * the block on the top left (blki) */\n firstrow = (mt-blki)*NB+1;\n /*calculate the size of each losange of Vs= (Vm,Vn)*/\n myrow = firstrow + blkj*Vblksiz;\n mycol = blkj*Vblksiz;\n Vm = min( NB+Vblksiz-1, N-myrow);\n if( ( blkj == nt-1 ) && ( blki == mt ) ){\n Vn = min (Vblksiz, Vm);\n }else{\n Vn = min (Vblksiz, Vm-1);\n }\n /*calculate the pointer to the Vs and the Ts.\n * Note that Vs and Ts have special storage done\n * by the bulgechasing function*/\n findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid);\n if((Vm>0)&&(Vn>0)) {\n CORE_clarfb_gemm(\n PlasmaLeft, trans,\n PlasmaForward, PlasmaColumnwise,\n Vm, corelen, Vn, V(vpos), LDV, T(tpos), LDT, E(myrow,corest), LDE, WORK, corelen);\n }\n }\n }\n }\n }\n /*\n * PlasmaRight\n */\n else {\n /*\n * Version 91:\n */\n if( versionR == 91 ) {\n nt = plasma_ceildiv((N-1),Vblksiz);\n for (blkj=0; blkj0)&&(Vn>0)){\n CORE_clarfb_gemm(\n PlasmaRight,\n trans,\n PlasmaForward,\n PlasmaColumnwise,\n corelen, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(corest,myrow), LDE, WORK, corelen);\n }\n }\n }\n }\n /*trans\n * Version 92:\n */\n else {\n mt = plasma_ceildiv((N-1),NB);\n for (blki = 1; blki<=mt; blki++) {\n /* nbcolinvolvd = number of column corresponding to this block_row (blki) */\n nbcolinvolvd = min(N-1, blki*NB);\n /*find the number of tile for this block (diagonal row of tiles) */\n nt = plasma_ceildiv(nbcolinvolvd,Vblksiz);\n /*loop over the tiles find the size of the Vs and apply it */\n for (blkj = 0; blkj0)&&(Vn>0)) {\n CORE_clarfb_gemm(\n PlasmaRight, trans,\n PlasmaForward, PlasmaColumnwise,\n corelen, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(corest,myrow), LDE, WORK, corelen);\n }\n }\n }\n }\n }\n } /* END my_core_id=coreid */\n } /* END loop over the chunk */\n } /* END ELSE of WANTZ == 1 */\n plasma_private_free(plasma, WORK);\n}\n#undef E\n#undef V\n#undef T\n#undef TAU\n/***************************************************************************/\n#undef COMPLEX\n", "meta": {"hexsha": "16c6677efe9f6ef43ef836da939bfbaa335bc299", "size": 23940, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/pcunmqr_blgtrd.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": "compute/pcunmqr_blgtrd.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": "compute/pcunmqr_blgtrd.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "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": 47.5, "max_line_length": 165, "alphanum_fraction": 0.4196324144, "num_tokens": 5532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.18902097608368892}} {"text": "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n//\n// \t\t\t //////////////////////////////////////////////////////////\n// \t\t\t //\t\t\t\t\t\t\t //\n// \t\t\t // \t hybridMANTIS v1.0\t\t //\n// \t\t\t // \t fastDETECT2 - C code \t\t //\n//\t\t\t //\t\t (optical photons transport)\t\t //\n//\t\t\t //\t\t\t\t\t\t\t //\n//\t\t\t //////////////////////////////////////////////////////////\n//\n// \n//\n//\n// ****Disclaimer****\n// This software and documentation (the \"Software\") were developed at the Food and Drug Administration (FDA) by employees of the Federal Government in\n// the course of their official duties. Pursuant to Title 17, Section 105 of the United States Code, this work is not subject to copyright protection\n// and is in the public domain. Permission is hereby granted, free of charge, to any person obtaining a copy of the Software, to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the\n// Software or derivatives, and to permit persons to whom the Software is furnished to do so. FDA assumes no responsibility whatsoever for use by other\n// parties of the Software, its source code, documentation or compiled executables, and makes no guarantees, expressed or implied, about its quality,\n// reliability, or any other characteristic. Further, use of this code in no way implies endorsement by the FDA or confers any advantage in regulatory\n// decisions. Although this software can be redistributed and/or modified freely, we ask that any derivative works bear some notice that they are\n// derived from it, and any modified versions bear some notice that they have been modified. \n//\n//\n//\tAssociated publication: Sharma Diksha, Badal Andreu and Badano Aldo, \"hybridMANTIS: a CPU-GPU Monte Carlo method for modeling indirect x-ray detectors with\n//\t\t\t\tcolumnar scintillators\". Physics in Medicine and Biology, 57(8), pp. 2357–2372 (2012)\n//\n//\n//\tFile: \thybridMANTIS_c_ver1_0.c \t\t\t\n//\tAuthor: \tDiksha Sharma (US Food and Drug Administration)\n//\tEmail: \t\tdiksha.sharma@fda.hhs.gov\t\t\t\n//\tLast updated: \tApr 13, 2012\n// \n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////\n//\n// Header libraries\n//\n/////////////////////////////////////////\n\n\t#include \n\t#include \n\n/////////////////////////////////////////\n//\n// Global variables\n//\n/////////////////////////////////////////\n\n\t#define max_photon_per_EDE 900000\t// maximum number of optical photons that can be generated per energy deposition event (EDE)\n\n\t#ifndef USING_CUDA\n\t\t#define mybufsize 2304000\t// CPU buffer size: # of events sent to the CPU\n\t#endif\n\n/////////////////////////////////////////\n//\n// Include kernel program\n//\n/////////////////////////////////////////\n\t#include \"kernel_cuda_c_ver1_0.cu\"\n\n////////////////////////////////////////////////////////////////////////////\n//\t\t\t\tMAIN PROGRAM\t\t\t //\n////////////////////////////////////////////////////////////////////////////\n\n#ifndef USING_CUDA\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// cpuoptical(): Performs optical transport using CPU \n//\t \t Input arguments: gpusize\n//\n// \t\t gpusize - buffer size already processed in the GPU. CPU runs optical transport for rest of the buffer.\n//\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\tvoid cpuoptical_(int *gpusize)\t\t\t\t\n\t{ \n\n\t\t// command line arguments\n\t\tfloat xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, lbound_x, lbound_y, ubound_x, ubound_y, d_max, yield, sensorRefl;\n\t\tint pixelsize, num_primary, min_optphotons, max_optphotons, num_bins;\n\n\t\tfloat dcos[3]={0}; \t\t// directional cosines\n\t\tfloat normal[3]={0}; \t\t// normal to surface in case of TIR\n\t\tfloat pos[3] = {0}; \t\t// intersecting point coordinates\n\t\tfloat old_pos[3] = {0}; \t// source coordinates\n\t\n\t\tint nbytes = (optical_.myctropt - (*gpusize))*sizeof(struct start_info);\n\t\tstruct start_info *structa;\n\t\tstructa = (struct start_info*) malloc(nbytes);\n\t\tif( structa == NULL )\n\t\t\tprintf(\"\\n Struct start_info array CANNOT BE ALLOCATED - %d !!\", (optical_.myctropt-(*gpusize)));\n\n\t\t// get cpu time\n\t\tclock_t start, end;\n\t\tfloat num_sec;\n\n\t\t// get current time stamp to initialize seed input for RNG\n\t\ttime_t seconds;\n\t\tseconds = time (NULL);\n\t\tstruct timeval tv;\n\t\tgettimeofday(&tv,NULL);\n\n\t\tfloat rr=0.0f, theta=0.0f;\t\n\t\tfloat r=0.0f;\t\t\t// random number\n\t\tfloat norm=0.0f;\n\t\tint jj=0;\n\t\tint my_index=0;\n\t\tint penindex = 0;\t\t// equal to *gpusize\n\t\tint result_algo = 0;\n\t\tunsigned long long int *num_rebound;\n\n\t\t// initialize random number generator (RANECU)\n\t\tint seed_input = 271828182 ; \t\t// ranecu seed input\n\t\tint seed[2];\n\n\t\t// GNU scientific library (gsl) variables\n\t\tconst gsl_rng_type * Tgsl;\n\t\tgsl_rng * rgsl;\n\t\tdouble mu_gsl;\t\n\t\t\t\t\n\t\t// output image variables\n\t\tint xdim = 0;\n\t\tint ydim = 0;\n\t\tint indexi=0, indexj=0;\n\n\t\t// copy to local variables from PENELOPE buffers\n\t\txdetector = inputargs_.detx;\t\t// x dimension of detector (in um). x in (0,xdetector)\n\t\tydetector = inputargs_.dety;\t\t// y dimension of detector (in um). y in (0,ydetector)\n\t\theight = inputargs_.detheight;\t\t// height of column and thickness of detector (in um). z in range (-H/2, H/2)\n\t\tradius = inputargs_.detradius;\t\t// radius of column (in um).\n\t\tn_C = inputargs_.detnC;\t\t\t// refractive index of columns\n\t\tn_IC = inputargs_.detnIC;\t\t// refractive index of intercolumnar material\n\t\ttop_absfrac = inputargs_.dettop;\t// column's top surface absorption fraction (0.0, 0.5, 0.98)\n\t\tbulk_abscoeff = inputargs_.detbulk;\t// column's bulk absorption coefficient (in um^-1) (0.001, 0.1 cm^-1) \n\t\tbeta = inputargs_.detbeta;\t\t// roughness coefficient of column walls\n\t\td_min = inputargs_.detdmin;\t\t// minimum distance a photon can travel when transmitted from a column\n\t\td_max = inputargs_.detdmax;\n\t\tlbound_x = inputargs_.detlboundx;\t// x lower bound of region of interest of output image (in um)\n\t\tlbound_y = inputargs_.detlboundy;\t// y lower bound (in um)\n\t\tubound_x = inputargs_.detuboundx;\t// x upper bound (in um) \n\t\tubound_y = inputargs_.detuboundy;\t// y upper bound (in um)\n\t\tyield = inputargs_.detyield;\t\t// yield (/eV)\n\t\tpixelsize = inputargs_.detpixel;\t// 1 pixel = pixelsize microns (in um)\n\t\tsensorRefl = inputargs_.detsensorRefl;\t// Non-Ideal sensor reflectivity (%)\n\t\tnum_primary = inputargs_.mynumhist;\t// total number of primaries to be simulated\n\t\tmin_optphotons = inputargs_.minphotons;\t// minimum number of optical photons detected to be included in PHS\n\t\tmax_optphotons = inputargs_.maxphotons;\t// maximum number of optical photons detected to be included in PHS\n\t\tnum_bins = inputargs_.mynumbins;\t// number of bins for genrating PHS\n\n\t \t// create a generator chosen by the environment variable GSL_RNG_TYPE\n\t \tgsl_rng_env_setup();\t \n\t \tTgsl = gsl_rng_default;\n\t \trgsl = gsl_rng_alloc (Tgsl);\n\t \t\n\t \t// dimensions of PRF image\n\t\txdim = ceil((ubound_x - lbound_x)/pixelsize);\n\t\tydim = ceil((ubound_y - lbound_y)/pixelsize);\n\t\tunsigned long long int myimage[xdim][ydim];\n\t\t\n\t\t//initialize the output image 2D array\n\t\tfor(indexi = 0; indexi < xdim; indexi++)\n\t\t{ \n\t\t for(indexj = 0; indexj < ydim; indexj++)\n\t\t {\n\t\t myimage[indexi][indexj] = 0;\n\t\t }\n\t\t}\n\t\n\t\t// memory for storing histogram of # photons detected/primary\n\t\tint *h_num_detected_prim = 0;\t\t\n\t\th_num_detected_prim = (int*)malloc(sizeof(int)*num_primary);\n\t\t\t\n\t\tfor(indexj=0; indexj < num_primary; indexj++)\n\t\t h_num_detected_prim[indexj] = 0;\n\t\t \t\n\t\t// memory for storing histogram of # photons detected/primary\n\t\tint *h_histogram = 0;\t\t\n\t\th_histogram = (int*)malloc(sizeof(int)*num_bins);\n\t\t\t\n\t\tfor(indexj=0; indexj < num_bins; indexj++)\n\t\t h_histogram[indexj] = 0;\n\n\tpenindex = *gpusize;\n\t\n\tfor(my_index = 0; my_index < (optical_.myctropt-(*gpusize)); my_index++)\t\t// iterate over x-rays\n\t{\n\n\t\t// reset the global counters\n\t\tnum_generated = 0;\n\t\tnum_detect=0;\n\t\tnum_abs_top=0;\t\n\t\tnum_abs_bulk=0;\t\n\t\tnum_lost=0;\n\t\tnum_outofcol=0;\n\t\tnum_theta1=0;\n\t\tphoton_distance=0.0f;\n\n\t\t//re-initialize the output image 2D array\n\t\tfor(indexi = 0; indexi < xdim; indexi++)\n\t\t for(indexj = 0; indexj < ydim; indexj++)\n\t\t myimage[indexi][indexj] = 0;\n\n\t\t// copying PENELOPE buffer into *structa\n\n\t\t// units in the penelope output file are in cm. Convert them to microns.\n\t\tstructa[my_index].str_x = optical_.xbufopt[penindex+my_index] * 10000.0f;\t// x-coordinate of interaction event\n\t\tstructa[my_index].str_y = optical_.ybufopt[penindex+my_index] * 10000.0f;\t// y-coordinate\n\t\tstructa[my_index].str_z = optical_.zbufopt[penindex+my_index] * 10000.0f;\t// z-coordinate\n\t\tstructa[my_index].str_E = optical_.debufopt[penindex+my_index];\t\t\t// energy deposited\n\t\tstructa[my_index].str_histnum = optical_.nbufopt[penindex+my_index];\t\t// x-ray history\n\n\t\t// sample # optical photons based on light yield and energy deposited for this interaction event (using Poisson distribution)\n\t\tmu_gsl = (double)structa[my_index].str_E * yield;\n\t\tstructa[my_index].str_N = gsl_ran_poisson(rgsl,mu_gsl);\n\n\t\tif(structa[my_index].str_N > max_photon_per_EDE)\n\t\t{\n\t\t\tprintf(\"\\n\\n str_n exceeds max photons. program is exiting - %d !! \\n\\n\",structa[my_index].str_N);\n\t\t\texit(0);\n\t\t}\n\n\n\t\tnum_rebound = (unsigned long long int*) malloc(structa[my_index].str_N*sizeof(unsigned long long int));\n\t\tif(num_rebound == NULL)\n\t\tprintf(\"\\n Error allocating num_rebound memory !\\n\");\n\n\t\t// start the clock\n\t\tstart = clock();\n\n\t\t// initialize the RANECU generator in a position far away from the previous history:\n\t\tseed_input = (int)(seconds/3600+tv.tv_usec);\t\t\t// seed input=seconds passed since 1970+current time in micro secs\n\t\tinit_PRNG(my_index, 50000, seed_input, seed); \t\t// intialize RNG\n\n\t\tfor(jj=0; jj (1.0f + epsilon)))\t// normalize\n\t\t {\n\t\t\tdcos[0] = dcos[0]/norm;\n\t\t\tdcos[1] = dcos[1]/norm;\n\t\t\tdcos[2] = dcos[2]/norm;\n\t\t }\n\n\n\t\tlocal_counter=0;\t// total number of photons terminated (either detected at sensor, absorbed at the top or in the bulk) [global variable]\n\t\twhile(local_counter < structa[my_index].str_N)\t\t// until all the optical photons are not transported\n\t\t { \n\t\t\t\n\t\t\tabsorbed = 0;\n\t\t\tdetect = 0;\n\t\t\tbulk_abs = 0;\n\n\t\t\t// set starting location of photon\n\t\t\tpos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;\t\n\t\t\told_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;\n\t\t\tnum_generated++;\n\t\t\tresult_algo = 0;\n\n\t\t\twhile(result_algo == 0)\n\t\t\t {\n\t\t\t \tresult_algo = algo(normal, old_pos, pos, dcos, num_rebound, seed, structa[my_index], &myimage[0][0], xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, pixelsize, lbound_x, lbound_y, ubound_x, ubound_y, sensorRefl, d_max, ydim, h_num_detected_prim); \n\t\t\t }\n\n\t\t }\t\n\n\n\t\t// end the clock\t\t\n\t\tend = clock();\n\n\t\tnum_sec = (((float)end - start)/CLOCKS_PER_SEC);\n\n\t\t\t\n\t\t // type cast unsigned long long int to double\n\t\t double cast_num_generated;\n\t\t double cast_num_detect;\n\t\t double cast_num_abs_top;\n\t\t double cast_num_abs_bulk;\n\t\t double cast_num_lost;\n\t\t double cast_num_outofcol;\n\t\t double cast_num_theta1;\n\t\t double cast_gputime;\n\n\t\t cast_num_generated = (double)num_generated;\n\t\t cast_num_detect = (double)num_detect;\n\t\t cast_num_abs_top = (double)num_abs_top;\n\t\t cast_num_abs_bulk = (double)num_abs_bulk;\n\t\t cast_num_lost = (double)num_lost;\n\t\t cast_num_outofcol = (double)num_outofcol;\n\t\t cast_num_theta1 = (double)num_theta1;\n\t\t cast_gputime\t = (double)(num_sec*1000.0);\t\t// convert in millisecond\n\n\t\t // save to global counters\n\t\t optstats_.glgen = optstats_.glgen + cast_num_generated;\n\t\t optstats_.gldetect = optstats_.gldetect + cast_num_detect;\n\t\t optstats_.glabstop = optstats_.glabstop + cast_num_abs_top;\n\t\t optstats_.glabsbulk = optstats_.glabsbulk + cast_num_abs_bulk;\n\t\t optstats_.gllost = optstats_.gllost + cast_num_lost;\n\t\t optstats_.gloutofcol = optstats_.gloutofcol + cast_num_outofcol;\n\t\t optstats_.gltheta1 = optstats_.gltheta1 + cast_num_theta1;\n\t\t optstats_.glgputime = optstats_.glgputime + cast_gputime;\n\n\t\t// release resources\n\t\tfree(num_rebound);\n\t\n\t}\t// my_index loop ends\n\t\n\t// make histogram of number of detected photons/primary for num_bins\n\tint binsize=0, newbin=0;\n\tint bincorr=0;\n\t\t\t\t\t\t\t\n\tbinsize = floor((max_optphotons-min_optphotons)/num_bins);\t// calculate size of each bin. Assuming equally spaced bins.\n\tbincorr = floor(min_optphotons/binsize);\t\t\t// correction in bin number if min_optphotons > 0.\n\t\t\t\n\tfor(indexi = 0; indexi < num_primary; indexi++)\n\t {\n\t \tnewbin = floor(h_num_detected_prim[indexi]/binsize) - bincorr;\t// find bin #\n\t\t \t\n\t \tif(h_num_detected_prim[indexi] > 0)\t// store only non-zero bins\n\t \t{\n\t\t \tif(h_num_detected_prim[indexi] <= min_optphotons)\t// # detected < minimum photons given by user, add to the first bin\n\t\t \t\th_histogram[0]++;\n\t\t \telse if(h_num_detected_prim[indexi] >= max_optphotons)\t// # detected > maximum photons given by user, then add to the last bin\n\t\t \t\th_histogram[num_bins-1]++;\n\t\t \telse\n\t\t \t\th_histogram[newbin]++; \n\t\t}\n\t }\n\t\t\t\n\t// add num_detected_primary to gldetprimary array in PENELOPE\n\tfor(indexi = 0; indexi < num_bins; indexi++)\n\t\toutputdetprim_.gldetprimary[indexi] = outputdetprim_.gldetprimary[indexi] + h_histogram[indexi];\n\t\t\n\t// release resources\n\tfree(structa);\n\tfree(h_num_detected_prim);\n\tfree(h_histogram);\n\n\t\treturn;\n\t}\t// C main() ends\n\t\n#endif\n\n\n", "meta": {"hexsha": "ac96416066b0628989e79c15d6b4e52e59cb12b6", "size": 15160, "ext": "c", "lang": "C", "max_stars_repo_path": "main/hybridMANTIS_c_ver1_0.c", "max_stars_repo_name": "diamfda/hybridmantis", "max_stars_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/hybridMANTIS_c_ver1_0.c", "max_issues_repo_name": "diamfda/hybridmantis", "max_issues_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/hybridMANTIS_c_ver1_0.c", "max_forks_repo_name": "diamfda/hybridmantis", "max_forks_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0, "max_line_length": 300, "alphanum_fraction": 0.6344327177, "num_tokens": 4368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759005519017088}} {"text": "#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core_allvars.h\"\n#include \"core_proto.h\"\n#include \"UVmag/UVmag.h\"\n\n// Local Proto-Types //\n\nint32_t init_delayedSN(void);\nint32_t init_nionlookup(void);\nint32_t init_metalcooling(void);\nvoid read_snap_list(void);\nvoid set_units(void);\nint32_t init_fesc(void);\nint32_t determine_fescMH_constants(void);\n\n// External Functions //\n\nvoid sage_init(void)\n{\n int32_t i, status;\n\n count_gal = 0; \n random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n gsl_rng_set(random_generator, 42);\t // start-up seed \n\n set_units();\n srand((unsigned) time(NULL));\n\n read_snap_list();\n for(i = 0; i < MAXSNAPS; i++)\n {\n ZZ[i] = 1 / AA[i] - 1;\n Age[i] = time_to_present(ZZ[i]);\n }\n\n a0 = 1.0 / (1.0 + Reionization_z0);\n ar = 1.0 / (1.0 + Reionization_zr);\n\n read_cooling_functions();\n\n status = init_fesc();\n if (status != EXIT_SUCCESS)\n {\n ABORT(0);\n }\n\n count_onehalo = 0; \n\n zeromass_count = 0;\n suppression_count = 0;\n previous_tree = 0;\n\n smallest_mass = 100000;\n lowmass_halo = 0;\n\n outside_box = 0;\n inside_box = 0;\n\n count_Mvir = 0;\n count_Len = 0;\n\n if (IMF == 0)\n {\n // Salpeter IMF //\n IMF_norm =0.1706;\n IMF_slope = -2.35;\n Eta_SNII = 7.432e-3; //Number fraction of stars that will end their lives as type II supernovae.\n m_SNII = 0.144; // Mass fraction of stars that will end their lives as type II supernovae.\n\n } else if (IMF == 1)\n {\n // Chabrier IMF //\n IMF_norm = 0.23638; \n IMF_slope = -2.3;\n Eta_SNII = 1.1893e-2; //Number fraction of stars that will end their lives as type II supernovae.\n m_SNII = 0.23638; // Mass fraction of stars that will end their lives as type II supernovae.\n\n }\n \n // Tiamat Parameters //\n\n V_energy = 70.0;\n alpha_energy = 0.5;\n beta_energy = 10.0;\n\n V_mass = 70.0; \n alpha_mass = 6.0; \n beta_mass = 10.0; \n\n epsilon_mass_max = 30.0;\n\n if (IRA == 0)\n {\n status = init_delayedSN();\n if (status != EXIT_SUCCESS)\n {\n ABORT(EXIT_FAILURE);\n } \n }\n\n if (PhotonPrescription == 1)\n {\n status = init_nionlookup();\n if (status != EXIT_SUCCESS)\n {\n ABORT(EXIT_FAILURE);\n }\n }\n\n if (calcUVmag == 1)\n {\n status = init_UVlookup();\n if (status != EXIT_SUCCESS)\n {\n ABORT(EXIT_FAILURE);\n }\n }\n\n if ((PhotonPrescription == 1) || (calcUVmag == 1))\n {\n StellarTracking_Len = STELLAR_TRACKING_TIME / TimeResolutionStellar;\n }\n \n mergedgal_mallocs = 0;\n gal_mallocs = 0 ;\n\n mergedgal_frees = 0;\n gal_frees = 0;\n\n Ngamma_HI_Total = 0.0;\n \n}\n\n// Local Functions //\n\nint32_t init_delayedSN(void)\n{ \n\n // We keep the past 50 Myrs of star formation stored for each galaxy.\n // Based on the TimeResolution specified need to find out how many elements this corresponds to. \n\n if(TimeResolutionSN > 50)\n {\n fprintf(stderr, \"The selected time resolution for SN feedback (TimeResolutionSN) is set too high (%d Myr). Using TimeResolutionSN > 50Myr is the same as using the instantaneous recycling approximation; set 'IRA' to 1 instead!\\n\", TimeResolutionSN); \n ABORT(EXIT_FAILURE); \n } else if(TimeResolutionSN > 35)\n {\n fprintf(stderr, \"Your selected time resolution for SN feedback (TimeResolutionSN) is quite high (%d Myr). Beyond 50Myr the instantaneous recycling approximation is valid hence with your value it would likely be correct to set 'IRA' to 1.\\n\", TimeResolutionSN);\n } else\n {\n Time_SFH = 0;\n SN_Array_Len = 0;\n while(Time_SFH < 50)\n {\n Time_SFH += TimeResolutionSN;\n ++SN_Array_Len;\n }\n\n }\n\n // For the delayed SN scheme the number of SN for each time step depends on the IMF.\n // As we will need to calculate this for every substep we create look-up tables for efficiency. \n\n // First we need to know given a timestep, what is the minimum mass star that will go supernova? \n\n double a = 0.7473; // Fits from Portinari et al. (1998). \n double b = -2.6979;\n double c = -4.7659;\n double d = 0.5934;\n\n coreburning_tbins_low = 2; // Any time below 2Myr will result in stars > 120Myr to explode. This is beyond the limits of the IMF.\n coreburning_tbins_high = 45; // Any time above 45Myr will result in stars > 8Myr to explode. Can just return 8.0 in this case. \n coreburning_tbins_delta = 0.00001;\n\n N_tbins = (coreburning_tbins_high - coreburning_tbins_low) / (coreburning_tbins_delta);\n int32_t bin_idx;\n\n coreburning_times = malloc(sizeof(*(coreburning_times)) * N_tbins);\n if (coreburning_times == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the grid to contains the coreburning times.\\n\");\n return EXIT_FAILURE;\n }\n\n for (bin_idx = 0; bin_idx < N_tbins; ++bin_idx)\n {\n double t = coreburning_tbins_low + ((double)bin_idx * coreburning_tbins_delta); \n coreburning_times[bin_idx] = exp10(a/log10(t) + b * exp(c/log10(t)) + d); \n }\n\n // Now need to know given a mass range (defined by the timestep) what is the number and mass fraction of SN that go supernova. \n\n m_IMFbins_low = 8.0; // The IMF range is from 8.0 to 120.0 Msun.\n m_IMFbins_high = 120.0;\n m_IMFbins_delta = 0.00001;\n\n N_massbins = (m_IMFbins_high - m_IMFbins_low) / (m_IMFbins_delta);\n \n IMF_massgrid_eta = malloc(sizeof(*(IMF_massgrid_eta)) * N_massbins); \n if (IMF_massgrid_eta == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the grid to contain the IMF eta masses for delayed supernova.\\n\");\n return EXIT_FAILURE;\n }\n\n IMF_massgrid_m = malloc(sizeof(*(IMF_massgrid_m)) * N_massbins); \n if (IMF_massgrid_m == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the grid to contain the IMF m masses for delayed supernova.\\n\");\n return EXIT_FAILURE;\n }\n\n for (bin_idx = 0; bin_idx < N_massbins; ++bin_idx)\n {\n IMF_massgrid_eta[bin_idx] = pow(m_IMFbins_low + ((double)bin_idx * m_IMFbins_delta), IMF_slope + 1.0);\n IMF_massgrid_m[bin_idx] = pow(m_IMFbins_low + ((double)bin_idx * m_IMFbins_delta), IMF_slope + 2.0);\n }\n\n return EXIT_SUCCESS;\n\n}\n\nint32_t init_nionlookup(void)\n{\n\n // For PhotonPrescription == 1 we wish to explicitly track the stellar ages of a galaxy.\n // Then we determine the number of ionizing photons using the age of the stellar population.\n\n // Using STARBURST99 it was determined that the number of ionizing photons emitted from an instantaneous starburst depends on the \n // mass of stars formed and the time since the starburst. Furthermore, the number of ionizing photons scales linearly with the mass of stars formed.\n // That is, a starburst that forms 7.0e10Msun worth of stars will emit 10x as many photons as a starburst that forms 6.0e10Msun worth of stars.\n\n // So if we read in a table that contains the number of ionizing photons emitted from a starburst for a 6.0e10Msun episode, then we can scale our values to this lookup table\n // using log10 Ngamma(Msun, t) = (log10 M* - 6.0) + log10 Ngamma(6.0, t). \n\n#define MAXBINS 10000\n\n char buf[MAX_STRING_LEN], fname[MAX_STRING_LEN];\n FILE *niontable;\n int32_t i = 0, num_lines = 0;\n float t, HI, HI_L, HeI, HeI_L, HeII, HeII_L, L;\n\n snprintf(fname, MAX_STRING_LEN - 1, ROOT_DIR \"/extra/nion_table.txt\");\n niontable = fopen(fname, \"r\");\n if (niontable == NULL)\n {\n fprintf(stderr, \"Could not open file %s\\n\", fname);\n return EXIT_FAILURE;\n }\n\n stars_tbins = calloc(MAXBINS, sizeof(*(stars_tbins)));\n if (stars_tbins == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the time bins for the tracking of stellar populations.\\n\");\n return EXIT_FAILURE;\n }\n\n stars_Ngamma = calloc(MAXBINS, sizeof(*(stars_Ngamma)));\n if (stars_Ngamma == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the Ngamma HI bins for the tracking of stellar populations.\\n\");\n return EXIT_FAILURE;\n }\n\n // The first 8 lines are all header information. So move past them.\n while (i < 8)\n {\n fgets(buf, MAX_STRING_LEN, niontable);\n ++i;\n }\n\n while (fscanf(niontable, \"%f %f %f %f %f %f %f %f\", &t, &HI, &HI_L, &HeI, &HeI_L, &HeII, &HeII_L, &L) == 8) \n {\n\n stars_tbins[num_lines] = t;\n stars_Ngamma[num_lines] = HI;\n\n ++num_lines;\n if (num_lines == MAXBINS - 1)\n {\n fprintf(stderr, \"Exceeding the maximum bins for the tracking of stellar populations.\\n\");\n return EXIT_FAILURE;\n } \n }\n fclose(niontable);\n\n // Check that the Nion lookup table had enough datapoints to cover the time we're tracking the ages for. \n if (stars_tbins[num_lines - 1] / 1.0e6 < STELLAR_TRACKING_TIME)\n {\n fprintf(stderr, \"The final time specified in the Nion lookup table is %.4f Myr. However we specified to track stellar ages over %d Myr.\\n\", stars_tbins[num_lines - 1] / 1.0e6, STELLAR_TRACKING_TIME);\n fprintf(stderr, \"Either update the Nion lookup table or reduce the value of STELLAR_TRACKING_TIME in `core_allvars.h`.\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n\n#undef MAXBINS\n}\n\nvoid set_units(void)\n{\n \n UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s; \n UnitTime_in_Megayears = UnitTime_in_s / SEC_PER_MEGAYEAR;\n UnitDensity_in_cgs = UnitMass_in_g / pow(UnitLength_in_cm, 3);\n UnitPressure_in_cgs = UnitMass_in_g / UnitLength_in_cm / pow(UnitTime_in_s, 2);\n UnitCoolingRate_in_cgs = UnitPressure_in_cgs / UnitTime_in_s;\n UnitEnergy_in_cgs = UnitMass_in_g * pow(UnitLength_in_cm, 2) / pow(UnitTime_in_s, 2);\n\n EnergySNcode = EnergySN / UnitEnergy_in_cgs * Hubble_h;\n\n sage_G = GRAVITY / pow(UnitLength_in_cm, 3) * UnitMass_in_g * pow(UnitTime_in_s, 2);\n \n // convert some physical input parameters to internal units\n sage_Hubble = HUBBLE * UnitTime_in_s;\n\n // compute a few quantitites \n RhoCrit = 3 * sage_Hubble * sage_Hubble / (8 * M_PI * sage_G);\n}\n\nvoid read_snap_list(void)\n{\n FILE *fd;\n char fname[1000];\n\n sprintf(fname, \"%s\", FileWithSnapList);\n\n if(!(fd = fopen(fname, \"r\")))\n {\n printf(\"can't read output list in file '%s'\\n\", fname);\n ABORT(0);\n }\n\n Snaplistlen = 0;\n do\n {\n if(fscanf(fd, \" %lg \", &AA[Snaplistlen]) == 1)\n Snaplistlen++;\n else\n break;\n }\n while(Snaplistlen < MAXSNAPS);\n\n fclose(fd);\n}\n\ndouble time_to_present(double z)\n{\n#define WORKSIZE 1000\n gsl_function F;\n gsl_integration_workspace *workspace;\n double time, result, abserr;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n F.function = &integrand_time_to_present;\n\n gsl_integration_qag(&F, 1.0 / (z + 1), 1.0, 1.0 / sage_Hubble,\n 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);\n\n time = 1 / sage_Hubble * result;\n\n gsl_integration_workspace_free(workspace);\n\n // return time to present as a function of redshift \n return time;\n}\n\ndouble integrand_time_to_present(double a, void *param)\n{\n (void)(param); // Avoids triggering unused-parameter warning.\n return 1 / sqrt(Omega / a + (1 - Omega - OmegaLambda) + OmegaLambda * a * a);\n}\n\n\nint32_t init_fesc(void)\n{\n switch(fescPrescription)\n {\n\n case 0:\n if (ThisTask == 0)\n {\n printf(\"\\n\\nUsing a constant escape fraction of %.4f\\n\", beta); \n }\n break;\n\n case 1:\n if (ThisTask == 0)\n {\n printf(\"\\n\\nUsing an fesc prescription that scales with the fraction of ejected mass in the galaxy.\\nThis takes the form A*fej + B with A = %.4e and B = %.4e\\n\", alpha, beta);\n }\n break;\n\n case 2:\n if (ThisTask == 0)\n {\n printf(\"\\n\\nUsing an fesc prescription that depends upon quasar activity.\\n\");\n printf(\"\\nFor a galaxy that had a quasar event within %.2f dynamical times go the escape fraction will be %.2f. Otherwise it will have a constant value of %.2f\\n\", N_dyntime, quasar_boosted, quasar_baseline);\n }\n break;\n\n case 3:\n if (ThisTask == 0)\n {\n printf(\"\\n\\nUsing Anne's functional form for an escape fraction that increases for descreasing halo mass.\\n\");\n printf(\"MH_low = %.4e\\tMH_high = %.4e\\tfesc_low = %.4f\\tfesc_high = %.4f.\\n\", MH_low, MH_high, fesc_low, fesc_high);\n }\n XASSERT(fesc_low > fesc_high, \"Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 3), we require fesc_low > fesc_high\\n\", fesc_low, fesc_high);\n\n break;\n\n case 4:\n if (ThisTask == 0)\n {\n printf(\"\\n\\nUsing Anne's functional form for an escape fraction that increases for increasing halo mass.\\n\");\n printf(\"MH_low = %.4e\\tMH_high = %.4e\\tfesc_low = %.4f\\tfesc_high = %.4f.\\n\", MH_low, MH_high, fesc_low, fesc_high);\n }\n XASSERT(fesc_low < fesc_high, \"Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 4), we require fesc_low < fesc_high\\n\", fesc_low, fesc_high);\n break;\n\n case 5:\n if (ThisTask == 0)\n {\n printf(\"\\n\\nUsing an fesc prescription that depends upon the SFR of the galaxy.\\n\");\n printf(\"This takes the function form of a logistic function, fesc = delta / (1.0 + exp(-alpha*(log10(SFR)-beta))), with range [0.0, delta]. `alpha` controls the steepness of the curve and beta defines the value of log10(SFR) gives fesc = delta/2.\\n\");\n printf(\"alpha = %.4f\\tbeta = %.4f\\tdelta = %.4f\\n\", alpha, beta, delta);\n }\n break;\n\n default:\n printf(\"\\n\\nOnly escape fraction prescriptions 0, 1, 2, 3, 4 or 5 are permitted.\\n\");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\n/*\nFor some escape fraction prescriptions, the functional form is a power law with the constants calculated using two fixed points.\nThis function determines these constants based on the fixed points specified.\nRefer to the .ini file or `determine_fesc()` function for full details on each `fescPrescription`.\n\nParameters\n----------\nNone. All variables used/adjusted are global.\n\nReturns\n----------\nNone. All variables adjusted are global\n.\nPointer Updates\n----------\nNone.\n\nUnits \n----------\nThe Halo Masses used to specify the fixed points (MH_low and MH_high) are in Msun.\n*/\n\nint32_t determine_fescMH_constants(void)\n{ \n \n double A, B, log_A;\n \n switch(fescPrescription)\n {\n case 3:\n log_A = (log10(fesc_high) - (log10(fesc_low)*log10(MH_high)/log10(MH_low))) * pow(1 - (log10(MH_high) / log10(MH_low)), -1);\n B = (log10(fesc_low) - log_A) / log10(MH_low);\n A = pow(10, log_A);\n \n fescMH_alpha = A;\n fescMH_beta = B;\n\n printf(\"Fixing the points (%.4e, %.2f) and (%.4e, %.2f)\\n\", MH_low, fesc_low, MH_high, fesc_high);\n printf(\"This gives a power law with constants A = %.4e, B = %.4e\\n\", fescMH_alpha, fescMH_beta);\n\n break;\n \n }\n\n return EXIT_SUCCESS;\n\n}\n", "meta": {"hexsha": "9c9428dc3ed01889d230e5ab816c187df1725f63", "size": 14760, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sage/core_init.c", "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_issues_repo_path": "src/sage/core_init.c", "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_forks_repo_path": "src/sage/core_init.c", "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "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": 29.7580645161, "max_line_length": 265, "alphanum_fraction": 0.6740514905, "num_tokens": 4430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1867701468018976}} {"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"psrsalsa.h\"\ntypedef struct {\n size_t n;\n double *x;\n double *y;\n double *sigma;\n fitfunc_collection_type *fitfunction;\n size_t iter;\n}levmar_internal_fitter_data_def;\nstatic levmar_internal_fitter_data_def levmar_internal_fitter_data;\ntypedef struct {\n gsl_vector_view func_params;\n const gsl_multifit_fdfsolver_type *solver_type;\n gsl_multifit_function_fdf user_itteration_funcs;\n gsl_multifit_fdfsolver *solver;\n gsl_matrix *covar;\n}levmar_internal_gsl_info;\ntypedef struct {\n double *covar;\n double *alpha;\n double *beta;\n double *alpha_tmp;\n double *beta_tmp;\n double *func_params_laststep;\n double *derivatives;\n double alambda;\n double chisq;\n long nrfitparams;\n levmar_internal_fitter_data_def *data;\n}levmar_internal_psrsalsa_info;\nvoid print_gsl_version_used(FILE *stream)\n{\n int major, minor;\n major = GSL_VERSION_NUMBER/100.0;\n minor = GSL_VERSION_NUMBER-100*major;\n fprintf(stream, \"%s (header) %d.%d (specified during compilation)\", GSL_VERSION, major, minor);\n}\ndouble evaluate_fitfunc_collection(fitfunc_collection_type *function, double x, verbose_definition verbose)\n{\n int i;\n double y;\n y = 0;\n for(i = 0; i < function->nrfuncs; i++) {\n if(function->func[i].type == FUNC_POLYNOMAL) {\n y += function->func[i].value[0]*pow(x, function->func[i].param[0]);\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR evaluate_fitfunction_collection: Unknown funtional type in specified function.\");\n exit(0);\n }\n }\n return y;\n}\ndouble evaluate_fitfunc_collection_deriv_param(fitfunc_collection_type *function, int functionnr, int paramnr, double x, verbose_definition verbose)\n{\n if(function->func[functionnr].type == FUNC_POLYNOMAL) {\n if(paramnr == 0) {\n return pow(x, function->func[functionnr].param[0]);\n }\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR evaluate_fitfunc_collection_deriv_param: Unknown funtional type in specified function.\");\n exit(0);\n }\n fflush(stdout);\n printerror(verbose.debug, \"ERROR evaluate_fitfunc_collection_deriv_param: Unknown paramer number specified for given funtional type.\");\n exit(0);\n}\nint print_fitfunctions(fitfunc_collection_type *function, int novalue, int showerror, int index, verbose_definition verbose)\n{\n int i, j, n;\n if(showerror)\n showerror = 1;\n for(n = 0; n <= showerror; n++) {\n if(n == 0)\n printf(\"y = \");\n j = 1;\n for(i = 0; i < function->nrfuncs; i++) {\n if(index == i || index < 0) {\n if(function->func[i].type == FUNC_POLYNOMAL) {\n if(novalue || showerror) {\n if(showerror && n == 1) {\n printf(\" a%d = %13e +- %13e (%lf +- %lf)\\n\", j, function->func[i].value[0], function->func[i].error[0], function->func[i].value[0], function->func[i].error[0]);\n }else {\n printf(\"a%d*x**%lf\", j, function->func[i].param[0]);\n }\n }else {\n printf(\"%lf*x**%lf\", function->func[i].value[0], function->func[i].param[0]);\n }\n j += 1;\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR print_fitfunctions: Unrecognized function type.\");\n return 0;\n }\n if(i == function->nrfuncs - 1)\n printf(\"\\n\");\n else if(n == 0)\n printf(\" + \");\n }\n }\n }\n return 1;\n}\nvoid countnrparameters_fitfunction(fitfunc_collection_type *function, int *nrfitparameters)\n{\n int n, fnr, nrvalues;\n *nrfitparameters = 0;\n for(fnr = 0; fnr < function->nrfuncs; fnr++) {\n if(function->func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(0, \"ERROR countnrparameters_fitfunction: Unknown funtional type.\");\n exit(0);\n }\n for(n = 0; n < nrvalues; n++) {\n if(function->func[fnr].fit_flag[n]) {\n *nrfitparameters += 1;\n }\n }\n }\n}\nint set_fitted_parameters_fitfunc_collection(fitfunc_collection_type *function, double *fitparameters, verbose_definition verbose)\n{\n int fnr, nrvalues, valnr, fitparamnr;\n fitparamnr = 0;\n for(fnr = 0; fnr < function->nrfuncs; fnr++) {\n if(function->func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR set_fitted_parameters_fitfunc_collection: Unknown funtional type.\");\n return 0;\n }\n for(valnr = 0; valnr < nrvalues; valnr++) {\n if(function->func[fnr].fit_flag[valnr]) {\n function->func[fnr].value[valnr] = fitparameters[fitparamnr++];\n }\n }\n }\n return 1;\n}\nint levmar_itteration_calc_function_internal_gsl(const gsl_vector *fitparams, void *data, gsl_vector *f)\n{\n int n;\n size_t npts = ((levmar_internal_fitter_data_def *)data)->n;\n double *xdata = ((levmar_internal_fitter_data_def *)data)->x;\n double *ydata = ((levmar_internal_fitter_data_def *)data)->y;\n double *sigma = ((levmar_internal_fitter_data_def *)data)->sigma;\n fitfunc_collection_type *fitfunction_internal = ((levmar_internal_fitter_data_def *)data)->fitfunction;\n double value;\n verbose_definition noverbose;\n cleanVerboseState(&noverbose);\n if(fitparams->stride != 1) {\n printerror(0, \"ERROR levmar_itteration_calc_function_internal_gsl: It is assumed the gsl vectors have a stride of 1.\");\n exit(0);\n }\n fitfunc_collection_type newfunction;\n memcpy(&newfunction, fitfunction_internal, sizeof(fitfunc_collection_type));\n if(set_fitted_parameters_fitfunc_collection(&newfunction, fitparams->data, noverbose) == 0) {\n printerror(0, \"ERROR levmar_itteration_calc_function_internal_gsl: Copying new fit parameters failed.\");\n exit(0);\n }\n for(n = 0; n < npts; n++) {\n value = evaluate_fitfunc_collection(&newfunction, xdata[n], noverbose);\n gsl_vector_set(f, n, (value - ydata[n])/sigma[n]);\n }\n return GSL_SUCCESS;\n}\nint levmar_itteration_calc_deriv_internal_gsl(const gsl_vector *fitparams, void *data, gsl_matrix *J)\n{\n int fnr, j, n, nrvalues, paramnr;\n size_t npts = ((levmar_internal_fitter_data_def *)data)->n;\n double *xdata = ((levmar_internal_fitter_data_def *)data)->x;\n double *sigma = ((levmar_internal_fitter_data_def *)data)->sigma;\n fitfunc_collection_type *fitfunction_internal = ((levmar_internal_fitter_data_def *)data)->fitfunction;\n double deriv;\n verbose_definition noverbose;\n cleanVerboseState(&noverbose);\n if(fitparams->stride != 1) {\n printerror(0, \"ERROR levmar_itteration_calc_function_internal_gsl: It is assumed the gsl vectors have a stride of 1.\");\n exit(0);\n }\n fitfunc_collection_type newfunction;\n memcpy(&newfunction, fitfunction_internal, sizeof(fitfunc_collection_type));\n if(set_fitted_parameters_fitfunc_collection(&newfunction, fitparams->data, noverbose) == 0) {\n printerror(0, \"ERROR levmar_itteration_calc_function_internal_gsl: Copying new fit parameters failed.\");\n exit(0);\n }\n j = 0;\n for(fnr = 0; fnr < newfunction.nrfuncs; fnr++) {\n if(newfunction.func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(noverbose.debug, \"ERROR levmar_itteration_calc_deriv_internal_gsl: Unknown funtional type.\");\n return 0;\n }\n for(paramnr = 0; paramnr < nrvalues; paramnr++) {\n if(newfunction.func[fnr].fit_flag[paramnr]) {\n for(n = 0; n < npts; n++) {\n deriv = evaluate_fitfunc_collection_deriv_param(&newfunction, fnr, paramnr, xdata[n], noverbose);\n gsl_matrix_set(J, n, j, deriv/sigma[n]);\n }\n j++;\n }\n }\n }\n return GSL_SUCCESS;\n}\nint levmar_itteration_calc_func_and_deriv_internal_gsl(const gsl_vector *x, void *data, gsl_vector *f, gsl_matrix *J)\n{\n levmar_itteration_calc_function_internal_gsl(x, data, f);\n levmar_itteration_calc_deriv_internal_gsl(x, data, J);\n return GSL_SUCCESS;\n}\nvoid levmar_itteration_calc_alpha_beta_chi2_internal_psrsalsa(double *params, void *info)\n{\n long curDataPoint, nrDataPoints, curparam, curparam2, nrfitparams, fnr, nrvalues, paramnr;\n double *alpha, *beta, *derivatives, *x, *y, *sigma, chi2, ypred, tmp1, tmp2, tmp3, tmp4;\n verbose_definition noverbose;\n cleanVerboseState(&noverbose);\n nrDataPoints = ((levmar_internal_psrsalsa_info *)info)->data->n;\n x = ((levmar_internal_psrsalsa_info *)info)->data->x;\n y = ((levmar_internal_psrsalsa_info *)info)->data->y;\n sigma = ((levmar_internal_psrsalsa_info *)info)->data->sigma;\n alpha = ((levmar_internal_psrsalsa_info *)info)->alpha;\n beta = ((levmar_internal_psrsalsa_info *)info)->beta;\n derivatives = ((levmar_internal_psrsalsa_info *)info)->derivatives;\n nrfitparams = ((levmar_internal_psrsalsa_info *)info)->nrfitparams;\n fitfunc_collection_type newfunction;\n memcpy(&newfunction, levmar_internal_fitter_data.fitfunction, sizeof(fitfunc_collection_type));\n if(set_fitted_parameters_fitfunc_collection(&newfunction, params, noverbose) == 0) {\n printerror(0, \"ERROR levmar_itteration_calc_func_and_deriv_internal_nr: Copying new fit parameters failed.\");\n exit(0);\n }\n for(curparam = 0; curparam < nrfitparams; curparam++) {\n beta[curparam] = 0;\n for(curparam2 = curparam; curparam2 < nrfitparams; curparam2++) {\n alpha[curparam*nrfitparams+curparam2] = 0;\n }\n }\n chi2 = 0;\n for(curDataPoint = 0; curDataPoint < nrDataPoints; curDataPoint++) {\n ypred = evaluate_fitfunc_collection(&newfunction, x[curDataPoint], noverbose);\n curparam = 0;\n for(fnr = 0; fnr < newfunction.nrfuncs; fnr++) {\n if(newfunction.func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(noverbose.debug, \"ERROR levmar_itteration_calc_alpha_beta_chi2_internal_psrsalsa: Unknown funtional type.\");\n exit(0);\n }\n for(paramnr = 0; paramnr < nrvalues; paramnr++) {\n if(newfunction.func[fnr].fit_flag[paramnr]) {\n derivatives[curparam++] = evaluate_fitfunc_collection_deriv_param(&newfunction, fnr, paramnr, x[curDataPoint], noverbose);\n }\n }\n }\n tmp1 = 1.0/(sigma[curDataPoint]*sigma[curDataPoint]);\n tmp2 = (y[curDataPoint] - ypred);\n tmp3 = tmp1*tmp2;\n chi2 += tmp2*tmp3;\n for(curparam = 0; curparam < nrfitparams; curparam++) {\n tmp4 = derivatives[curparam]*tmp3;\n beta[curparam] += tmp4;\n for(curparam2 = curparam; curparam2 < nrfitparams; curparam2++) {\n alpha[curparam*nrfitparams+curparam2] += derivatives[curparam]*derivatives[curparam2]*tmp1;\n }\n }\n }\n for(curparam = 0; curparam < nrfitparams; curparam++) {\n for(curparam2 = curparam+1; curparam2 < nrfitparams; curparam2++) {\n alpha[curparam2*nrfitparams+curparam] = alpha[curparam*nrfitparams+curparam2];\n }\n }\n ((levmar_internal_psrsalsa_info *)info)->chisq = chi2;\n}\nint initialize_levmar_check_start_and_current_are_the_same(fitfunc_collection_type *function, verbose_definition verbose)\n{\n int fnr, nrvalues, paramnr;\n for(fnr = 0; fnr < function->nrfuncs; fnr++) {\n if(function->func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR levmar_itteration_calc_func_and_deriv_internal_nr: Unknown funtional type.\");\n return 0;\n }\n for(paramnr = 0; paramnr < nrvalues; paramnr++) {\n if(function->func[fnr].fit_flag[paramnr]) {\n if(function->func[fnr].value[paramnr] != function->func[fnr].start[paramnr]) {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR initialize_levmar_check_start_and_current_are_the_same: Start and current value appear to be different (%lf != %lf)\", function->func[fnr].value[paramnr], function->func[fnr].start[paramnr]);\n return 0;\n }\n }\n }\n }\n return 1;\n}\nint levmar_initialize(fitfunc_collection_type *function, double **func_params, double **func_params_err, int *nrfitparameters, double *datax, double *datay, double *datasigma, long nrdatapoints, levmar_internal_gsl_info *gsl_params, levmar_internal_psrsalsa_info *psrsalsa_params,\n#ifdef NRAVAIL\nlevmar_internal_nr_info *nr_params,\n#endif\nint algorithm, int mode, int showcovariance, verbose_definition verbose)\n{\n int fnr, nrvalues, paramnr, n, n2;\n if(mode == 0) {\n countnrparameters_fitfunction(function, nrfitparameters);\n if(verbose.verbose) printf(\" Initializing fitter with %d fit parameters\\n\", *nrfitparameters);\n }else if(mode == 1) {\n levmar_internal_fitter_data.n = nrdatapoints;\n levmar_internal_fitter_data.x = datax;\n levmar_internal_fitter_data.y = datay;\n levmar_internal_fitter_data.sigma = datasigma;\n levmar_internal_fitter_data.fitfunction = function;\n *func_params = malloc(*nrfitparameters*sizeof(double));\n *func_params_err = malloc(*nrfitparameters*sizeof(double));\n if(*func_params == NULL || *func_params_err == NULL) {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR levmar_initialize: Cannot allocate memory\");\n return 0;\n }\n paramnr = 0;\n for(fnr = 0; fnr < function->nrfuncs; fnr++) {\n if(function->func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR levmar_initialize: Unknown funtional type.\");\n return 0;\n }\n for(n = 0; n < nrvalues; n++) {\n if(function->func[fnr].fit_flag[n]) {\n (*func_params)[paramnr++] = function->func[fnr].value[n];\n }\n function->func[fnr].error[n] = sqrt(-1);\n }\n }\n if(algorithm == 1) {\n gsl_params->func_params = gsl_vector_view_array(*func_params, *nrfitparameters);\n gsl_params->covar = gsl_matrix_alloc(*nrfitparameters, *nrfitparameters);\n gsl_params->user_itteration_funcs.f = &levmar_itteration_calc_function_internal_gsl;\n gsl_params->user_itteration_funcs.df = &levmar_itteration_calc_deriv_internal_gsl;\n gsl_params->user_itteration_funcs.fdf = &levmar_itteration_calc_func_and_deriv_internal_gsl;\n gsl_params->user_itteration_funcs.n = nrdatapoints;\n gsl_params->user_itteration_funcs.p = *nrfitparameters;\n gsl_params->user_itteration_funcs.params = &levmar_internal_fitter_data;\n gsl_params->solver_type = gsl_multifit_fdfsolver_lmsder;\n gsl_params->solver = gsl_multifit_fdfsolver_alloc (gsl_params->solver_type, nrdatapoints, *nrfitparameters);\n gsl_multifit_fdfsolver_set(gsl_params->solver, &(gsl_params->user_itteration_funcs), &(gsl_params->func_params.vector));\n }else if(algorithm == 2) {\n psrsalsa_params->func_params_laststep = malloc(sizeof(double)*(*nrfitparameters));\n psrsalsa_params->beta = malloc(sizeof(double)*(*nrfitparameters));\n psrsalsa_params->derivatives = malloc(sizeof(double)*(*nrfitparameters));\n psrsalsa_params->covar = malloc(sizeof(double)*(*nrfitparameters)*(*nrfitparameters));\n psrsalsa_params->alpha = malloc(sizeof(double)*(*nrfitparameters)*(*nrfitparameters));\n psrsalsa_params->alpha_tmp = malloc(sizeof(double)*(*nrfitparameters)*(*nrfitparameters));\n psrsalsa_params->beta_tmp = malloc(sizeof(double)*(*nrfitparameters));\n if(psrsalsa_params->func_params_laststep == NULL || psrsalsa_params->beta == NULL || psrsalsa_params->derivatives == NULL || psrsalsa_params->alpha == NULL || psrsalsa_params->covar == NULL || psrsalsa_params->beta_tmp == NULL || psrsalsa_params->alpha_tmp == NULL) {\n printerror(verbose.debug, \"ERROR levmar_initialize: Memory allocation error\");\n return 0;\n }\n psrsalsa_params->nrfitparams = *nrfitparameters;\n psrsalsa_params->data = &levmar_internal_fitter_data;\n psrsalsa_params->alambda = 0.001;\n levmar_itteration_calc_alpha_beta_chi2_internal_psrsalsa(*func_params, psrsalsa_params);\n }else if(algorithm == 3) {\n#ifdef NRAVAIL\n nr_params->ia = malloc(sizeof(int)*(*nrfitparameters));\n nr_params->func_params_laststep = malloc(sizeof(double)*(*nrfitparameters));\n if(nr_params->ia == NULL || nr_params->func_params_laststep == NULL) {\n printerror(verbose.debug, \"ERROR levmar_initialize: Memory allocation error\");\n return 0;\n }\n for(n = 0; n < *nrfitparameters; n++)\n nr_params->ia[n] = 1;\n double **matrix_nr_d(long nrl, long nrh, long ncl, long nch);\n nr_params->covar = matrix_nr_d(1, *nrfitparameters, 1, *nrfitparameters);\n nr_params->alpha = matrix_nr_d(1, *nrfitparameters, 1, *nrfitparameters);\n void mrqmin_nr_d(double x[], double y[], double sig[], int ndata, double a[], int ia[],\n int ma, double **covar, double **alpha, double *chisq,\n void (*funcs)(double, double [], double *, double [], int), double *alamda);\n nr_params->alambda = -1;\n mrqmin_nr_d(levmar_internal_fitter_data.x-1, levmar_internal_fitter_data.y-1, levmar_internal_fitter_data.sigma-1, nrdatapoints, (*func_params)-1, nr_params->ia-1, *nrfitparameters, nr_params->covar, nr_params->alpha, &nr_params->chisq, levmar_itteration_calc_func_and_deriv_internal_nr, &(nr_params->alambda));\n#else\n printerror(verbose.debug, \"ERROR levmar_initialize: Code is not compiled with NR support\");\n return 0;\n#endif\n }\n }else if(mode == 2) {\n paramnr = 0;\n for(fnr = 0; fnr < function->nrfuncs; fnr++) {\n if(function->func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(0, \"ERROR levmar_initialize: Unknown funtional type.\");\n return 0;\n }\n for(n = 0; n < nrvalues; n++) {\n if(function->func[fnr].fit_flag[n]) {\n function->func[fnr].value[n] = (*func_params)[paramnr];\n function->func[fnr].error[n] = (*func_params_err)[paramnr];\n paramnr++;\n }\n }\n }\n if(algorithm == 1) {\n if(showcovariance) {\n printf(\"Covariance matrix: \\n\");\n for(n = 0; n < *nrfitparameters; n++) {\n for(n2 = 0; n2 < *nrfitparameters; n2++) {\n printf(\"%lf \", gsl_matrix_get(gsl_params->covar,n,n2));\n }\n printf(\"\\n\");\n }\n }\n gsl_multifit_fdfsolver_free(gsl_params->solver);\n gsl_matrix_free(gsl_params->covar);\n }else if(algorithm == 2) {\n if(showcovariance) {\n printf(\"Covariance matrix: \\n\");\n for(n = 0; n < *nrfitparameters; n++) {\n for(n2 = 0; n2 < *nrfitparameters; n2++) {\n printf(\"%lf \", psrsalsa_params->covar[n*(*nrfitparameters)+n2]);\n }\n printf(\"\\n\");\n }\n }\n free(psrsalsa_params->beta);\n free(psrsalsa_params->derivatives);\n free(psrsalsa_params->alpha);\n free(psrsalsa_params->covar);\n free(psrsalsa_params->func_params_laststep);\n free(psrsalsa_params->alpha_tmp);\n free(psrsalsa_params->beta_tmp);\n }else if(algorithm == 3) {\n#ifdef NRAVAIL\n if(showcovariance) {\n printf(\"Covariance matrix: \\n\");\n for(n = 0; n < *nrfitparameters; n++) {\n for(n2 = 0; n2 < *nrfitparameters; n2++) {\n printf(\"%lf \", nr_params->covar[n+1][n2+1]);\n }\n printf(\"\\n\");\n }\n }\n void free_matrix_nr_d(double **m, long nrl, long nrh, long ncl, long nch);\n free_matrix_nr_d(nr_params->covar, 1, *nrfitparameters, 1, *nrfitparameters);\n free_matrix_nr_d(nr_params->alpha, 1, *nrfitparameters, 1, *nrfitparameters);\n free(nr_params->ia);\n free(nr_params->func_params_laststep);\n#else\n printerror(verbose.debug, \"ERROR levmar_initialize: Code is not compiled with NR support\");\n return 0;\n#endif\n }\n free(*func_params);\n free(*func_params_err);\n }\n return 1;\n}\nint fit_levmar_internal(int algorithm, int nrdatapoints, int nrfitparameters, double *func_params, double *func_params_err, levmar_internal_gsl_info *gsl_params, levmar_internal_psrsalsa_info *psrsalsa_params,\n#ifdef NRAVAIL\n levmar_internal_nr_info *nr_params,\n#endif\n double epsabs, double epsrel, int maxiter, verbose_definition verbose)\n{\n int status, i, converged;\n long iter;\n double chisq_last_nr;\n#ifdef NRAVAIL\n void mrqmin_nr_d(double x[], double y[], double sig[], int ndata, double a[], int ia[],\n int ma, double **covar, double **alpha, double *chisq,\n void (*funcs)(double, double [], double *, double [], int), double *alamda);\n#else\n if(algorithm == 3) {\n printerror(verbose.debug, \"ERROR fit_levmar_internal: Code is not compiled with NR support\");\n return 0;\n }\n#endif\n if(algorithm == 2) {\n memcpy(psrsalsa_params->func_params_laststep, func_params, sizeof(double)*nrfitparameters);\n chisq_last_nr = psrsalsa_params->chisq;\n#ifdef NRAVAIL\n }else if(algorithm == 3) {\n memcpy(nr_params->func_params_laststep, func_params, sizeof(double)*nrfitparameters);\n chisq_last_nr = nr_params->chisq;\n#endif\n }\n iter = 0;\n do {\n iter++;\n levmar_internal_fitter_data.iter += 1;\n if(algorithm == 1) {\n status = gsl_multifit_fdfsolver_iterate(gsl_params->solver);\n if(status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG) {\n int status2;\n status2 = gsl_multifit_test_delta(gsl_params->solver->dx, gsl_params->solver->x, epsabs, epsrel);\n if(status2 == GSL_SUCCESS) {\n status = 0;\n }else {\n if(verbose.debug == 0) {\n printwarning(verbose.debug, \"Machine precision reached, but required precision tolerance conditions are not met.\");\n }else {\n printwarning(verbose.debug, \"Machine precision reached, but required precision tolerance conditions are not met:\");\n for(i = 0; i < nrfitparameters; i++) {\n printwarning(verbose.debug, \"parameter %d: value=%e stepsize=%e\", i+1, gsl_vector_get(gsl_params->solver->x, i), gsl_vector_get(gsl_params->solver->dx, i));\n }\n }\n }\n }\n if(verbose.debug) {\n printf(\"fit_levmar_internal: itteration %ld - status = %s\\n\", iter, gsl_strerror(status));\n }\n if(status) {\n break;\n }else {\n status = gsl_multifit_test_delta(gsl_params->solver->dx, gsl_params->solver->x, epsabs, epsrel);\n }\n }else if(algorithm == 2) {\n for(i = 0; i < nrfitparameters*nrfitparameters; i++)\n psrsalsa_params->alpha_tmp[i] = psrsalsa_params->alpha[i];\n for(i = 0; i < nrfitparameters; i++)\n psrsalsa_params->beta_tmp[i] = psrsalsa_params->beta[i];\n for (i = 0; i < nrfitparameters; i++) {\n psrsalsa_params->alpha[i*nrfitparameters+i] *= 1.0+psrsalsa_params->alambda;\n }\n int linalg_solve_matrix_eq_gauss_jordan(double *matrixa, double *matrixb, int n, int m, verbose_definition verbose);\n if(linalg_solve_matrix_eq_gauss_jordan(psrsalsa_params->alpha, psrsalsa_params->beta, nrfitparameters, 1, verbose) != 0) {\n printerror(verbose.debug, \"ERROR fit_levmar_internal: Solving matrix equation failed.\");\n return 9;\n }\n for (i = 0; i < nrfitparameters; i++)\n func_params[i] += psrsalsa_params->beta[i];\n levmar_itteration_calc_alpha_beta_chi2_internal_psrsalsa(func_params, psrsalsa_params);\n status = GSL_SUCCESS;\n if(chisq_last_nr < psrsalsa_params->chisq) {\n status = GSL_ETOLF;\n memcpy(func_params, psrsalsa_params->func_params_laststep, sizeof(double)*nrfitparameters);\n for(i = 0; i < nrfitparameters*nrfitparameters; i++)\n psrsalsa_params->alpha[i] = psrsalsa_params->alpha_tmp[i];\n for(i = 0; i < nrfitparameters; i++)\n psrsalsa_params->beta[i] = psrsalsa_params->beta_tmp[i];\n psrsalsa_params->alambda *= 10.1;\n }\n converged = 1;\n for(i = 0; i < nrfitparameters; i++) {\n if(fabs(func_params[i] - psrsalsa_params->func_params_laststep[i]) >= 1.2e-16+epsabs+epsrel*fabs(psrsalsa_params->func_params_laststep[i])) {\n converged = 0;\n break;\n }\n }\n if(converged && status == GSL_ETOLF)\n status = GSL_SUCCESS;\n if(status == GSL_ETOLF) {\n printwarning(verbose.debug, \"Machine precision reached, but required precision tolerance conditions are not met.\");\n }else if(converged == 0) {\n status = GSL_CONTINUE;\n }\n if(chisq_last_nr > psrsalsa_params->chisq) {\n memcpy(psrsalsa_params->func_params_laststep, func_params, sizeof(double)*nrfitparameters);\n chisq_last_nr = psrsalsa_params->chisq;\n psrsalsa_params->alambda *= 0.1;\n }\n if(verbose.debug) {\n printf(\"fit_levmar_internal: itteration %ld - status = %s\\n\", iter, gsl_strerror(status));\n }\n#ifdef NRAVAIL\n }else if(algorithm == 3) {\n mrqmin_nr_d(levmar_internal_fitter_data.x-1, levmar_internal_fitter_data.y-1, levmar_internal_fitter_data.sigma-1, nrdatapoints, func_params-1, nr_params->ia-1, nrfitparameters, nr_params->covar, nr_params->alpha, &(nr_params->chisq), levmar_itteration_calc_func_and_deriv_internal_nr, &(nr_params->alambda));\n status = GSL_SUCCESS;\n for(i = 0; i < nrfitparameters; i++) {\n if(fabs(func_params[i] - nr_params->func_params_laststep[i]) >= epsabs+epsrel*fabs(nr_params->func_params_laststep[i])) {\n status = GSL_CONTINUE;\n break;\n }\n }\n if(verbose.debug) {\n printf(\"fit_levmar_internal: itteration %ld - status = %s\\n\", iter, gsl_strerror(status));\n }\n if(status == GSL_CONTINUE) {\n if(chisq_last_nr <= nr_params->chisq) {\n status = GSL_ETOLF;\n printwarning(verbose.debug, \"Machine precision reached, but required precision tolerance conditions are not met.\");\n }else {\n memcpy(nr_params->func_params_laststep, func_params, sizeof(double)*nrfitparameters);\n chisq_last_nr = nr_params->chisq;\n }\n }\n#endif\n }\n }while(status == GSL_CONTINUE && iter < maxiter);\n if(algorithm == 1) {\n#if GSL_VERSION_NUMBER >= 200\n if(verbose.debug) {\n printf(\"fit_levmar_internal: Entering gsl >= 2.0 specific part of the code\\n\");\n }\n gsl_matrix *J = gsl_matrix_alloc(nrdatapoints, nrfitparameters);\n gsl_multifit_fdfsolver_jac(gsl_params->solver, J);\n gsl_multifit_covar(J, 0.0, gsl_params->covar);\n#else\n if(verbose.debug) {\n printf(\"fit_levmar_internal: Entering gsl < 2.0 specific part of the code\\n\");\n }\n gsl_multifit_covar(gsl_params->solver->J, 0.0, gsl_params->covar);\n#endif\n levmar_internal_fitter_data.fitfunction->chi2 = gsl_blas_dnrm2(gsl_params->solver->f);\n levmar_internal_fitter_data.fitfunction->chi2_red = (levmar_internal_fitter_data.fitfunction->chi2)/sqrt(nrdatapoints - nrfitparameters);\n levmar_internal_fitter_data.fitfunction->chi2_red *= levmar_internal_fitter_data.fitfunction->chi2_red;\n levmar_internal_fitter_data.fitfunction->chi2 *= levmar_internal_fitter_data.fitfunction->chi2;\n }else if(algorithm == 2) {\n int linalg_solve_matrix_eq_gauss_jordan(double *matrixa, double *matrixb, int n, int m, verbose_definition verbose);\n if(linalg_solve_matrix_eq_gauss_jordan(psrsalsa_params->alpha, psrsalsa_params->beta, nrfitparameters, 1, verbose) != 0) {\n printerror(verbose.debug, \"ERROR fit_levmar_internal: Solving matrix equation failed.\");\n return 9;\n }\n for(i = 0; i < nrfitparameters*nrfitparameters; i++)\n psrsalsa_params->covar[i] = psrsalsa_params->alpha[i];\n levmar_internal_fitter_data.fitfunction->chi2 = psrsalsa_params->chisq;\n levmar_internal_fitter_data.fitfunction->chi2_red = psrsalsa_params->chisq/(double)(nrdatapoints - nrfitparameters);\n#ifdef NRAVAIL\n }else if(algorithm == 3) {\n nr_params->alambda = 0;\n mrqmin_nr_d(levmar_internal_fitter_data.x-1, levmar_internal_fitter_data.y-1, levmar_internal_fitter_data.sigma-1, nrdatapoints, func_params-1, nr_params->ia-1, nrfitparameters, nr_params->covar, nr_params->alpha, &nr_params->chisq, levmar_itteration_calc_func_and_deriv_internal_nr, &nr_params->alambda);\n levmar_internal_fitter_data.fitfunction->chi2 = nr_params->chisq;\n levmar_internal_fitter_data.fitfunction->chi2_red = nr_params->chisq/(double)(nrdatapoints - nrfitparameters);\n#endif\n }\n if(verbose.debug) {\n printf(\"chisq/dof = %g after %ld iterations\\n\", levmar_internal_fitter_data.fitfunction->chi2_red, iter);\n }\n if(algorithm == 1) {\n for(i = 0; i < nrfitparameters; i++) {\n func_params[i] = gsl_vector_get(gsl_params->solver->x, i);\n func_params_err[i] = sqrt(gsl_matrix_get(gsl_params->covar,i,i));\n }\n }else if(algorithm == 2) {\n for(i = 0; i < nrfitparameters; i++) {\n func_params_err[i] = sqrt(psrsalsa_params->covar[i*nrfitparameters+i]);\n }\n#ifdef NRAVAIL\n }else if(algorithm == 3) {\n for(i = 0; i < nrfitparameters; i++) {\n func_params_err[i] = sqrt(nr_params->covar[i+1][i+1]);\n }\n#endif\n }\n if(levmar_internal_fitter_data.iter == maxiter)\n return 2;\n if(algorithm == 1) {\n if(status == 0)\n return 0;\n if(status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG) {\n return 3;\n }\n if(status == GSL_ENOPROG) {\n fflush(stdout);\n printerror(verbose.debug, \"fit_levmar_internal: Cannot determine suitable trial step. Continue itterating might help\");\n return 4;\n }\n }else if(algorithm == 2 || algorithm == 3) {\n return 0;\n }\n fflush(stdout);\n printerror(verbose.debug, \"fit_levmar_internal: UNKNOWN RETURN CODE\");\n return 10;\n}\nint fit_levmar(int algorithm, fitfunc_collection_type *function, double *data_x, double *data_y, double *data_sigma, long ndata, int oneatatime, int force_chi2_1, double epsabs, double epsrel, int maxiter, int *status, int showresults, int showcovariance, verbose_definition verbose)\n{\n int loopnr, improved, i, j, k, fnr, valuenr, nrfitparameters_one, nrfitparameters, free_data_sigma, nrvalues;\n double old_chi2, sig_scale, *func_params, *func_params_err;\n verbose_definition noverbose;\n levmar_internal_gsl_info gsl_params;\n levmar_internal_psrsalsa_info psrsalsa_params;\n#ifndef NRAVAIL\n if(algorithm == 3) {\n printerror(verbose.debug, \"ERROR fit_levmar: Code is not compiled with NR support\");\n return 0;\n }\n#else\n levmar_internal_nr_info nr_params;\n#endif\n cleanVerboseState(&noverbose);\n noverbose.nocounters = 1;\n if(verbose.verbose) {\n printf(\"Levenberg-Marquardt algorithm:\\n\");\n if(verbose.debug) {\n printf(\" Fit function: \");\n print_fitfunctions(function, 1, 0, -1, verbose);\n }\n }\n if(initialize_levmar_check_start_and_current_are_the_same(function, verbose) == 0) {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR fit_levmar: Start and current value appear to be different\");\n return 1;\n }\n free_data_sigma = 0;\n if(data_sigma == NULL) {\n data_sigma = malloc(ndata*sizeof(double));\n for(i = 0; i < ndata; i++)\n data_sigma[i] = 1;\n free_data_sigma = 1;\n force_chi2_1 = 1;\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 0, showcovariance, verbose) == 0) {\n return 1;\n }\n levmar_internal_fitter_data.iter = 0;\n if(oneatatime == 0) {\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 1, showcovariance, verbose) == 0) {\n return 1;\n }\n *status = fit_levmar_internal(algorithm, ndata, nrfitparameters, func_params, func_params_err, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n epsabs, epsrel, maxiter, verbose);\n }else {\n fitfunc_collection_type *original_function;\n original_function = malloc(sizeof(fitfunc_collection_type));\n if(original_function == NULL) {\n printerror(verbose.debug, \"ERROR fit_levmar: Memory allocation error.\");\n return 1;\n }\n memcpy(original_function, function, sizeof(fitfunc_collection_type));\n old_chi2 = -1;\n loopnr = 0;\n do {\n improved = 0;\n i = 0;\n for(fnr = 0; fnr < function->nrfuncs; fnr++) {\n if(function->func[fnr].type == FUNC_POLYNOMAL) {\n nrvalues = 1;\n }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR fit_levmar: Unknown funtional type.\");\n return 1;\n }\n for(valuenr = 0; valuenr < nrvalues; valuenr++) {\n if(original_function->func[fnr].fit_flag[valuenr]) {\n for(j = 0; j < function->nrfuncs; j++) {\n for(k = 0; k < MaxNrFitParameters; k++)\n function->func[j].fit_flag[k] = 0;\n }\n function->func[fnr].fit_flag[valuenr] = 1;\n if(verbose.debug) {\n printf(\" Loop %d: chi2 = %f\", loopnr, old_chi2);\n printf(\"\\n\");\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters_one, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 0, showcovariance, noverbose) == 0) {\n free(original_function);\n return 1;\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters_one, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 1, showcovariance, verbose) == 0) {\n free(original_function);\n return 1;\n }\n *status = fit_levmar_internal(algorithm, ndata, nrfitparameters_one, func_params, func_params_err, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n epsabs, epsrel, maxiter, verbose);\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters_one, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 2, showcovariance, verbose) == 0) {\n free(original_function);\n return 1;\n }\n if(function->chi2 < old_chi2 || old_chi2 < 0) {\n old_chi2 = function->chi2;\n improved = 1;\n }\n loopnr++;\n i++;\n }\n }\n }\n }while(improved);\n for(j = 0; j < function->nrfuncs; j++) {\n for(k = 0; k < MaxNrFitParameters; k++)\n function->func[j].fit_flag[k] = original_function->func[j].fit_flag[k];\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 0, showcovariance, verbose) == 0) {\n free(original_function);\n return 1;\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 1, showcovariance, verbose) == 0) {\n free(original_function);\n return 1;\n }\n *status = fit_levmar_internal(algorithm, ndata, nrfitparameters, func_params, func_params_err, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n epsabs, epsrel, maxiter, verbose);\n free(original_function);\n }\n if(verbose.verbose) {\n printf(\" After %ld iterations found chisq/dof = %g\\n\", levmar_internal_fitter_data.iter, levmar_internal_fitter_data.fitfunction->chi2_red);\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 2, showcovariance, verbose) == 0) {\n return 1;\n }\n if(force_chi2_1) {\n sig_scale = sqrt(function->chi2_red);\n for(i = 0; i < ndata; i++) {\n data_sigma[i] *= sig_scale;\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 0, showcovariance, verbose) == 0) {\n return 1;\n }\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 1, showcovariance, verbose) == 0) {\n return 1;\n }\n *status = fit_levmar_internal(algorithm, ndata, nrfitparameters, func_params, func_params_err, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n epsabs, epsrel, maxiter, verbose);\n if(levmar_initialize(function, &func_params, &func_params_err, &nrfitparameters, data_x, data_y, data_sigma, ndata, &gsl_params, &psrsalsa_params,\n#ifdef NRAVAIL\n &nr_params,\n#endif\n algorithm, 2, showcovariance, verbose) == 0) {\n return 1;\n }\n }\n if(verbose.verbose || showresults) {\n printf(\" Fit function: \");\n print_fitfunctions(function, 0, 1, -1, verbose);\n printf(\" \");\n print_fitfunctions(function, 0, 0, -1, verbose);\n printf(\"\\n chi2 = %f\\n reduced chi2 = %f (%ld points - %d params)\\n\", function->chi2, function->chi2_red, ndata, nrfitparameters);\n }\n if(free_data_sigma) {\n free(data_sigma);\n data_sigma = NULL;\n }\n return *status;\n}\n", "meta": {"hexsha": "cff3ff27091a6b12f9b853c2cdd3d41162ca045d", "size": 37516, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/fitting.c", "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/lib/fitting.c", "max_issues_repo_name": "David-McKenna/psrsalsa", "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/lib/fitting.c", "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 41.408388521, "max_line_length": 755, "alphanum_fraction": 0.7032999254, "num_tokens": 10642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18248938347718766}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hdf5.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \"mclib_3d.h\"\n#include \"mclib.h\"\n#include \n#include \"mpi.h\"\n#include \"mc_synch.h\"\n\n#define PROP_DIM1 1\n#define PROP_DIM2 8\n#define PROP_DIM3 8\n#define COORD_DIM1 2\n#define R_DIM_2D 9120\n#define THETA_DIM_2D 2000\n\n//define constants\nconst double A_RAD=7.56e-15, C_LIGHT=2.99792458e10, PL_CONST=6.6260755e-27, FINE_STRUCT=7.29735308e-3, CHARGE_EL= 4.8032068e-10;\nconst double K_B=1.380658e-16, M_P=1.6726231e-24, THOM_X_SECT=6.65246e-25, M_EL=9.1093879e-28 , R_EL=2.817941499892705e-13;\n\nint getOrigNumProcesses(int *counted_cont_procs, int **proc_array, char dir[200], int angle_rank, int angle_procs, int last_frame)\n{\n int i=0, j=0, val=0, original_num_procs=-1, rand_num=0;\n int frame2=0, framestart=0, scatt_framestart=0, ph_num=0;\n double time=0;\n char mc_chkpt_files[200]=\"\", restrt=\"\"; //define new variable that wont write over the restrt variable in the main part of the code, when its put into the readCheckpoint function\n struct photon *phPtr=NULL; //pointer to array of photons \n //DIR * dirp;\n //struct dirent * entry;\n //struct stat st = {0};\n glob_t files;\n \n //if (angle_rank==0)\n {\n //find number of mc_checkpt files there are\n //loop through them and find out which prior processes didnt finish and keep track of which ones didnt\n snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), \"%s%s\", dir,\"mc_chkpt_*\" );\n val=glob(mc_chkpt_files, 0, NULL,&files );\n \n //printf(\"TEST: %s\\n\", mc_chkpt_files);\n \n //look @ a file by choosing rand int between 0 and files.gl_pathc and if the file exists open and read it to get the actual value for the old number of angle_procs\n srand(angle_rank);\n //printf(\"NUM_FILES: %d\\n\",files.gl_pathc);\n \n rand_num=rand() % files.gl_pathc;\n snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), \"%s%s%d%s\", dir,\"mc_chkpt_\", rand_num,\".dat\" );\n //printf(\"TEST: %s\\n\", mc_chkpt_files);\n \n if ( access( mc_chkpt_files, F_OK ) == -1 )\n {\n while(( access( mc_chkpt_files, F_OK ) == -1 ) )\n {\n rand_num=rand() % files.gl_pathc;\n snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), \"%s%s%d%s\", dir,\"mc_chkpt_\", rand_num,\".dat\" );\n //printf(\"TEST: %s\\n\", mc_chkpt_files);\n }\n }\n readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, rand_num, &original_num_procs);\n \n //original_num_procs= 70;\n \n \n }\n \n int count_procs[original_num_procs], count=0;\n int cont_procs[original_num_procs];\n //create array of files including any checkpoint file which may not have been created yet b/c old process was still in 1st frame of scattering\n \n for (j=0;jweight != 0)\n {\n p0[count]= ((ph+i)->p0);\n p1[count]= ((ph+i)->p1);\n p2[count]= ((ph+i)->p2);\n p3[count]= ((ph+i)->p3); \n r0[count]= ((ph+i)->r0);\n r1[count]= ((ph+i)->r1);\n r2[count]= ((ph+i)->r2);\n s0[count]= ((ph+i)->s0);\n s1[count]= ((ph+i)->s1);\n s2[count]= ((ph+i)->s2);\n s3[count]= ((ph+i)->s3);\n num_scatt[count]= ((ph+i)->num_scatt);\n //if ((frame==frame_inj) || ((scatt_synch_num_ph > 0) && ((ph+i)->type == COMPTONIZED_PHOTON))) //if the frame is the same one that the photons were injected in, save the photon weights OR if there are synchrotron photons that havent been absorbed\n {\n weight[weight_net_num_ph]= ((ph+i)->weight);\n weight_net_num_ph++;\n //fprintf(fPtr, \"%d %c %e %e %e %e %e %e %e %e\\n\", i, (ph+i)->type, (ph+i)->r0, (ph+i)->r1, (ph+i)->r2, (ph+i)->num_scatt, (ph+i)->weight, (ph+i)->p0, (ph+i)->comv_p0, (ph+i)->p0*C_LIGHT/1.6e-9);\n }\n \n if ((frame==frame_last))\n {\n global_weight[count]=((ph+i)->weight);\n }\n \n *(ph_type+count)=(ph+i)->type;\n //printf(\"%d %c %e %e %e %e %e %e %e %e %c\\n\", i, (ph+i)->type, (ph+i)->r0, (ph+i)->r1, (ph+i)->r2, (ph+i)->num_scatt, (ph+i)->weight, (ph+i)->p0, (ph+i)->comv_p0, (ph+i)->p0*C_LIGHT/1.6e-9, *(ph_type+count));\n \n count++;\n }\n \n }\n \n \n //make strings for file name and group\n snprintf(mc_file,sizeof(mc_file),\"%s%s%d%s\",dir,\"mc_proc_\", angle_rank, \".h5\" );\n snprintf(group,sizeof(mc_file),\"%d\",frame );\n \n //see if file exists, if not create it, if it does just open it\n status = H5Eset_auto(NULL, NULL, NULL); //turn off automatic error printing\n file_init=H5Fcreate(mc_file, H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT); //see if the file initially does/doesnt exist\n file=file_init;\n status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //turn on auto error printing\n\n \n if (file_init<0)\n {\n //the file exists, open it with read write \n file=H5Fopen(mc_file, H5F_ACC_RDWR, H5P_DEFAULT);\n //fprintf(fPtr,\"In IF\\n\");\n \n //see if the group exists\n status = H5Eset_auto(NULL, NULL, NULL);\n status_group = H5Gget_objinfo (file, group, 0, NULL);\n status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n \n \n \n /*\n fprintf(fPtr, group);\n if (status_group == 0)\n { \n fprintf (fPtr, \"The group exists.\\n\");\n //now try to see if there's a weight data set for this group\n }\n else \n {\n fprintf (fPtr, \"The group either does NOT exist\\n or some other error occurred.\\n\"); \n }\n */\n }\n \n \n if ((file_init>=0) || (status_group != 0) )\n {\n //printf(\"In IF\\n\");\n //if the file exists, see if the weight exists\n //snprintf(group_weight,sizeof(group),\"/PW\",i );\n status = H5Eset_auto(NULL, NULL, NULL);\n status_weight = H5Gget_objinfo (file, \"/PW\", 0, NULL);\n status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n \n fprintf(fPtr,\"Status of /PW %d\\n\", status_weight);\n \n //the file has been newly created or if the group does not exist then create the group for the frame\n group_id = H5Gcreate2(file, group, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n \n \n /* Modify dataset creation properties, i.e. enable chunking */\n prop = H5Pcreate (H5P_DATASET_CREATE);\n status = H5Pset_chunk (prop, rank, dims);\n \n if ((frame==frame_inj) || (scatt_synch_num_ph > 0))\n {\n prop_weight= H5Pcreate (H5P_DATASET_CREATE);\n status = H5Pset_chunk (prop_weight, rank, dims_weight);\n }\n \n if ((frame==frame_last))\n {\n status = H5Pset_chunk (prop, rank, dims);\n }\n \n /* Create the data space with unlimited dimensions. */\n dspace = H5Screate_simple (rank, dims, maxdims);\n \n dspace_weight=H5Screate_simple (rank, dims_weight, maxdims);\n \n /* Create a new dataset within the file using chunk creation properties. */\n dset_p0 = H5Dcreate2 (group_id, \"P0\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_p1 = H5Dcreate2 (group_id, \"P1\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_p2 = H5Dcreate2 (group_id, \"P2\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_p3 = H5Dcreate2 (group_id, \"P3\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n //if (COMV_SWITCH!=0)\n #if COMV_SWITCH == ON\n {\n dset_comv_p0 = H5Dcreate2 (group_id, \"COMV_P0\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_comv_p1 = H5Dcreate2 (group_id, \"COMV_P1\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_comv_p2 = H5Dcreate2 (group_id, \"COMV_P2\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_comv_p3 = H5Dcreate2 (group_id, \"COMV_P3\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n }\n #endif\n \n dset_r0 = H5Dcreate2 (group_id, \"R0\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_r1 = H5Dcreate2 (group_id, \"R1\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_r2 = H5Dcreate2 (group_id, \"R2\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n //if (STOKES_SWITCH!=0)\n #if STOKES_SWITCH == ON\n {\n dset_s0 = H5Dcreate2 (group_id, \"S0\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_s1 = H5Dcreate2 (group_id, \"S1\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_s2 = H5Dcreate2 (group_id, \"S2\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n dset_s3 = H5Dcreate2 (group_id, \"S3\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n }\n #endif\n \n #if SAVE_TYPE == ON\n {\n dset_ph_type = H5Dcreate2 (group_id, \"PT\", H5T_NATIVE_CHAR, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n }\n #endif\n \n dset_num_scatt = H5Dcreate2 (group_id, \"NS\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n \n if ((frame==frame_inj) || (scatt_synch_num_ph > 0)) //if the frame is the same one that the photons were injected in, save the photon weights or if there are emitted photons that havent been absorbed\n {\n dset_weight_2 = H5Dcreate2 (group_id, \"PW\", H5T_NATIVE_DOUBLE, dspace_weight,\n H5P_DEFAULT, prop_weight, H5P_DEFAULT); //save the new injected photons' weights\n }\n \n if ((frame==frame_last))\n {\n //if saving the injected photons weight dont have to worry about the major ph_weight thats not in a group\n dset_weight = H5Dcreate2 (file, \"PW\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT);\n }\n \n /* Write data to dataset */\n status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, p0);\n \n status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, p1);\n \n status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, p2);\n \n status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, p3);\n \n //if (COMV_SWITCH!=0)\n #if COMV_SWITCH == ON\n {\n status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, comv_p0);\n \n status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, comv_p1);\n \n status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, comv_p2);\n \n status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, comv_p3);\n }\n #endif\n \n status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, r0);\n \n status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, r1);\n \n status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, r2);\n \n //if (STOKES_SWITCH!=0)\n #if STOKES_SWITCH == ON\n {\n status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, s0);\n \n status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, s1);\n \n status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, s2);\n \n status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, s3);\n }\n #endif\n \n #if SAVE_TYPE == ON\n {\n status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, ph_type);\n }\n #endif\n\n \n status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, num_scatt);\n \n if ((frame==frame_inj) || (scatt_synch_num_ph > 0))\n {\n status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, weight);\n \n status = H5Pclose (prop_weight);\n status = H5Dclose (dset_weight_2);\n }\n \n if ((frame==frame_last))\n {\n //printf(\"Before write\\n\");\n status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, global_weight);\n //printf(\"After write\\n\");\n }\n \n status = H5Pclose (prop);\n }\n else\n {\n //if the group already exists then extend it\n //find the size of it now\n \n /* Open an existing group of the specified file. */\n group_id = H5Gopen2(file, group, H5P_DEFAULT);\n dset_p0 = H5Dopen (group_id, \"P0\", H5P_DEFAULT); //open dataset\n \n //get dimensions of array and save it\n dspace = H5Dget_space (dset_p0);\n \n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old\n \n //extend the dataset\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_p0, size);\n \n /* Select a hyperslab in extended portion of dataset */\n fspace = H5Dget_space (dset_p0);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n \n /* Define memory space */\n mspace = H5Screate_simple (rank, dims, NULL);\n \n /* Write the data to the extended portion of dataset */\n status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, p0);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_p1 = H5Dopen (group_id, \"P1\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_p1);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_p1, size);\n fspace = H5Dget_space (dset_p1);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, p1);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_p2 = H5Dopen (group_id, \"P2\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_p2);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_p2, size);\n fspace = H5Dget_space (dset_p2);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, p2);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_p3 = H5Dopen (group_id, \"P3\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_p3);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_p3, size);\n fspace = H5Dget_space (dset_p3);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, p3);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n //if (COMV_SWITCH!=0)\n #if COMV_SWITCH == ON\n {\n dset_comv_p0 = H5Dopen (group_id, \"COMV_P0\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_comv_p0);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_comv_p0, size);\n fspace = H5Dget_space (dset_comv_p0);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, comv_p0);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_comv_p1 = H5Dopen (group_id, \"COMV_P1\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_comv_p1);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_comv_p1, size);\n fspace = H5Dget_space (dset_comv_p1);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, comv_p1);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_comv_p2 = H5Dopen (group_id, \"COMV_P2\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_comv_p2);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_comv_p2, size);\n fspace = H5Dget_space (dset_comv_p2);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, comv_p2);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_comv_p3 = H5Dopen (group_id, \"COMV_P3\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_comv_p3);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_comv_p3, size);\n fspace = H5Dget_space (dset_comv_p3);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, comv_p3);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n }\n #endif\n \n dset_r0 = H5Dopen (group_id, \"R0\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_r0);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_r0, size);\n fspace = H5Dget_space (dset_r0);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, r0);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_r1 = H5Dopen (group_id, \"R1\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_r1);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_r1, size);\n fspace = H5Dget_space (dset_r1);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, r1);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_r2 = H5Dopen (group_id, \"R2\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_r2);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_r2, size);\n fspace = H5Dget_space (dset_r2);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, r2);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n //if (STOKES_SWITCH!=0)\n #if STOKES_SWITCH == ON\n {\n dset_s0 = H5Dopen (group_id, \"S0\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_s0);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_s0, size);\n fspace = H5Dget_space (dset_s0);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, s0);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_s1 = H5Dopen (group_id, \"S1\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_s1);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_s1, size);\n fspace = H5Dget_space (dset_s1);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, s1);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_s2 = H5Dopen (group_id, \"S2\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_s2);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_s2, size);\n fspace = H5Dget_space (dset_s2);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, s2);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n dset_s3 = H5Dopen (group_id, \"S3\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_s3);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_s3, size);\n fspace = H5Dget_space (dset_s3);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, s3);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n }\n #endif\n \n #if SAVE_TYPE == ON\n {\n dset_ph_type = H5Dopen (group_id, \"PT\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_ph_type);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_ph_type, size);\n fspace = H5Dget_space (dset_ph_type);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL);\n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, mspace, fspace,\n H5P_DEFAULT, ph_type);\n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n }\n #endif\n\n \n dset_num_scatt = H5Dopen (group_id, \"NS\", H5P_DEFAULT); //open dataset\n dspace = H5Dget_space (dset_num_scatt);\n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n size[0] = dims[0]+ dims_old[0];\n status = H5Dset_extent (dset_num_scatt, size);\n fspace = H5Dget_space (dset_num_scatt);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims, NULL); \n mspace = H5Screate_simple (rank, dims, NULL);\n status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, num_scatt);\n \n //see if the weights group exists, if it does then we can extend it, otherwise we need to create it and write the new values to it\n snprintf(group_weight,sizeof(group_weight),\"PW\",i );\n status = H5Eset_auto(NULL, NULL, NULL);\n status_weight = H5Gget_objinfo (group_id, \"PW\", 0, NULL);\n status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n \n fprintf(fPtr,\"Status of /frame/PW %d\\n\", status_weight);\n \n //if (((frame==frame_inj) || (scatt_synch_num_ph > 0)) )\n {\n \n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n if (((frame==frame_last)))\n {\n //make sure to append the newly injected/emitted photons from the most recent set of injected photons to the global weights\n \n dset_weight = H5Dopen (file, \"PW\", H5P_DEFAULT); //open dataset\n \n //get dimensions of array and save it\n dspace = H5Dget_space (dset_weight);\n \n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n \n //extend the dataset\n size[0] = dims_weight[0]+ dims_old[0];\n status = H5Dset_extent (dset_weight, size);\n \n /* Select a hyperslab in extended portion of dataset */\n fspace = H5Dget_space (dset_weight);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims_weight, NULL);\n \n /* Define memory space */\n mspace = H5Screate_simple (rank, dims_weight, NULL);\n \n /* Write the data to the extended portion of dataset */\n status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, weight);\n }\n \n if (status_weight >= 0)\n {\n //will have to create the weight dataset for the new set of phtons that have been injected, although it may already be created since emitting photons now\n //see if the group exists\n status = H5Eset_auto(NULL, NULL, NULL);\n status_weight_2 = H5Gget_objinfo (group_id, \"/PW\", 0, NULL);\n status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr);\n \n if (status_weight_2 < 0)\n {\n //the dataset doesnt exist\n /* Modify dataset creation properties, i.e. enable chunking */\n prop = H5Pcreate (H5P_DATASET_CREATE);\n status = H5Pset_chunk (prop, rank, dims);\n \n /* Create the data space with unlimited dimensions. */\n dspace = H5Screate_simple (rank, dims, maxdims);\n \n dset_weight_2 = H5Dcreate2 (group_id, \"PW\", H5T_NATIVE_DOUBLE, dspace,\n H5P_DEFAULT, prop, H5P_DEFAULT); //save the new injected photons' weights\n \n status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, weight);\n \n status = H5Pclose (prop);\n }\n else\n {\n //it exists and need to modify it\n dset_weight_2 = H5Dopen (group_id, \"PW\", H5P_DEFAULT); //open dataset\n \n //get dimensions of array and save it\n dspace = H5Dget_space (dset_weight_2);\n \n status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims\n \n //extend the dataset\n size[0] = dims_weight[0]+ dims_old[0];\n status = H5Dset_extent (dset_weight_2, size);\n \n /* Select a hyperslab in extended portion of dataset */\n fspace = H5Dget_space (dset_weight_2);\n offset[0] = dims_old[0];\n status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL,\n dims_weight, NULL);\n \n /* Define memory space */\n mspace = H5Screate_simple (rank, dims_weight, NULL);\n \n /* Write the data to the extended portion of dataset */\n status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, mspace, fspace,\n H5P_DEFAULT, weight);\n }\n }\n else\n {\n fprintf(fPtr, \"The frame exists in the hdf5 file but the weight dataset for the frame doesnt exist, therefore creating it.\\n\");\n fflush(fPtr);\n \n prop_weight= H5Pcreate (H5P_DATASET_CREATE);\n status = H5Pset_chunk (prop_weight, rank, dims_weight);\n \n dspace_weight=H5Screate_simple (rank, dims_weight, maxdims);\n \n dset_weight_2 = H5Dcreate2 (group_id, \"PW\", H5T_NATIVE_DOUBLE, dspace_weight,\n H5P_DEFAULT, prop_weight, H5P_DEFAULT);\n \n status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL,\n H5P_DEFAULT, weight);\n \n status = H5Pclose (prop_weight);\n }\n \n status = H5Dclose (dset_weight_2);\n }\n \n \n \n status = H5Sclose (dspace);\n status = H5Sclose (mspace);\n status = H5Sclose (fspace);\n \n }\n \n \n /* Close resources */\n \n free(ph_type);\n //status = H5Sclose (dspace);\n status = H5Dclose (dset_p0); status = H5Dclose (dset_p1); status = H5Dclose (dset_p2); status = H5Dclose (dset_p3);\n //if (COMV_SWITCH!=0)\n #if COMV_SWITCH == ON\n {\n status = H5Dclose (dset_comv_p0); status = H5Dclose (dset_comv_p1); status = H5Dclose (dset_comv_p2); status = H5Dclose (dset_comv_p3);\n }\n #endif\n status = H5Dclose (dset_r0); status = H5Dclose (dset_r1); status = H5Dclose (dset_r2);\n //if (STOKES_SWITCH!=0)\n #if STOKES_SWITCH == ON\n {\n status = H5Dclose (dset_s0); status = H5Dclose (dset_s1); status = H5Dclose (dset_s2); status = H5Dclose (dset_s3);\n }\n #endif\n \n #if SAVE_TYPE == ON\n {\n status = H5Dclose (dset_ph_type);\n }\n #endif\n \n status = H5Dclose (dset_num_scatt); \n\n if ((frame==frame_last))\n {\n status = H5Dclose (dset_weight);\n }\n \n /* Close the group. */\n status = H5Gclose(group_id);\n \n /* Terminate access to the file. */\n status = H5Fclose(file);\n \n\n}\n\nint saveCheckpoint(char dir[200], int frame, int frame2, int scatt_frame, int ph_num,double time_now, struct photon *ph, int last_frame, int angle_rank,int angle_size )\n{\n //function to save data necessary to restart simulation if it ends\n //need to save all photon data\n FILE *fPtr=NULL;\n char checkptfile[2000]=\"\";\n char command[2000]=\"\";\n char restart;\n int i=0, success=0;;\n \n \n snprintf(checkptfile,sizeof(checkptfile),\"%s%s%d%s\",dir,\"mc_chkpt_\", angle_rank,\".dat\" );\n //snprintf(checkptfile,sizeof(checkptfile),\"%s%s%d%s%d%s\",dir,\"mc_chkpt_\", angle_rank, \"_frame_\", scatt_frame, \".dat\" ); //look at frame 1341?\n\n \n if ((scatt_frame!=last_frame) && (scatt_frame != frame))\n {\n //quick way to preserve old chkpt file if the new one overwrites the old one and corrupts it for some reason\n snprintf(command, sizeof(command), \"%s%s %s_old\",\"exec cp \",checkptfile, checkptfile);\n system(command);\n \n fPtr=fopen(checkptfile, \"wb\");\n //printf(\"%s\\n\", checkptfile);\n \n if (fPtr==NULL)\n {\n printf(\"Cannot open %s to save checkpoint\\n\", checkptfile);\n success=1;\n }\n else\n {\n //can call printPhotons here or return an int signifying if the checkpoint save worked\n fwrite(&angle_size, sizeof(int), 1, fPtr);\n restart='c';\n fwrite(&restart, sizeof(char), 1, fPtr);\n //printf(\"Rank: %d wrote restart %c\\n\", angle_rank, restart);\n fflush(stdout);\n fwrite(&frame, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote frame\\n\", angle_rank);\n fflush(stdout);\n fwrite(&frame2, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote frame2\\n\", angle_rank);\n fflush(stdout);\n fwrite(&scatt_frame, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote scatt_frame\\n\", angle_rank);\n fflush(stdout);\n fwrite(&time_now, sizeof(double), 1, fPtr);\n //printf(\"Rank: %d wrote time_now\\n\", angle_rank);\n fflush(stdout);\n fwrite(&ph_num, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote ph_num\\n\", angle_rank);\n fflush(stdout);\n for(i=0;itype == COMPTONIZED_PHOTON) && ((ph+i)->weight != 0))\n {\n (ph+i)->type = OLD_COMPTONIZED_PHOTON; //set this to be an old synchrotron scattered photon\n }\n #endif\n fwrite((ph+i), sizeof(struct photon ), 1, fPtr);\n //fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr);\n }\n success=0;\n }\n //printf(\"Rank: %d wrote photons\\n\", angle_rank);\n fflush(stdout);\n }\n else if (scatt_frame == frame)\n {\n snprintf(command, sizeof(command), \"%s%s\",\"exec rm \",checkptfile);\n system(command);\n \n fPtr=fopen(checkptfile, \"wb\");\n //printf(\"%s\\n\", checkptfile);\n fflush(stdout);\n \n if (fPtr==NULL)\n {\n printf(\"Cannot open %s to save checkpoint\\n\", checkptfile);\n success=1;\n }\n else\n {\n fwrite(&angle_size, sizeof(int), 1, fPtr);\n restart='c';\n fwrite(&restart, sizeof(char), 1, fPtr);\n //printf(\"Rank: %d wrote restart %c\\n\", angle_rank, restart);\n fflush(stdout);\n fwrite(&frame, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote frame\\n\", angle_rank);\n fflush(stdout);\n fwrite(&frame2, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote frame2\\n\", angle_rank);\n fflush(stdout);\n fwrite(&scatt_frame, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote scatt_frame\\n\", angle_rank);\n fflush(stdout);\n fwrite(&time_now, sizeof(double), 1, fPtr);\n //printf(\"Rank: %d wrote time_now\\n\", angle_rank);\n fflush(stdout);\n fwrite(&ph_num, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote ph_num\\n\", angle_rank);\n fflush(stdout);\n for(i=0;itype == COMPTONIZED_PHOTON) && ((ph+i)->weight != 0))\n {\n (ph+i)->type = OLD_COMPTONIZED_PHOTON; //set this to be an old synchrotron scattered photon\n }\n #endif\n //fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr);\n fwrite((ph+i), sizeof(struct photon ), 1, fPtr);\n }\n //printf(\"Rank: %d wrote photons\\n\", angle_rank);\n success=0;\n }\n fflush(stdout);\n \n }\n else\n {\n //quick way to preserve old chkpt file if the new one overwrites the old one and corrupts it for some reason\n snprintf(command, sizeof(command), \"%s%s %s_old\",\"exec cp \",checkptfile, checkptfile);\n system(command);\n \n fPtr=fopen(checkptfile, \"wb\");\n //printf(\"%s\\n\", checkptfile);\n \n if (fPtr==NULL)\n {\n printf(\"Cannot open %s to save checkpoint\\n\", checkptfile);\n success=1;\n }\n else\n {\n //just finished last iteration of scatt_frame\n fwrite(&angle_size, sizeof(int), 1, fPtr);\n restart='r';\n fwrite(&restart, sizeof(char), 1, fPtr);\n fwrite(&frame, sizeof(int), 1, fPtr);\n fwrite(&frame2, sizeof(int), 1, fPtr);\n for(i=0;itype == COMPTONIZED_PHOTON) && ((ph+i)->weight != 0))\n {\n (ph+i)->type = OLD_COMPTONIZED_PHOTON; //set this to be an old synchrotron scattered photon\n }\n #endif\n fwrite((ph+i), sizeof(struct photon ), 1, fPtr);\n }\n\n success=0;\n }\n }\n if (success==0)\n {\n fclose(fPtr);\n }\n \n return success;\n}\n\nint readCheckpoint(char dir[200], struct photon **ph, int *frame2, int *framestart, int *scatt_framestart, int *ph_num, char *restart, double *time, int angle_rank, int *angle_size )\n{\n //function to read in data from checkpoint file\n FILE *fPtr=NULL;\n char checkptfile[200]=\"\";\n int i=0;\n int scatt_synch_num_ph=0;//count the number of scattered synchrotron photons from the previosu frame that were saved\n //int frame, scatt_frame, ph_num, i=0;\n struct photon *phHolder=NULL; //pointer to struct to hold data read in from checkpoint file\n \n \n snprintf(checkptfile,sizeof(checkptfile),\"%s%s%d%s\",dir,\"mc_chkpt_\", angle_rank,\".dat\" );\n \n printf(\"Checkpoint file: %s\\n\", checkptfile);\n \n if (access( checkptfile, F_OK ) != -1) //if you can access the file, open and read it\n {\n fPtr=fopen(checkptfile, \"rb\");\n //if ((angle_rank==2) || (angle_rank==3) || (angle_rank==4) || (angle_rank==5))\n {\n fread(angle_size, sizeof(int), 1, fPtr); //uncomment once I run MCRAT for the sims that didnt save this originally\n }\n fread(restart, sizeof(char), 1, fPtr);\n //printf(\"%c\\n\", *restart);\n fread(framestart, sizeof(int), 1, fPtr);\n //printf(\"%d\\n\", *framestart);\n fread(frame2, sizeof(int), 1, fPtr);\n \n if((*restart)=='c')\n {\n fread(scatt_framestart, sizeof(int), 1, fPtr);\n \n //if ((riken_switch==1) && (strcmp(DIM_SWITCH, dim_3d_str)==0) && ((*scatt_framestart)>=3000))\n #if SIM_SWITCH == RIKEN && DIMENSIONS == 3\n if ((*scatt_framestart)>=3000)\n {\n *scatt_framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 \n }\n #else\n {\n *scatt_framestart+=1; //add one to start at the next frame after the simulation was interrrupted\n }\n #endif\n\n //printf(\"%d\\n\", *scatt_framestart);\n fread(time, sizeof(double), 1, fPtr);\n //printf(\"%e\\n\", *time);\n fread(ph_num, sizeof(int), 1, fPtr);\n //printf(\"%d\\n\", *ph_num);\n \n phHolder=malloc(sizeof(struct photon));\n (*ph)=malloc(sizeof(struct photon)*(*ph_num)); //allocate memory to hold photon data\n \n \n for (i=0;i<(*ph_num);i++)\n {\n fread(phHolder, sizeof(struct photon), 1, fPtr);\n //printf(\"%e,%e,%e, %e,%e,%e, %e, %e\\n\",(ph)->p0, (ph)->p1, (ph)->p2, ph->p3, (ph)->r0, (ph)->r1, (ph)->r2, ph->num_scatt );\n \n (*ph)[i].p0=phHolder->p0;\n (*ph)[i].p1=phHolder->p1;\n (*ph)[i].p2=phHolder->p2;\n (*ph)[i].p3=phHolder->p3;\n (*ph)[i].comv_p0=phHolder->comv_p0;\n (*ph)[i].comv_p1=phHolder->comv_p1;\n (*ph)[i].comv_p2=phHolder->comv_p2;\n (*ph)[i].comv_p3=phHolder->comv_p3;\n (*ph)[i].r0= phHolder->r0; \n (*ph)[i].r1=phHolder->r1 ;\n (*ph)[i].r2=phHolder->r2; \n (*ph)[i].s0=phHolder->s0; \n (*ph)[i].s1=phHolder->s1;\n (*ph)[i].s2=phHolder->s2;\n (*ph)[i].s3=phHolder->s3;\n (*ph)[i].num_scatt=phHolder->num_scatt;\n (*ph)[i].weight=phHolder->weight;\n (*ph)[i].nearest_block_index= phHolder->nearest_block_index;\n (*ph)[i].type= phHolder->type;\n \n #if SYNCHROTRON_SWITCH == ON\n if (((*ph)[i].weight != 0) && (((*ph)[i].type == COMPTONIZED_PHOTON) || ((*ph)[i].type == OLD_COMPTONIZED_PHOTON)) && ((*ph)[i].p0 > 0))\n {\n scatt_synch_num_ph++;\n }\n //printf(\"%d %c %e %e %e %e %e %e %e\\n\", i, (*ph)[i].type, (*ph)[i].r0, (*ph)[i].r1, (*ph)[i].r2, (*ph)[i].num_scatt, (*ph)[i].weight, (*ph)[i].p0*C_LIGHT/1.6e-9, (*ph)[i].comv_p0);\n #endif\n }\n \n free(phHolder);\n //printf(\"In readcheckpoint count=%d\\n\", count);\n }\n else\n {\n //if ((riken_switch==1) && (strcmp(DIM_SWITCH, dim_3d_str)==0) && ((*framestart)>=3000))\n #if SIM_SWITCH == RIKEN && DIMENSIONS == 3\n if ((*framestart)>=3000)\n {\n *framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 \n }\n #else\n {\n *framestart+=1; //if the checkpoint file saved and the program was inturrupted before the frame variable had just increased and before the scatt_frame iteration was saved, add one to the frame start\n }\n #endif\n \n *scatt_framestart=(*framestart);\n }\n \n fclose(fPtr);\n }\n else //if not use default\n {\n //*framestart=(*framestart);\n *scatt_framestart=(*framestart);\n *restart='r';\n \n }\n \n return scatt_synch_num_ph;\n}\n\nvoid readMcPar(char file[200], double *fluid_domain_x, double *fluid_domain_y, double *fps, double *theta_jmin, double *theta_j, double *d_theta_j, double *inj_radius_small, double *inj_radius_large, int *frm0_small, int *frm0_large, int *last_frm, int *frm2_small,int *frm2_large , double *ph_weight_small,double *ph_weight_large,int *min_photons, int *max_photons, char *spect, char *restart)\n{\n //function to read mc.par file\n\tFILE *fptr=NULL;\n\tchar buf[100]=\"\";\n\tdouble theta_deg;\n\t\n\t//open file\n\tfptr=fopen(file,\"r\");\n\t//read in frames per sec and other variables outlined in main()\n fscanf(fptr, \"%lf\",fluid_domain_x);\n\t//printf(\"%lf\\n\", *fluid_domain_x );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",fluid_domain_y);\n\t//printf(\"%lf\\n\", *fluid_domain_y );\n\t\n\tfgets(buf, 100,fptr);\n \n\tfscanf(fptr, \"%lf\",fps);\n\t//printf(\"%f\\n\", *fps );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%d\",frm0_small);\n\t//printf(\"%d\\n\", *frm0_small );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",frm0_large);\n\t//printf(\"%d\\n\", *frm0_large );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%d\",last_frm);\n\t//printf(\"%d\\n\", *last_frm );\n \n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%d\",frm2_small);\n *frm2_small+=*frm0_small; //frame to go to is what is given in the file plus the starting frame\n\t//printf(\"%d\\n\", *frm2_small );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\t//fscanf(fptr, \"%d\",photon_num); remove photon num because we dont need this\n\t//printf(\"%d\\n\", *photon_num );\n \n fscanf(fptr, \"%d\",frm2_large);\n *frm2_large+=*frm0_large; //frame to go to is what is given in the file plus the starting frame\n //printf(\"%d\\n\", *frm2_large );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\t//fgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%lf\",inj_radius_small);\n\t//printf(\"%lf\\n\", *inj_radius_small );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",inj_radius_large);\n\t//printf(\"%lf\\n\", *inj_radius_large );\n\t\n\tfgets(buf, 100,fptr);\n \n\t//theta jmin\n\tfscanf(fptr, \"%lf\",&theta_deg);\n\t*theta_jmin=theta_deg;//*M_PI/180; leave as degrees to manipulate processes \n\t//printf(\"%f\\n\", *theta_jmin );\n\t\n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%lf\",&theta_deg);\n *theta_j=theta_deg;//*M_PI/180;\n\t//printf(\"%f\\n\", *theta_j );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",d_theta_j);\n //*theta_j=theta_deg;//*M_PI/180;\n\t//printf(\"%f\\n\", *theta_j );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",ph_weight_small);\n //printf(\"%f\\n\", *ph_weight_small );\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",ph_weight_large);\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",min_photons);\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",max_photons);\n fgets(buf, 100,fptr);\n \n *spect=getc(fptr);\n fgets(buf, 100,fptr);\n //printf(\"%c\\n\",*spect);\n \n *restart=getc(fptr);\n fgets(buf, 100,fptr);\n \n //dont need this line fo code for MPI \n //fscanf(fptr, \"%d\",num_threads);\n //printf(\"MAKE SURE THERE IS NO NUM_THREADS LINE IN THE MC.PAR FILE.\\n\");\n //fgets(buf, 100,fptr);\n \n //fscanf(fptr, \"%d\",dim_switch);\n //printf(\"MAKE SURE THERE IS NO DIM_SWITCH LINE IN THE MC.PAR FILE.\\n\");\n //printf(\"%d\\n\",*dim_switch);\n \n\t//close file\n\tfclose(fptr);\n}\n\nvoid readAndDecimate(char flash_file[200], double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r,\\\n double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double min_theta, double max_theta, FILE *fPtr)\n{\n //function to read in data from FLASH file\n hid_t file,dset, space;\n herr_t status;\n hsize_t dims[2]={0,0}; //hold dimension size for coordinate data set (mostly interested in dims[0])\n double **vel_x_buffer=NULL, **vel_y_buffer=NULL, **dens_buffer=NULL, **pres_buffer=NULL, **coord_buffer=NULL, **block_sz_buffer=NULL;\n double *velx_unprc=NULL, *vely_unprc=NULL, *dens_unprc=NULL, *pres_unprc=NULL, *x_unprc=NULL, *y_unprc=NULL, *r_unprc=NULL, *szx_unprc=NULL, *szy_unprc=NULL;\n int i,j,count,x1_count, y1_count, r_count, **node_buffer=NULL, num_nodes=0, elem_factor=0;\n double x1[8]={-7.0/16,-5.0/16,-3.0/16,-1.0/16,1.0/16,3.0/16,5.0/16,7.0/16};\n double ph_rmin=0, ph_rmax=0, ph_thetamin=0, ph_thetamax=0, r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0, track_min_r=DBL_MAX, track_max_r=0;\n #if defined(_OPENMP)\n int num_thread=omp_get_num_threads();\n #endif\n \n\n if (ph_inj_switch==0)\n {\n ph_rmin=min_r;\n ph_rmax=max_r;\n ph_thetamin=min_theta-2*0.017453292519943295; //min_theta - 2*Pi/180 (2 degrees)\n ph_thetamax=max_theta+2*0.017453292519943295; //max_theta + 2*Pi/180 (2 degrees)\n\n }\n \n file = H5Fopen (flash_file, H5F_ACC_RDONLY, H5P_DEFAULT);\n \n //ret=H5Pclose(acc_tpl1);\n \n fprintf(fPtr, \">> MCRaT: Reading positional, density, pressure, and velocity information...\\n\");\n fflush(fPtr);\n //printf(\"Reading coord\\n\");\n dset = H5Dopen (file, \"coordinates\", H5P_DEFAULT);\n \n //get dimensions of array and save it\n space = H5Dget_space (dset);\n \n H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims\n \n //status = H5Sclose (space);\n //status = H5Dclose (dset);\n //status = H5Fclose (file);\n \n /*\n * Allocate array of pointers to rows. \n */\n coord_buffer = (double **) malloc (dims[0] * sizeof (double *));\n \n coord_buffer[0] = (double *) malloc (dims[0] * dims[1] * sizeof (double));\n \n block_sz_buffer= (double **) malloc (dims[0] * sizeof (double *));\n\n block_sz_buffer[0] = (double *) malloc (dims[0] * COORD_DIM1 * sizeof (double));\n \n node_buffer= (int **) malloc (dims[0] * sizeof (int *));\n node_buffer[0] = (int *) malloc (dims[0] * sizeof (int));\n \n vel_x_buffer= (double **) malloc (dims[0] * sizeof (double *));\n vel_x_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n vel_y_buffer= (double **) malloc (dims[0] * sizeof (double *));\n vel_y_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n dens_buffer= (double **) malloc (dims[0] * sizeof (double *));\n dens_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n pres_buffer= (double **) malloc (dims[0] * sizeof (double *));\n pres_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n /*\n * Set the rest of the pointers to rows to the correct addresses.\n */\n for (i=1; i> Selecting good node types (=1)\\n\");\n //find out how many good nodes there are\n\n for (i=0;i> Creating and reshaping arrays\\n\");\n count=0;\n \n\n for (i=0;i injection radius\n//have single thread execute this while loop and then have inner loop be parallel\n #if SYNCHROTRON_SWITCH == ON\n elem_factor=2;\n #else\n elem_factor=0;\n #endif\n r_count=0;\n while (r_count==0)\n {\n r_count=0;\n elem_factor++;\n for (i=0;i= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax) )\n {\n r_count++;\n }\n \n }\n else\n {\n if (*(r_unprc+i)> (0.95*r_inj) )\n {\n r_count++;\n }\n }\n }\n //fprintf(fPtr, \"r_count: %d count: %d\\n\", r_count, count);\n }\n fprintf(fPtr, \"Elem factor: %d Ph_rmin: %e rmax: %e Chosen FLASH min_r: %e max_r: %e min_theta: %e degrees max_theta: %e degrees\\n\", elem_factor, ph_rmin, ph_rmax, ph_rmin - (elem_factor*C_LIGHT/fps), ph_rmax + (elem_factor*C_LIGHT/fps), ph_thetamin*180/M_PI, ph_thetamax*180/M_PI);\n fflush(fPtr);\n \n //allocate memory to hold processed data\n (*pres)=malloc (r_count * sizeof (double ));\n (*velx)=malloc (r_count * sizeof (double ));\n (*vely)=malloc (r_count * sizeof (double ));\n (*dens)=malloc (r_count * sizeof (double ));\n (*x)=malloc (r_count * sizeof (double ));\n (*y)=malloc (r_count * sizeof (double ));\n (*r)=malloc (r_count * sizeof (double ));\n (*theta)=malloc (r_count * sizeof (double ));\n (*gamma)=malloc (r_count * sizeof (double ));\n (*dens_lab)=malloc (r_count * sizeof (double ));\n (*szx)=malloc (r_count * sizeof (double ));\n (*szy)=malloc (r_count * sizeof (double ));\n (*temp)=malloc (r_count * sizeof (double ));\n\n \n //assign values based on r> 0.95*r_inj\n j=0;\n for (i=0;i= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax))\n {\n (*pres)[j]=*(pres_unprc+i);\n (*velx)[j]=*(velx_unprc+i);\n (*vely)[j]=*(vely_unprc+i);\n \n (*dens)[j]=*(dens_unprc+i);\n (*x)[j]=*(x_unprc+i);\n (*y)[j]=*(y_unprc+i);\n (*r)[j]=*(r_unprc+i);\n (*szx)[j]=*(szx_unprc+i);\n (*szy)[j]=*(szy_unprc+i);\n (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis\n (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c\n (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));\n (*temp)[j]=pow(3*(*(pres_unprc+i))/(A_RAD) ,1.0/4.0);\n j++;\n /*\n if (*(r_unprc+i)track_max_r)\n {\n track_max_r=*(r_unprc+i);\n }\n */\n }\n }\n else\n {\n if (*(r_unprc+i)> (0.95*r_inj) )\n {\n (*pres)[j]=*(pres_unprc+i);\n (*velx)[j]=*(velx_unprc+i);\n (*vely)[j]=*(vely_unprc+i);\n (*dens)[j]=*(dens_unprc+i);\n (*x)[j]=*(x_unprc+i);\n (*y)[j]=*(y_unprc+i);\n (*r)[j]=*(r_unprc+i);\n (*szx)[j]=*(szx_unprc+i);\n (*szy)[j]=*(szy_unprc+i);\n (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis\n (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c\n (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));\n (*temp)[j]=pow(3*(*(pres_unprc+i))/(A_RAD) ,1.0/4.0);\n j++;\n }\n }\n }\n \n //fprintf(fPtr, \"Actual Min and Max Flash grid radii are: %e %e\\n\", track_min_r, track_max_r);\n //fflush(fPtr);\n\n *number=r_count;\n\n free(pres_unprc); free(velx_unprc);free(vely_unprc);free(dens_unprc);free(x_unprc); free(y_unprc);free(r_unprc);free(szx_unprc);free(szy_unprc);\n //exit(0);\n}\n\n\nvoid photonInjection( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\\\ndouble *x, double *y, double *szx, double *szy, double *r, double *theta, double *temps, double *vx, double *vy, gsl_rng * rand, FILE *fPtr)\n{\n int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;\n double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, rmin, rmax;\n double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)\n double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values\n float num_dens_coeff;\n double r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0;\n double position_rand=0, position2_rand=0;\n \n if (spect=='w') //from MCRAT paper, w for wien spectrum \n {\n num_dens_coeff=8.44;\n //printf(\"in wien spectrum\\n\");\n }\n else\n {\n num_dens_coeff=20.29; //this is for black body spectrum\n //printf(\"in BB spectrum\");\n }\n \n //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for \n //and then rcord which blocks have to have \"x\" amount of photons injected there\n \n rmin=r_inj - 0.5*C_LIGHT/fps;\n rmax=r_inj + 0.5*C_LIGHT/fps;\n \n for(i=0;i= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )\n if ((rmin <= r_grid_outercorner) && (r_grid_innercorner <= rmax ) && (theta_grid_outercorner >= theta_min) && (theta_grid_innercorner <= theta_max))\n {\n block_cnt++;\n }\n }\n //printf(\"Blocks: %d\\n\", block_cnt);\n \n //allocate memory to record density of photons for each block\n ph_dens=malloc(block_cnt * sizeof(int));\n \n //calculate the photon density for each block and save it to the array\n j=0;\n ph_tot=0;\n ph_weight_adjusted=ph_weight;\n //printf(\"%d %d\\n\", max_photons, min_photons);\n while ((ph_tot>max_photons) || (ph_tot= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )\n if ((rmin <= r_grid_outercorner) && (r_grid_innercorner <= rmax ) && (theta_grid_outercorner >= theta_min) && (theta_grid_innercorner <= theta_max))\n {\n #if GEOMETRY == SPHERICAL\n {\n ph_dens_calc=(num_dens_coeff*2.0*M_PI*pow(*(r+i),2)*sin(*(theta+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1); //dV=2 *pi* r^2 Sin(theta) dr dtheta\n }\n #else\n {\n //using FLASH\n ph_dens_calc=(4.0/3.0)*(num_dens_coeff*2.0*M_PI*(*(x+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2,\n }\n #endif\n \n (*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc\n \n //printf(\"%d, %lf \\n\",*(ph_dens+j), ph_dens_calc);\n \n //sum up all the densities to get total number of photons\n ph_tot+=(*(ph_dens+j));\n \n j++;\n }\n }\n \n if (ph_tot>max_photons)\n {\n //if the number of photons is too big make ph_weight larger\n ph_weight_adjusted*=10;\n \n }\n else if (ph_tot= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )\n if ((rmin <= r_grid_outercorner) && (r_grid_innercorner <= rmax ) && (theta_grid_outercorner >= theta_min) && (theta_grid_innercorner <= theta_max))\n {\n\n //*(temps+i)=0.76*(*(temps+i));\n for(j=0;j<( *(ph_dens+k) ); j++ )\n {\n //have to get random frequency for the photon comoving frequency\n y_dum=1; //initalize loop\n yfr_dum=0;\n while (y_dum>yfr_dum)\n {\n fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz\n //printf(\"%lf, %lf \",gsl_rng_uniform_pos(rand), (*(temps+i)));\n y_dum=gsl_rng_uniform_pos(rand);\n //printf(\"%lf \",fr_dum);\n \n if (spect=='w')\n {\n yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum\n }\n else\n {\n fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb\n bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max\n yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency\n \t\n }\n //printf(\"%lf, %lf,%lf,%e \\n\",(*(temps+i)),fr_dum, y_dum, yfr_dum);\n \n }\n //printf(\"i: %d freq:%lf\\n \",ph_tot, fr_dum);\n position_phi=gsl_rng_uniform(rand)*2*M_PI;\n com_v_phi=gsl_rng_uniform(rand)*2*M_PI;\n com_v_theta=acos((gsl_rng_uniform(rand)*2)-1);\n //printf(\"%lf, %lf, %lf\\n\", position_phi, com_v_phi, com_v_theta);\n \n //populate 4 momentum comoving array\n *(p_comv+0)=PL_CONST*fr_dum/C_LIGHT;\n *(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi);\n *(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi);\n *(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta);\n \n \n //populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code...\n *(boost+0)=-1*(*(vx+i))*cos(position_phi);\n *(boost+1)=-1*(*(vx+i))*sin(position_phi);\n *(boost+2)=-1*(*(vy+i));\n \n //boost to lab frame\n lorentzBoost(boost, p_comv, l_boost, 'p', fPtr);\n //printf(\"Assignemnt: %e, %e, %e, %e\\n\", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3));\n \n (*ph)[ph_tot].p0=(*(l_boost+0));\n (*ph)[ph_tot].p1=(*(l_boost+1));\n (*ph)[ph_tot].p2=(*(l_boost+2));\n (*ph)[ph_tot].p3=(*(l_boost+3));\n (*ph)[ph_tot].comv_p0=(*(p_comv+0));\n (*ph)[ph_tot].comv_p1=(*(p_comv+1));\n (*ph)[ph_tot].comv_p2=(*(p_comv+2));\n (*ph)[ph_tot].comv_p3=(*(p_comv+3));\n \n //place photons in rand positions within fluid element\n #if GEOMETRY == CARTESIAN\n position_rand=gsl_rng_uniform_pos(rand)*(*(szx+i))-(*(szx+i))/2.0; //choose between -size/2 to size/2\n (*ph)[ph_tot].r0= (*(x+i)+position_rand)*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi\n (*ph)[ph_tot].r1=(*(x+i)+position_rand)*sin(position_phi) ;\n position_rand=gsl_rng_uniform_pos(rand)*(*(szx+i))-(*(szx+i))/2.0;\n (*ph)[ph_tot].r2=(*(y+i)+position_rand); //y coordinate in flash becomes z coordinate in MCRaT\n #elif GEOMETRY == SPHERICAL\n position_rand=gsl_rng_uniform_pos(rand)*(*(szx+i))-(*(szx+i))/2.0; //choose between -size/2 to size/2\n position2_rand=gsl_rng_uniform_pos(rand)*(*(szy+i))-(*(szy+i))/2.0;\n \n (*ph)[ph_tot].r0= (*(r+i)+position_rand)*sin(*(theta+i)+position2_rand)*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi\n (*ph)[ph_tot].r1=(*(r+i)+position_rand)*sin(*(theta+i)+position2_rand)*sin(position_phi) ;\n \n (*ph)[ph_tot].r2=(*(r+i)+position_rand)*cos(*(theta+i)+position2_rand); //y coordinate in flash becomes z coordinate in MCRaT\n #endif\n \n (*ph)[ph_tot].s0=1; //initalize stokes parameters as non polarized photon, stokes parameterized are normalized such that I always =1 \n (*ph)[ph_tot].s1=0;\n (*ph)[ph_tot].s2=0;\n (*ph)[ph_tot].s3=0;\n (*ph)[ph_tot].num_scatt=0;\n (*ph)[ph_tot].weight=ph_weight_adjusted;\n (*ph)[ph_tot].nearest_block_index=0;\n (*ph)[ph_tot].type=INJECTED_PHOTON; //i for injected\n //printf(\"%d\\n\",ph_tot);\n ph_tot++;\n }\n k++;\n }\n }\n \n *ph_num=ph_tot; //save number of photons\n //printf(\" %d: %d\\n\", *(ph_dens+(k-1)), *ph_num);\n free(ph_dens); free(p_comv);free(boost); free(l_boost);\n \n}\n\nvoid lorentzBoost(double *boost, double *p_ph, double *result, char object, FILE *fPtr)\n{\n //function to perform lorentz boost\n //if doing boost for an electron last argument is 'e' and there wont be a check for zero norm\n //if doing boost for a photon last argument is 'p' and there will be a check for zero norm\n double beta=0, gamma=0, *boosted_p=NULL;\n \n gsl_vector_view b=gsl_vector_view_array(boost, 3); //make boost pointer into vector\n gsl_vector_view p=gsl_vector_view_array(p_ph, 4); //make boost pointer into vector\n gsl_matrix *lambda1= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do lorentz boost \n gsl_vector *p_ph_prime =gsl_vector_calloc(4); //create vestor to hold lorentz boosted vector\n \n /*\n fprintf(fPtr,\"Boost: %e, %e, %e, %e\\n\",gsl_blas_dnrm2(&b.vector), *(boost+0), *(boost+1), *(boost+2));\n fflush(fPtr);\n fprintf(fPtr,\"4 Momentum to Boost: %e, %e, %e, %e\\n\",*(p_ph+0), *(p_ph+1), *(p_ph+2), *(p_ph+3));\n fflush(fPtr);\n */\n \n //if magnitude of fluid velocity is != 0 do lorentz boost otherwise dont need to do a boost\n if (gsl_blas_dnrm2(&b.vector) > 0)\n {\n //fprintf(fPtr,\"in If\\n\");\n //fflush(fPtr);\n beta=gsl_blas_dnrm2(&b.vector);\n gamma=1.0/sqrt(1-pow(beta, 2.0));\n //fprintf(fPtr,\"Beta: %e\\tGamma: %e\\n\",beta,gamma );\n //fflush(fPtr);\n \n //initalize matrix values\n gsl_matrix_set(lambda1, 0,0, gamma);\n gsl_matrix_set(lambda1, 0,1, -1*gsl_vector_get(&b.vector,0)*gamma);\n gsl_matrix_set(lambda1, 0,2, -1*gsl_vector_get(&b.vector,1)*gamma);\n gsl_matrix_set(lambda1, 0,3, -1*gsl_vector_get(&b.vector,2)*gamma);\n gsl_matrix_set(lambda1, 1,1, 1+((gamma-1)*(gsl_vector_get(&b.vector,0)*gsl_vector_get(&b.vector,0))/(beta*beta) ) );\n gsl_matrix_set(lambda1, 1,2, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,1)/(beta*beta) ) ));\n gsl_matrix_set(lambda1, 1,3, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,2)/(beta*beta) ) ));\n gsl_matrix_set(lambda1, 2,2, 1+((gamma-1)*(gsl_vector_get(&b.vector,1)*gsl_vector_get(&b.vector,1))/(beta*beta) ) );\n gsl_matrix_set(lambda1, 2,3, ((gamma-1)*(gsl_vector_get(&b.vector,1)* gsl_vector_get(&b.vector,2))/(beta*beta) ) );\n gsl_matrix_set(lambda1, 3,3, 1+((gamma-1)*(gsl_vector_get(&b.vector,2)*gsl_vector_get(&b.vector,2))/(beta*beta) ) );\n \n gsl_matrix_set(lambda1, 1,0, gsl_matrix_get(lambda1,0,1));\n gsl_matrix_set(lambda1, 2,0, gsl_matrix_get(lambda1,0,2));\n gsl_matrix_set(lambda1, 3,0, gsl_matrix_get(lambda1,0,3));\n gsl_matrix_set(lambda1, 2,1, gsl_matrix_get(lambda1,1,2));\n gsl_matrix_set(lambda1, 3,1, gsl_matrix_get(lambda1,1,3));\n gsl_matrix_set(lambda1, 3,2, gsl_matrix_get(lambda1,2,3));\n \n gsl_blas_dgemv(CblasNoTrans, 1, lambda1, &p.vector, 0, p_ph_prime );\n \n /*\n fprintf(fPtr,\"Lorentz Boost Matrix 0: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 0,0), gsl_matrix_get(lambda1, 0,1), gsl_matrix_get(lambda1, 0,2), gsl_matrix_get(lambda1, 0,3));\n fflush(fPtr);\n fprintf(fPtr,\"Lorentz Boost Matrix 1: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 1,0), gsl_matrix_get(lambda1, 1,1), gsl_matrix_get(lambda1, 1,2), gsl_matrix_get(lambda1, 1,3));\n fflush(fPtr);\n fprintf(fPtr,\"Lorentz Boost Matrix 2: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 2,0), gsl_matrix_get(lambda1, 2,1), gsl_matrix_get(lambda1, 2,2), gsl_matrix_get(lambda1, 2,3));\n fflush(fPtr);\n fprintf(fPtr,\"Lorentz Boost Matrix 3: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 3,0), gsl_matrix_get(lambda1, 3,1), gsl_matrix_get(lambda1, 3,2), gsl_matrix_get(lambda1, 3,3));\n fflush(fPtr);\n \n fprintf(fPtr,\"Before Check: %e %e %e %e\\n \",gsl_vector_get(p_ph_prime, 0), gsl_vector_get(p_ph_prime, 1), gsl_vector_get(p_ph_prime, 2), gsl_vector_get(p_ph_prime, 3));\n fflush(fPtr);\n */\n \n //double check vector for 0 norm condition if photon\n if (object == 'p')\n {\n //fprintf(fPtr,\"In if\\n\");\n boosted_p=zeroNorm(gsl_vector_ptr(p_ph_prime, 0));\n }\n else\n {\n boosted_p=gsl_vector_ptr(p_ph_prime, 0);\n }\n /*\n fprintf(fPtr,\"After Check: %e %e %e %e\\n \", *(boosted_p+0),*(boosted_p+1),*(boosted_p+2),*(boosted_p+3) );\n fflush(fPtr);\n * */\n }\n else\n {\n /*\n fprintf(fPtr,\"in else\");\n fflush(fPtr);\n * */\n //double check vector for 0 norm condition\n if (object=='p')\n {\n boosted_p=zeroNorm(p_ph);\n }\n else\n {\n //if 4 momentum isnt for photon and there is no boost to be done, we dont care about normality and just want back what was passed to lorentz boost\n boosted_p=gsl_vector_ptr(&p.vector, 0);\n }\n }\n //assign values to result\n *(result+0)=*(boosted_p+0);\n *(result+1)=*(boosted_p+1);\n *(result+2)=*(boosted_p+2);\n *(result+3)=*(boosted_p+3);\n \n //free up memory\n //free(boosted_p);\n gsl_matrix_free (lambda1); gsl_vector_free(p_ph_prime);\n}\n\ndouble *zeroNorm(double *p_ph)\n{\n //ensures zero norm condition of photon 4 monetum is held\n int i=0;\n double normalizing_factor=0;\n gsl_vector_view p=gsl_vector_view_array((p_ph+1), 3); //make last 3 elements of p_ph pointer into vector\n \n if (*(p_ph+0) != gsl_blas_dnrm2(&p.vector ) )\n {\n normalizing_factor=(gsl_blas_dnrm2(&p.vector ));\n //fprintf(fPtr,\"in zero norm if\\n\");\n //fflush(fPtr);\n //go through and correct 4 momentum assuming the energy is correct\n \n *(p_ph+1)= ((*(p_ph+1))/(normalizing_factor))*(*(p_ph+0));\n *(p_ph+2)= ((*(p_ph+2))/(normalizing_factor))*(*(p_ph+0));\n *(p_ph+3)= ((*(p_ph+3))/(normalizing_factor))*(*(p_ph+0));\n \n }\n /*\n if (pow((*(p_ph+0)),2) != ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) )\n {\n printf(\"This isnt normalized in the function\\nThe difference is: %e\\n\", pow((*(p_ph+0)),2) - ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) );\n }\n */ //normalized within a factor of 10^-53\n return p_ph;\n}\n\nint findNearestBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z)\n{\n double dist=0, dist_min=1e15, block_dist=0;\n int min_index=0, j=0;\n \n dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved\n block_dist=3e9;\n while (dist_min==1e15) //if this is true, then the algorithm hasnt found blocks within the acceptable range given by block_dist\n {\n \n for(j=0;jnearest_block_index), ((ph+i)->weight));\n //fflush(fPtr);\n \n if (find_nearest_block_switch==0)\n {\n ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault here\n }\n else\n {\n ph_block_index=0; // therefore if starting a new frame set index=0 to avoid this issue\n }\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n #if GEOMETRY == SPHERICAL\n ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to 2d spherical coordinate\n ph_y=((ph+i)->r2);\n ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5);\n ph_theta=acos(ph_y/ph_r); //this is actually theta in this context\n ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));\n #elif GEOMETRY == CARTESIAN\n ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate (2d cartesian hydro coordinates)\n ph_y=((ph+i)->r2);\n ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));\n ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5);\n #endif\n \n }\n #else\n {\n ph_x=((ph+i)->r0);\n ph_y=((ph+i)->r1);\n ph_z=((ph+i)->r2);\n ph_r=pow(ph_x*ph_x + ph_y*ph_y+ph_z*ph_z, 0.5);\n }\n #endif\n //printf(\"ph_x:%e, ph_y:%e\\n\", ph_x, ph_y);\n \n //if the location of the photon is less than the domain of the hydro simulation then do all of this, otherwise assing huge mfp value so no scattering occurs and the next frame is loaded\n // absorbed photons have ph_block_index=-1, therefore if this value is not less than 0, calulate the mfp properly but doesnt work when go to new frame and find new indexes (will change b/c will get rid of these photons when printing)\n //alternatively make decision based on 0 weight\n if (((ph_ynearest_block_index != -1) ) //can use sorted index to see which photons have been absorbed efficiently before printing and get the indexes\n {\n #if GEOMETRY == SPHERICAL\n is_in_block=checkInBlock(ph_block_index, ph_r, ph_theta, ph_z, x, y, z, szx, szy);\n #elif GEOMETRY == CARTESIAN\n is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy);\n #endif\n \n //when rebinning photons can have comoving 4 momenta=0 and nearest_block_index=0 (and block 0 be the actual block the photon is in making it not refind the proper index and reclaulate the comoving 4 momenta) which can make counting synch scattered photons be thrown off, thus take care of this case by forcing the function to recalc things\n #if SYNCHROTRON_SWITCH == ON\n if ((ph_block_index==0) && ( ((ph+i)->comv_p0)+((ph+i)->comv_p1)+((ph+i)->comv_p2)+((ph+i)->comv_p3) == 0 ) )\n {\n is_in_block=0; //say that photon is not in the block, force it to recompute things\n }\n #endif\n \n if (find_nearest_block_switch==0 && is_in_block)\n {\n //keep the saved grid index\n min_index=ph_block_index;\n }\n else\n {\n //find the new index of the block closest to the photon\n //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh\n \n //find the new index of the block that the photon is actually in\n #if DIMENSIONS == 2\n {\n #if GEOMETRY == SPHERICAL\n min_index=findContainingBlock(array_num, ph_r, ph_theta, ph_z, x, y, z, szx, szy, ph_block_index, find_nearest_block_switch, fPtr);\n #elif GEOMETRY == CARTESIAN\n min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, ph_block_index, find_nearest_block_switch, fPtr);\n #endif\n }\n #endif\n if (min_index != -1)\n {\n (ph+i)->nearest_block_index=min_index; //save the index if min_index != -1\n \n //also recalculate the photons' comoving frequency in this new fluid element\n ph_p[0]=((ph+i)->p0);\n ph_p[1]=((ph+i)->p1);\n ph_p[2]=((ph+i)->p2);\n ph_p[3]=((ph+i)->p3);\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n fluid_beta[0]=(*(velx+min_index))*cos(ph_phi);\n fluid_beta[1]=(*(velx+min_index))*sin(ph_phi);\n fluid_beta[2]=(*(vely+min_index));\n }\n #else\n {\n fluid_beta[0]=(*(velx+min_index));\n fluid_beta[1]=(*(vely+min_index));\n fluid_beta[2]=(*(velz+min_index));\n }\n #endif\n \n lorentzBoost(&fluid_beta, &ph_p, &ph_p_comv, 'p', fPtr);\n \n ((ph+i)->comv_p0)=ph_p_comv[0];\n ((ph+i)->comv_p1)=ph_p_comv[1];\n ((ph+i)->comv_p2)=ph_p_comv[2];\n ((ph+i)->comv_p3)=ph_p_comv[3];\n \n num_photons_find_new_element+=1;\n }\n else\n {\n \tfprintf(fPtr, \"Photon number %d FLASH index not found, making sure it doesnt scatter.\\n\", i);\n }\n \n }\n \n //if min_index!= -1 (know which fluid element photon is in) do all this stuff, otherwise make sure photon doesnt scatter\n if (min_index != -1)\n {\n //fprintf(fPtr,\"Min Index: %d\\n\", min_index);\n \n //save values\n (n_dens_lab_tmp)= (*(dens_lab+min_index));\n (n_vx_tmp)= (*(velx+min_index));\n (n_vy_tmp)= (*(vely+min_index));\n (n_temp_tmp)= (*(temp+min_index));\n \n\n //if (strcmp(DIM_SWITCH, dim_3d_str)==0)\n #if DIMENSIONS == 3\n {\n (n_vz_tmp)= (*(velz+min_index));\n }\n #endif\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n fl_v_x=(*(velx+min_index))*cos(ph_phi);\n fl_v_y=(*(velx+min_index))*sin(ph_phi);\n fl_v_z=(*(vely+min_index));\n }\n #else\n {\n fl_v_x=(*(velx+min_index));\n fl_v_y=(*(vely+min_index));\n fl_v_z=(*(velz+min_index));\n }\n #endif\n \n fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);\n ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);\n \n //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product\n (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n beta=pow((n_vx_tmp*n_vx_tmp)+(n_vy_tmp*n_vy_tmp),0.5);\n }\n #else\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);\n }\n #endif\n\n *(ph_p+0)=((ph+i)->p0);\n *(ph_p+1)=((ph+i)->p1);\n *(ph_p+2)=((ph+i)->p2);\n *(ph_p+3)=((ph+i)->p3);\n \n //ph_p_comv[0]=((ph+i)->comv_p0);\n //ph_p_comv[1]=((ph+i)->comv_p1);\n //ph_p_comv[2]=((ph+i)->comv_p2);\n //ph_p_comv[3]=((ph+i)->comv_p3);\n \n //printf(\"ph: p0 %e p1 %e p2 %e p3 %e\\n\", *(ph_p_comv+0), *(ph_p_comv+1), *(ph_p_comv+2), *(ph_p_comv+3));\n\n \n //singleElectron(&el_p[0], n_temp_tmp, &ph_p_comv[0], rng[omp_get_thread_num()], fPtr); //get random electron\n //printf(\"after singleElectron n_temp_tmp %e from ptr %e n_dens_tmp %e from ptr %e\\n\", n_temp_tmp, (*(temp+min_index)), n_dens_tmp, (*(dens+min_index)));\n \n //printf(\"Chosen el: p0 %e p1 %e p2 %e p3 %e\\nph: p0 %e p1 %e p2 %e p3 %e\\n\", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3), *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3));\n \n //synch_x_sect=synCrossSection(n_dens_tmp/M_P, n_temp_tmp, ph_p_comv[0]*C_LIGHT/PL_CONST, sqrt((el_p[0]*el_p[0]/(M_EL*M_EL*C_LIGHT*C_LIGHT))-1), epsilon_b);\n //printf(\"i: %d flash_array_idx %d synch_x_sect %e freq %e temp %e el_dens %e\\n\", i, min_index, synch_x_sect, *(ph_p+0)*C_LIGHT/PL_CONST, n_temp_tmp, n_dens_tmp/M_P);\n \n //if (synch_x_sect==0)\n //{\n //*(will_scatter+i)=1; //this photon will scatter b/c probability of absorption=0\n //}\n /*\n else\n {\n if (gsl_rng_uniform_pos(rng[omp_get_thread_num()])>(THOM_X_SECT/(THOM_X_SECT+synch_x_sect)))\n {\n //this photon will be absorbed\n *(will_scatter+i)=0;\n }\n else\n {\n *(will_scatter+i)=1;\n }\n \n } photons can onlt scatter now\n */\n \n //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case\n rnd_tracker=0;\n #if defined(_OPENMP)\n thread_id=omp_get_thread_num();\n #endif\n \n rnd_tracker=gsl_rng_uniform_pos(rng[thread_id]);\n //printf(\"Rnd_tracker: %e Thread number %d \\n\",rnd_tracker, omp_get_thread_num() );\n \n //mfp=(-1)*log(rnd_tracker)*(M_P/((n_dens_tmp))/(THOM_X_SECT)); ///(1.0-beta*((n_cosangle)))) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths DO EVERYTHING IN COMOV FRAME NOW\n mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOM_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ;\n \n //if (mfp/C_LIGHT < 1e-100)\n //{\n // fprintf(\"Photon %d has a mfp of %d\\n\", i, mfp);\n // exit(0);\n //}\n \n }\n else\n {\n mfp=min_mfp;\n }\n }\n else\n {\n mfp=min_mfp;\n //fprintf(fPtr,\"Photon %d In ELSE\\n\", i);\n //exit(0);\n }\n \n *(all_time_steps+i)=mfp/C_LIGHT;\n }\n //exit(0);\n //free rand number generator\n for (i=1;i arr[bb])\n return 1;\n */\n return ((arr[aa] > arr[bb]) - (arr[aa] < arr[bb]));\n}\n\nint compare2 ( const void *a, const void *b, void *ar)\n{\n //have 2 compare funcions b/c of changes in qsort_r between BSD and GNU\n //from https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/\n int aa = *(int *) a;\n int bb = *(int *) b;\n double *arr=NULL;\n arr=ar;\n \n //printf(\"%d, %d\\n\", aa, bb);\n //printf(\"%e, %e\\n\", arr[aa] , arr[bb]);\n //return (aa - bb);\n /*\n if (arr[aa] < arr[bb])\n return -1; \n if (arr[aa] == arr[bb])\n return 0;\n if (arr[aa] > arr[bb])\n return 1;\n */\n return ((arr[aa] > arr[bb]) - (arr[aa] < arr[bb]));\n}\n\nint interpolatePropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\\\n double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int find_nearest_block_switch, FILE *fPtr)\n{\n /*\n * THIS FUNCTION IS WRITTEN JUST FOR 2D SIMS AS OF NOW, not used\n */\n int i=0, j=0, min_index=0, ph_block_index=0, thread_id=0;\n int left_block_index=0, right_block_index=0, bottom_block_index=0, top_block_index=0, all_adjacent_block_indexes[4];\n double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, dist=0, left_dist_min=0, right_dist_min=0, top_dist_min=0, bottom_dist_min=0, dv=0, v=0;\n double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates\n double r=0, theta=0;\n\n double ph_v_norm=0, fl_v_norm=0;\n double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0;\n double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0;\n int num_thread=2;//omp_get_max_threads();\n bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block\n \n int index=0;\n double mfp=0,min_mfp=0, beta=0;\n \n \n //initialize gsl random number generator fo each thread\n \n const gsl_rng_type *rng_t;\n gsl_rng **rng;\n gsl_rng_env_setup();\n rng_t = gsl_rng_ranlxs0;\n\n rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); \n rng[0]=rand;\n\n //#pragma omp parallel for num_threads(nt)\n for(i=1;ir0), ((ph+i)->r1));\n if (find_nearest_block_switch==0)\n {\n ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault\n }\n else\n {\n ph_block_index=0; //if starting a new frame set index=0 to avoid this issue\n }\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate\n ph_y=((ph+i)->r2);\n ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));\n \n }\n #else\n {\n ph_x=((ph+i)->r0);\n ph_y=((ph+i)->r1);\n ph_z=((ph+i)->r2);\n \n }\n #endif\n //printf(\"ph_x:%e, ph_y:%e\\n\", ph_x, ph_y);\n \n is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy);\n \n if (find_nearest_block_switch==0 && is_in_block)\n {\n //keep the saved grid index\n min_index=ph_block_index;\n }\n else\n {\n //find the new index of the block closest to the photon\n //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh\n \n //find the new index of the block that the photon is actually in\n min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, ph_block_index, find_nearest_block_switch, fPtr);\n \n (ph+i)->nearest_block_index=min_index; //save the index\n \n }\n \n //look for the blocks surounding the block of interest and order them by the \n left_dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved\n right_dist_min=1e15;\n top_dist_min=1e15;\n bottom_dist_min=1e15;\n for (j=0;j(*(x+min_index)) && (dist < right_dist_min))\n {\n right_block_index=j;\n right_dist_min=dist;\n }\n \n if ((*(y+j))<(*(y+min_index)) && (dist < bottom_dist_min) )\n {\n bottom_block_index=j;\n bottom_dist_min=dist;\n }\n else if ((*(y+j))>(*(y+min_index)) && (dist < top_dist_min) )\n {\n top_block_index=j;\n top_dist_min=dist;\n }\n \n }\n all_adjacent_block_indexes[0]=left_block_index;\n all_adjacent_block_indexes[1]=right_block_index;\n all_adjacent_block_indexes[2]=bottom_block_index;\n all_adjacent_block_indexes[3]=top_block_index; \n \n //do a weighted average of the 4 nearest grids based on volume\n v=0;\n (n_dens_lab_tmp)=0;\n (n_vx_tmp)= 0;\n (n_vy_tmp)= 0;\n (n_temp_tmp)= 0;\n (n_vz_tmp)= 0;\n \n for (j=0;j<4;j++)\n {\n \n #if SIM_SWITCH == RIKEN\n {\n r=pow(pow((*(x+all_adjacent_block_indexes[j])),2.0)+pow((*(y+all_adjacent_block_indexes[j])),2.0), 0.5);\n theta=atan2((*(x+all_adjacent_block_indexes[j])), (*(y+all_adjacent_block_indexes[j])));\n dv=2.0*M_PI*pow(r,2)*sin(theta)*(*(szx+all_adjacent_block_indexes[j]))*(*(szy+all_adjacent_block_indexes[j])) ;\n }\n #else\n {\n //using FLASH\n dv=2.0*M_PI*(*(x+all_adjacent_block_indexes[j]))*pow(*(szx+all_adjacent_block_indexes[j]),2.0) ;\n\n }\n #endif\n \n v+=dv;\n \n //save values\n (n_dens_lab_tmp)+= (*(dens_lab+all_adjacent_block_indexes[j]))*dv;\n (n_vx_tmp)+= (*(velx+all_adjacent_block_indexes[j]))*dv;\n (n_vy_tmp)+= (*(vely+all_adjacent_block_indexes[j]))*dv;\n (n_temp_tmp)+= (*(temp+all_adjacent_block_indexes[j]))*dv;\n \n //if (strcmp(DIM_SWITCH, dim_3d_str)==0)\n #if DIMENSIONS == 3\n {\n (n_vz_tmp)+= (*(velz+all_adjacent_block_indexes[j]))*dv;\n }\n #endif\n \n }\n \n\n //fprintf(fPtr,\"Outside\\n\");\n \n //save values\n (n_dens_lab_tmp)/= v;\n (n_vx_tmp)/= v;\n (n_vy_tmp)/= v;\n (n_temp_tmp)/= v;\n //if (strcmp(DIM_SWITCH, dim_3d_str)==0)\n #if DIMENSIONS == 3\n {\n (n_vz_tmp)/= v;\n }\n #endif\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n fl_v_x=n_vx_tmp*cos(ph_phi);\n fl_v_y=n_vx_tmp*sin(ph_phi);\n fl_v_z=n_vy_tmp;\n }\n #else\n {\n fl_v_x=n_vx_tmp;\n fl_v_y=n_vy_tmp;\n fl_v_z=n_vz_tmp;\n }\n #endif\n \n fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);\n ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);\n \n //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product\n (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);\n }\n #else\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);\n }\n #endif\n //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case\n rnd_tracker=0;\n #if defined(_OPENMP)\n thread_id=omp_get_thread_num();\n #endif\n \n rnd_tracker=gsl_rng_uniform_pos(rng[thread_id]);\n \n mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOM_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths \n \n \n #pragma omp critical \n if ( mfptype != SYNCHROTRON_POOL_PHOTON) && ((ph+i)->weight != 0))\n {\n old_position= pow( pow((ph+i)->r0,2)+pow((ph+i)->r1,2)+pow((ph+i)->r2,2), 0.5 ); //uncommented checks since they were not necessary anymore\n \n divide_p0=1.0/((ph+i)->p0);\n \n ((ph+i)->r0)+=((ph+i)->p1)*divide_p0*C_LIGHT*t; //update x position\n \n ((ph+i)->r1)+=((ph+i)->p2)*divide_p0*C_LIGHT*t;//update y\n \n ((ph+i)->r2)+=((ph+i)->p3)*divide_p0*C_LIGHT*t;//update z\n \n new_position= pow( pow((ph+i)->r0,2)+pow((ph+i)->r1,2)+pow((ph+i)->r2,2), 0.5 );\n /*\n if ((new_position-old_position)/t > C_LIGHT)\n {\n fprintf(fPtr, \"PHOTON NUMBER %d IS SUPERLUMINAL. ITS SPEED IS %e c.\\n\", i, ((new_position-old_position)/t)/C_LIGHT);\n }\n */\n //if ( (ph+i)->s0 != 1)\n {\n //\tfprintf(fPtr, \"PHOTON NUMBER %d DOES NOT HAVE I=1. Instead it is: %e\\n\", i, (ph+i)->s0);\n }\n \n //printf(\"In update function: %e, %e, %e, %e, %e, %e, %e\\n\",((ph+i)->r0), ((ph+i)->r1), ((ph+i)->r2), t, ((ph+i)->p1)/((ph+i)->p0), ((ph+i)->p2)/((ph+i)->p0), ((ph+i)->p3)/((ph+i)->p0) );\n }\n }\n \n //printf(\"In update function: %e, %e, %e, %e\\n\",t, ((ph)->p1)/((ph)->p0), ((ph)->p2)/((ph)->p0), ((ph)->p3)/((ph)->p0) ); \n \n}\n\nvoid mullerMatrixRotation(double theta, double *s, FILE *fPtr)\n{\n //makes a CCW rotation od the stokes parameters when the photon velocity vector is pointed towards the observer, follows Lundman\n gsl_matrix *M= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do rotation as defined in McMaster 1961 (has it to rotate CW in that paper)\n gsl_vector *result= gsl_vector_alloc(4);\n gsl_vector_view stokes;\n \n stokes=gsl_vector_view_array(s, 4);\n //fprintf(fPtr, \"sokes parameter before= %e %e %e %e\\n\", gsl_vector_get(&stokes.vector, 0), gsl_vector_get(&stokes.vector, 1), gsl_vector_get(&stokes.vector, 2), gsl_vector_get(&stokes.vector, 3));\n \n gsl_matrix_set(M, 0,0,1);\n gsl_matrix_set(M, 3,3,1);\n gsl_matrix_set(M, 1,1,cos(2*theta));\n gsl_matrix_set(M, 2,2,cos(2*theta));\n gsl_matrix_set(M, 1,2,-1*sin(2*theta));\n gsl_matrix_set(M, 2,1,sin(2*theta));\n gsl_blas_dgemv(CblasNoTrans, 1, M, &stokes.vector, 0, result); //Ms=s\n \n //fprintf(fPtr, \"stokes parameter after= %e %e %e %e\\n\\n\", gsl_vector_get(result, 0), gsl_vector_get(result, 1), gsl_vector_get(result, 2), gsl_vector_get(result, 3));\n \n //save back to the original stokes vector\n *(s+0)=gsl_vector_get(result, 0);\n *(s+1)=gsl_vector_get(result, 1);\n *(s+2)=gsl_vector_get(result, 2);\n *(s+3)=gsl_vector_get(result, 3);\n \n gsl_vector_free(result);\n gsl_matrix_free (M);\n \n}\n\nvoid findXY(double *v_ph, double *vector, double *x, double *y)\n{\n //finds the stokes plane coordinate x,y axis for the photon velocity with respect to some reference vector\n //assumes that pointers point to array of 3 doubles in length\n double norm=0;\n \n *(y+0)= ((*(v_ph+1))*(*(vector+2))-(*(v_ph+2))*(*(vector+1)));\n *(y+1)= -1*((*(v_ph+0))*(*(vector+2))-(*(v_ph+2))*(*(vector+0)));\n *(y+2)= ((*(v_ph+0))*(*(vector+1))-(*(v_ph+1))*(*(vector+0))); // vector X v_ph\n \n norm=1.0/sqrt( (*(y+0))*(*(y+0)) + (*(y+1))*(*(y+1)) + (*(y+2))*(*(y+2)));\n *(y+0) *= norm;\n *(y+1) *= norm;\n *(y+2) *= norm;\n \n *(x+0)= (*(y+1))*(*(v_ph+2))-(*(y+2))*(*(v_ph+1));\n *(x+1)= -1*((*(y+0))*(*(v_ph+2))-(*(y+2))*(*(v_ph+0)));\n *(x+2)= (*(y+0))*(*(v_ph+1))-(*(y+1))*(*(v_ph+0));\n \n norm=1.0/sqrt( (*(x+0))*(*(x+0)) + (*(x+1))*(*(x+1)) + (*(x+2))*(*(x+2)));\n *(x+0) *= norm;\n *(x+1) *= norm;\n *(x+2) *= norm;\n \n}\n\ndouble findPhi(double *x_old, double *y_old, double *x_new, double *y_new)\n{\n //find the angle to rotate the stokes vector to transform from one set of stokes coordinates to another\n //this is given by Lundman\n gsl_vector_view y=gsl_vector_view_array(y_old, 3);\n gsl_vector_view x=gsl_vector_view_array(x_old, 3);\n gsl_vector_view y_prime=gsl_vector_view_array(y_new, 3);\n gsl_vector_view x_prime=gsl_vector_view_array(x_new, 3);\n double factor=0, dot_prod_result=0;\n \n gsl_blas_ddot(&x.vector, &y_prime.vector, &dot_prod_result);\n \n if (dot_prod_result>0)\n {\n factor=1;\n }\n else if (dot_prod_result<0)\n {\n factor=-1;\n }\n else\n {\n factor=0;\n }\n \n gsl_blas_ddot(&y.vector, &y_prime.vector, &dot_prod_result);\n \n if ((dot_prod_result<-1) || (dot_prod_result>1))\n {\n //printf(\"The old dot poduct was %e, the new one is %e\\n\",dot_prod_result, round(dot_prod_result));\n dot_prod_result=round(dot_prod_result);//do this rounding so numerical error that causes value to be <-1 or >1 gets rounded and becomes a real value if its close enough to these limits\n }\n \n return -1*factor*acos(dot_prod_result);\n}\n\nvoid stokesRotation(double *v, double *v_ph, double *v_ph_boosted, double *s, FILE *fPtr)\n{\n //takes 3 velocities of the initial photon, v_ph, the boosted photon, v_ph_boosted. and the boost vector, v\n double z_hat[3]={0,0,1}; //z to calulate stokes\n double x[3]={0,0,0}, y[3]={0,0,0}, x_new[3]={0,0,0}, y_new[3]={0,0,0};//initalize arrays to hold stokes coordinate system\n double phi=0;\n \n //if (i==0)\n {\n //find stokes coordinate sys in orig frame with respect to z axis\n findXY(v_ph, &z_hat, &x, &y);\n }\n \n //find stokes coordinate sys in orig frame with respect to boost vector\n findXY(v_ph, v, &x_new, &y_new);\n \n phi=findPhi(x, y, x_new, y_new);//now find rotation between the two coordinate systems\n \n //rotate the stokes vector now to put it in the coordinate system fo the boosted photon and the boost evctor\n mullerMatrixRotation(phi, s, fPtr);\n \n /*\n if ( isnan(*(s+0)) || isnan(*(s+1)) || isnan(*(s+2)) || isnan(*(s+3)) )\n {\n printf(\"A stokes value is nan\\n\\n\");\n }\n */\n \n //find the new coordinates of the rotated stokes vector with the boosted photon and the boost vector\n findXY(v_ph_boosted, v, &x, &y);\n \n //find stokes coordinate sys in orig frame with respect to z axis\n findXY(v_ph_boosted, &z_hat, &x_new, &y_new);\n \n phi=findPhi(x, y, x_new, y_new);//now find rotation between the two coordinate systems\n \n //do the rotation of the stokes vector to put it in the coordinate system of the boosted photon and the z axis\n mullerMatrixRotation(phi, s, fPtr);\n \n /*\n if ( isnan(*(s+0)) || isnan(*(s+1)) || isnan(*(s+2)) || isnan(*(s+3)) )\n {\n printf(\"A stokes value is nan\\n\\n\");\n }\n */\n \n}\n\n\ndouble photonEvent(struct photon *ph, int num_ph, double dt_max, double *all_time_steps, int *sorted_indexes, double *all_flash_vx, double *all_flash_vy, double *all_flash_vz, double *all_fluid_temp, int *scattered_ph_index, int *frame_scatt_cnt, int *frame_abs_cnt, gsl_rng * rand, FILE *fPtr)\n{\n //function to perform single photon scattering\n int i=0, index=0, ph_index=0, event_did_occur=0; //variable event_did_occur is to keep track of wether a scattering or absorption actually occured or not,\n double scatt_time=0, old_scatt_time=0; //keep track of new time to scatter vs old time to scatter to know how much to incrementally propagate the photons if necessary\n double phi=0, theta=0; //phi and theta for the 4 momentum \n double ph_phi=0, flash_vx=0, flash_vy=0, flash_vz=0, fluid_temp=0; \n double *ph_p=malloc(4*sizeof(double)); //pointer to hold only photon 4 momentum @ start\n double *el_p_comov=malloc(4*sizeof(double));//pointer to hold the electron 4 momenta in comoving frame\n double *ph_p_comov=malloc(4*sizeof(double));//pointer to hold the comoving photon 4 momenta\n double *fluid_beta=malloc(3*sizeof(double));//pointer to hold fluid velocity vector\n double *negative_fluid_beta=malloc(3*sizeof(double));//pointer to hold negative fluid velocity vector\n double *s=malloc(4*sizeof(double)); //vector to hold the stokes parameters for a given photon\n \n i=0;\n old_scatt_time=0;\n event_did_occur=0;\n //fprintf(fPtr,\"In this function Num_ph %d\\n\", num_ph);\n //fflush(fPtr);\n \n while (inearest_block_index; //the sorted_indexes gives index of photon with smallest time to potentially scatter then extract the index of the block closest to that photon\n \n flash_vx=*(all_flash_vx+ index);\n flash_vy=*(all_flash_vy+ index);\n fluid_temp=*(all_fluid_temp+ index);\n //if (strcmp(DIM_SWITCH, dim_3d_str)==0)\n #if DIMENSIONS == 3\n {\n flash_vz=*(all_flash_vz+ index);\n }\n #endif\n \n ph_phi=atan2(((ph+ph_index)->r1), (((ph+ph_index)->r0)));\n \n /*\n if (isnan((ph+ph_index)->r0) || isnan((ph+ph_index)->r1) || isnan((ph+ph_index)->r2))\n {\n printf(\"Not a number\\n\");\n }\n \n \n fprintf(fPtr,\"ph_phi=%e\\n\", ph_phi);\n fflush(fPtr);\n */\n\n //convert flash coordinated into MCRaT coordinates\n //printf(\"Getting fluid_beta\\n\");\n \n //if (strcmp(DIM_SWITCH, dim_2d_str)==0)\n #if DIMENSIONS == 2\n {\n (*(fluid_beta+0))=flash_vx*cos(ph_phi);\n (*(fluid_beta+1))=flash_vx*sin(ph_phi);\n (*(fluid_beta+2))=flash_vy;\n }\n #else\n {\n (*(fluid_beta+0))=flash_vx;\n (*(fluid_beta+1))=flash_vy;\n (*(fluid_beta+2))=flash_vz;\n }\n #endif\n \n /*\n fprintf(fPtr,\"FLASH v: %e, %e\\n\", flash_vx,flash_vy);\n fflush(fPtr);\n */\n \n //fill in photon 4 momentum\n //printf(\"filling in 4 momentum in photonScatter for photon index %d\\n\", ph_index);\n //if ((ph+ph_index)->type == SYNCHROTRON_POOL_PHOTON)\n {\n //printf(\"The scattering photon is a seed photon w/ comv freq %e Hz.\\n\", ((ph+ph_index)->comv_p0)*C_LIGHT/PL_CONST);\n //*nu_c_scatt=((ph+ph_index)->comv_p0)*C_LIGHT/PL_CONST;//dont need this anymore b/c the SYNCHROTRON_POOL_PHOTON photon doesnt move from its cell\n \n }\n \n \n *(ph_p+0)=((ph+ph_index)->p0);\n *(ph_p+1)=((ph+ph_index)->p1);\n *(ph_p+2)=((ph+ph_index)->p2);\n *(ph_p+3)=((ph+ph_index)->p3);\n \n *(ph_p_comov+0)=((ph+ph_index)->comv_p0);\n *(ph_p_comov+1)=((ph+ph_index)->comv_p1);\n *(ph_p_comov+2)=((ph+ph_index)->comv_p2);\n *(ph_p_comov+3)=((ph+ph_index)->comv_p3);\n \n //fill in stokes parameters\n *(s+0)=((ph+ph_index)->s0); //I ==1\n *(s+1)=((ph+ph_index)->s1); //Q/I\n *(s+2)=((ph+ph_index)->s2); //U/I\n *(s+3)=((ph+ph_index)->s3); //V/I\n \n /*\n fprintf(fPtr,\"Unscattered Photon in Lab frame: %e, %e, %e,%e, %e, %e, %e\\nStokes params %e %e %e %e\\n\", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3), (ph->r0), (ph->r1), (ph->r2), *(s+0), *(s+1), *(s+2), *(s+3));\n fflush(fPtr);\n fprintf(fPtr,\"Fluid Beta: %e, %e, %e\\n\", *(fluid_beta+0),*(fluid_beta+1), *(fluid_beta+2));\n fflush(fPtr);\n */\n \n \n //first we bring the photon to the fluid's comoving frame\n //lorentzBoost(fluid_beta, ph_p, ph_p_comov, 'p', fPtr);\n //*(ph_p_comov+0)=((ph+ph_index)->comv_p0);\n //*(ph_p_comov+1)=((ph+ph_index)->comv_p1);\n //*(ph_p_comov+2)=((ph+ph_index)->comv_p2);\n //*(ph_p_comov+3)=((ph+ph_index)->comv_p3);\n \n /*\n fprintf(fPtr,\"Old: %e, %e, %e,%e\\n\", ph->p0, ph->p1, ph->p2, ph->p3);\n fflush(fPtr);\n \n fprintf(fPtr, \"Before Scattering, In Comov_frame:\\n\");\n fflush(fPtr);\n fprintf(fPtr, \"ph_comov: %e, %e, %e,%e\\n\", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));\n fflush(fPtr);\n */\n \n //fprintf(fPtr, \"Theta: %e Phi %e Lab: x_tilde: %e, %e, %e, y_tilde: %e %e %e\\n\", theta, phi, *(x_tilde+0), *(x_tilde+1), *(x_tilde+2), *(y_tilde+0), *(y_tilde+1), *(y_tilde+2));\n \n //then rotate the stokes plane by some angle such that we are in the stokes coordinat eystsem after the lorentz boost\n //if (STOKES_SWITCH != 0)\n #if STOKES_SWITCH == ON\n {\n\n stokesRotation(fluid_beta, (ph_p+1), (ph_p_comov+1), s, fPtr);\n \n }\n #endif\n \n //exit(0);\n //second we generate a thermal electron at the correct temperature\n singleElectron(el_p_comov, fluid_temp, ph_p_comov, rand, fPtr);\n \n //fprintf(fPtr,\"el_comov: %e, %e, %e,%e\\n\", *(el_p_comov+0), *(el_p_comov+1), *(el_p_comov+2), *(el_p_comov+3));\n //fflush(fPtr);\n \n \n //third we perform the scattering and save scattered photon 4 monetum in ph_p_comov @ end of function\n event_did_occur=singleScatter(el_p_comov, ph_p_comov, s, rand, fPtr);\n \n \n //fprintf(fPtr,\"After Scattering, After Lorentz Boost to Comov frame: %e, %e, %e,%e\\n\", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));\n //fflush(fPtr);\n //event_did_occur=0;\n if (event_did_occur==1)\n {\n //fprintf(fPtr,\"Within the if!\\n\");\n //fflush(fPtr);\n \n //if the scattering occured have to uodate the phtoon 4 momentum. if photon didnt scatter nothing changes\n //fourth we bring the photon back to the lab frame\n *(negative_fluid_beta+0)=-1*( *(fluid_beta+0));\n *(negative_fluid_beta+1)=-1*( *(fluid_beta+1));\n *(negative_fluid_beta+2)=-1*( *(fluid_beta+2));\n lorentzBoost(negative_fluid_beta, ph_p_comov, ph_p, 'p', fPtr);\n //fprintf(fPtr,\"Scattered Photon in Lab frame: %e, %e, %e,%e\\n\", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3));\n //fflush(fPtr);\n \n #if STOKES_SWITCH == ON\n {\n stokesRotation(negative_fluid_beta, (ph_p_comov+1), (ph_p+1), s, fPtr); //rotate to boost back to lab frame\n \n //save stokes parameters\n ((ph+ph_index)->s0)= *(s+0); //I ==1\n ((ph+ph_index)->s1)= *(s+1);\n ((ph+ph_index)->s2)= *(s+2);\n ((ph+ph_index)->s3)= *(s+3);\n }\n #endif\n \n\n if (((*(ph_p+0))*C_LIGHT/1.6e-9) > 1e4)\n {\n fprintf(fPtr,\"Extremely High Photon Energy!!!!!!!!\\n\");\n fflush(fPtr);\n }\n \n //fprintf(fPtr,\"Old: %e, %e, %e,%e\\n\", ph->p0, ph->p1, ph->p2, ph->p3);\n //fprintf(fPtr, \"Old: %e, %e, %e,%e\\n\", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));\n \n \n //assign the photon its new lab 4 momentum\n ((ph+ph_index)->p0)=(*(ph_p+0));\n ((ph+ph_index)->p1)=(*(ph_p+1));\n ((ph+ph_index)->p2)=(*(ph_p+2));\n ((ph+ph_index)->p3)=(*(ph_p+3));\n \n //assign it the comoving frame 4 momentum\n ((ph+ph_index)->comv_p0)=(*(ph_p_comov+0));\n ((ph+ph_index)->comv_p1)=(*(ph_p_comov+1));\n ((ph+ph_index)->comv_p2)=(*(ph_p_comov+2));\n ((ph+ph_index)->comv_p3)=(*(ph_p_comov+3));\n \n //printf(\"Done assigning values to original struct\\n\");\n \n //incremement that photons number of scatterings\n ((ph+ph_index)->num_scatt)+=1;\n *frame_scatt_cnt+=1; //incrememnt total number of scatterings\n \n\n \n }\n \n }\n else\n {\n // if the photon scatt_time > dt_max\n //have to adjust the time properly so that the time si now appropriate for the next frame\n scatt_time=dt_max;\n updatePhotonPosition(ph, num_ph, scatt_time-old_scatt_time, fPtr); \n event_did_occur=1; //set equal to 1 to get out of the loop b/c other subsequent photons will have scatt_time > dt_max\n \n }\n \n old_scatt_time=scatt_time;\n i++;\n\t}\n //exit(0);\n *scattered_ph_index=ph_index; //save the index of the photon that was scattered\n \n //fprintf(fPtr,\"scattered_ph_index: %d %d\\n\", *scattered_ph_index, (*(sorted_indexes+i-1)));\n //fflush(fPtr);\n \n free(el_p_comov); \n free(ph_p_comov);\n free(fluid_beta); \n free(negative_fluid_beta);\n free(ph_p);\n free(s);\n ph_p=NULL;negative_fluid_beta=NULL;ph_p_comov=NULL; el_p_comov=NULL;\n \n //retrun total time elapsed to scatter a photon\n return scatt_time;\n}\n\nvoid singleElectron(double *el_p, double temp, double *ph_p, gsl_rng * rand, FILE *fPtr)\n{\n //generates an electron with random energy \n double factor=0, gamma=0;\n double y_dum=0, f_x_dum=0, x_dum=0, beta_x_dum=0, beta=0, phi=0, theta=0, ph_theta=0, ph_phi=0;\n gsl_matrix *rot= gsl_matrix_calloc (3, 3); //create matrix thats 3x3 to do rotation \n gsl_vector_view el_p_prime ; //create vector to hold rotated electron 4 momentum\n gsl_vector *result=gsl_vector_alloc (3);\n \n //fprintf(fPtr, \"Temp in singleElectron: %e\\n\", temp);\n if (temp>= 1e7)\n {\n //printf(\"In if\\n\");\n factor=K_B*temp/(M_EL*pow(C_LIGHT,2.0));\n y_dum=1; //initalize loop to get a random gamma from the distribution of electron velocities\n f_x_dum=0;\n while ((isnan(f_x_dum) !=0) || (y_dum>f_x_dum) )\n {\n \n x_dum=gsl_rng_uniform_pos(rand)*(1+100*factor);\n beta_x_dum=pow(1-(pow(x_dum, -2.0)) ,0.5);\n y_dum=gsl_rng_uniform(rand)/2.0;\n \n f_x_dum=pow(x_dum,2)*(beta_x_dum/gsl_sf_bessel_Kn (2, 1.0/factor))*exp(-1*x_dum/factor); //\n //fprintf(fPtr,\"Choosing a Gamma: xdum: %e, f_x_dum: %e, y_dum: %e\\n\", x_dum, f_x_dum, y_dum);\n }\n gamma=x_dum;\n \n }\n else\n {\n\n //printf(\"In else\\n\");\n factor=pow(K_B*temp/M_EL,0.5);\n //calculate a random gamma from 3 random velocities drawn from a gaussian distribution with std deviation of \"factor\"\n gamma=pow( 1- (pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+ pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2) ) ,-0.5); //each vel direction is normal distribution -> maxwellian when multiplied\n }\n \n //fprintf(fPtr,\"Chosen Gamma: %e\\n\",gamma);\n \n beta=pow( 1- (1/pow( gamma,2.0 )) ,0.5);\n //printf(\"Beta is: %e in singleElectron\\n\", beta);\n phi=gsl_rng_uniform(rand)*2*M_PI;\n \n y_dum=1; //initalize loop to get a random theta\n f_x_dum=0;\n while (y_dum>f_x_dum)\n {\n y_dum=gsl_rng_uniform(rand)*1.3;\n x_dum=gsl_rng_uniform(rand)*M_PI;\n f_x_dum=sin(x_dum)*(1-(beta*cos(x_dum)));\n }\n theta=x_dum;\n //fprintf(fPtr,\"Beta: %e\\tPhi: %e\\tTheta: %e\\n\",beta,phi, theta);\n //fill in electron 4 momentum NOT SURE WHY THE ORDER IS AS SUCH SEEMS TO BE E/c, pz,py,px!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \n *(el_p+0)=gamma*(M_EL)*(C_LIGHT);\n *(el_p+1)=gamma*(M_EL)*(C_LIGHT)*beta*cos(theta);\n *(el_p+2)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*sin(phi);\n *(el_p+3)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*cos(phi);\n \n //printf(\"Old: %e, %e, %e,%e\\n\", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3));\n \n el_p_prime=gsl_vector_view_array((el_p+1), 3);\n \n //find angles of photon NOT SURE WHY WERE CHANGING REFERENCE FRAMES HERE???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n ph_phi=atan2(*(ph_p+2), *(ph_p+3)); //Double Check\n ph_theta=atan2(pow( pow(*(ph_p+2),2)+ pow(*(ph_p+3),2) , 0.5) , (*(ph_p+1)) );\n \n //printf(\"Calculated Photon phi and theta in singleElectron:%e, %e\\n\", ph_phi, ph_theta);\n \n //fill in rotation matrix to rotate around x axis to get rid of phi angle\n gsl_matrix_set(rot, 1,1,1);\n gsl_matrix_set(rot, 2,2,cos(ph_theta));\n gsl_matrix_set(rot, 0,0,cos(ph_theta));\n gsl_matrix_set(rot, 0,2,-sin(ph_theta));\n gsl_matrix_set(rot, 2,0,sin(ph_theta));\n gsl_blas_dgemv(CblasNoTrans, 1, rot, &el_p_prime.vector, 0, result);\n \n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));\n\n printf(\"Middle: %e, %e, %e,%e\\n\", *(el_p+0), gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2));\n */\n \n gsl_matrix_set_all(rot,0);\n \n gsl_matrix_set(rot, 0,0,1);\n gsl_matrix_set(rot, 1,1,cos(-ph_phi));\n gsl_matrix_set(rot, 2,2,cos(-ph_phi));\n gsl_matrix_set(rot, 1,2,-sin(-ph_phi));\n gsl_matrix_set(rot, 2,1,sin(-ph_phi));\n gsl_blas_dgemv(CblasNoTrans, 1, rot, result, 0, &el_p_prime.vector);\n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));\n printf(\"Final EL_P_vec: %e, %e, %e,%e\\n\", *(el_p+0), gsl_vector_get(&el_p_prime.vector,0), gsl_vector_get(&el_p_prime.vector,1), gsl_vector_get(&el_p_prime.vector,2));\n */\n \n \n gsl_matrix_free (rot);gsl_vector_free(result);\n}\n\n\nint singleScatter(double *el_comov, double *ph_comov, double *s, gsl_rng * rand, FILE *fPtr)\n{\n //This routine performs a scattering between a photon and a moving electron.\n int i=0, scattering_occured=0;\n double dotprod_1; //to test orthogonality\n double *z_axis_electron_rest_frame=malloc(3*sizeof(double)); //basis vector of the z axis in the elctron rest frame\n double *el_v=malloc(3*sizeof(double));\n double *negative_el_v=malloc(3*sizeof(double));\n double *ph_p_prime=malloc(4*sizeof(double));//use this to keep track of how the ph 4 momentum changes with each rotation\n double *el_p_prime=malloc(4*sizeof(double));\n double phi0=0, phi1=0, phi=0, theta=0;\n double y_dum, f_x_dum, x_dum;\n double x_tilde[3]={0,0,0}, y_tilde[3]={0,0,0}, x_tilde_new[3]={0,0,0}, y_tilde_new[3]={0,0,0};//initalize arrays to hold stokes coordinate system\n gsl_matrix *rot0= gsl_matrix_calloc (3, 3); //create matricies thats 3x3 to do rotations\n gsl_matrix *rot1= gsl_matrix_calloc (3, 3);\n gsl_matrix *scatt= gsl_matrix_calloc (4, 4); //fano's matrix for scattering stokes parameters\n gsl_vector *scatt_result=gsl_vector_alloc (4);\n gsl_vector *result0=gsl_vector_alloc (3); //vectors to hold results of rotations\n gsl_vector *result1=gsl_vector_alloc (3);\n gsl_vector *result=gsl_vector_alloc (4);\n gsl_vector *whole_ph_p=gsl_vector_alloc (4);\n gsl_vector *ph_p_orig=gsl_vector_alloc (4) ;//vector to hold the original incoming photon velocity vector in the electron rest frame\n gsl_vector_view ph_p ;//create vector to hold comoving photon and electron 4 momentum\n gsl_vector_view el_p ;\n gsl_vector_view stokes, test, test_x, test_y;\n \n\n /*\n Dont need these vectors anymore, plus didnt have code to free allocations so it was causing memory leaks\n gsl_vector *result0_x=gsl_vector_alloc (3); //vectors to hold results of rotations for stokes coordinates\n gsl_vector *result1_x=gsl_vector_alloc (3);\n gsl_vector *result0_y=gsl_vector_alloc (3); //vectors to hold results of rotations for stokes coordinates\n gsl_vector *result1_y=gsl_vector_alloc (3);\n */\n \n //fill in z-axis basis vector\n *(z_axis_electron_rest_frame+0)=0;\n *(z_axis_electron_rest_frame+1)=0;\n *(z_axis_electron_rest_frame+2)=1;\n \n /* was for testing against Kraw\n *(s+0)=1; //should be 1.0\n *(s+1)=1;\n *(s+2)=0;\n *(s+3)=0;\n \n *(ph_comov+0)=PL_CONST*1e12/C_LIGHT;\n *(ph_comov+1)=0; //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product\n *(ph_comov+2)=0;\n *(ph_comov+3)=PL_CONST*1e12/C_LIGHT;\n \n theta=85*M_PI/180;\n phi=0;\n dotprod_1=pow(1-(pow(100, -2.0)) ,0.5);\n *(el_comov+0)=100*M_EL*C_LIGHT;\n *(el_comov+1)=100*M_EL*C_LIGHT*dotprod_1*sin(theta)*cos(phi); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product\n *(el_comov+2)=100*M_EL*C_LIGHT*dotprod_1*sin(theta)*sin(phi);\n *(el_comov+3)=100*M_EL*C_LIGHT*dotprod_1*cos(theta);\n */\n \n //fill in electron velocity array and photon 4 momentum\n *(el_v+0)=(*(el_comov+1))/(*(el_comov+0));\n *(el_v+1)=(*(el_comov+2))/(*(el_comov+0));\n *(el_v+2)=(*(el_comov+3))/(*(el_comov+0));\n //printf(\"el_v: %e, %e, %e\\n\", *(el_v+0), *(el_v+1), *(el_v+2));\n \n //lorentz boost into frame where the electron is stationary\n lorentzBoost(el_v, el_comov, el_p_prime, 'e', fPtr);\n lorentzBoost(el_v, ph_comov, ph_p_prime, 'p', fPtr);\n //printf(\"New ph_p in electron rest frame: %e, %e, %e,%e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n \n //rotate 'stokes plane'\n //if (STOKES_SWITCH != 0)\n #if STOKES_SWITCH == ON\n {\n stokesRotation(el_v, (ph_comov+1), (ph_p_prime+1), s, fPtr);\n stokes=gsl_vector_view_array(s, 4);\n\n }\n #endif\n \n //printf(fPtr, \"y_tilde: %e, %e, %e\\n\", *(y_tilde+0), *(y_tilde+1), *(y_tilde+2));\n \n ph_p=gsl_vector_view_array((ph_p_prime+1), 3);\n el_p=gsl_vector_view_array(el_p_prime,4);\n \n gsl_vector_set(ph_p_orig, 0, *(ph_p_prime+0));\n gsl_vector_set(ph_p_orig, 1, *(ph_p_prime+1));\n gsl_vector_set(ph_p_orig, 2, *(ph_p_prime+2));\n gsl_vector_set(ph_p_orig, 3, *(ph_p_prime+3));\n \n //gsl_blas_ddot(&y_tilde_rot.vector, &ph_p.vector, &dotprod_1);\n //fprintf(fPtr, \"After lorentz boost Angle between the y_tilde_rot and the photon velocity vector is: %e\\n\", acos(dotprod_1/ gsl_blas_dnrm2(&ph_p.vector))*180/M_PI);\n \n phi0=atan2(*(ph_p_prime+2), *(ph_p_prime+1) );\n //fprintf(fPtr,\"Photon Phi: %e\\n\", phi0);\n //rotate the axes so that the photon incomes along the x-axis\n gsl_matrix_set(rot0, 2,2,1);\n gsl_matrix_set(rot0, 0,0,cos(-phi0));\n gsl_matrix_set(rot0, 1,1,cos(-phi0));\n gsl_matrix_set(rot0, 0,1,-sin(-phi0));\n gsl_matrix_set(rot0, 1,0,sin(-phi0));\n gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);\n \n //printf(\"Before Scatter rot0: stokes x=(%e, %e, %e) y=(%e, %e, %e)\", gsl_vector_get(result0_x,0), gsl_vector_get(result0_x,1), gsl_vector_get(result0_x,2), gsl_vector_get(result0_y,0), gsl_vector_get(result0_y,1), gsl_vector_get(result0_y,2));\n \n //fprintf(fPtr, \"y_tilde: %e, %e, %e y_tilde_rot_result: %e, %e, %e\\n\", *(y_tilde+0), *(y_tilde+1), *(y_tilde+2), gsl_vector_get(y_tilde_rot_result,0), gsl_vector_get(y_tilde_rot_result,1), gsl_vector_get(y_tilde_rot_result,2));\n \n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));\n */\n \n //set values of ph_p_prime equal to the result and get new phi from result\n *(ph_p_prime+1)=gsl_vector_get(result0,0);\n *(ph_p_prime+2)=0;//gsl_vector_get(result,1); //just directly setting it to 0 now?\n *(ph_p_prime+3)=gsl_vector_get(result0,2);\n \n phi1=atan2(gsl_vector_get(result0,2), gsl_vector_get(result0,0));\n \n \n //printf(\"rotation 1: %e, %e, %e\\n\", *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n //fprintf(fPtr, \"Photon Phi: %e\\n\", phi1);\n //printf(\"make sure the vector view is good: %e, %e, %e,%e\\n\", *(ph_p_prime+0), gsl_vector_get(&ph_p.vector,0), gsl_vector_get(&ph_p.vector,1), gsl_vector_get(&ph_p.vector,2));\n \n \n //rotate around y to bring it all along x\n gsl_matrix_set(rot1, 1,1,1);\n gsl_matrix_set(rot1, 0,0,cos(-phi1));\n gsl_matrix_set(rot1, 2,2,cos(-phi1));\n gsl_matrix_set(rot1, 0,2,-sin(-phi1));\n gsl_matrix_set(rot1, 2,0,sin(-phi1));\n gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);\n \n //fprintf(fPtr, \"y_tilde: %e, %e, %e y_tilde_rot vector view: %e, %e, %e\\n\", *(y_tilde+0), *(y_tilde+1), *(y_tilde+2), gsl_vector_get(&y_tilde_rot.vector,0), gsl_vector_get(&y_tilde_rot.vector,1), gsl_vector_get(&y_tilde_rot.vector,2));\n \n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));\n */\n \n //set values of ph_p_prime equal to the result and get new phi from result\n *(ph_p_prime+1)=*(ph_p_prime+0);//why setting it to the energy?\n *(ph_p_prime+2)=gsl_vector_get(result1,1);\n *(ph_p_prime+3)=0; //just directly setting it to 0 now?\n \n //printf(\"rotation 2: %e, %e, %e, %e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n \n //know that the stokes y axis is in -y_hat direction and stokes x asis is in the z_hat direction due to rotations and making inclimg photn come along x_hat direction, dont need to rotate the stokes plane/vector. this happens as the rotations occur (tested in python code)\n //double checking here\n //printf(\"Before Scatter: stokes x=(%e, %e, %e) y=(%e, %e, %e) ph_p=(%e, %e, %e, %e)\\n\", gsl_vector_get(result1_x,0), gsl_vector_get(result1_x,1), gsl_vector_get(result1_x,2), gsl_vector_get(result1_y,0), gsl_vector_get(result1_y,1), gsl_vector_get(result1_y,2), *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n \n \n //determine if the scattering will occur between photon and electron\n //scattering_occured=comptonScatter(&theta, &phi, rand, fPtr); //determine the angles phi and theta for the photon to scatter into using thompson differential cross section\n scattering_occured=kleinNishinaScatter(&theta, &phi, *(ph_p_prime+0), *(s+1), *(s+2), rand, fPtr);//determine the angles phi and theta for the photon to scatter into using KN differential cross section, if the photon will end up scattering\n \n //fprintf(fPtr,\"Phi: %e, Theta: %e\\n\", phi, theta);\n //theta=2.4475668271885342;\n //phi=4.014719957630734;\n //*(s+0)=1; //should be 1.0\n //*(s+1)=1;\n //*(s+2)=0;\n //*(s+3)=0;\n \n \n if (scattering_occured==1)\n {\n //perform scattering and compute new 4-momenta of electron and photon\n //scattered photon 4 momentum\n gsl_vector_set(result, 0, (*(ph_p_prime+0))/(1+ (( (*(ph_p_prime+0))*(1-cos(theta)) )/(M_EL*C_LIGHT )) ) ); // scattered energy of photon\n gsl_vector_set(result, 1, gsl_vector_get(result,0)*cos(theta) );\n gsl_vector_set(result, 2, gsl_vector_get(result,0)*sin(theta)*sin(phi) );//assume phi is clockwise from z to y\n gsl_vector_set(result, 3, gsl_vector_get(result,0)*sin(theta)*cos(phi) );\n //fprintf(fPtr, \"New ph_p0=%e Old= %e\\n\", gsl_vector_get(result,0), *(ph_p_prime+0));\n //gsl_vector_fprintf(fPtr,result, \"%e\" );\n \n //recalc x_tilde from rotation about y by angle theta do x_tilde=y_tilde X v_ph\n //test =gsl_vector_view_array(gsl_vector_ptr(result, 1), 3);\n \n //scatt_result is a dummy, dont need to change the stokes parameters here, just need to find the axis such that y is out of the plane of k_o-k see Ito figure 12 in polarized emission from stratisfied jets\n \n //gsl_blas_ddot(&y_tilde_rot.vector, &test.vector, &dotprod_1);\n //fprintf(fPtr, \"Angle between the y_tilde_rot and the photon velocity vector is: %e\\n\", acos(dotprod_1/ gsl_blas_dnrm2(&test.vector))*180/M_PI);\n //gsl_vector_fprintf(fPtr,&y_tilde_rot.vector, \"%e\" );\n //gsl_vector_fprintf(fPtr,&x_tilde_rot.vector, \"%e\" );\n \n //exit(0);\n //calculate electron 4 momentum\n //prescattered photon 4 momentum\n gsl_vector_set(whole_ph_p, 0, (*(ph_p_prime+0)));\n gsl_vector_set(whole_ph_p, 1, (*(ph_p_prime+1)));\n gsl_vector_set(whole_ph_p, 2, (*(ph_p_prime+2)));\n gsl_vector_set(whole_ph_p, 3, (*(ph_p_prime+3)));\n \n gsl_vector_sub(whole_ph_p,result); //resut is saved into ph_p vector, unscattered-scattered 4 mometum of photon\n gsl_vector_add(&el_p.vector ,whole_ph_p);\n /*\n printf(\"After scattering:\\n\");\n printf(\"el_p: %e, %e, %e,%e\\n\", gsl_vector_get(&el_p.vector,0), gsl_vector_get(&el_p.vector,1), gsl_vector_get(&el_p.vector,2), gsl_vector_get(&el_p.vector,3));\n printf(\"ph_p: %e, %e, %e,%e\\n\", gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2), gsl_vector_get(result,3));\n */\n \n //rotate back to comoving frame\n *(ph_p_prime+0)=gsl_vector_get(result,0);\n *(ph_p_prime+1)=gsl_vector_get(result,1); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product\n *(ph_p_prime+2)=gsl_vector_get(result,2);\n *(ph_p_prime+3)=gsl_vector_get(result,3);\n gsl_matrix_set_all(rot1,0);\n gsl_matrix_set(rot1, 1,1,1);\n gsl_matrix_set(rot1, 0,0,cos(-phi1));\n gsl_matrix_set(rot1, 2,2,cos(-phi1));\n gsl_matrix_set(rot1, 0,2,sin(-phi1));\n gsl_matrix_set(rot1, 2,0,-sin(-phi1));\n gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);\n /*\n printf(\"Photon Phi: %e\\n\", phi1);\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));\n */\n \n //set values of ph_p_prime to result1 from undoing 2nd rotation\n *(ph_p_prime+1)=gsl_vector_get(result1,0);\n *(ph_p_prime+2)=gsl_vector_get(result1,1);\n *(ph_p_prime+3)=gsl_vector_get(result1,2);\n //printf(\"Undo rotation 2: %e, %e, %e, %e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n //ignore the electron, dont care about it, undo the first rotation\n gsl_matrix_set_all(rot0,0);\n gsl_matrix_set(rot0, 2,2,1);\n gsl_matrix_set(rot0, 0,0,cos(-phi0));\n gsl_matrix_set(rot0, 1,1,cos(-phi0));\n gsl_matrix_set(rot0, 0,1,sin(-phi0));\n gsl_matrix_set(rot0, 1,0,-sin(-phi0));\n gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);\n \n \n /*\n printf(\"Photon Phi: %e\\n\", phi0);\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));\n */\n \n //do the scattering of the stokes vector\n //rotate it by phi and then scatter it and rotate back and then renormalize it such that i=1\n //if (STOKES_SWITCH != 0)\n #if STOKES_SWITCH == ON\n {\n //orient the stokes coordinate system such that its perpendicular to the scattering plane\n findXY(gsl_vector_ptr(ph_p_orig, 1),z_axis_electron_rest_frame, x_tilde, y_tilde);\n findXY(gsl_vector_ptr(result0,0),gsl_vector_ptr(ph_p_orig, 1), x_tilde_new, y_tilde_new);\n phi=findPhi(x_tilde, y_tilde, x_tilde_new, y_tilde_new);\n mullerMatrixRotation(phi, s, fPtr);\n \n //find the theta between the incoming and scattered photons, by doing dot product and taking arccos of it\n theta=acos((gsl_vector_get(ph_p_orig,1)*gsl_vector_get(result0,0)+gsl_vector_get(ph_p_orig,2)*gsl_vector_get(result0,1)+gsl_vector_get(ph_p_orig,3)*gsl_vector_get(result0,2) )/(gsl_vector_get(ph_p_orig,0)*(*(ph_p_prime+0))) );\n \n //do the scattering of the stokes parameters\n gsl_matrix_set(scatt, 0,0,1.0+pow(cos(theta), 2.0)+((1-cos(theta))*(gsl_vector_get(ph_p_orig,0) - gsl_vector_get(result,0))/(M_EL*C_LIGHT ) ) ); //following lundman's matrix\n gsl_matrix_set(scatt, 0,1, sin(theta)*sin(theta));\n gsl_matrix_set(scatt, 1,0, sin(theta)*sin(theta));\n gsl_matrix_set(scatt, 1,1,1.0+cos(theta)*cos(theta));\n gsl_matrix_set(scatt, 2,2, 2.0*cos(theta));\n gsl_matrix_set(scatt, 3,3, 2.0*cos(theta)+ ((cos(theta))*(1-cos(theta))*(gsl_vector_get(ph_p_orig,0) - gsl_vector_get(result,0))/(M_EL*C_LIGHT )) );\n //gsl_matrix_scale(scatt, (gsl_vector_get(result,0)/(*(ph_p_prime+0)))*((gsl_vector_get(result,0)/(*(ph_p_prime+0))))*0.5*3*THOM_X_SECT/(8*M_PI) ); //scale the matrix by 0.5*r_0^2 (\\epsilon/\\epsilon_0)^2 DONT NEED THIS BECAUSE WE NORMALIZE STOKES VECTOR SO THIS CANCELS ITSELF OUT\n gsl_blas_dgemv(CblasNoTrans, 1, scatt, &stokes.vector, 0, scatt_result);\n /*\n fprintf(fPtr,\"before s: %e, %e, %e,%e\\n\", gsl_vector_get(&stokes.vector,0), gsl_vector_get(&stokes.vector,1), gsl_vector_get(&stokes.vector,2), gsl_vector_get(&stokes.vector,3));\n fprintf(fPtr,\"Scatt Matrix 0: %e,%e, %e, %e\\n\", gsl_matrix_get(scatt, 0,0), gsl_matrix_get(scatt, 0,1), gsl_matrix_get(scatt, 0,2), gsl_matrix_get(scatt, 0,3));\n fprintf(fPtr,\"Scatt Matrix 1: %e,%e, %e, %e\\n\", gsl_matrix_get(scatt, 1,0), gsl_matrix_get(scatt, 1,1), gsl_matrix_get(scatt, 1,2), gsl_matrix_get(scatt, 1,3));\n fprintf(fPtr,\"Scatt Matrix 2: %e,%e, %e, %e\\n\", gsl_matrix_get(scatt, 2,0), gsl_matrix_get(scatt, 2,1), gsl_matrix_get(scatt, 2,2), gsl_matrix_get(scatt, 2,3));\n fprintf(fPtr,\"Scatt Matrix 3: %e,%e, %e, %e\\n\", gsl_matrix_get(scatt, 3,0), gsl_matrix_get(scatt, 3,1), gsl_matrix_get(scatt, 3,2), gsl_matrix_get(scatt, 3,3));\n fprintf(fPtr,\"s: %e, %e, %e,%e\\n\", gsl_vector_get(scatt_result,0), gsl_vector_get(scatt_result,1), gsl_vector_get(scatt_result,2), gsl_vector_get(scatt_result,3));\n */\n \n \n //normalize and rotate back\n *(s+0)=gsl_vector_get(scatt_result,0)/gsl_vector_get(scatt_result,0); //should be 1.0\n *(s+1)=gsl_vector_get(scatt_result,1)/gsl_vector_get(scatt_result,0);\n *(s+2)=gsl_vector_get(scatt_result,2)/gsl_vector_get(scatt_result,0);\n *(s+3)=gsl_vector_get(scatt_result,3)/gsl_vector_get(scatt_result,0);\n //fprintf(fPtr,\"s after norm: %e, %e, %e,%e\\n\", gsl_vector_get(&stokes.vector,0), gsl_vector_get(&stokes.vector,1), gsl_vector_get(&stokes.vector,2), gsl_vector_get(&stokes.vector,3));\n \n \n //need to find current stokes coordinate system defined in the plane of k-k_0\n findXY(gsl_vector_ptr(result0,0),gsl_vector_ptr(ph_p_orig, 1), x_tilde, y_tilde);\n \n //then find the new coordinate system between scattered photon 4 onetum and the z axis\n findXY(gsl_vector_ptr(result0,0),z_axis_electron_rest_frame, x_tilde_new, y_tilde_new);\n \n //find phi to transform between the two coodinate systems\n phi=findPhi(x_tilde, y_tilde, x_tilde_new, y_tilde_new);\n \n //do the rotation\n mullerMatrixRotation(phi, s, fPtr);\n }\n #endif\n \n //now update the array with the new scattered photon 4 monetum\n *(ph_p_prime+1)=gsl_vector_get(result0,0);\n *(ph_p_prime+2)=gsl_vector_get(result0,1);\n *(ph_p_prime+3)=gsl_vector_get(result0,2);\n \n //gsl_blas_ddot(&y_tilde_rot.vector, &ph_p.vector, &dotprod_1);\n //fprintf(fPtr, \"Angle between the y_tilde_rot and the photon velocity vector is: %e\\n\", acos(dotprod_1/ gsl_blas_dnrm2(&ph_p.vector))*180/M_PI);\n \n //printf(\"Undo rotation 1: %e, %e, %e, %e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n //deboost photon to lab frame\n *(negative_el_v+0)=(-1*(*(el_v+0)));\n *(negative_el_v+1)=(-1*(*(el_v+1)));\n *(negative_el_v+2)=(-1*(*(el_v+2)));\n \n lorentzBoost(negative_el_v, ph_p_prime, ph_comov, 'p', fPtr);\n //printf(\"Undo boost 1: %e, %e, %e, %e\\n\", *(ph_comov+0), *(ph_comov+1), *(ph_comov+2), *(ph_comov+3));\n \n \n //dont need to find stokes vector and do previosu rotations, can just find the stokes coordinates in function because the stokes coordinate vectors rotate with the photon vector and no rotations to a new stokes coordinate system are needed\n //if (STOKES_SWITCH != 0)\n #if STOKES_SWITCH == ON\n {\n stokesRotation(negative_el_v, (ph_p_prime+1), (ph_comov+1), s, fPtr);\n }\n #endif\n \n //exit(0);\n }\n \n gsl_matrix_free(rot0); gsl_matrix_free(rot1);gsl_matrix_free(scatt);gsl_vector_free(result0);gsl_vector_free(result1);gsl_vector_free(result);\n gsl_vector_free(scatt_result);gsl_vector_free(ph_p_orig);\n gsl_vector_free(whole_ph_p);free(ph_p_prime);free(el_p_prime);free(el_v); free(negative_el_v); free(z_axis_electron_rest_frame);\n \n return scattering_occured;\n}\n\nint comptonScatter(double *theta, double *phi, gsl_rng * rand, FILE *fPtr)\n{\n \n double y_dum, f_x_dum, x_dum;\n \n //generate random theta and phi angles for scattering\n *phi=gsl_rng_uniform(rand)*2*M_PI;\n //printf(\"Phi: %e\\n\", phi);\n \n y_dum=1; //initalize loop to get a random theta\n f_x_dum=0;\n while (y_dum>f_x_dum)\n {\n y_dum=gsl_rng_uniform(rand)*1.09;\n x_dum=gsl_rng_uniform(rand)*M_PI;\n f_x_dum=sin(x_dum)*(1+pow(cos(x_dum),2));\n }\n *theta=x_dum;\n \n return 1;\n}\n\n\nint kleinNishinaScatter(double *theta, double *phi, double p0, double q, double u, gsl_rng * rand, FILE *fPtr)\n{\n //sample theta using: https://doi.org/10.13182/NSE11-57\n double phi_dum=0, cos_theta_dum=0, f_phi_dum=0, f_cos_theta_dum=0, f_theta_dum=0, phi_y_dum=0, cos_theta_y_dum=0, KN_x_section_over_thomson_x_section=0, rand_num=0;\n double mu=0, phi_norm=0, phi_max=0, norm=0;\n int will_scatter=0;\n double energy_ratio= p0/(M_EL*C_LIGHT ); //h*nu / mc^2 , units of p0 is erg/c \n \n //determine the KN cross section over the thomson cross section From RYBICKI AND LIGHTMAN pg 197\n KN_x_section_over_thomson_x_section= (3.0/4.0)*( ( ((1+energy_ratio)/ pow(energy_ratio,3.0))*(((2*energy_ratio)*(1+energy_ratio)/(1+2*energy_ratio)) - log(1+2*energy_ratio))) + (log(1+2*energy_ratio)/(2*energy_ratio)) - ((1+3*energy_ratio)/pow((1+2*energy_ratio),2.0)) );\n rand_num=gsl_rng_uniform(rand);\n \n if ((rand_num<= KN_x_section_over_thomson_x_section) || (p0 < 1e-2*(M_EL*C_LIGHT ) ))\n {\n //include last condition so low energy seed phtoons can scatter (as they should under thompson scattering), calculating KN_x_section_over_thomson_x_section incurs numerical error at very low frequencies\n //fprintf(fPtr,\"In If!\\n\");\n //fflush(fPtr);\n \n //sample a theta and phi from the differential cross sections\n phi_y_dum=1; //initalize loop to get a random phi and theta\n cos_theta_y_dum=1;\n f_cos_theta_dum=0;\n f_phi_dum=0;\n \n while ((cos_theta_y_dum>f_cos_theta_dum))\n {\n //do phi and theta seperately, sample theta using: https://doi.org/10.13182/NSE11-57\n cos_theta_y_dum=gsl_rng_uniform(rand)*2;\n cos_theta_dum=gsl_rng_uniform(rand)*2-1;\n f_cos_theta_dum=pow((1+energy_ratio*(1-cos_theta_dum)),-2)*(energy_ratio*(1-cos_theta_dum)+(1/(1+energy_ratio*(1-cos_theta_dum))) + cos_theta_dum*cos_theta_dum);\n \n }\n *theta=acos(cos_theta_dum);\n mu=1+energy_ratio*(1-cos(*theta));\n f_theta_dum=(pow(mu, -1.0) + pow(mu, -3.0) - pow(mu, -2.0)*pow(sin(*theta), 2.0))*sin(*theta);\n \n while ((phi_y_dum>f_phi_dum) )\n {\n \n #if STOKES_SWITCH == OFF\n {\n //not considering polarization therefore can jjst sample between 0 and 2*pi evenly\n phi_dum=gsl_rng_uniform(rand)*2*M_PI;\n phi_y_dum=-1; // this is to exit the while statement\n \n //fprintf(fPtr,\" phi_dum: %e\\n\", phi_dum);\n //fflush(fPtr);\n\n }\n #else\n {\n if (u==0 && q==0)\n {\n phi_dum=gsl_rng_uniform(rand)*2*M_PI;\n phi_y_dum=-1; // this is to exit the while statement\n\n }\n else\n {\n //if we are considering polarization calulate the norm for the distributiion to be between 1 and 0\n phi_max=abs(atan2(-u,q))/2.0;\n norm=(f_theta_dum + pow(mu, -2.0)*pow(sin(*theta), 3.0) * (q*cos(2*phi_max)-u*sin(2*phi_max)));\n //fprintf(fPtr,\"norm: %e\\n\", norm);\n //fflush(fPtr);\n \n phi_y_dum=gsl_rng_uniform(rand);\n phi_dum=gsl_rng_uniform(rand)*2*M_PI;\n f_phi_dum=(f_theta_dum + pow(mu, -2.0)*pow(sin(*theta), 3.0) * (q*cos(2*phi_dum)-u*sin(2*phi_dum)))/norm; //signs on q and u based on Lundman/ McMaster\n \n //fprintf(fPtr,\"phi_y_dum: %e, theta_dum: %e, mu: %e, f_theta_dum: %e, phi_dum: %e, f_phi_dum: %e, u: %e, q: %e\\n\", phi_y_dum, theta_dum, mu, f_theta_dum, phi_dum, f_phi_dum, u, q);\n //fflush(fPtr);\n\n }\n }\n #endif\n \n }\n *phi=phi_dum;\n \n will_scatter=1;\n }\n else\n {\n will_scatter=0;\n }\n \n return will_scatter;\n}\n\ndouble averagePhotonEnergy(struct photon *ph, int num_ph)\n{\n //to calculate weighted photon energy in ergs\n int i=0;\n #if defined(_OPENMP)\n int num_thread=omp_get_num_threads();\n #endif\n double e_sum=0, w_sum=0;\n \n #pragma omp parallel for reduction(+:e_sum) reduction(+:w_sum)\n for (i=0;iweight != 0)) //dont want account for null or absorbed OLD_COMPTONIZED_PHOTON photons\n #endif\n {\n e_sum+=(((ph+i)->p0)*((ph+i)->weight));\n w_sum+=((ph+i)->weight);\n }\n }\n \n return (e_sum*C_LIGHT)/w_sum;\n}\n\nvoid phScattStats(struct photon *ph, int ph_num, int *max, int *min, double *avg, double *r_avg, FILE *fPtr )\n{\n int temp_max=0, temp_min=INT_MAX, i=0, count=0, count_synch=0, count_comp=0, count_i=0;\n #if defined(_OPENMP)\n int num_thread=omp_get_num_threads();\n #endif\n double sum=0, avg_r_sum=0, avg_r_sum_synch=0, avg_r_sum_comp=0, avg_r_sum_inject=0;\n \n //printf(\"Num threads: %d\", num_thread);\n#pragma omp parallel for num_threads(num_thread) reduction(min:temp_min) reduction(max:temp_max) reduction(+:sum) reduction(+:avg_r_sum) reduction(+:count)\n for (i=0;iweight != 0)) //dont want account for null or absorbed OLD_COMPTONIZED_PHOTON photons\n #endif\n {\n sum+=((ph+i)->num_scatt);\n avg_r_sum+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);\n \n //printf(\"%d %c %e %e %e %e %e %e\\n\", i, (ph+i)->type, (ph+i)->p0, (ph+i)->comv_p0, (ph+i)->r0, (ph+i)->r1, (ph+i)->r2, (ph+i)->num_scatt);\n \n if (((ph+i)->num_scatt) > temp_max )\n {\n temp_max=((ph+i)->num_scatt);\n //printf(\"The new max is: %d\\n\", temp_max);\n }\n \n //if ((i==0) || (((ph+i)->num_scatt)num_scatt)num_scatt);\n //printf(\"The new min is: %d\\n\", temp_min);\n }\n \n if (((ph+i)->type) == INJECTED_PHOTON )\n {\n avg_r_sum_inject+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);\n count_i++;\n }\n \n if ((((ph+i)->type) == COMPTONIZED_PHOTON) || (((ph+i)->type) == OLD_COMPTONIZED_PHOTON))\n {\n avg_r_sum_comp+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);\n count_comp++;\n }\n \n \n count++;\n }\n \n if (((ph+i)->type) == SYNCHROTRON_POOL_PHOTON )\n {\n avg_r_sum_synch+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);\n count_synch++;\n }\n\n \n }\n fprintf(fPtr, \"In this frame Avg r for i type: %e c and o type: %e and s type: %e\\n\", avg_r_sum_inject/count_i, avg_r_sum_comp/count_comp, avg_r_sum_synch/count_synch);\n fflush(fPtr);\n //exit(0);\n \n *avg=sum/count;\n *r_avg=avg_r_sum/count;\n *max=temp_max;\n *min=temp_min;\n \n}\n\nvoid cylindricalPrep(double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array)\n{\n double gamma_infinity=100, t_comov=1*pow(10, 5), ddensity=3e-7;// the comoving temperature in Kelvin, and the comoving density in g/cm^2\n int i=0;\n double vel=pow(1-pow(gamma_infinity, -2.0) ,0.5), lab_dens=gamma_infinity*ddensity;\n \n for (i=0; i= (r00*gamma_infinity))\n {\n *(gamma+i)=gamma_infinity;\n *(pres+i)=(lumi*pow(r00, 2.0/3.0)*pow(*(r+i), -8.0/3.0) )/(12.0*M_PI*C_LIGHT*pow(gamma_infinity, 4.0/3.0));\n }\n else\n {\n *(gamma+i)=(*(r+i))/r00;\n *(pres+i)=(lumi*pow(r00, 2.0))/(12.0*M_PI*C_LIGHT*pow(*(r+i), 4.0) );\n }\n \n vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5);\n *(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);\n *(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);\n *(dens+i)=lumi/(4*M_PI*pow(*(r+i), 2.0)*pow(C_LIGHT, 3.0)*gamma_infinity*(*(gamma+i)));\n *(dens_lab+i)=(*(dens+i))*(*(gamma+i));\n *(temp+i)=pow(3*(*(pres+i))/(A_RAD) ,1.0/4.0);\n //fprintf(fPtr,\"Gamma: %lf\\nR: %lf\\nPres: %e\\nvel %lf\\nX: %lf\\nY %lf\\nVx: %lf\\nVy: %lf\\nDens: %e\\nLab_Dens: %e\\nTemp: %lf\\n\", *(gamma+i), *(r+i), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i));\n\n }\n \n}\n\nvoid structuredFireballPrep(double *r, double *theta, double *x, double *y, double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array, FILE *fPtr)\n{\n //This model is provided by Lundman, Peer, Ryde 2014, use this to compare our MCRaT polarization to their polarizations\n double gamma_0=100, lumi=1e52, r00=1e8, theta_j=1e-2, p=4; //theta_j in paper is 1e-2, 3e-2, 1e-1 and p is 1,2,4\n double T_0=pow(lumi/(4*M_PI*r00*r00*A_RAD*C_LIGHT), 1.0/4.0);\n double eta=0, r_sat=0;\n double vel=0, theta_ratio=0;\n int i=0;\n \n for (i=0;i= theta_j*pow(gamma_0/2, 1.0/p))\n {\n //*(gamma+i)=2; //outside with of shear layer have gamma be 2 like in paper\n eta=2.0;\n }\n \n r_sat=eta*r00;\n \n if ((*(r+i)) >= r_sat)\n {\n *(gamma+i)=eta;\n *(temp+i)=T_0*pow(r_sat/(*(r+i)), 2.0/3.0)/eta;\n }\n else\n {\n *(gamma+i)=(*(r+i))/r_sat; //not sure if this is right but it shouldn't matter since we're injecting our photons far from r00\n *(temp+i)=T_0;\n }\n \n vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5);\n *(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);\n *(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);\n *(dens+i)=M_P*lumi/(4*M_PI*M_P*C_LIGHT*C_LIGHT*C_LIGHT*eta*vel*(*(gamma+i))*(*(r+i))*(*(r+i))); //equation paper has extra c, but then units dont work out\n *(dens_lab+i)=(*(dens+i))*(*(gamma+i));\n *(pres+i)=(A_RAD*pow(*(temp+i), 4.0))/(3);\n //fprintf(fPtr,\"eta: %lf\\nr_sat: %lf\\nGamma: %lf\\nR: %lf\\nTheta: %lf\\nPres: %e\\nvel %lf\\nX: %lf\\nY %lf\\nVx: %lf\\nVy: %lf\\nDens: %e\\nLab_Dens: %e\\nTemp: %lf\\n\\n\", eta, r_sat, *(gamma+i), *(r+i), (*(theta+i)), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i));\n \n }\n \n}\n\n\nvoid dirFileMerge(char dir[200], int start_frame, int last_frame, int numprocs, int angle_id, FILE *fPtr )\n{\n //function to merge files in mcdir produced by various threads\n double *p0=NULL, *p1=NULL, *p2=NULL, *p3=NULL, *comv_p0=NULL, *comv_p1=NULL, *comv_p2=NULL, *comv_p3=NULL, *r0=NULL, *r1=NULL, *r2=NULL, *s0=NULL, *s1=NULL, *s2=NULL, *s3=NULL, *num_scatt=NULL, *weight=NULL;\n int i=0, j=0, k=0, isNotCorrupted=0, num_types=9; //just save lab 4 momentum, position and num_scatt by default\n int increment=1;\n char filename_k[2000]=\"\", file_no_thread_num[2000]=\"\", cmd[2000]=\"\", mcdata_type[20]=\"\";\n char group[200]=\"\", *ph_type=NULL;\n hid_t file, file_new, group_id, dspace;\n hsize_t dims[1]={0};\n herr_t status, status_group;\n hid_t dset_p0, dset_p1, dset_p2, dset_p3, dset_comv_p0, dset_comv_p1, dset_comv_p2, dset_comv_p3, dset_r0, dset_r1, dset_r2, dset_s0, dset_s1, dset_s2, dset_s3, dset_num_scatt, dset_weight, dset_weight_frame, dset_ph_type;\n \n //printf(\"Merging files in %s\\n\", dir); \n //#pragma omp parallel for num_threads(num_thread) firstprivate( filename_k, file_no_thread_num, cmd,mcdata_type,num_files, increment ) private(i,j,k)\n // i < last frame because calculation before this function gives last_frame as the first frame of the next process set of frames to merge files for\n \n #if COMV_SWITCH == ON && STOKES_SWITCH == ON\n {\n num_types=17;//both switches on, want to save comv and stokes\n }\n #elif COMV_SWITCH == ON || STOKES_SWITCH == ON\n {\n num_types=13;//either switch acivated, just subtract 4 datasets\n }\n #else\n {\n num_types=9;//just save lab 4 momentum, position and num_scatt\n }\n #endif\n \n #if SAVE_TYPE == ON\n {\n num_types+=1;\n }\n #endif\n \n \n for (i=start_frame;i=3000)\n {\n increment=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n }\n #endif\n \n j=0;\n for (k=0;k=0) || (isNotCorrupted != 0 ))\n {\n \n //fprintf(fPtr, \"In IF\\n\" );\n //fflush(fPtr);\n \n if (isNotCorrupted != 0)\n {\n //if the data is corrupted overwrite the file\n file_new = H5Fcreate (file_no_thread_num, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n }\n \n //now allocate enough ememory for j number of points\n p0=malloc(j*sizeof(double)); p1=malloc(j*sizeof(double)); p2=malloc(j*sizeof(double)); p3=malloc(j*sizeof(double));\n comv_p0=malloc(j*sizeof(double)); comv_p1=malloc(j*sizeof(double)); comv_p2=malloc(j*sizeof(double)); comv_p3=malloc(j*sizeof(double));\n r0=malloc(j*sizeof(double)); r1=malloc(j*sizeof(double)); r2=malloc(j*sizeof(double));\n s0=malloc(j*sizeof(double)); s1=malloc(j*sizeof(double)); s2=malloc(j*sizeof(double)); s3=malloc(j*sizeof(double));\n num_scatt=malloc(j*sizeof(double)); weight=malloc(j*sizeof(double));\n ph_type=malloc((j)*sizeof(char));\n \n j=0;\n for (k=0;k> Opening file %s\\n\", file_num);\n fflush(fPtr);\n \n snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, file_end);\n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr);\n fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr);\n fread(&r_min_index, sizeof(int)*1, 1,hydroPtr);\n fread(&r_max_index, sizeof(int)*1, 1,hydroPtr);\n fclose(hydroPtr);\n \n //fortran indexing starts @ 1, but C starts @ 0\n r_min_index--;//=r_min_index-1;\n r_max_index--;//=r_max_index-1;\n theta_min_index--;//=theta_min_index-1;\n theta_max_index--;//=theta_max_index-1;\n \n elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index); //max index is max number of elements minus 1, there add one to get total number of elements\n fprintf(fPtr,\"Elem %d\\n\", elem);\n fprintf(fPtr,\"Limits %d, %d, %d, %d, %d, %d\\n\", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); \n fflush(fPtr);\n \n //now with number of elements allocate data\n dens_unprc=malloc(elem*sizeof(float));\n vel_r_unprc=malloc(elem*sizeof(float));\n vel_theta_unprc=malloc(elem*sizeof(float));\n pres_unprc=malloc(elem*sizeof(float));\n \n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n /*\n for (i=0;i> Opening file %s\\n\", full_file);\n //fflush(fPtr);\n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n \n //elem=(r_max_index-r_min_index)*(theta_max_index-theta_min_index);\n //fprintf(fPtr,\"Elem %d\\n\", elem);\n //fprintf(fPtr,\"Limits %d, %d, %d, %d, %d, %d\\n\", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); \n //fflush(fPtr);\n\n fread(pres_unprc, sizeof(float),elem, hydroPtr); //data\n \n fclose(hydroPtr);\n \n \n /*\n for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)\n { \n for (k=0; k<(r_max_index+1-r_min_index); k++)\n {\n \n fprintf(fPtr,\"Pres %d: %e\\n\", ( j*(r_max_index+1-r_min_index)+k ), *(pres_unprc+( j*(r_max_index+1-r_min_index)+k )));\n //fprintf(fPtr,\"Pres %d: %e\\n\", ( j*(r_max_index)+k ), *(pres_unprc+( j*(r_max_index)+k )));\n fflush(fPtr);\n \n }\n }\n exit(0); \n */\n \n //R\n snprintf(hydrofile,sizeof(hydrofile),\"%s%s\",hydro_prefix,\"grid-x1.data\" );\n hydroPtr=fopen(hydrofile, \"r\");\n //fprintf(fPtr,\">> Opening file %s\\n\", hydrofile);\n //fflush(fPtr);\n \n i=0;\n while (i> Opening file %s\\n\", hydrofile);\n //fflush(fPtr);\n \n i=0;\n while (i injection radius\n elem_factor=0;\n elem=0;\n while (elem==0)\n {\n elem_factor++;\n elem=0;\n for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)\n { \n for (k=0; k<(r_max_index+1-r_min_index); k++)\n {\n i=r_min_index+k; //look at indexes of r that are included in small hydro file\n //if I have photons do selection differently than if injecting photons\n if (ph_inj_switch==0)\n {\n //if calling this function when propagating photons, choose blocks based on where the photons are\n if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (ph_rmax + elem_factor*C_LIGHT/fps) ))\n {\n // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )\n elem++;\n }\n }\n else\n {\n //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient\n if (((r_inj - C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (r_inj + C_LIGHT/fps) ))\n {\n // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )\n elem++;\n }\n \n }\n \n }\n }\n }\n fprintf(fPtr, \"Number of post restricted Elems: %d %e\\n\", elem, r_inj);\n fflush(fPtr);\n\n \n (*pres)=malloc (elem * sizeof (double ));\n (*velx)=malloc (elem * sizeof (double ));\n (*vely)=malloc (elem * sizeof (double ));\n (*dens)=malloc (elem * sizeof (double ));\n (*x)=malloc (elem * sizeof (double ));\n (*y)=malloc (elem * sizeof (double ));\n (*r)=malloc (elem * sizeof (double ));\n (*theta)=malloc (elem * sizeof (double ));\n (*gamma)=malloc (elem * sizeof (double ));\n (*dens_lab)=malloc (elem * sizeof (double ));\n //szx becomes delta r szy becomes delta theta\n (*szx)=malloc (elem * sizeof (double ));\n (*szy)=malloc (elem * sizeof (double ));\n (*temp)=malloc (elem * sizeof (double ));\n\n elem=0;\n for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)\n { \n for (k=0; k<(r_max_index+1-r_min_index); k++)\n {\n r_index=r_min_index+k; //look at indexes of r that are included in small hydro file\n theta_index=theta_min_index+j;\n \n if (ph_inj_switch==0)\n {\n if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) ))\n {\n (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));\n (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));\n (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));\n (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));\n (*r)[elem]=*(r_unprc+r_index);\n (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);\n (*szy)[elem]=(M_PI/2)/2000;\n (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis\n (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c\n (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);\n (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n elem++;\n }\n }\n else\n {\n if (((r_inj - C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + C_LIGHT/fps) ))\n {\n (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));\n (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));\n (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));\n (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));\n (*r)[elem]=*(r_unprc+r_index);\n (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);\n (*szy)[elem]=(M_PI/2)/2000;\n (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis\n (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c\n (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);\n (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n elem++;\n \n }\n }\n }\n }\n\n (*number)=elem;\n //fprintf(fPtr, \"Number of post restricted Elems: %d %e\\n\", elem, r_inj);\n //fflush(fPtr);\n \n \n free(pres_unprc); //works when not being freed?\n //fprintf(fPtr, \"pres Done\\n\\n\");\n //fflush(fPtr);\n \n free(vel_r_unprc);\n //fprintf(fPtr, \"vel_r Done\\n\\n\");\n //fflush(fPtr);\n \n free(vel_theta_unprc);\n //fprintf(fPtr, \"vel_theta Done\\n\\n\");\n //fflush(fPtr);\n \n free(dens_unprc);\n //fprintf(fPtr, \"dens Done\\n\\n\");\n //fflush(fPtr);\n \n free(r_unprc); \n //fprintf(fPtr, \"r Done\\n\\n\");\n //fflush(fPtr);\n \n free(theta_unprc); \n //fprintf(fPtr, \"theta Done\\n\\n\");\n //fflush(fPtr);\n \n pres_unprc=NULL;\n vel_r_unprc=NULL;\n vel_theta_unprc=NULL;\n dens_unprc=NULL;\n r_unprc=NULL;\n theta_unprc=NULL;\n \n //fprintf(fPtr, \"ALL Done\\n\\n\");\n //fflush(fPtr);\n}\n\n", "meta": {"hexsha": "80bd2767cab1854de40c499f0fd5bcdd95a35052", "size": 228721, "ext": "c", "lang": "C", "max_stars_repo_path": "Src/mclib.c", "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "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": "Src/mclib.c", "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "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": "Src/mclib.c", "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T09:13:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:13:42.000Z", "avg_line_length": 45.3002574767, "max_line_length": 420, "alphanum_fraction": 0.5508457903, "num_tokens": 66745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.18102937100442973}} {"text": "/*\n\n\n Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at\n\n http://aws.amazon.com/apache2.0/\n\n or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n */\n\n#ifndef NNTYPES_H\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef __NVCC__\n#include \n#include \n#endif\n#include \n#include \n\nclass NNDataSetBase;\nclass NNLayer;\nclass NNNetwork;\nclass NNWeight;\n\n// Activates step by step CPU validation\n#define VALIDATION\n#ifdef VALIDATION\nextern \"C\"\n{\n #include \n}\n#endif\n\n\nstatic const float NN_VERSION = 0.81f;\nstatic const float MIN_ERROR = 1.0e-12f;\nstatic const float MIN_ACTIVATION = 0.000001f;\nstatic const float MAX_ACTIVATION = 0.999999f;\nstatic const float MAX_VALUE = 999999999999999.0f;\n\ntemplate struct GpuBuffer;\n\nenum \n{\n DefaultBatch = 512\n};\n\nenum TrainingMode \n{\n SGD = 0,\n Momentum = 1,\n AdaGrad = 2,\n Nesterov = 3,\n RMSProp = 4,\n AdaDelta = 5,\n};\n\nostream& operator<< (ostream& out, const TrainingMode& e);\n\nenum ErrorFunction \n{\n L1,\n L2,\n CrossEntropy,\n ScaledMarginalCrossEntropy,\n};\n\nostream& operator<< (ostream& out, const ErrorFunction& e);\n\nenum Activation {\n Sigmoid,\n Tanh,\n RectifiedLinear,\n Linear,\n ParametricRectifiedLinear,\n SoftPlus,\n SoftSign,\n SoftMax,\n ReluMax,\n LinearMax,\n};\n\nostream& operator<< (ostream& out, const Activation& a);\n\nenum WeightInitialization\n{\n Xavier,\n CaffeXavier,\n Gaussian,\n Uniform,\n UnitBall,\n Constant \n};\n \nostream& operator<< (ostream& out, const WeightInitialization& w);\n \nenum PoolingFunction {\n None,\n Max,\n Average,\n Stochastic,\n LocalContrastNormalization,\n LocalResponseNormalization,\n GlobalTemporal,\n};\n\nostream& operator<< (ostream& out, const PoolingFunction& p);\n\n#include \"kernels.h\"\n#include \"GpuSort.h\"\n#include \"NNEnum.h\"\n#include \"NNWeight.h\"\n#include \"NNLayer.h\"\n#include \"NNNetwork.h\"\n\n\nint MPI_Bcast_string(string& s);\n\nstruct NNDataSetDimensions\n{\n uint32_t _dimensions;\n uint32_t _width;\n uint32_t _height;\n uint32_t _length;\n};\n\nstruct NNDataSetBase {\n\n string _name; // Dataset name\n NNDataSetEnums::DataType _dataType; // Dataset type (see above enum)\n uint32_t _attributes; // Dataset characteristics (see NNDataSetEnum::Attributes in NNEnum.h)\n uint32_t _examples; // Number of examples\n uint32_t _dimensions; // Dimensionality of data set\n uint32_t _width; // Dataset x dimension\n uint32_t _height; // Dataset y dimension\n uint32_t _length; // Dataset z dimension\n uint32_t _stride; // Stride between examples\n NNDataSetEnums::Sharding _sharding; // Sharding of dataset for parallel execution\n uint32_t _minX; // Beginning of local X sharding for model parallel execution \n uint32_t _maxX; // End of local X sharding for model parallel execution\n uint64_t _sparseDataSize; // Total sparse datapoints\n uint32_t _maxSparseDatapoints; // Maximum observed sparse datapoints per example\n NNFloat _sparseDensity; // Overall sparse density (0.0 - 1.0)\n vector _vSparseStart; // Vector of sparse datapoint starts per example\n GpuBuffer* _pbSparseStart; // GPU copy of _vSparseStart\n vector _vSparseEnd; // Vector of sparse datapoint ends per example\n GpuBuffer* _pbSparseEnd; // GPU copy of _vSparseEnd\n vector _vSparseIndex; // Vector of sparse indices\n GpuBuffer* _pbSparseIndex; // GPU copy of _vSparseIndex\n GpuBuffer* _pbDenoisingRandom; // Denoising randoms \n \n // Transposed sparse lookup for sparse backpropagation\n vector _vSparseDatapointCount;\n vector _vSparseTransposedStart;\n uint32_t _sparseTransposedIndices;\n GpuBuffer* _pbSparseTransposedStart;\n GpuBuffer* _pbSparseTransposedEnd;\n GpuBuffer* _pbSparseTransposedIndex;\n\n // States\n bool _bDenoising;\n bool _bDirty;\n uint32_t _batch;\n \n \n\n\n NNDataSetBase();\n NNDataSetDimensions GetDimensions();\n uint32_t GetExamples() { return _examples; };\n\n virtual bool SaveNetCDF(const string& fname) = 0;\n virtual bool WriteNetCDF(netCDF::NcFile& nfc, const string& fname, const uint32_t n) = 0;\n virtual ~NNDataSetBase() = 0;\n virtual void RefreshState(uint32_t batch) = 0;\n virtual bool Shard(NNDataSetEnums::Sharding sharding) = 0;\n virtual bool UnShard() = 0;\n virtual vector > getMemoryUsage() = 0;\n virtual bool CalculateSparseDatapointCounts() = 0;\n virtual bool GenerateSparseTransposedMatrix(uint32_t batch, NNLayer* pLayer) = 0;\n virtual bool CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer) = 0;\n virtual bool CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer) = 0;\n virtual bool CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient) = 0;\n virtual bool SetDenoising(bool flag) = 0;\n virtual bool GenerateDenoisingData() = 0;\n virtual bool LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual bool LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual bool LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual bool CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta = (NNFloat)0.0) = 0;\n virtual bool CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta = (NNFloat)0.0) = 0;\n virtual float CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual float CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual float CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual float CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual float CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual float CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;\n virtual bool CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;\n virtual bool CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0; \n virtual bool CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0; \n virtual bool CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0; \n};\n\nostream& operator<< (ostream& out, NNDataSetEnums::Attributes& a);\nostream& operator<< (ostream& out, NNDataSetEnums::Kind& k);\nostream& operator<< (ostream& out, NNDataSetEnums::DataType& t);\nostream& operator<< (ostream& out, NNDataSetEnums::Sharding& s);\n\n\n\ntemplate class NNDataSet : public NNDataSetBase {\npublic:\n friend class NNetwork;\n friend class NNLayer;\n friend vector LoadNetCDF(const string& fname);\n friend bool SaveNetCDF(const string& fname, vector vDataSet);\n\nprivate:\n\n vector _vData;\n GpuBuffer* _pbData;\n vector _vSparseData;\n GpuBuffer* _pbSparseData;\n GpuBuffer* _pbSparseTransposedData;\n\n\n // Force constructor private\n NNDataSet(const string& fname, uint32_t n);\n bool Rename(const string& name);\n bool SaveNetCDF(const string& fname);\n bool WriteNetCDF(netCDF::NcFile& nfc, const string& fname, const uint32_t n);\n void RefreshState(uint32_t batch) {} \n bool Shard(NNDataSetEnums::Sharding sharding);\n bool UnShard();\n vector > getMemoryUsage();\n bool CalculateSparseDatapointCounts();\n bool GenerateSparseTransposedMatrix(uint32_t batch, NNLayer* pLayer);\n bool CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer);\n bool CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer);\n bool CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient); \n bool SetDenoising(bool flag);\n bool GenerateDenoisingData();\n bool LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n bool LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n bool LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n bool CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta);\n bool CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta);\n float CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n float CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n float CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n float CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n float CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n float CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);\n bool CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);\n bool CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);\n bool CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta); \n bool CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);\n\npublic:\n\n ~NNDataSet();\n void Shuffle();\n T GetDataPoint(uint32_t n, uint32_t x, uint32_t y = 0, uint32_t z = 0);\n bool SetDataPoint(T v, uint32_t n, uint32_t x, uint32_t y = 0, uint32_t z = 0);\n uint32_t GetSparseDataPoints(uint32_t n);\n uint32_t GetSparseIndex(uint32_t n, uint32_t i);\n bool SetSparseIndex(uint32_t n, uint32_t i, uint32_t v);\n T GetSparseDataPoint(uint32_t n, uint32_t i);\n bool SetSparseDataPoint(uint32_t n, uint32_t i, T v);\n};\n\ntemplate bool NNDataSet::LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n kLoadInputUnit(position, batch, stride, pUnit, _pbData->_pDevData);\n return true;\n}\n\ntemplate bool NNDataSet::LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) \n{\n if (_attributes & NNDataSetEnums::Boolean)\n kLoadSparseInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData);\n else\n kLoadSparseAnalogInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData);\n return true;\n}\n\ntemplate bool NNDataSet::LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) \n{\n if (_attributes & NNDataSetEnums::Boolean)\n kLoadSparseDenoisedInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbDenoisingRandom->_pDevData);\n else\n kLoadSparseAnalogDenoisedInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData);\n return true;\n}\n\ntemplate bool NNDataSet::CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta) \n{\n if (_attributes & NNDataSetEnums::Boolean)\n kCalculateSparseZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pUnit, beta);\n else\n kCalculateSparseAnalogZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, pUnit, beta);\n return true;\n}\n\ntemplate bool NNDataSet::CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta) \n{\n if (_attributes & NNDataSetEnums::Boolean)\n kCalculateSparseDenoisedZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbDenoisingRandom->_pDevData, pUnit, beta);\n else\n kCalculateSparseAnalogDenoisedZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, pUnit, beta);\n return true;\n}\n\ntemplate bool NNDataSet::CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer)\n{\n // Rebuild sparse data table if dataset changed\n if (_bDirty || (batch != _batch))\n { \n GenerateSparseTransposedMatrix(batch, pLayer);\n }\n\n // Initialize transposed sparse offsets\n _pbSparseTransposedEnd->Copy(_pbSparseTransposedStart->_pDevData);\n \n // Call appropriate matrix generation kernel\n if (_attributes & NNDataSetEnums::Boolean)\n kCalculateSparseTransposedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData);\n else\n kCalculateSparseTransposedAnalogMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData); \n \n return true;\n}\n\ntemplate bool NNDataSet::CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer)\n{\n\n // Rebuild sparse data table if dataset changed\n if (_bDirty || (batch != _batch))\n { \n GenerateSparseTransposedMatrix(batch, pLayer);\n }\n\n // Initialize transposed sparse offsets\n _pbSparseTransposedEnd->Copy(_pbSparseTransposedStart->_pDevData);\n \n // Call appropriate matrix generation kernel \n if (_attributes & NNDataSetEnums::Boolean)\n kCalculateSparseTransposedDenoisedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData);\n else\n kCalculateSparseTransposedAnalogDenoisedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData); \n \n \n#if 0 \n vector vSparseTransposedStart(53120); \n vector vSparseTransposedEnd(53120);\n _pbSparseTransposedStart->Download(&vSparseTransposedStart[0]);\n _pbSparseTransposedEnd->Download(&vSparseTransposedEnd[0]);\n for (uint32_t i = 0; i < 53120; i++)\n printf(\"%6u %9u %9u %9u %9u\\n\", i, vSparseTransposedStart[i], vSparseTransposedEnd[i], vSparseTransposedEnd[i] - vSparseTransposedStart[i], (uint32_t)_vSparseDatapointCount[i]);\n exit(-1);\n#endif \n return true;\n}\n\n\ntemplate bool NNDataSet::CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient)\n{ \n if (_attributes & NNDataSetEnums::Boolean)\n kCalculateSparseTransposedWeightGradient(alpha, beta, m, n, _pbSparseTransposedStart->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pDelta, pWeightGradient);\n else\n kCalculateSparseTransposedAnalogWeightGradient(alpha, beta, m, n, _pbSparseTransposedStart->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData, pDelta, pWeightGradient); \n return true;\n}\n\ntemplate float NNDataSet::CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;\n if (_attributes & NNDataSetEnums::Boolean)\n return kCalculateSparseL1Error(position, batch, stride, pUnit, \n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n bSparseIgnoreZero);\n else\n return kCalculateSparseAnalogL1Error(position, batch, stride, pUnit, \n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n _pbSparseData->_pDevData,\n bSparseIgnoreZero); \n }\n else \n return kCalculateL1Error(position, batch, stride, pUnit, _pbData->_pDevData);\n}\n\ntemplate float NNDataSet::CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero; \n if (_attributes & NNDataSetEnums::Boolean)\n return kCalculateSparseL2Error(position, batch, stride, pUnit, \n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n bSparseIgnoreZero);\n else\n return kCalculateSparseAnalogL2Error(position, batch, stride, pUnit, \n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n _pbSparseData->_pDevData,\n bSparseIgnoreZero); \n }\n else\n return kCalculateL2Error(position, batch, stride, pUnit, _pbData->_pDevData);\n}\n\ntemplate float NNDataSet::CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero; \n return kCalculateSparseCrossEntropyError(position, batch, stride, pUnit,\n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n bSparseIgnoreZero);\n }\n else\n return kCalculateCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);\n}\n\ntemplate float NNDataSet::CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero; \n return kCalculateSparseScaledMarginalCrossEntropyError(position, batch, stride, pUnit,\n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n bSparseIgnoreZero);\n }\n else\n return kCalculateScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);\n}\n\ntemplate float NNDataSet::CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n { \n if (_attributes & NNDataSetEnums::Boolean)\n {\n return kCalculateSparseMultinomialCrossEntropyError(position, batch, stride, pUnit,\n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData);\n }\n else\n return kCalculateSparseAnalogMultinomialCrossEntropyError(position, batch, stride, pUnit,\n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n _pbSparseData->_pDevData);\n }\n else\n return kCalculateMultinomialCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);\n}\n\ntemplate float NNDataSet::CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)\n{\n if (_attributes & NNDataSetEnums::Sparse) \n {\n if (_attributes & NNDataSetEnums::Boolean)\n return kCalculateSparseMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,\n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData);\n else\n return kCalculateSparseAnalogMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,\n _pbSparseStart->_pDevData, \n _pbSparseEnd->_pDevData, \n _pbSparseIndex->_pDevData,\n _pbSparseData->_pDevData);\n }\n else\n return kCalculateMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);\n}\n\ntemplate bool NNDataSet::CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;\n kCalculateSparseL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);\n }\n else\n kCalculateL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);\n return true;\n}\n\ntemplate bool NNDataSet::CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;\n kCalculateSparseCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);\n }\n else\n kCalculateCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);\n return true;\n}\n\ntemplate bool NNDataSet::CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)\n{\n if (_attributes & NNDataSetEnums::Sparse)\n {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;\n kCalculateSparseScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);\n }\n else\n {\n kCalculateScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);\n }\n return true;\n}\n\ntemplate bool NNDataSet::CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)\n{\n if (_attributes & NNDataSetEnums::Sparse) {\n bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero; \n if (_attributes & NNDataSetEnums::Boolean) \n {\n kCalculateSparseOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero); \n } \n else \n {\n kCalculateSparseAnalogOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, bSparseIgnoreZero);\n }\n } \n else \n {\n kCalculateOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);\n }\n return true;\n}\n\n\n\nvector LoadNetCDF(const string& fname);\nbool SaveNetCDF(const string& fname, vector vDataset);\nvector LoadImageData(const string& fname);\nvector LoadCSVData(const string& fname);\nvector LoadJSONData(const string& fname);\nvector LoadAudioData(const string& name);\n\n#define NNTYPES_H\n#endif\n", "meta": {"hexsha": "15e76a8dc2f3ec3293121384755a2dfee029bc99", "size": 27034, "ext": "h", "lang": "C", "max_stars_repo_path": "src/amazon/dsstne/engine/NNTypes.h", "max_stars_repo_name": "just4jc/amazon-dsstne", "max_stars_repo_head_hexsha": "7d57d23f4971e2c95fd9933d1c71a1c67ab2d63a", "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/amazon/dsstne/engine/NNTypes.h", "max_issues_repo_name": "just4jc/amazon-dsstne", "max_issues_repo_head_hexsha": "7d57d23f4971e2c95fd9933d1c71a1c67ab2d63a", "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/amazon/dsstne/engine/NNTypes.h", "max_forks_repo_name": "just4jc/amazon-dsstne", "max_forks_repo_head_hexsha": "7d57d23f4971e2c95fd9933d1c71a1c67ab2d63a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3450087566, "max_line_length": 318, "alphanum_fraction": 0.7123252201, "num_tokens": 7016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.173900672123696}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"core_allvars.h\"\n#include \"core_proto.h\"\n\n#define IMF_CONSTANT IMF_norm/(IMF_slope + 1.0) \n\n// Local Proto-Types //\n\nvoid update_SN_stars_array(int p, double stars, double dt, int tree, int ngal);\nvoid update_stellar_tracking(int p, double stars, double dt, int tree, int ngal);\n\n// External Functions //\n\nvoid update_from_SN_feedback(int p, int centralgal, double reheated_mass, double ejected_mass, double mass_stars_recycled, double mass_metals_new, double NSN, double dt) \n{\n\n double metallicity, metallicityHot, dust_fraction_cold, dust_fraction_hot;\n double dust_fraction_coldhot, dust_fraction_hotcold; // These are the dust fractions defined by M_colddust / (Mcold + Mhot) and M_hotdust / (Mcold + Mhot). \n // These second dust fractions are required because when we annihilate dust from SN we want the TOTAL amount to be NSN * eta * Ms.\n\n // Dust constants, taken mainly from Dayal, Ferrara and Saro 2011.\n double yd = 0.5 / 1.0e10 * Hubble_h; // Amount of dust mass created from each supernova event. Units of Msun.\n double eta = 0.4; // Coupling between shock energy and annihilation of dust.\n double Ms = 6.8e3 / 1.0e10 * Hubble_h; // Amount of mass that is accelerated to 100km/s by SN blastwave. Units of Msun. \n double dust_added = 0.0, dust_removed = 0.0;\n\n XASSERT((reheated_mass >= 0.0) && (ejected_mass >= 0.0) && (mass_stars_recycled >= 0.0) && (mass_metals_new >= 0.0), \"When trying to update from the supernova feedback we got negative masses.\\nReheated Mass = %.4e (1.0e10 Msun/h) \\t Ejected Mass = %.4e (1.0e10 Msun/h) \\t Mass of Stars Recycled = %.4e (1.0e10 Msun/h) \\t Mass of Metals Added = %.4e (1.0e10 Msun/h)\\n\", reheated_mass, ejected_mass, mass_stars_recycled, mass_metals_new);\n \n Gal[p].StellarMass -= mass_stars_recycled; // The supernova remnants are instantly moved back into the cold ISM. \n Gal[p].Total_Stellar_Stars -= mass_stars_recycled;\n\n if (Gal[p].Total_Stellar_Stars < 0.0)\n Gal[p].Total_Stellar_Stars = 0.0;\n \n Gal[p].ColdGas += mass_stars_recycled; \n\n Gal[p].DustColdGas += yd * NSN; // Dust is created by supernova (something) on cold gas. \n Gal[p].ColdGas -= yd * NSN; // Hence the created dust is subtracted from the cold gas reservoir.\n\n dust_added += yd * NSN;\n\n if(Gal[p].ColdGas > 1.0e-10)\n Gal[p].MetalsColdGas += mass_metals_new; // ISM is enriched by new metals.\n else\n Gal[centralgal].MetalsHotGas += mass_metals_new;\n\n // Here we do checks to see if we need to rescale the amount of mass that has been ejected/reheated. //\n\n if(reheated_mass > Gal[p].ColdGas) // Just perform this check again to be sure.\n reheated_mass = Gal[p].ColdGas; // Because SF takes gas out of cold resevoir.\n \n if(ejected_mass > Gal[centralgal].HotGas)\n ejected_mass = Gal[centralgal].HotGas; \n\n metallicity = get_metallicity(Gal[p].ColdGas, Gal[p].MetalsColdGas);\n dust_fraction_cold = get_dust_fraction(Gal[p].ColdGas, Gal[p].DustColdGas);\n dust_fraction_coldhot = get_dust_fraction(Gal[p].ColdGas + Gal[p].HotGas + Gal[p].EjectedMass, Gal[p].DustColdGas);\n\n Gal[p].ColdGas -= reheated_mass;\n Gal[p].MetalsColdGas -= reheated_mass * metallicity;\n Gal[p].DustColdGas -= reheated_mass * dust_fraction_cold; // Dust that has been reheated to the hot reservoir.\n Gal[p].DustColdGas -= NSN * eta * Ms * dust_fraction_coldhot; // Dust that has been annihilated by shocks.\n\n dust_removed += NSN * eta * Ms * dust_fraction_coldhot;\n\n Gal[centralgal].HotGas += reheated_mass;\n Gal[centralgal].MetalsHotGas += reheated_mass * metallicity;\n Gal[centralgal].DustHotGas += reheated_mass * dust_fraction_cold; \n\n metallicityHot = get_metallicity(Gal[centralgal].HotGas, Gal[centralgal].MetalsHotGas);\n dust_fraction_hot = get_dust_fraction(Gal[p].HotGas, Gal[p].DustHotGas);\n dust_fraction_hotcold = get_dust_fraction(Gal[p].ColdGas + Gal[p].HotGas + Gal[p].EjectedMass, Gal[p].DustHotGas);\n // When dust_fraction_hotcold is calculated is irrelevant (i.e., before or after mass is added/subtracted from ColdGas).\n // This is because mass is conserved between ColdGas and HotGas during this step.\n\n Gal[centralgal].HotGas -= ejected_mass;\n Gal[centralgal].MetalsHotGas -= ejected_mass * metallicityHot;\n Gal[centralgal].DustHotGas -= ejected_mass * dust_fraction_hot; // Dust that has been ejected from the galaxy.\n Gal[centralgal].DustHotGas -= NSN * eta * Ms * dust_fraction_hotcold; // Dust that has been annihilated by shocks.\n dust_removed += NSN * eta * Ms * dust_fraction_hotcold;\n \n Gal[centralgal].EjectedMass += ejected_mass;\n Gal[centralgal].MetalsEjectedMass += ejected_mass * metallicityHot;\n Gal[centralgal].DustEjectedMass += ejected_mass * dust_fraction_hot; \n\n Gal[centralgal].EjectedMassSN += ejected_mass;\n\n Gal[p].GridOutflowRate[Halo[Gal[centralgal].HaloNr].SnapNum] += ejected_mass / dt; \n\n Gal[p].GrandSum -= mass_stars_recycled;\n\n if(Gal[p].ColdGas < 0.0) // Some final checks. \n Gal[p].ColdGas = 0.0;\n if(Gal[p].MetalsColdGas < 0.0)\n Gal[p].MetalsColdGas = 0.0;\n if(Gal[p].StellarMass < 0.0)\n Gal[p].StellarMass = 0.0;\n if(Gal[centralgal].HotGas < 0.0)\n Gal[centralgal].HotGas = 0.0;\n if(Gal[p].MetalsHotGas < 0.0)\n Gal[p].MetalsHotGas = 0.0; \n if(Gal[p].GrandSum < 0.0)\n Gal[p].GrandSum = 0.0;\n\n if (Gal[p].DustColdGas < 0.0)\n Gal[p].DustColdGas = 0.0;\n if (Gal[p].DustHotGas < 0.0)\n Gal[p].DustHotGas = 0.0; \n}\n\n\nvoid update_from_star_formation(int p, double stars, double dt, int step, bool ismerger, int tree, int ngal)\n{\n \n double metallicity = get_metallicity(Gal[p].ColdGas, Gal[p].MetalsColdGas);\n double dust_fraction_cold = get_dust_fraction(Gal[p].ColdGas, Gal[p].DustColdGas);\n double time_spanned;\n\n // If the SF episode was from a merger the stars are placed in different reservoirs. \n if(!ismerger)\n {\n Gal[p].SfrDisk[step] += stars / dt;\n Gal[p].SfrDiskColdGas[step] = Gal[p].ColdGas;\n Gal[p].SfrDiskColdGasMetals[step] = Gal[p].MetalsColdGas;\n } else\n {\n \n Gal[p].SfrBulge[step] += stars / dt;\n Gal[p].SfrBulgeColdGas[step] += Gal[p].ColdGas;\n Gal[p].SfrBulgeColdGasMetals[step] += Gal[p].MetalsColdGas;\n \n Gal[p].BulgeMass += stars;\n Gal[p].MetalsBulgeMass += stars;\n\n }\n\n // If we're doing delayed SN we need to update the tracking \n if (ismerger == true)\n { \n time_spanned = 0.0;\n }\n else\n {\n time_spanned = dt;\n }\n \n //time_spanned = dt;\n\n if (IRA == 0)\n { \n update_SN_stars_array(p, stars, time_spanned, tree, ngal);\n }\n\n if (PhotonPrescription == 1)\n {\n update_stellar_tracking(p, stars, dt, tree, ngal);\n }\n\n // update gas and metals from star formation \n Gal[p].ColdGas -= stars;\n Gal[p].MetalsColdGas -= metallicity * stars;\n Gal[p].StellarMass += stars;\n Gal[p].MetalsStellarMass += metallicity * stars;\n Gal[p].DustColdGas -= dust_fraction_cold * stars; // When stars form they eat up dust. \n if (Gal[p].ColdGas < 0.0)\n Gal[p].ColdGas = 0.0;\n if (Gal[p].MetalsColdGas < 0.0)\n Gal[p].MetalsColdGas = 0.0;\n\n}\n\nvoid starformation_and_feedback(int p, int centralgal, double time, double dt, int halonr, int step, int tree, int ngal)\n{\n double reff, tdyn, strdot, stars;\n double cold_crit; \n double reheated_mass = 0.0, mass_metals_new = 0.0, mass_stars_recycled = 0.0, ejected_mass = 0.0, NSN = 0.0;\n\n // Initialise variables\n strdot = 0.0;\n\n // First we check to see if we need to do delayed supernova feedback.\n\n if(IRA == 0)\n {\n do_previous_recycling(p, centralgal, step, dt); \n\n // The total amount that the reservoirs need to be adjusted by for this evolution step (i.e., ALL steps) has already been determined.\n // Within each substep (i.e., each `step` iteration) we ask 'how many iterations are left?' and then adjusts the reservoirs by this amount.\n // After the reservoirs have been updated, we subtract the amount of mass that we added from the running totals.\n //\n // These running totals are required because contemporaneous SN could cause extra mass to be added/removed within the next step iteration. \n\n update_from_SN_feedback(p, centralgal, Gal[p].reheated_mass / (STEPS-step), Gal[p].ejected_mass / (STEPS-step), Gal[p].mass_stars_recycled / (STEPS-step), Gal[p].mass_metals_new / (STEPS-step), Gal[p].NSN / (STEPS-step), dt);\n\n Gal[p].reheated_mass -= Gal[p].reheated_mass / (STEPS-step);\n Gal[p].ejected_mass -= Gal[p].ejected_mass / (STEPS-step);\n Gal[p].mass_stars_recycled -= Gal[p].mass_stars_recycled / (STEPS-step);\n Gal[p].mass_metals_new -= Gal[p].mass_metals_new / (STEPS-step);\n Gal[p].NSN -= Gal[p].NSN / (STEPS-step);\n\n }\n\n // star formation recipes \n if(SFprescription == 0)\n {\n // we take the typical star forming region as 3.0*r_s using the Milky Way as a guide\n reff = 3.0 * Gal[p].DiskScaleRadius;\n tdyn = reff / Gal[p].Vvir;\n\n // from Kauffmann (1996) eq7 x piR^2, (Vvir in km/s, reff in Mpc/h) in units of 10^10Msun/h \n cold_crit = 0.19 * Gal[p].Vvir * reff;\n\n if(Gal[p].ColdGas > cold_crit && tdyn > 0.0)\n \tstrdot = SfrEfficiency * (Gal[p].ColdGas - cold_crit) / tdyn;\n else\n {\n \tstrdot = 0.0;\n }\n }\n else\n {\n printf(\"No star formation prescription selected!\\n\");\n ABORT(0);\n }\n\n stars = strdot * dt;\n if(stars < 0.0)\n stars = 0.0;\n\n if(SupernovaRecipeOn == 1)\n { \n if(IRA == 0)\n do_contemporaneous_SN(p, centralgal, dt, &stars, &reheated_mass, &mass_metals_new, &mass_stars_recycled, &ejected_mass, &NSN); \n else if(IRA == 1)\n {\n do_IRA_SN(p, centralgal, &stars, &reheated_mass, &mass_metals_new, &mass_stars_recycled, &ejected_mass, &NSN); \n } \n\n } \n \n if(stars > Gal[p].ColdGas) // we do this check in 'do_current_sn()' but if supernovarecipeon == 0 then we don't do the check.\n {\n double factor = Gal[p].ColdGas / stars; \n stars *= factor; \n }\n \n update_from_star_formation(p, stars, dt, step, false, tree, ngal);\n \n update_from_SN_feedback(p, centralgal, reheated_mass, ejected_mass, mass_stars_recycled, mass_metals_new, NSN, dt);\n\n // check for disk instability\n if(DiskInstabilityOn)\n check_disk_instability(p, centralgal, halonr, time, dt, step, tree, ngal);\n\n}\n\n// This function will calculate the fraction of stars formed in snapshot i that go nova in snapshot j.\n// Will also calculate the mass fraction of stars formed in snapshot i that go nova in snapshot j.\n// Based off equation (17) and (24) of Mutch et al. (2016).\n//\n// INPUT: The bounds for the integral (m_low and m_high). ## UNITS: Msun.\n// \t: Pointers to modify the values for number and mass fraction of stars that go nova (*Delta_Eta and *Delta_m). ## UNITS: Msun^-1 (Delta_Eta) and unitless (Delta_m).\n//\n// OUTPUT: None but delta_Eta, the number fraction of stars, and delta_m, the mass fraction of stars, will be modified.\n\nvoid calculate_Delta_Eta(double m_low, double m_high, double *Delta_Eta, double *Delta_m)\n{\n\n if (m_low < 8.0)\n m_low = 8.0;\n\n if (m_high < 8.0)\n m_high = 8.0;\n\n int32_t bin_idx_low = round((m_low - m_IMFbins_low) / (m_IMFbins_delta)); \n int32_t bin_idx_high = round((m_high - m_IMFbins_low) / (m_IMFbins_delta)); \n\n if (bin_idx_high == N_massbins)\n --bin_idx_high;\n\n if (bin_idx_low == N_massbins)\n --bin_idx_low;\n\n *Delta_Eta = IMF_CONSTANT * (IMF_massgrid_eta[bin_idx_high] - IMF_massgrid_eta[bin_idx_low]);\n *Delta_m = IMF_CONSTANT * (IMF_massgrid_m[bin_idx_high] - IMF_massgrid_m[bin_idx_low]);\n\n}\n\n// This function determines the amount of mass reheated for a supernova event.\n//\n// INPUT: The number fraction of stars that have gone nova (Delta_Eta) ## UNITS: Msun^-1.\n// \t: The mass of stars formed (stars). ## UNITS: 1.0e10Msun/h (code units).\n// \t: The maximum velocity of the galaxy disc (Vmax). ## UNITS: km/s.\n//\n// OUTPUT: The amount of mass reheated by the supernova event. ## UNITS: 1.0e10Msun/h (code units). \n\ndouble calculate_reheated_mass(double Delta_Eta, double stars, double Vmax)\n{\n\n // if(stars < 1e-10)\n // return 0.0;\n\n double epsilon_mass;\n\n if(RescaleSN == 0)\n { \n epsilon_mass = FeedbackReheatingEpsilon;\n } else\n {\n epsilon_mass = alpha_mass * (0.5 + pow(Vmax/V_mass, -beta_mass));\n }\n\n\n\n if (epsilon_mass > epsilon_mass_max)\n {\n epsilon_mass = epsilon_mass_max; // We enforce a maximum value for the mass loading factor. \n }\n\n double reheated_mass = Delta_Eta/Eta_SNII * stars * epsilon_mass;\n\n return reheated_mass; \n\n}\n\n// This function determines the amount of energy injected from a supernova event. \n//\n// INPUT: The number fraction of stars that have gone nova (Delta_Eta) ## UNITS: Msun^-1.\n// \t: The mass of stars formed (stars). ## UNITS: 1.0e10Msun/h (code units).\n// \t: The maximum velocity of the galaxy disc (Vmax). ## UNITS: km/s.\n//\n// OUTPUT: The amount of energy from a supernova event. ## UNITS: erg. \n\ndouble calculate_reheated_energy(double Delta_Eta, double stars, double Vmax)\n{\n\n double epsilon_energy;\n\n if(RescaleSN == 0)\n {\n epsilon_energy = FeedbackEjectionEfficiency;\n } else \n {\n epsilon_energy = alpha_energy * (0.5 + pow(Vmax/V_energy, -beta_energy));\n }\n\n double reheated_energy = 0.5 * Delta_Eta * stars * epsilon_energy * EnergySN; // Delta_Eta was in Msun so need to convert to stars to Msun. \n \n return reheated_energy; \n\n}\n\n// This function calculates the mass of stars that would have gone supernova in time t.\n// Function and fit taken from Portinari et al. (1998).\n//\n// INPUT: Time (in Myr).\n//\n// OUTPUT: Mass of stars (in Msun) that would have gone Nova in time t.\n\ndouble calculate_coreburning(double t)\n{\n\n /*\n double a = 0.7473; // Fits from Portinari et al. (1998). \n double b = -2.6979;\n double c = -4.7659;\n double d = 0.5934;\n\n double m = pow(10, a/log10(t) + b * exp(c/log10(t)) + d); \n\n return m; \n */\n\n int32_t bin_idx = (t - coreburning_tbins_low) / (coreburning_tbins_delta); \n\n if (bin_idx < 0) // Time is so short that only stars with mass greater than 120Msun can go nova.\n return 120.0;\n\n if (bin_idx > N_tbins) // Time is so long that all stars within the IMF range can go nova.\n return 8.0; \n\n return coreburning_times[bin_idx];\n\n \n}\n\n// If the cold gas that has been reheated has enough energy, it is possible to unbind some of the gas in the hot halo.\n// This function determines this threshhold and how much mass is unbound and ejected.\n//\n// INPUT: Amount of cold gas reheated by supernova events (reheated_mass). ## UNITS: 1.0e10Msun/h (code units).\n// \t: Amount of energy injected from the supernova events (reheated_energy). ## UNITS: erg.\n// \t: Virial velocity of the background FoF halo (Vvir). ## UNITS: km/s.\n//\n// OUTPUT: Mass of ejected material. ## UNITS: 1.0e10Msun/h (code units).\n//\n// Note: Be aware here that a number of unit changes have occurred.\n// This is necessary because of how Joules are defined. \n\ndouble calculate_ejected_mass(double *reheated_mass, double reheated_energy, double Vvir) \n{\n double ejected_mass;\n double Delta_Ehot;\n const double Joule_to_erg = 0.5 * SOLAR_MASS / 1.0e3 * 1.0e3 * 1.0e3 * 1.0e7; // Note: This is ergs assuming the mass used is in kg.\n // As we use 1.0e10 Msun/h our energy isn't quite ergs.\n // However we have kept this consistent throughout allowing the factor to be cancelled.\n const double inv_Joule_to_erg = 1.0 / Joule_to_erg;\n \n if(Vvir > 0.0)\n {\n Delta_Ehot = *reheated_mass * Vvir * Vvir * Joule_to_erg; // Change in the thermal energy of the hot resevoir in erg..\n // Note the units here. Want final answer in Ergs (which is 1e-7 Joules) which has SI units of kg m^2 s^-2.\n // We change the mass from 1.0e10Msun/h to kg. Change virial velocity from km/s to m/s. Finally change Joules to erg. \n\n if(reheated_energy > Delta_Ehot) // Have enough energy to have some ejected mass.\n {\n \tejected_mass = (reheated_energy - Delta_Ehot) * inv_Joule_to_erg / (Vvir * Vvir); // Balance between the excess thermal energy and the thermal energy of the hot gas.\n // Energy changed from erg to Joules (kg m^2 s^-2) then divided by virial velocity (converted to m/s) giving final units of kg.\n\n }\n else // Not enough energy to eject mass. \n {\n ejected_mass = 0.0;\n *reheated_mass = reheated_energy * inv_Joule_to_erg / (Vvir * Vvir); // Amount of mass that can be reheated to virial temperature of the hot halo.\n }\n\n } \t\t\t\t\t\n else\n ejected_mass = 0.0;\n\t\t\n if(ejected_mass < 0.0)\n ejected_mass = 0.0;\n\n return ejected_mass;\n\n}\n\n// This function answers the question, \"How many stars formed in the previous time steps will explode during the current supernova timestep.\"\n// Note: Since the time scale on which we calculate SN feedback is variable (defined by the user in 'TimeResolutionSN') we use the terminology 'supernova timestep'.\n// Double note: This function is different to \"do_contemporaneous_SN\" because that looks at the stars formed during the CURRENT STAR FORMATION time step, not previous ones.\nvoid do_previous_SN(int p, int centralgal, double dt)\n{\n double reheated_mass = 0.0; \n double reheated_energy = 0.0;\n double mass_stars_recycled = 0.0;\n double mass_metals_new = 0.0;\n double ejected_mass = 0.0;\n double NSN = 0.0; // This is the number of supernova events during this time step.\n\n int i; \n double m_low = -1.0, m_high = -1.0, t_low = -1.0, t_high = -1.0;\n double Delta_Eta, Delta_m;\n double time_until_next_SN;\n\n if(dt * UnitTime_in_Megayears / Hubble_h < TimeResolutionSN) // If the star formation time scale is smaller than the time scale on which we do SN feedback\n time_until_next_SN = TimeResolutionSN; // Then the time that we next calculate delayed SN feedback would be given dictated by the time resolution of SN. \n else // Otherwise the star formation time scale is larger than the SN feedback time scale.\n {\n time_until_next_SN = dt * UnitTime_in_Megayears / Hubble_h; // Then the time that we next calculate delayed SN feedback is in the next SF timestep.\n } \n\n if(SupernovaRecipeOn == 1) // Calculating the ejected mass due to previous star formation episodes.\n { \n for(i = 1; i < SN_Array_Len; ++i)\n {\n if(Gal[p].SN_Stars[i] < 1e-10)\n\t continue;\n\n // First calculate the smallest star which would have expended its H and He and gone supernova. \n // This defines the mass boundary below which a star will not go nova in the current SN step.\n\n t_low = (i * TimeResolutionSN) / 2.0 + time_until_next_SN; // (i * TimeResolutionSN) is the number of stars that were formed that many megayears ago. time_until_next_SN allows us to ask how many of stars will explode in this SN step.\n if(t_low < 2)\n \t t_low = 2;\n if (t_low > 45)\n m_low = 120.0;\n \n m_low = calculate_coreburning(t_low); \n\n if (m_low < 8.0) // We enforce that SN-II only occur in stars M > 8Msun. \n m_low = 8.0;\n\n if (m_low > 120.0)\n continue;\n\n // Next we calculate the largest stellar mass which would have expended its H and He and gone supernova.\n // This defines the mass boundary beyond which a star would have gone nova BEFORE the current SN step. \n\n t_high = (i * TimeResolutionSN) / 2.0; // (i * TimeResolutionSN) is the number of stars that were formed that many Megayears ago. The / 2.0 factor arises from the fact that we assume stars were formed in a single co-eval burst in the middle of this period.\n if(t_high < 2)\n t_high = 2;\n\n m_high = calculate_coreburning(t_high);\n\n\n if (m_high < 8) // In this instance every star that has formed in i Myr ago has already gone supernova and accounted for.\n continue;\n\n if (m_high > 120.0)\n continue;\n\n calculate_Delta_Eta(m_low, m_high, &Delta_Eta, &Delta_m); // Calculate the number and mass fraction of stars i Myr ago that go supernova in the current SF step. \n reheated_mass += calculate_reheated_mass(Delta_Eta, Gal[p].SN_Stars[i], Gal[centralgal].Vmax); // Update the amount of mass reheated from previous stars that have gone nova.\n\n reheated_energy += calculate_reheated_energy(Delta_Eta, Gal[p].SN_Stars[i], Gal[centralgal].Vmax); // Update the energy injected from previous stars that have gone nova. \n mass_stars_recycled += Delta_m * Gal[p].SN_Stars[i]; // Update the amount of stellar mass recycled from previous stars that have gone nova.\n\n // Since stars have gone supernova, need to update the number of stars remaining at that time. \n if (PhotonPrescription == 1)\n {\n Gal[p].Stellar_Stars[i] -= Delta_m * Gal[p].SN_Stars[i]; \n if (Gal[p].Stellar_Stars[i] < 0.0)\n Gal[p].Stellar_Stars[i] = 0.0;\n }\n\n Gal[p].SN_Stars[i] -= Delta_m * Gal[p].SN_Stars[i];\n if (Gal[p].SN_Stars[i] < 0.0)\n Gal[p].SN_Stars[i] = 0.0;\n\n\n mass_metals_new += Delta_m / m_SNII * Yield * Gal[p].SN_Stars[i]; // Update the amount of new metals that the supernova has enriched the ISM with.\n\n NSN += Delta_Eta * Gal[p].SN_Stars[i] * 1.0e10 / Hubble_h; // The number of supernova events will be simply given by the number fraction of stars that exploded times the mass of stars. \n \n XASSERT(reheated_mass >= 0.0, \"i = %d \\t Reheated mass = %.4e \\t t_low = %.4e Myr \\t m_low = %.4e \\t t_high = %.4e Myr \\t m_high = %.4e\\n\", i, reheated_mass, t_low, m_low, t_high, m_high); // Just make sure we're doing this right.\n\n } \n \n if(reheated_mass > Gal[p].ColdGas) // Can't reheated more cold gas than we currently have.\n reheated_mass = Gal[p].ColdGas;\n \n XASSERT(reheated_mass >= 0.0, \"Reheated mass = %.4e \\t t_low = %.4e Myr \\t m_low = %.4e \\t t_high = %.4e Myr \\t m_high = %.4e\\n\", reheated_mass, t_low, m_low, t_high, m_high); // Just make sure we're doing this right.\n assert(reheated_energy >= 0.0);\n assert(mass_stars_recycled >= 0.0);\n assert(mass_metals_new >= 0.0);\n\n ejected_mass = calculate_ejected_mass(&reheated_mass, reheated_energy, Gal[centralgal].Vmax); // Calculate the amount of mass ejected from supernova events.\n\n XASSERT(ejected_mass >= 0.0, \"For galaxy %d the ejected mass was %.4e \\t reheated_mass = %.4e\\n\", p, ejected_mass, reheated_mass); \n }\n\n Gal[p].reheated_mass = reheated_mass;\n Gal[p].ejected_mass = ejected_mass;\n Gal[p].mass_stars_recycled = mass_stars_recycled;\n Gal[p].mass_metals_new = mass_metals_new;\n Gal[p].NSN = NSN;\n \n}\n\n/*\nvoid do_current_SN(int p, int centralgal, int halonr, double *stars, double *reheated_mass, double *mass_metals_new, double *mass_stars_recycled, double *ejected_mass)\n{\n\n *reheated_mass = 0.0; \n double reheated_energy = 0.0;\n *mass_stars_recycled = 0.0;\n *mass_metals_new = 0.0;\n *ejected_mass = 0.0;\n\n double Delta_Eta = Eta_SNII;\n double Delta_m = RecycleFraction;\n double mass_fraction = 1.0; \n\n *mass_stars_recycled = Delta_m * (*stars); \n *reheated_mass = calculate_reheated_mass(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the amount of mass reheated from stars that have gone nova. \n\n if(*reheated_mass > Gal[p].ColdGas) // Can only reheat as much cold gas we have available.\n *reheated_mass = Gal[p].ColdGas;\n if((*reheated_mass + *stars > Gal[p].ColdGas) && (*reheated_mass + *stars > 0.0))\n {\n double factor = Gal[p].ColdGas / (*reheated_mass + *stars);\n *reheated_mass *= factor;\n *stars *= factor; \n }\n\n\n *mass_metals_new = mass_fraction * Yield * (*stars); // Update the amount of new metals that the supernova has enriched the ISM with.\n reheated_energy = calculate_reheated_energy(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the energy injected from previous stars that have gone nova. \n \n assert(*reheated_mass >= 0.0); // Just make sure we're doing this right.\n assert(reheated_energy >= 0.0);\n assert(*mass_stars_recycled >= 0.0);\n assert(*mass_metals_new >= 0.0);\n\n *ejected_mass = calculate_ejected_mass(&(*reheated_mass), reheated_energy, Gal[centralgal].Vvir); // Calculate the amount of mass ejected from supernova events. \n\n}\n*/\n\nvoid do_previous_recycling(int p, int centralgal, int step, double dt) \n{\n \n if(Gal[p].StellarAge_Numerator > 0.0)\n { \n double t_low, t_high;\n double m_low, m_high;\n double Delta_Eta, Delta_m;\n double mass_stars_recycled;\n double NSN; \n \n double mwmsa = Gal[p].StellarAge_Numerator / Gal[p].StellarAge_Denominator; // The numerator is weighted by the age of the stars with the denominator simply being the number of stars.\n double time_into_snap = dt * step; \n\n t_high = (mwmsa - ((Age[Gal[p].SnapNum - 1]) - time_into_snap)) * UnitTime_in_Megayears / Hubble_h;\n if (t_high < 2.0)\n t_high = 2.0;\n if (t_high > 45.0)\n m_high = 8.0;\n else\n m_high = calculate_coreburning(t_high);\n\n t_low = (mwmsa - (Age[Gal[p].SnapNum] - time_into_snap)) * UnitTime_in_Megayears / Hubble_h;\n if (t_low < 2.0)\n t_low = 2.0;\n\n if (t_low > 45.0)\n m_low = 8.0;\n else\n m_low = calculate_coreburning(t_low);\n\n\n calculate_Delta_Eta(m_low, m_high, &Delta_Eta, &Delta_m); // Calculate the number and mass fraction of stars from snapshot i that go nova in the snapshot we are evolving FROM. \n mass_stars_recycled = Delta_m * Gal[p].StellarAge_Denominator; // Update the amount of stellar mass recycled from previous stars that have gone nova.\n NSN = Delta_Eta * Gal[p].StellarAge_Denominator * 1.0e10 / Hubble_h;\n update_from_SN_feedback(p, centralgal, 0.0, 0.0, mass_stars_recycled, 0.0, NSN, dt);\n } \n}\n\n// In this function we answer the question, \"How many stars formed in the current star formation time step will explode by the time we next calculate our supernova feedback?\"\n// Note: This function only concerns itself with stars formed in the CURRENT STAR FORMATION time step, unlike \"do_previous_SN\" which focuses on calculated SN feedback from PREVIOUS STAR FORMATION time steps.\n\nvoid do_contemporaneous_SN(int p, int centralgal, double dt, double *stars, double *reheated_mass, double *mass_metals_new, double *mass_stars_recycled, double *ejected_mass, double *NSN)\n{\n\n *reheated_mass = 0.0; \n double reheated_energy = 0.0;\n *mass_stars_recycled = 0.0;\n *mass_metals_new = 0.0;\n *ejected_mass = 0.0;\n \n double m_low, m_high, t_low;\n double Delta_Eta, Delta_m;\n double fac;\n \n if(dt * UnitTime_in_Megayears / Hubble_h / 2.0 < TimeResolutionSN) // If the star formation time scale is smaller than the time scale on which we do SN feedback\n t_low = (TimeResolutionSN - Gal[p].Total_SN_SF_Time); // Then our 'sub-grid' SN feedback time will be the time from this SF episode until we next calculate SN feedback (divided by 2 as we assume the stars are formed in the middle of the interval).\n else // Otherwise the star formation time scale is larger than the SN feedback time scale.\n t_low = (dt * UnitTime_in_Megayears / Hubble_h) / 2.0; // Then the feedback time will be the time from this SF event to the next star formation event. This is because SN feedback is only calculated when star formation occurs regardless of the actual value of 'TimeResolutionSN'. \n \n if (t_low < 2.0)\n t_low = 2.0;\n \n m_low = calculate_coreburning(t_low); \n if(m_low < 8.0)\n m_low = 8.0;\n \n if(m_low > 120.0)\n return; \n \n m_high = 120.0; \n\n calculate_Delta_Eta(m_low, m_high, &Delta_Eta, &Delta_m); // Calculate the number and mass fraction of stars i Myr ago that go supernova in the current SF step. \n *reheated_mass = calculate_reheated_mass(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the amount of mass reheated from previous stars that have gone nova.\n\n if((*stars + *reheated_mass) > Gal[p].ColdGas && (*stars + *reheated_mass) > 0.0)\n {\n fac = Gal[p].ColdGas / (*stars + *reheated_mass);\n *stars *= fac;\n *reheated_mass *= fac;\n } \n\n reheated_energy += calculate_reheated_energy(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the energy injected from previous stars that have gone nova. \n *mass_stars_recycled += Delta_m * (*stars); // Update the amount of stellar mass recycled from previous stars that have gone nova.\n *mass_metals_new += Delta_m / m_SNII * Yield * (*stars); // Update the amount of new metals that the supernova has enriched the ISM with.\n\n if(*reheated_mass > Gal[p].ColdGas) // Can't reheated more cold gas than we currently have.\n *reheated_mass = Gal[p].ColdGas;\n\n *ejected_mass = calculate_ejected_mass(&(*reheated_mass), reheated_energy, Gal[centralgal].Vmax); // Calculate the amount of mass ejected from supernova events. \n *NSN = Delta_Eta * (*stars * 1.0e10 / Hubble_h);\n\n assert(*reheated_mass >= 0.0); // Just make sure we're doing this right.\n assert(reheated_energy >= 0.0);\n assert(*mass_stars_recycled >= 0.0);\n assert(*mass_metals_new >= 0.0);\n assert(*ejected_mass >= 0.0); \n\n}\n\nvoid do_IRA_SN(int p, int centralgal, double *stars, double *reheated_mass, double *mass_metals_new, double *mass_stars_recycled, double *ejected_mass, double *NSN)\n{\n\n double fac;\n *reheated_mass = 0.0;\n *mass_metals_new = 0.0;\n *mass_stars_recycled = 0.0;\n *ejected_mass = 0.0;\n\n *reheated_mass = calculate_reheated_mass(Eta_SNII, *stars, Gal[centralgal].Vmax);\n *NSN = Eta_SNII * (*stars);\n\n if((*stars + *reheated_mass) > Gal[p].ColdGas && (*stars + *reheated_mass) > 0.0)\n {\n fac = Gal[p].ColdGas / (*stars + *reheated_mass);\n *stars *= fac;\n *reheated_mass *= fac;\n } \n\n double reheated_energy = calculate_reheated_energy(Eta_SNII, *stars, Gal[centralgal].Vmax); \n\n *ejected_mass = calculate_ejected_mass(&(*reheated_mass), reheated_energy, Gal[centralgal].Vmax);\n\t\n if(*ejected_mass < 0.0)\n *ejected_mass = 0.0;\n \n *mass_metals_new = Yield * (*stars); \n *mass_stars_recycled = RecycleFraction * (*stars);\n\n}\n\n// Local Functions //\n\n// This function updates the array which holds the amount of stars formed in the past 50 Myr.\n// As we only need this array for doing delayed SN, if we are using the IRA then this function will never be called.\n// If the SF timestep is less than the resolution on which we do supernova feedback then we will keep track of the total stars formed over these small timesteps and then update them all in one bin.\n// If the SF timestep is larger than the resolution on which we do supernova feedback we will spread the stars formed evenly over a number of elements (>= 1). \n//\n// INPUT: The index of the galaxy (p).\n// \t: The number of stars formed in the current SF episode (stars). ## UNITS: 1.0e10 Msun/h (Code Units). \n// \t: The timestep over which the SF is occuring (dt). ## UNITS: Code Units, multiply by 'UnitTime_in_Megayears / Hubble_h' for Myr.\n// \t: The tree currently being used (tree); currently used for debugging purposes.\n//\n// OUTPUT: None.\n\nvoid update_SN_stars_array(int p, double stars, double dt, int tree, int ngal)\n{\n\n double time_spanned = dt * UnitTime_in_Megayears / Hubble_h; // The time spanned by this star formation event.\n\n Gal[p].Total_SN_SF_Time += time_spanned; // How long it has been since we've updated the array?\n Gal[p].Total_SN_Stars += stars; // How many stars we will need to bin once we do update the array?\n\n if(Gal[p].Total_SN_SF_Time > TimeResolutionSN * SN_Array_Len) // This handles cases in which the time spanned is greater than 50Myr. In this case we wipe the array clean and push the star formation into a 50Myr bin. \n Gal[p].Total_SN_SF_Time = TimeResolutionSN * SN_Array_Len;\n\n if(Gal[p].Total_SN_SF_Time < TimeResolutionSN) // If it hasn't been long enough yet, don't update the array. \n return;\n\n int num_shuffled = round(Gal[p].Total_SN_SF_Time/TimeResolutionSN); // How many cells will this SF event span.\n\n double stars_spread = Gal[p].Total_SN_Stars/num_shuffled; // We spread the stars evenly over time.\n\n int i;\n\n XASSERT(Gal[p].IsMalloced == 1, \"We are attempting to update the stars array but this galaxy has already had its arrays freed.\\nGalaxy %d \\t Halo %d \\t Tree %d \\t Time spanned %.4eMyr\\n\", p, Gal[p].HaloNr, tree, time_spanned); \n\n for(i = SN_Array_Len - 1; i > num_shuffled - 1; --i)\n {\n Gal[p].SN_Stars[i] = Gal[p].SN_Stars[i-num_shuffled]; // Shuffle the current elements of the array far enough along so we can store the new stars.\n }\n XPRINT(p < ngal, \"We have the case where the galaxy p is greater than the number of galaxies. p = %d \\t ngal = %d\\n\", p, ngal);\n for(i = SN_Array_Len - 1; i > (SN_Array_Len - num_shuffled - 1); --i)\n {\n Gal[p].StellarAge_Numerator += Gal[p].SN_Stars[i] * (Age[Gal[p].SnapNum - 4]);\n Gal[p].StellarAge_Denominator += Gal[p].SN_Stars[i]; \n }\n\n for(i = 0; i < num_shuffled; ++i) \n {\n Gal[p].StellarAge_Numerator += Gal[p].SN_Stars[i] * (Age[Gal[p].SnapNum - 4]);\n Gal[p].SN_Stars[i] = stars_spread; // Update the vacated elements with the new stars.\n Gal[p].GrandSum += stars_spread; \n } \n\n Gal[p].Total_SN_SF_Time = 0.0; // We've updated so reset our variables.\n Gal[p].Total_SN_Stars = 0.0;\n}\n\n\nvoid update_stellar_tracking(int p, double stars, double dt, int tree, int ngal)\n{\n\n double time_spanned = dt * UnitTime_in_Megayears / Hubble_h; // The time spanned by this star formation event.\n\n Gal[p].Total_Stellar_SF_Time += time_spanned; // How long it has been since we've updated the array?\n Gal[p].Total_Stellar_Stars += stars; // How many stars we will need to bin once we do update the array?\n\n if(Gal[p].Total_Stellar_SF_Time > TimeResolutionStellar * StellarTracking_Len) \n Gal[p].Total_Stellar_SF_Time = TimeResolutionStellar * StellarTracking_Len;\n\n if(Gal[p].Total_Stellar_SF_Time < TimeResolutionStellar) // If it hasn't been long enough yet, don't update the array. \n return;\n\n int num_shuffled = round(Gal[p].Total_Stellar_SF_Time/TimeResolutionStellar); // How many cells will this SF event span.\n double stars_spread = Gal[p].Total_Stellar_Stars/num_shuffled; // We spread the stars evenly over time.\n\n int i;\n\n XASSERT(Gal[p].IsMalloced == 1, \"We are attempting to update the Stellar Tracking array but this galaxy has already had its arrays freed.\\nGalaxy %d \\t Halo %d \\t Tree %d \\t Time spanned %.4eMyr\\n\", p, Gal[p].HaloNr, tree, time_spanned); \n\n for(i = StellarTracking_Len - 1; i > num_shuffled - 1; --i)\n {\n Gal[p].Stellar_Stars[i] = Gal[p].Stellar_Stars[i-num_shuffled]; // Shuffle the current elements of the array far enough along so we can store the new stars.\n }\n XPRINT(p < ngal, \"We have the case where the galaxy p is greater than the number of galaxies. p = %d \\t ngal = %d\\n\", p, ngal);\n \n for(i = 0; i < num_shuffled; ++i) \n {\n Gal[p].Stellar_Stars[i] = stars_spread; // Update the vacated elements with the new stars. \n } \n\n Gal[p].Total_Stellar_SF_Time = 0.0; // We've updated so reset our variables.\n Gal[p].Total_Stellar_Stars = 0.0;\n}\n\n", "meta": {"hexsha": "b7db9f59026869032e934f489097c08d01410794", "size": 34920, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sage/model_starformation_and_feedback.c", "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_issues_repo_path": "src/sage/model_starformation_and_feedback.c", "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_forks_repo_path": "src/sage/model_starformation_and_feedback.c", "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "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": 42.3786407767, "max_line_length": 438, "alphanum_fraction": 0.6958190149, "num_tokens": 10481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.17125706018508952}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hdf5.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mclib_3d.h\"\n#include \n#include \"mpi.h\"\n\n#define PROP_DIM1 1\n#define PROP_DIM2 8\n#define PROP_DIM3 8\n#define COORD_DIM1 2\n#define R_DIM_2D 9120\n#define THETA_DIM_2D 2000\n\n//define constants\nconst double A_RAD=7.56e-15, C_LIGHT=2.99792458e10, PL_CONST=6.6260755e-27;\nconst double K_B=1.380658e-16, M_P=1.6726231e-24, THOMP_X_SECT=6.65246e-25, M_EL=9.1093879e-28 ;\n\nint getOrigNumProcesses(int *counted_cont_procs, int **proc_array, char dir[200], int angle_rank, int angle_procs, int last_frame, int dim_switch, int riken_switch)\n{\n int i=0, j=0, val=0, original_num_procs=-1, rand_num=0;\n int frame2=0, framestart=0, scatt_framestart=0, ph_num=0;\n double time=0;\n char mc_chkpt_files[200]=\"\", restrt=\"\"; //define new variable that wont write over the restrt variable in the main part of the code, when its put into the readCheckpoint function\n struct photon *phPtr=NULL; //pointer to array of photons \n //DIR * dirp;\n //struct dirent * entry;\n //struct stat st = {0};\n glob_t files;\n \n //if (angle_rank==0)\n {\n //find number of mc_checkpt files there are\n //loop through them and find out which prior processes didnt finish and keep track of which ones didnt\n snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), \"%s%s\", dir,\"mc_chkpt_*\" );\n val=glob(mc_chkpt_files, 0, NULL,&files );\n \n printf(\"TEST: %s\\n\", mc_chkpt_files);\n \n //look @ a file by choosing rand int between 0 and files.gl_pathc and if the file exists open and read it to get the actual value for the old number of angle_procs\n srand(angle_rank);\n //printf(\"NUM_FILES: %d\\n\",files.gl_pathc);\n \n rand_num=rand() % files.gl_pathc;\n snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), \"%s%s%d%s\", dir,\"mc_chkpt_\", rand_num,\".dat\" );\n printf(\"TEST: %s\\n\", mc_chkpt_files);\n \n if ( access( mc_chkpt_files, F_OK ) == -1 )\n {\n while(( access( mc_chkpt_files, F_OK ) == -1 ) )\n {\n rand_num=rand() % files.gl_pathc;\n snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), \"%s%s%d%s\", dir,\"mc_chkpt_\", rand_num,\".dat\" );\n //printf(\"TEST: %s\\n\", mc_chkpt_files);\n }\n }\n readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, rand_num, &original_num_procs, dim_switch, riken_switch);\n \n //original_num_procs= 70;\n \n \n }\n \n int count_procs[original_num_procs], count=0;\n int cont_procs[original_num_procs];\n //create array of files including any checkpoint file which may not have been created yet b/c old process was still in 1st frame of scattering\n \n for (j=0;jp0);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->p0);\n \n fprintf(fPtr1,\"%0.13e\\t\", (ph+i)->p1);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->p1);\n \n fprintf(fPtr2,\"%0.13e\\t\", (ph+i)->p2);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->p2);\n \n fprintf(fPtr3,\"%0.13e\\t\", (ph+i)->p3);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->p3);\n \n fprintf(fPtr4,\"%0.13e\\t\", (ph+i)->r0);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->r0);\n \n fprintf(fPtr5,\"%0.13e\\t\", (ph+i)->r1);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->r1);\n \n fprintf(fPtr6,\"%0.13e\\t\", (ph+i)->r2);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->r2);\n \n //fprintf(fPtr7,\"%0.13e\\t\", *(ph_num_scatt+i));\n fprintf(fPtr7,\"%e\\t\", (ph+i)->num_scatt);\n //printf(\"%d: %0.13e \\n\", i, (ph+i)->num_scatt);\n if (frame==frame_inj)\n {\n fprintf(fPtr8,\"%e\\t\", (ph+i)->weight);\n }\n } \n fclose(fPtr);\n fclose(fPtr1);\n fclose(fPtr2);\n fclose(fPtr3);\n fclose(fPtr4);\n fclose(fPtr5);\n fclose(fPtr6);\n fclose(fPtr7);\n if (frame==frame_inj)\n {\n fclose(fPtr8);\n }\n \n //printf(\"%s\\n%s\\n%s\\n\", mc_file_p0, mc_file_r0, mc_file_ns);\n}\n\nvoid saveCheckpoint(char dir[200], int frame, int frame2, int scatt_frame, int ph_num,double time_now, struct photon *ph, int last_frame, int angle_rank,int angle_size )\n{\n //function to save data necessary to restart simulation if it ends\n //need to save all photon data \n FILE *fPtr=NULL;\n char checkptfile[200]=\"\";\n char command[200]=\"\";\n char restart;\n int i=0;\n \n //for openMPI have some type of problem with saving the checkpoint file for the frame in which photons have been injected and scattered in, can try to delete old mc_checkpoint file \n //and creating a new one in that case?\n \n snprintf(checkptfile,sizeof(checkptfile),\"%s%s%d%s\",dir,\"mc_chkpt_\", angle_rank,\".dat\" );\n \n if ((scatt_frame!=last_frame) && (scatt_frame != frame))\n {\n \n fPtr=fopen(checkptfile, \"wb\");\n //printf(\"%s\\n\", checkptfile);\n \n if (fPtr==NULL)\n {\n printf(\"Cannot open %s to save checkpoint\\n\", checkptfile);\n }\n fwrite(&angle_size, sizeof(int), 1, fPtr);\n restart='c';\n fwrite(&restart, sizeof(char), 1, fPtr);\n //printf(\"Rank: %d wrote restart %c\\n\", angle_rank, restart);\n fflush(stdout);\n fwrite(&frame, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote frame\\n\", angle_rank);\n fflush(stdout);\n fwrite(&frame2, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote frame2\\n\", angle_rank);\n fflush(stdout);\n fwrite(&scatt_frame, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote scatt_frame\\n\", angle_rank);\n fflush(stdout);\n fwrite(&time_now, sizeof(double), 1, fPtr);\n //printf(\"Rank: %d wrote time_now\\n\", angle_rank);\n fflush(stdout);\n fwrite(&ph_num, sizeof(int), 1, fPtr);\n //printf(\"Rank: %d wrote ph_num\\n\", angle_rank);\n fflush(stdout);\n for(i=0;i=3000))\n {\n *scatt_framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 \n }\n else\n {\n *scatt_framestart+=1; //add one to start at the next frame after the simulation was interrrupted\n }\n\n //printf(\"%d\\n\", *scatt_framestart);\n fread(time, sizeof(double), 1, fPtr);\n //printf(\"%e\\n\", *time);\n fread(ph_num, sizeof(int), 1, fPtr);\n //printf(\"%d\\n\", *ph_num);\n \n phHolder=malloc(sizeof(struct photon));\n (*ph)=malloc(sizeof(struct photon)*(*ph_num)); //allocate memory to hold photon data\n \n for (i=0;i<(*ph_num);i++)\n {\n fread(phHolder, sizeof(struct photon), 1, fPtr);\n //printf(\"%e,%e,%e, %e,%e,%e, %e, %e\\n\",(ph)->p0, (ph)->p1, (ph)->p2, ph->p3, (ph)->r0, (ph)->r1, (ph)->r2, ph->num_scatt );\n \n (*ph)[i].p0=phHolder->p0;\n (*ph)[i].p1=phHolder->p1;\n (*ph)[i].p2=phHolder->p2;\n (*ph)[i].p3=phHolder->p3;\n (*ph)[i].r0= phHolder->r0; \n (*ph)[i].r1=phHolder->r1 ;\n (*ph)[i].r2=phHolder->r2; \n (*ph)[i].num_scatt=phHolder->num_scatt;\n (*ph)[i].weight=phHolder->weight;\n (*ph)[i].nearest_block_index= phHolder->nearest_block_index;\n }\n \n free(phHolder);\n }\n else\n {\n if ((riken_switch==1) && (dim_switch==1) && ((*framestart)>=3000))\n {\n *framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 \n }\n else\n {\n *framestart+=1; //if the checkpoint file saved and the program was inturrupted before the frame variable had just increased and before the scatt_frame iteration was saved, add one to the frame start\n }\n \n *scatt_framestart=(*framestart);\n }\n \n fclose(fPtr);\n }\n else //if not use default\n {\n //*framestart=(*framestart);\n *scatt_framestart=(*framestart);\n *restart='r';\n \n }\n}\n\nvoid readMcPar(char file[200], double *fluid_domain_x, double *fluid_domain_y, double *fps, double *theta_jmin, double *theta_j, double *d_theta_j, double *inj_radius_small, double *inj_radius_large, int *frm0_small, int *frm0_large, int *last_frm, int *frm2_small,int *frm2_large , double *ph_weight_small,double *ph_weight_large,int *min_photons, int *max_photons, char *spect, char *restart, int *num_threads, int *dim_switch)\n{\n //function to read mc.par file\n\tFILE *fptr=NULL;\n\tchar buf[100]=\"\";\n\tdouble theta_deg;\n\t\n\t//open file\n\tfptr=fopen(file,\"r\");\n\t//read in frames per sec and other variables outlined in main()\n \n fscanf(fptr, \"%lf\",fluid_domain_x);\n\t//printf(\"%lf\\n\", *fluid_domain_x );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",fluid_domain_y);\n\t//printf(\"%lf\\n\", *fluid_domain_y );\n\t\n\tfgets(buf, 100,fptr);\n \n\tfscanf(fptr, \"%lf\",fps);\n\t//printf(\"%f\\n\", *fps );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%d\",frm0_small);\n\t//printf(\"%d\\n\", *frm0_small );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",frm0_large);\n\t//printf(\"%d\\n\", *frm0_large );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%d\",last_frm);\n\t//printf(\"%d\\n\", *last_frm );\n \n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%d\",frm2_small);\n *frm2_small+=*frm0_small; //frame to go to is what is given in the file plus the starting frame\n\t//printf(\"%d\\n\", *frm2_small );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\t//fscanf(fptr, \"%d\",photon_num); remove photon num because we dont need this\n\t//printf(\"%d\\n\", *photon_num );\n \n fscanf(fptr, \"%d\",frm2_large);\n *frm2_large+=*frm0_large; //frame to go to is what is given in the file plus the starting frame\n //printf(\"%d\\n\", *frm2_large );\n\t\n\tfgets(buf, 100,fptr);\n\t\n\t//fgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%lf\",inj_radius_small);\n\t//printf(\"%lf\\n\", *inj_radius_small );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",inj_radius_large);\n\t//printf(\"%lf\\n\", *inj_radius_large );\n\t\n\tfgets(buf, 100,fptr);\n \n\t//theta jmin\n\tfscanf(fptr, \"%lf\",&theta_deg);\n\t*theta_jmin=theta_deg;//*M_PI/180; leave as degrees to manipulate processes \n\t//printf(\"%f\\n\", *theta_jmin );\n\t\n\t\n\tfgets(buf, 100,fptr);\n\t\n\tfscanf(fptr, \"%lf\",&theta_deg);\n *theta_j=theta_deg;//*M_PI/180;\n\t//printf(\"%f\\n\", *theta_j );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",d_theta_j);\n //*theta_j=theta_deg;//*M_PI/180;\n\t//printf(\"%f\\n\", *theta_j );\n\t\n\tfgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",ph_weight_small);\n //printf(\"%f\\n\", *ph_weight_small );\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%lf\",ph_weight_large);\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",min_photons);\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",max_photons);\n fgets(buf, 100,fptr);\n \n *spect=getc(fptr);\n fgets(buf, 100,fptr);\n //printf(\"%c\\n\",*spect);\n \n *restart=getc(fptr);\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",num_threads);\n //printf(\"%d\\n\",*num_threads);\n fgets(buf, 100,fptr);\n \n fscanf(fptr, \"%d\",dim_switch);\n //printf(\"%d\\n\",*dim_switch);\n \n\t//close file\n\tfclose(fptr);\n}\n\nvoid readAndDecimate(char flash_file[200], double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r,\\\n double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double min_theta, double max_theta, FILE *fPtr)\n{\n //function to read in data from FLASH file\n hid_t file,dset, space;\n herr_t status;\n hsize_t dims[2]={0,0}; //hold dimension size for coordinate data set (mostly interested in dims[0])\n double **vel_x_buffer=NULL, **vel_y_buffer=NULL, **dens_buffer=NULL, **pres_buffer=NULL, **coord_buffer=NULL, **block_sz_buffer=NULL;\n double *velx_unprc=NULL, *vely_unprc=NULL, *dens_unprc=NULL, *pres_unprc=NULL, *x_unprc=NULL, *y_unprc=NULL, *r_unprc=NULL, *szx_unprc=NULL, *szy_unprc=NULL;\n int i,j,count,x1_count, y1_count, r_count, **node_buffer=NULL, num_nodes=0, elem_factor=0;\n double x1[8]={-7.0/16,-5.0/16,-3.0/16,-1.0/16,1.0/16,3.0/16,5.0/16,7.0/16};\n double ph_rmin=0, ph_rmax=0, ph_thetamin=0, ph_thetamax=0, r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0;\n\n\n if (ph_inj_switch==0)\n {\n ph_rmin=min_r;\n ph_rmax=max_r;\n ph_thetamin=min_theta-2*0.017453292519943295; //min_theta - 2*Pi/180 (2 degrees)\n ph_thetamax=max_theta+2*0.017453292519943295; //max_theta + 2*Pi/180 (2 degrees)\n }\n \n file = H5Fopen (flash_file, H5F_ACC_RDONLY, H5P_DEFAULT);\n \n //ret=H5Pclose(acc_tpl1);\n \n fprintf(fPtr, \">> mc.py: Reading positional, density, pressure, and velocity information...\\n\");\n fflush(fPtr);\n //printf(\"Reading coord\\n\");\n dset = H5Dopen (file, \"coordinates\", H5P_DEFAULT);\n \n //get dimensions of array and save it\n space = H5Dget_space (dset);\n \n H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims\n \n /*\n * Allocate array of pointers to rows. OPTIMIZE HERE: INITALIZE ALL THE BUFFERS AT ONCE IN 1 FOR LOOP\n */\n coord_buffer = (double **) malloc (dims[0] * sizeof (double *));\n \n coord_buffer[0] = (double *) malloc (dims[0] * dims[1] * sizeof (double));\n \n block_sz_buffer= (double **) malloc (dims[0] * sizeof (double *));\n\n block_sz_buffer[0] = (double *) malloc (dims[0] * COORD_DIM1 * sizeof (double));\n \n node_buffer= (int **) malloc (dims[0] * sizeof (int *));\n node_buffer[0] = (int *) malloc (dims[0] * sizeof (int));\n \n vel_x_buffer= (double **) malloc (dims[0] * sizeof (double *));\n vel_x_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n vel_y_buffer= (double **) malloc (dims[0] * sizeof (double *));\n vel_y_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n dens_buffer= (double **) malloc (dims[0] * sizeof (double *));\n dens_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n pres_buffer= (double **) malloc (dims[0] * sizeof (double *));\n pres_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));\n \n /*\n * Set the rest of the pointers to rows to the correct addresses.\n */\n for (i=1; i> Selecting good node types (=1)\\n\");\n //find out how many good nodes there are\n for (i=0;i> Creating and reshaping arrays\\n\");\n count=0;\n for (i=0;i injection radius\n elem_factor=1;\n r_count=0;\n while (r_count==0)\n {\n r_count=0;\n elem_factor++;\n for (i=0;i= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax) )\n {\n r_count++;\n }\n \n }\n else\n {\n if (*(r_unprc+i)> (0.95*r_inj) )\n {\n r_count++;\n }\n }\n }\n //fprintf(fPtr, \"r_count: %d count: %d\\n\", r_count, count);\n }\n fprintf(fPtr, \"Elem factor: %d Ph_rmin: %e rmax: %e Chosen FLASH min_r: %e max_r: %e min_theta: %e degrees max_theta: %e degrees\\n\", elem_factor, ph_rmin, ph_rmax, ph_rmin - (elem_factor*C_LIGHT/fps), ph_rmax + (elem_factor*C_LIGHT/fps), ph_thetamin*180/M_PI, ph_thetamax*180/M_PI);\n fflush(fPtr);\n\n \n //allocate memory to hold processed data\n (*pres)=malloc (r_count * sizeof (double ));\n (*velx)=malloc (r_count * sizeof (double ));\n (*vely)=malloc (r_count * sizeof (double ));\n (*dens)=malloc (r_count * sizeof (double ));\n (*x)=malloc (r_count * sizeof (double ));\n (*y)=malloc (r_count * sizeof (double ));\n (*r)=malloc (r_count * sizeof (double ));\n (*theta)=malloc (r_count * sizeof (double ));\n (*gamma)=malloc (r_count * sizeof (double ));\n (*dens_lab)=malloc (r_count * sizeof (double ));\n (*szx)=malloc (r_count * sizeof (double ));\n (*szy)=malloc (r_count * sizeof (double ));\n (*temp)=malloc (r_count * sizeof (double ));\n \n //assign values based on r> 0.95*r_inj\n j=0;\n for (i=0;i= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax))\n {\n (*pres)[j]=*(pres_unprc+i);\n (*velx)[j]=*(velx_unprc+i);\n (*vely)[j]=*(vely_unprc+i);\n \n (*dens)[j]=*(dens_unprc+i);\n (*x)[j]=*(x_unprc+i);\n (*y)[j]=*(y_unprc+i);\n (*r)[j]=*(r_unprc+i);\n (*szx)[j]=*(szx_unprc+i);\n (*szy)[j]=*(szy_unprc+i);\n (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis\n (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c\n (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));\n (*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n j++;\n }\n }\n else\n {\n if (*(r_unprc+i)> (0.95*r_inj) )\n {\n (*pres)[j]=*(pres_unprc+i);\n (*velx)[j]=*(velx_unprc+i);\n (*vely)[j]=*(vely_unprc+i);\n (*dens)[j]=*(dens_unprc+i);\n (*x)[j]=*(x_unprc+i);\n (*y)[j]=*(y_unprc+i);\n (*r)[j]=*(r_unprc+i);\n (*szx)[j]=*(szx_unprc+i);\n (*szy)[j]=*(szy_unprc+i);\n (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis\n (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c\n (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));\n (*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n j++;\n }\n }\n }\n *number=j;\n //fprintf(fPtr, \"number: %d\\n\", j);\n \n free(pres_unprc); free(velx_unprc);free(vely_unprc);free(dens_unprc);free(x_unprc); free(y_unprc);free(r_unprc);free(szx_unprc);free(szy_unprc);\n \n}\n\n\nvoid photonInjection( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\\\ndouble *x, double *y, double *szx, double *szy, double *r, double *theta, double *temps, double *vx, double *vy, gsl_rng * rand, int riken_switch, FILE *fPtr)\n{\n int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;\n double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, rmin, rmax;\n double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)\n double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values\n float num_dens_coeff;\n \n if (spect=='w') //from MCRAT paper, w for wien spectrum \n {\n num_dens_coeff=8.44;\n //printf(\"in wien spectrum\\n\");\n }\n else\n {\n num_dens_coeff=20.29; //this is for black body spectrum\n //printf(\"in BB spectrum\");\n }\n \n //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for \n //and then rcord which blocks have to have \"x\" amount of photons injected there\n \n rmin=r_inj - 0.5*C_LIGHT/fps;\n rmax=r_inj + 0.5*C_LIGHT/fps;\n \n for(i=0;i= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) \n {\n block_cnt++;\n }\n }\n //printf(\"Blocks: %d\\n\", block_cnt);\n \n ph_dens=malloc(block_cnt * sizeof(int));\n \n //calculate the photon density for each block and save it to the array\n j=0;\n ph_tot=0;\n ph_weight_adjusted=ph_weight;\n //printf(\"%d %d\\n\", max_photons, min_photons);\n while ((ph_tot>max_photons) || (ph_tot= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) \n {\n if (riken_switch==0)\n {\n //using FLASH\n ph_dens_calc=(num_dens_coeff*2.0*M_PI*(*(x+i))*pow(*(temps+i),3.0)*pow(*(szx+i),2.0) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2,\n }\n else\n {\n ph_dens_calc=(num_dens_coeff*2.0*M_PI*pow(*(r+i),2)*sin(*(theta+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1); //dV=2 *pi* r^2 Sin(theta) dr dtheta\n }\n \n (*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc\n \n //printf(\"%d, %lf \\n\",*(ph_dens+j), ph_dens_calc);\n \n //sum up all the densities to get total number of photons\n ph_tot+=(*(ph_dens+j));\n \n j++;\n }\n }\n \n if (ph_tot>max_photons)\n {\n //if the number of photons is too big make ph_weight larger\n ph_weight_adjusted*=10;\n //free(ph_dens);\n }\n else if (ph_tot= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >= theta_min) )\n {\n\n //*(temps+i)=0.76*(*(temps+i));\n for(j=0;j<( *(ph_dens+k) ); j++ )\n {\n //have to get random frequency for the photon comoving frequency\n y_dum=1; //initalize loop\n yfr_dum=0;\n while (y_dum>yfr_dum)\n {\n fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz\n //printf(\"%lf, %lf \",gsl_rng_uniform_pos(rand), (*(temps+i)));\n y_dum=gsl_rng_uniform_pos(rand);\n //printf(\"%lf \",fr_dum);\n \n if (spect=='w')\n {\n yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum\n }\n else\n {\n fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb\n bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max\n yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency\n \t\n\t\t\t}\n //printf(\"%lf, %lf,%lf,%e \\n\",(*(temps+i)),fr_dum, y_dum, yfr_dum);\n \n }\n //printf(\"%lf\\n \",fr_dum);\n position_phi=gsl_rng_uniform(rand)*2*M_PI;\n com_v_phi=gsl_rng_uniform(rand)*2*M_PI;\n com_v_theta=acos((gsl_rng_uniform(rand)*2)-1);\n //printf(\"%lf, %lf, %lf\\n\", position_phi, com_v_phi, com_v_theta);\n \n //populate 4 momentum comoving array\n *(p_comv+0)=PL_CONST*fr_dum/C_LIGHT;\n *(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi);\n *(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi);\n *(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta);\n \n //populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code...\n *(boost+0)=-1*(*(vx+i))*cos(position_phi);\n *(boost+1)=-1*(*(vx+i))*sin(position_phi);\n *(boost+2)=-1*(*(vy+i));\n //printf(\"%lf, %lf, %lf\\n\", *(boost+0), *(boost+1), *(boost+2));\n \n //boost to lab frame\n lorentzBoost(boost, p_comv, l_boost, 'p', fPtr);\n //printf(\"Assignemnt: %e, %e, %e, %e\\n\", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3));\n \n (*ph)[ph_tot].p0=(*(l_boost+0));\n (*ph)[ph_tot].p1=(*(l_boost+1));\n (*ph)[ph_tot].p2=(*(l_boost+2));\n (*ph)[ph_tot].p3=(*(l_boost+3));\n (*ph)[ph_tot].r0= (*(x+i))*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi \n (*ph)[ph_tot].r1=(*(x+i))*sin(position_phi) ;\n (*ph)[ph_tot].r2=(*(y+i)); //y coordinate in flash becomes z coordinate in MCRaT\n (*ph)[ph_tot].num_scatt=0;\n (*ph)[ph_tot].weight=ph_weight_adjusted;\n (*ph)[ph_tot].nearest_block_index=0;\n //printf(\"%d\\n\",ph_tot);\n ph_tot++;\n }\n k++;\n }\n }\n \n *ph_num=ph_tot; //save number of photons\n //printf(\" %d: %d\\n\", *(ph_dens+(k-1)), *ph_num);\n free(ph_dens); free(p_comv);free(boost); free(l_boost);\n \n}\n\nvoid lorentzBoost(double *boost, double *p_ph, double *result, char object, FILE *fPtr)\n{\n //function to perform lorentz boost\n //if doing boost for an electron last argument is 'e' and there wont be a check for zero norm\n //if doing boost for a photon last argument is 'p' and there will be a check for zero norm\n double beta=0, gamma=0, *boosted_p=NULL;\n \n gsl_vector_view b=gsl_vector_view_array(boost, 3); //make boost pointer into vector\n gsl_vector_view p=gsl_vector_view_array(p_ph, 4); //make boost pointer into vector\n gsl_matrix *lambda1= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do lorentz boost \n gsl_vector *p_ph_prime =gsl_vector_calloc(4); //create vestor to hold lorentz boosted vector\n \n /*\n fprintf(fPtr,\"Boost: %e, %e, %e, %e\\n\",gsl_blas_dnrm2(&b.vector), *(boost+0), *(boost+1), *(boost+2));\n fflush(fPtr);\n fprintf(fPtr,\"4 Momentum to Boost: %e, %e, %e, %e\\n\",*(p_ph+0), *(p_ph+1), *(p_ph+2), *(p_ph+3));\n fflush(fPtr);\n */\n \n //if magnitude of fluid velocity is != 0 do lorentz boost otherwise dont need to do a boost\n if (gsl_blas_dnrm2(&b.vector) > 0)\n {\n //fprintf(fPtr,\"in If\\n\");\n //fflush(fPtr);\n beta=gsl_blas_dnrm2(&b.vector);\n gamma=1.0/sqrt(1-pow(beta, 2.0));\n //fprintf(fPtr,\"Beta: %e\\tGamma: %e\\n\",beta,gamma );\n //fflush(fPtr);\n \n //initalize matrix values\n gsl_matrix_set(lambda1, 0,0, gamma);\n gsl_matrix_set(lambda1, 0,1, -1*gsl_vector_get(&b.vector,0)*gamma);\n gsl_matrix_set(lambda1, 0,2, -1*gsl_vector_get(&b.vector,1)*gamma);\n gsl_matrix_set(lambda1, 0,3, -1*gsl_vector_get(&b.vector,2)*gamma);\n gsl_matrix_set(lambda1, 1,1, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,0),2.0)/pow(beta,2.0) ) );\n gsl_matrix_set(lambda1, 1,2, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,1)/pow(beta,2.0) ) ));\n gsl_matrix_set(lambda1, 1,3, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,2)/pow(beta,2.0) ) ));\n gsl_matrix_set(lambda1, 2,2, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,1),2.0)/pow(beta,2.0) ) );\n gsl_matrix_set(lambda1, 2,3, ((gamma-1)*(gsl_vector_get(&b.vector,1)* gsl_vector_get(&b.vector,2)/pow(beta,2.0)) ) );\n gsl_matrix_set(lambda1, 3,3, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,2),2.0)/pow(beta,2.0) ) );\n \n gsl_matrix_set(lambda1, 1,0, gsl_matrix_get(lambda1,0,1));\n gsl_matrix_set(lambda1, 2,0, gsl_matrix_get(lambda1,0,2));\n gsl_matrix_set(lambda1, 3,0, gsl_matrix_get(lambda1,0,3));\n gsl_matrix_set(lambda1, 2,1, gsl_matrix_get(lambda1,1,2));\n gsl_matrix_set(lambda1, 3,1, gsl_matrix_get(lambda1,1,3));\n gsl_matrix_set(lambda1, 3,2, gsl_matrix_get(lambda1,2,3));\n \n gsl_blas_dgemv(CblasNoTrans, 1, lambda1, &p.vector, 0, p_ph_prime );\n \n /*\n fprintf(fPtr,\"Lorentz Boost Matrix 0: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 0,0), gsl_matrix_get(lambda1, 0,1), gsl_matrix_get(lambda1, 0,2), gsl_matrix_get(lambda1, 0,3));\n fflush(fPtr);\n fprintf(fPtr,\"Lorentz Boost Matrix 1: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 1,0), gsl_matrix_get(lambda1, 1,1), gsl_matrix_get(lambda1, 1,2), gsl_matrix_get(lambda1, 1,3));\n fflush(fPtr);\n fprintf(fPtr,\"Lorentz Boost Matrix 2: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 2,0), gsl_matrix_get(lambda1, 2,1), gsl_matrix_get(lambda1, 2,2), gsl_matrix_get(lambda1, 2,3));\n fflush(fPtr);\n fprintf(fPtr,\"Lorentz Boost Matrix 3: %e,%e, %e, %e\\n\", gsl_matrix_get(lambda1, 3,0), gsl_matrix_get(lambda1, 3,1), gsl_matrix_get(lambda1, 3,2), gsl_matrix_get(lambda1, 3,3));\n fflush(fPtr);\n \n fprintf(fPtr,\"Before Check: %e %e %e %e\\n \",gsl_vector_get(p_ph_prime, 0), gsl_vector_get(p_ph_prime, 1), gsl_vector_get(p_ph_prime, 2), gsl_vector_get(p_ph_prime, 3));\n fflush(fPtr);\n */\n \n //double check vector for 0 norm condition if photon\n if (object == 'p')\n {\n //fprintf(fPtr,\"In if\\n\");\n boosted_p=zeroNorm(gsl_vector_ptr(p_ph_prime, 0));\n }\n else\n {\n boosted_p=gsl_vector_ptr(p_ph_prime, 0);\n }\n /*\n fprintf(fPtr,\"After Check: %e %e %e %e\\n \", *(boosted_p+0),*(boosted_p+1),*(boosted_p+2),*(boosted_p+3) );\n fflush(fPtr);\n * */\n }\n else\n {\n /*\n fprintf(fPtr,\"in else\");\n fflush(fPtr);\n * */\n //double check vector for 0 norm condition\n if (object=='p')\n {\n boosted_p=zeroNorm(p_ph);\n }\n else\n {\n //if 4 momentum isnt for photon and there is no boost to be done, we dont care about normality and just want back what was passed to lorentz boost\n boosted_p=gsl_vector_ptr(&p.vector, 0);\n }\n }\n //assign values to result\n *(result+0)=*(boosted_p+0);\n *(result+1)=*(boosted_p+1);\n *(result+2)=*(boosted_p+2);\n *(result+3)=*(boosted_p+3);\n \n //free up memory\n //free(boosted_p);\n gsl_matrix_free (lambda1); gsl_vector_free(p_ph_prime);\n}\n\ndouble *zeroNorm(double *p_ph)\n{\n //ensures zero norm condition of photon 4 monetum is held\n int i=0;\n double normalizing_factor=0;\n gsl_vector_view p=gsl_vector_view_array((p_ph+1), 3); //make last 3 elements of p_ph pointer into vector\n \n if (*(p_ph+0) != gsl_blas_dnrm2(&p.vector ) )\n {\n normalizing_factor=(gsl_blas_dnrm2(&p.vector ));\n //fprintf(fPtr,\"in zero norm if\\n\");\n //fflush(fPtr);\n //go through and correct 4 momentum assuming the energy is correct\n \n *(p_ph+1)= ((*(p_ph+1))/(normalizing_factor))*(*(p_ph+0));\n *(p_ph+2)= ((*(p_ph+2))/(normalizing_factor))*(*(p_ph+0));\n *(p_ph+3)= ((*(p_ph+3))/(normalizing_factor))*(*(p_ph+0));\n \n }\n /*\n if (pow((*(p_ph+0)),2) != ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) )\n {\n printf(\"This isnt normalized in the function\\nThe difference is: %e\\n\", pow((*(p_ph+0)),2) - ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) );\n }\n */ //normalized within a factor of 10^-53\n return p_ph;\n}\n\nint findNearestBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, int dim_switch_3d)\n{\n double dist=0, dist_min=1e15, block_dist=0;\n int min_index=0, j=0;\n \n dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved\n block_dist=3e9;\n while (dist_min==1e15) //if this is true, then the algorithm hasnt found blocks within the acceptable range given by block_dist\n {\n \n for(j=0;jr0), ((ph+i)->r1));\n if (find_nearest_block_switch==0)\n {\n ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault\n }\n else\n {\n ph_block_index=0; //if starting a new frame set index=0 to avoid this issue\n }\n \n if (dim_switch_3d==0)\n {\n ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate\n ph_y=((ph+i)->r2);\n ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));\n ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5);\n }\n else\n {\n ph_x=((ph+i)->r0);\n ph_y=((ph+i)->r1);\n ph_z=((ph+i)->r2);\n ph_r=pow(ph_x*ph_x + ph_y*ph_y+ph_z*ph_z, 0.5);\n }\n //if the location of the photon is less than the domain of the hydro simulation then do all of this, otherwise assing huge mfp value so no scattering occurs and the next frame is loaded\n if ((ph_ynearest_block_index=min_index; //save the index\n \n }\n\n //fprintf(fPtr,\"Outside\\n\");\n \n //save values\n (n_dens_lab_tmp)= (*(dens_lab+min_index));\n (n_vx_tmp)= (*(velx+min_index));\n (n_vy_tmp)= (*(vely+min_index));\n (n_temp_tmp)= (*(temp+min_index));\n if (dim_switch_3d==1)\n {\n (n_vz_tmp)= (*(velz+min_index));\n }\n \n if (dim_switch_3d==0)\n {\n fl_v_x=(*(velx+min_index))*cos(ph_phi);\n fl_v_y=(*(velx+min_index))*sin(ph_phi);\n fl_v_z=(*(vely+min_index));\n }\n else\n {\n fl_v_x=(*(velx+min_index));\n fl_v_y=(*(vely+min_index));\n fl_v_z=(*(velz+min_index));\n }\n \n fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);\n ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);\n \n //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product\n (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined\n \n if (dim_switch_3d==0)\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);\n }\n else\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);\n }\n //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case\n rnd_tracker=0;\n \n rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]);\n //printf(\"Rnd_tracker: %e Thread number %d \\n\",rnd_tracker, omp_get_thread_num() );\n \n mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths \n }\n else\n {\n mfp=min_mfp;\n //printf(\"In ELSE\\n\");\n }\n \n *(all_time_steps+i)=mfp/C_LIGHT;\n }\n \n //free rand number generator\n for (i=1;idata[i]; //save sorted indexes to array to use outside of function\n //}\n \n \n (*time_step)=*(all_time_steps+( (int) perm->data[0] ));\n index= (int) perm->data[0] ;//first element of sorted array, index of photon\n min_index=(ph+index)->nearest_block_index; //index of FLASH element closest to photon that will scatter\n \n *(n_dens_lab)= (*(dens_lab+min_index));\n *(n_vx)= (*(velx+min_index));\n *(n_vy)= (*(vely+min_index));\n *(n_temp)= (*(temp+min_index));\n if (dim_switch_3d==1)\n {\n *(n_vz)= (*(velz+min_index));\n }\n \n free (all_time_steps);\n gsl_permutation_free(perm);\n all_time_steps=NULL;\n return index;\n \n}\n\nint interpolatePropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\\\n double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr)\n{\n /*\n * THIS FUNCTION IS WRITTEN JUST FOR 2D SIMS AS OF NOW \n */\n int i=0, j=0, min_index=0, ph_block_index=0;\n int left_block_index=0, right_block_index=0, bottom_block_index=0, top_block_index=0, all_adjacent_block_indexes[4];\n double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, dist=0, left_dist_min=0, right_dist_min=0, top_dist_min=0, bottom_dist_min=0, dv=0, v=0;\n double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates\n double r=0, theta=0;\n\n double ph_v_norm=0, fl_v_norm=0;\n double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0;\n double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0;\n int num_thread=2;//omp_get_max_threads();\n bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block\n \n int index=0;\n double mfp=0,min_mfp=0, beta=0;\n \n \n //initialize gsl random number generator fo each thread\n \n const gsl_rng_type *rng_t;\n gsl_rng **rng;\n gsl_rng_env_setup();\n rng_t = gsl_rng_ranlxs0;\n\n rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); \n rng[0]=rand;\n\n //#pragma omp parallel for num_threads(nt)\n for(i=1;ir0), ((ph+i)->r1));\n if (find_nearest_block_switch==0)\n {\n ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault\n }\n else\n {\n ph_block_index=0; //if starting a new frame set index=0 to avoid this issue\n }\n \n if (dim_switch_3d==0)\n {\n ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate\n ph_y=((ph+i)->r2);\n ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));\n \n }\n else\n {\n ph_x=((ph+i)->r0);\n ph_y=((ph+i)->r1);\n ph_z=((ph+i)->r2);\n \n }\n //printf(\"ph_x:%e, ph_y:%e\\n\", ph_x, ph_y);\n \n is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);\n \n if (find_nearest_block_switch==0 && is_in_block)\n {\n //keep the saved grid index\n min_index=ph_block_index;\n }\n else\n {\n //find the new index of the block closest to the photon\n //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh\n \n //find the new index of the block that the photon is actually in\n min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr);\n \n (ph+i)->nearest_block_index=min_index; //save the index\n \n }\n \n //look for the blocks surounding the block of interest and order them by the \n left_dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved\n right_dist_min=1e15;\n top_dist_min=1e15;\n bottom_dist_min=1e15;\n for (j=0;j(*(x+min_index)) && (dist < right_dist_min))\n {\n right_block_index=j;\n right_dist_min=dist;\n }\n \n if ((*(y+j))<(*(y+min_index)) && (dist < bottom_dist_min) )\n {\n bottom_block_index=j;\n bottom_dist_min=dist;\n }\n else if ((*(y+j))>(*(y+min_index)) && (dist < top_dist_min) )\n {\n top_block_index=j;\n top_dist_min=dist;\n }\n \n }\n all_adjacent_block_indexes[0]=left_block_index;\n all_adjacent_block_indexes[1]=right_block_index;\n all_adjacent_block_indexes[2]=bottom_block_index;\n all_adjacent_block_indexes[3]=top_block_index; \n \n //do a weighted average of the 4 nearest grids based on volume\n v=0;\n (n_dens_lab_tmp)=0;\n (n_vx_tmp)= 0;\n (n_vy_tmp)= 0;\n (n_temp_tmp)= 0;\n (n_vz_tmp)= 0;\n \n for (j=0;j<4;j++)\n {\n if (riken_switch==0)\n {\n //using FLASH\n dv=2.0*M_PI*(*(x+all_adjacent_block_indexes[j]))*pow(*(szx+all_adjacent_block_indexes[j]),2.0) ; \n }\n else\n {\n r=pow(pow((*(x+all_adjacent_block_indexes[j])),2.0)+pow((*(y+all_adjacent_block_indexes[j])),2.0), 0.5);\n theta=atan2((*(x+all_adjacent_block_indexes[j])), (*(y+all_adjacent_block_indexes[j])));\n dv=2.0*M_PI*pow(r,2)*sin(theta)*(*(szx+all_adjacent_block_indexes[j]))*(*(szy+all_adjacent_block_indexes[j])) ; \n }\n v+=dv;\n \n //save values\n (n_dens_lab_tmp)+= (*(dens_lab+all_adjacent_block_indexes[j]))*dv;\n (n_vx_tmp)+= (*(velx+all_adjacent_block_indexes[j]))*dv;\n (n_vy_tmp)+= (*(vely+all_adjacent_block_indexes[j]))*dv;\n (n_temp_tmp)+= (*(temp+all_adjacent_block_indexes[j]))*dv;\n if (dim_switch_3d==1)\n {\n (n_vz_tmp)+= (*(velz+all_adjacent_block_indexes[j]))*dv;\n }\n \n }\n \n\n //fprintf(fPtr,\"Outside\\n\");\n \n //save values\n (n_dens_lab_tmp)/= v;\n (n_vx_tmp)/= v;\n (n_vy_tmp)/= v;\n (n_temp_tmp)/= v;\n if (dim_switch_3d==1)\n {\n (n_vz_tmp)/= v;\n }\n \n if (dim_switch_3d==0)\n {\n fl_v_x=n_vx_tmp*cos(ph_phi);\n fl_v_y=n_vx_tmp*sin(ph_phi);\n fl_v_z=n_vy_tmp;\n }\n else\n {\n fl_v_x=n_vx_tmp;\n fl_v_y=n_vy_tmp;\n fl_v_z=n_vz_tmp;\n }\n \n fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);\n ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);\n \n //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product\n (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined\n \n if (dim_switch_3d==0)\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);\n }\n else\n {\n beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);\n }\n //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case\n rnd_tracker=0;\n \n rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]);\n \n mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths \n \n \n #pragma omp critical \n if ( mfpr0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 );\n \n divide_p0=1.0/((ph+i)->p0);\n \n ((ph+i)->r0)+=((ph+i)->p1)*divide_p0*C_LIGHT*t; //update x position\n \n ((ph+i)->r1)+=((ph+i)->p2)*divide_p0*C_LIGHT*t;//update y\n \n ((ph+i)->r2)+=((ph+i)->p3)*divide_p0*C_LIGHT*t;//update z\n \n new_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 );\n \n if ((new_position-old_position)/t > C_LIGHT)\n {\n fprintf(fPtr, \"PHOTON NUMBER %d IS SUPERLUMINAL. ITS SPEED IS %e c.\\n\", i, ((new_position-old_position)/t)/C_LIGHT);\n }\n //printf(\"In update function: %e, %e, %e, %e, %e, %e, %e\\n\",((ph+i)->r0), ((ph+i)->r1), ((ph+i)->r2), t, ((ph+i)->p1)/((ph+i)->p0), ((ph+i)->p2)/((ph+i)->p0), ((ph+i)->p3)/((ph+i)->p0) ); \n }\n \n //printf(\"In update function: %e, %e, %e, %e\\n\",t, ((ph)->p1)/((ph)->p0), ((ph)->p2)/((ph)->p0), ((ph)->p3)/((ph)->p0) ); \n \n}\n\n\nvoid photonScatter(struct photon *ph, double flash_vx, double flash_vy, double flash_vz, double fluid_temp, gsl_rng * rand,int dim_switch_3d, FILE *fPtr)\n{\n //function to perform single photon scattering\n double ph_phi=0; \n double *ph_p=malloc(4*sizeof(double)); //pointer to hold only photon 4 momentum @ start\n double *el_p_comov=malloc(4*sizeof(double));//pointer to hold the electron 4 momenta in comoving frame\n double *ph_p_comov=malloc(4*sizeof(double));//pointer to hold the comoving photon 4 momenta\n double *fluid_beta=malloc(3*sizeof(double));//pointer to hold fluid velocity vector\n double *negative_fluid_beta=malloc(3*sizeof(double));//pointer to hold negative fluid velocity vector\n \n \n ph_phi=atan2((ph->r1), ((ph->r0)));\n /*\n fprintf(fPtr,\"ph_phi=%e\\n\", ph_phi);\n fflush(fPtr);\n */\n\n //convert flash coordinated into MCRaT coordinates\n //printf(\"Getting fluid_beta\\n\");\n \n if (dim_switch_3d==0)\n {\n (*(fluid_beta+0))=flash_vx*cos(ph_phi);\n (*(fluid_beta+1))=flash_vx*sin(ph_phi);\n (*(fluid_beta+2))=flash_vy;\n }\n else\n {\n (*(fluid_beta+0))=flash_vx;\n (*(fluid_beta+1))=flash_vy;\n (*(fluid_beta+2))=flash_vz;\n }\n \n /*\n fprintf(fPtr,\"FLASH v: %e, %e\\n\", flash_vx,flash_vy);\n fflush(fPtr);\n */\n \n //fill in photon 4 momentum \n //printf(\"filling in 4 momentum in photonScatter\\n\");\n *(ph_p+0)=(ph->p0);\n *(ph_p+1)=(ph->p1);\n *(ph_p+2)=(ph->p2);\n *(ph_p+3)=(ph->p3);\n \n /*\n fprintf(fPtr,\"Unscattered Photon in Lab frame: %e, %e, %e,%e, %e, %e, %e\\n\", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3), (ph->r0), (ph->r1), (ph->r2));\n fflush(fPtr);\n fprintf(fPtr,\"Fluid Beta: %e, %e, %e\\n\", *(fluid_beta+0),*(fluid_beta+1), *(fluid_beta+2));\n fflush(fPtr);\n */\n \n //first we bring the photon to the fluid's comoving frame\n lorentzBoost(fluid_beta, ph_p, ph_p_comov, 'p', fPtr);\n /*\n fprintf(fPtr,\"Old: %e, %e, %e,%e\\n\", ph->p0, ph->p1, ph->p2, ph->p3);\n fflush(fPtr);\n \n fprintf(fPtr, \"Before Scattering, In Comov_frame:\\n\");\n fflush(fPtr);\n fprintf(fPtr, \"ph_comov: %e, %e, %e,%e\\n\", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));\n fflush(fPtr);\n */\n \n \n //second we generate a thermal electron at the correct temperature\n singleElectron(el_p_comov, fluid_temp, ph_p_comov, rand, fPtr);\n \n //fprintf(fPtr,\"el_comov: %e, %e, %e,%e\\n\", *(el_p_comov+0), *(el_p_comov+1), *(el_p_comov+2), *(el_p_comov+3));\n //fflush(fPtr);\n \n \n //third we perform the scattering and save scattered photon 4 monetum in ph_p_comov @ end of function\n singleComptonScatter(el_p_comov, ph_p_comov, rand, fPtr);\n \n \n //fprintf(fPtr,\"After Scattering, After Lorentz Boost to Comov frame: %e, %e, %e,%e\\n\", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));\n //fflush(fPtr);\n \n \n //fourth we bring the photon back to the lab frame\n *(negative_fluid_beta+0)=-1*( *(fluid_beta+0));\n *(negative_fluid_beta+1)=-1*( *(fluid_beta+1));\n *(negative_fluid_beta+2)=-1*( *(fluid_beta+2));\n lorentzBoost(negative_fluid_beta, ph_p_comov, ph_p, 'p', fPtr);\n //fprintf(fPtr,\"Scattered Photon in Lab frame: %e, %e, %e,%e\\n\", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3));\n fflush(fPtr);\n if (((*(ph_p+0))*C_LIGHT/1.6e-9) > 1e4)\n {\n fprintf(fPtr,\"Extremely High Photon Energy!!!!!!!!\\n\");\n fflush(fPtr);\n }\n //fprintf(fPtr,\"Old: %e, %e, %e,%e\\n\", ph->p0, ph->p1, ph->p2, ph->p3);\n //fprintf(fPtr, \"Old: %e, %e, %e,%e\\n\", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));\n \n //assign the photon its new lab 4 momentum\n (ph->p0)=(*(ph_p+0));\n (ph->p1)=(*(ph_p+1));\n (ph->p2)=(*(ph_p+2));\n (ph->p3)=(*(ph_p+3));\n //printf(\"Done assigning values to original struct\\n\");\n\t\n free(el_p_comov); \n free(ph_p_comov);\n free(fluid_beta); \n free(negative_fluid_beta);\n free(ph_p);\n ph_p=NULL;negative_fluid_beta=NULL;ph_p_comov=NULL; el_p_comov=NULL;\n}\n\nvoid singleElectron(double *el_p, double temp, double *ph_p, gsl_rng * rand, FILE *fPtr)\n{\n //generates an electron with random energy \n \n double factor=0, gamma=0;\n double y_dum=0, f_x_dum=0, x_dum=0, beta_x_dum=0, beta=0, phi=0, theta=0, ph_theta=0, ph_phi=0;\n gsl_matrix *rot= gsl_matrix_calloc (3, 3); //create matrix thats 3x3 to do rotation \n gsl_vector_view el_p_prime ; //create vector to hold rotated electron 4 momentum\n gsl_vector *result=gsl_vector_alloc (3);\n \n //fprintf(fPtr, \"Temp in singleElectron: %e\\n\", temp);\n if (temp>= 1e7)\n {\n //printf(\"In if\\n\");\n factor=K_B*temp/(M_EL*pow(C_LIGHT,2.0));\n y_dum=1; //initalize loop to get a random gamma from the distribution of electron velocities\n f_x_dum=0;\n while ((isnan(f_x_dum) !=0) || (y_dum>f_x_dum) )\n {\n \n x_dum=gsl_rng_uniform_pos(rand)*(1+100*factor);\n beta_x_dum=pow(1-(pow(x_dum, -2.0)) ,0.5);\n y_dum=gsl_rng_uniform(rand)/2.0;\n \n f_x_dum=pow(x_dum,2)*(beta_x_dum/gsl_sf_bessel_Kn (2, 1.0/factor))*exp(-1*x_dum/factor); //not sure if this is right is giving small values of gamma -> beta=nan\n //fprintf(fPtr,\"Choosing a Gamma: xdum: %e, f_x_dum: %e, y_dum: %e\\n\", x_dum, f_x_dum, y_dum);\n }\n gamma=x_dum;\n \n }\n else\n {\n\n //printf(\"In else\\n\");\n factor=pow(K_B*temp/M_EL,0.5);\n //calculate a random gamma from 3 random velocities drawn from a gaussian distribution with std deviation of \"factor\"\n gamma=pow( 1- (pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+ pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2) ) ,-0.5);\n }\n \n //fprintf(fPtr,\"Chosen Gamma: %e\\n\",gamma);\n \n beta=pow( 1- (1/pow( gamma,2.0 )) ,0.5);\n //printf(\"Beta is: %e in singleElectron\\n\", beta);\n phi=gsl_rng_uniform(rand)*2*M_PI;\n \n y_dum=1; //initalize loop to get a random theta\n f_x_dum=0;\n while (y_dum>f_x_dum)\n {\n y_dum=gsl_rng_uniform(rand)*1.3;\n x_dum=gsl_rng_uniform(rand)*M_PI;\n f_x_dum=sin(x_dum)*(1-(beta*cos(x_dum)));\n }\n theta=x_dum;\n //fprintf(fPtr,\"Beta: %e\\tPhi: %e\\tTheta: %e\\n\",beta,phi, theta);\n //fill in electron 4 momentum NOT SURE WHY THE ORDER IS AS SUCH SEEMS TO BE E/c, pz,py,px!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \n *(el_p+0)=gamma*(M_EL)*(C_LIGHT);\n *(el_p+1)=gamma*(M_EL)*(C_LIGHT)*beta*cos(theta);\n *(el_p+2)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*sin(phi);\n *(el_p+3)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*cos(phi);\n \n //printf(\"Old: %e, %e, %e,%e\\n\", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3));\n \n el_p_prime=gsl_vector_view_array((el_p+1), 3);\n \n //find angles of photon NOT SURE WHY WERE CHANGING REFERENCE FRAMES HERE???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n ph_phi=atan2(*(ph_p+2), *(ph_p+3)); //Double Check\n ph_theta=atan2(pow( pow(*(ph_p+2),2)+ pow(*(ph_p+3),2) , 0.5) , (*(ph_p+1)) );\n \n //printf(\"Calculated Photon phi and theta in singleElectron:%e, %e\\n\", ph_phi, ph_theta);\n \n //fill in rotation matrix to rotate around x axis to get rid of phi angle\n gsl_matrix_set(rot, 1,1,1);\n gsl_matrix_set(rot, 2,2,cos(ph_theta));\n gsl_matrix_set(rot, 0,0,cos(ph_theta));\n gsl_matrix_set(rot, 0,2,-sin(ph_theta));\n gsl_matrix_set(rot, 2,0,sin(ph_theta));\n gsl_blas_dgemv(CblasNoTrans, 1, rot, &el_p_prime.vector, 0, result);\n \n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));\n\n printf(\"Middle: %e, %e, %e,%e\\n\", *(el_p+0), gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2));\n */\n \n gsl_matrix_set_all(rot,0);\n \n gsl_matrix_set(rot, 0,0,1);\n gsl_matrix_set(rot, 1,1,cos(-ph_phi));\n gsl_matrix_set(rot, 2,2,cos(-ph_phi));\n gsl_matrix_set(rot, 1,2,-sin(-ph_phi));\n gsl_matrix_set(rot, 2,1,sin(-ph_phi));\n gsl_blas_dgemv(CblasNoTrans, 1, rot, result, 0, &el_p_prime.vector);\n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));\n printf(\"Final EL_P_vec: %e, %e, %e,%e\\n\", *(el_p+0), gsl_vector_get(&el_p_prime.vector,0), gsl_vector_get(&el_p_prime.vector,1), gsl_vector_get(&el_p_prime.vector,2));\n */\n \n \n gsl_matrix_free (rot);gsl_vector_free(result);\n}\n\nvoid singleComptonScatter(double *el_comov, double *ph_comov, gsl_rng * rand, FILE *fPtr)\n{\n //This routine performs a Compton scattering between a photon and a moving electron.\n int i=0;\n double *el_v=malloc(3*sizeof(double));\n double *negative_el_v=malloc(3*sizeof(double));\n double *ph_p_prime=malloc(4*sizeof(double));//use this to keep track of how the ph 4 momentum changes with each rotation\n double *el_p_prime=malloc(4*sizeof(double));\n double phi0=0, phi1=0, phi=0, theta=0;\n double y_dum, f_x_dum, x_dum;\n gsl_matrix *rot0= gsl_matrix_calloc (3, 3); //create matricies thats 3x3 to do rotations\n gsl_matrix *rot1= gsl_matrix_calloc (3, 3);\n gsl_vector *result0=gsl_vector_alloc (3); //vectors to hold results of rotations\n gsl_vector *result1=gsl_vector_alloc (3); \n gsl_vector *result=gsl_vector_alloc (4); \n gsl_vector *whole_ph_p=gsl_vector_alloc (4); \n gsl_vector_view ph_p ; //create vector to hold comoving photon and electron 4 momentum\n gsl_vector_view el_p ;\n \n //fill in electron velocity array and photon 4 momentum\n *(el_v+0)=(*(el_comov+1))/(*(el_comov+0));\n *(el_v+1)=(*(el_comov+2))/(*(el_comov+0));\n *(el_v+2)=(*(el_comov+3))/(*(el_comov+0));\n //printf(\"el_v: %e, %e, %e\\n\", *(el_v+0), *(el_v+1), *(el_v+2));\n \n //lorentz boost into frame where the electron is stationary\n lorentzBoost(el_v, el_comov, el_p_prime, 'e', fPtr);\n lorentzBoost(el_v, ph_comov, ph_p_prime, 'p', fPtr);\n //printf(\"New ph_p in electron rest frame: %e, %e, %e,%e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n \n ph_p=gsl_vector_view_array((ph_p_prime+1), 3);\n el_p=gsl_vector_view_array(el_p_prime,4);\n phi0=atan2(*(ph_p_prime+2), *(ph_p_prime+1) );\n //printf(\"Photon Phi: %e\\n\", phi0);\n //rotate the axes so that the photon incomes along the x-axis\n gsl_matrix_set(rot0, 2,2,1);\n gsl_matrix_set(rot0, 0,0,cos(-phi0));\n gsl_matrix_set(rot0, 1,1,cos(-phi0));\n gsl_matrix_set(rot0, 0,1,-sin(-phi0));\n gsl_matrix_set(rot0, 1,0,sin(-phi0));\n gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);\n \n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));\n */\n \n //set values of ph_p_prime equal to the result and get new phi from result\n *(ph_p_prime+1)=gsl_vector_get(result0,0);\n *(ph_p_prime+2)=0;//gsl_vector_get(result,1); //just directly setting it to 0 now?\n *(ph_p_prime+3)=gsl_vector_get(result0,2);\n \n phi1=atan2(gsl_vector_get(result0,2), gsl_vector_get(result0,0));\n \n /*\n printf(\"rotation 1: %e, %e, %e\\n\", *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n printf(\"Photon Phi: %e\\n\", phi1);\n printf(\"make sure the vector view is good: %e, %e, %e,%e\\n\", *(ph_p_prime+0), gsl_vector_get(&ph_p.vector,0), gsl_vector_get(&ph_p.vector,1), gsl_vector_get(&ph_p.vector,2));\n */\n \n //rotate around y to bring it all along x\n gsl_matrix_set(rot1, 1,1,1);\n gsl_matrix_set(rot1, 0,0,cos(-phi1));\n gsl_matrix_set(rot1, 2,2,cos(-phi1));\n gsl_matrix_set(rot1, 0,2,-sin(-phi1));\n gsl_matrix_set(rot1, 2,0,sin(-phi1));\n gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);\n \n /*\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));\n */\n \n //set values of ph_p_prime equal to the result and get new phi from result\n *(ph_p_prime+1)=*(ph_p_prime+0);//why setting it to the energy?\n *(ph_p_prime+2)=gsl_vector_get(result1,1); \n *(ph_p_prime+3)=0; //just directly setting it to 0 now?\n \n //printf(\"rotation 2: %e, %e, %e, %e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n \n //generate random theta and phi angles for scattering\n phi=gsl_rng_uniform(rand)*2*M_PI;\n //printf(\"Phi: %e\\n\", phi);\n \n y_dum=1; //initalize loop to get a random theta\n f_x_dum=0;\n while (y_dum>f_x_dum)\n {\n y_dum=gsl_rng_uniform(rand)*1.09;\n x_dum=gsl_rng_uniform(rand)*M_PI;\n f_x_dum=sin(x_dum)*(1+pow(cos(x_dum),2));\n }\n theta=x_dum;\n \n //printf(\"Theta: %e\\n\", theta);\n \n //perform scattering and compute new 4-momenta of electron and photon\n //scattered photon 4 momentum\n gsl_vector_set(result, 0, (*(ph_p_prime+0))/(1+ (( (*(ph_p_prime+0))*(1-cos(theta)) )/(M_EL*C_LIGHT )) ) ); //DOUBLE CHECK HERE!!!! \n gsl_vector_set(result, 1, gsl_vector_get(result,0)*cos(theta) );\n gsl_vector_set(result, 2, gsl_vector_get(result,0)*sin(theta)*sin(phi) );\n gsl_vector_set(result, 3, gsl_vector_get(result,0)*sin(theta)*cos(phi) );\n //printf(\"%e\\n\", gsl_vector_get(result,0));\n \n //calculate electron 4 momentum OPTIMIZE HERE: DONT USE A FOR LOOP HERE!!!! Done\n //prescattered photon 4 momentum\n gsl_vector_set(whole_ph_p, 0, (*(ph_p_prime+0)));\n gsl_vector_set(whole_ph_p, 1, (*(ph_p_prime+1)));\n gsl_vector_set(whole_ph_p, 2, (*(ph_p_prime+2)));\n gsl_vector_set(whole_ph_p, 3, (*(ph_p_prime+3)));\n /*\n for (i=0;i<4;i++)\n {\n gsl_vector_set(whole_ph_p, i, (*(ph_p_prime+i)));\n }\n */\n gsl_vector_sub(whole_ph_p,result); //resut is saved into ph_p vector, unscattered-scattered 4 mometum of photon\n gsl_vector_add(&el_p.vector ,whole_ph_p);\n /*\n printf(\"After scattering:\\n\");\n printf(\"el_p: %e, %e, %e,%e\\n\", gsl_vector_get(&el_p.vector,0), gsl_vector_get(&el_p.vector,1), gsl_vector_get(&el_p.vector,2), gsl_vector_get(&el_p.vector,3));\n printf(\"ph_p: %e, %e, %e,%e\\n\", gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2), gsl_vector_get(result,3));\n */\n \n //rotate back to comoving frame\n *(ph_p_prime+0)=gsl_vector_get(result,0);\n *(ph_p_prime+1)=gsl_vector_get(result,1); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product\n *(ph_p_prime+2)=gsl_vector_get(result,2); \n *(ph_p_prime+3)=gsl_vector_get(result,3); \n gsl_matrix_set_all(rot1,0);\n gsl_matrix_set(rot1, 1,1,1);\n gsl_matrix_set(rot1, 0,0,cos(-phi1));\n gsl_matrix_set(rot1, 2,2,cos(-phi1));\n gsl_matrix_set(rot1, 0,2,sin(-phi1));\n gsl_matrix_set(rot1, 2,0,-sin(-phi1));\n gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);\n /*\n printf(\"Photon Phi: %e\\n\", phi1);\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));\n */\n \n //set values of ph_p_prime to result1 from undoing 2nd rotation\n *(ph_p_prime+1)=gsl_vector_get(result1,0);\n *(ph_p_prime+2)=gsl_vector_get(result1,1); \n *(ph_p_prime+3)=gsl_vector_get(result1,2); \n //printf(\"Undo rotation 2: %e, %e, %e, %e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n //ignore the electron, dont care about it, undo the first rotation\n gsl_matrix_set_all(rot0,0);\n gsl_matrix_set(rot0, 2,2,1);\n gsl_matrix_set(rot0, 0,0,cos(-phi0));\n gsl_matrix_set(rot0, 1,1,cos(-phi0));\n gsl_matrix_set(rot0, 0,1,sin(-phi0));\n gsl_matrix_set(rot0, 1,0,-sin(-phi0));\n gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);\n \n /*\n printf(\"Photon Phi: %e\\n\", phi0);\n printf(\"Rotation Matrix 0: %e,%e, %e\\n\", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));\n printf(\"Rotation Matrix 1: %e,%e, %e\\n\", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));\n printf(\"Rotation Matrix 2: %e,%e, %e\\n\", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));\n */\n \n *(ph_p_prime+1)=gsl_vector_get(result0,0);\n *(ph_p_prime+2)=gsl_vector_get(result0,1); \n *(ph_p_prime+3)=gsl_vector_get(result0,2); \n //printf(\"Undo rotation 1: %e, %e, %e, %e\\n\", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));\n //deboost photon to lab frame\n *(negative_el_v+0)=(-1*(*(el_v+0)));\n *(negative_el_v+1)=(-1*(*(el_v+1)));\n *(negative_el_v+2)=(-1*(*(el_v+2)));\n \n lorentzBoost(negative_el_v, ph_p_prime, ph_comov, 'p', fPtr);\n //printf(\"Undo boost 1: %e, %e, %e, %e\\n\", *(ph_comov+0), *(ph_comov+1), *(ph_comov+2), *(ph_comov+3));\n \n gsl_matrix_free(rot0); gsl_matrix_free(rot1);gsl_vector_free(result0);gsl_vector_free(result1);gsl_vector_free(result);\n //gsl_rng_free (rand); \n gsl_vector_free(whole_ph_p);free(ph_p_prime);free(el_p_prime);free(el_v); free(negative_el_v);\n}\n\n\ndouble averagePhotonEnergy(struct photon *ph, int num_ph)\n{\n //to calculate weighted photon energy\n int i=0;\n double e_sum=0, w_sum=0;\n for (i=0;ip0)*((ph+i)->weight));\n w_sum+=((ph+i)->weight);\n }\n \n return (e_sum*C_LIGHT)/w_sum;\n}\n\nvoid phScattStats(struct photon *ph, int ph_num, int *max, int *min, double *avg, double *r_avg )\n{\n int temp_max=0, temp_min=-1, i=0;\n double sum=0, avg_r_sum=0;\n \n for (i=0;inum_scatt);\n avg_r_sum+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);\n \n if (((ph+i)->num_scatt) > temp_max )\n {\n temp_max=((ph+i)->num_scatt);\n //printf(\"The new max is: %d\\n\", temp_max);\n }\n \n if ((i==0) || (((ph+i)->num_scatt)num_scatt);\n //printf(\"The new min is: %d\\n\", temp_min);\n }\n }\n \n *avg=sum/ph_num;\n *r_avg=avg_r_sum/ph_num;\n *max=temp_max;\n *min=temp_min;\n \n}\n\nvoid cylindricalPrep(double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array)\n{\n double gamma_infinity=100, t_comov=1*pow(10, 5), ddensity=3e-7;// the comoving temperature in Kelvin, and the comoving density in g/cm^2\n int i=0;\n double vel=pow(1-pow(gamma_infinity, -2.0) ,0.5), lab_dens=gamma_infinity*ddensity;\n \n for (i=0; i= (r00*gamma_infinity))\n {\n *(gamma+i)=gamma_infinity;\n *(pres+i)=(lumi*pow(r00, 2.0/3.0)*pow(*(r+i), -8.0/3.0) )/(12.0*M_PI*C_LIGHT*pow(gamma_infinity, 4.0/3.0)*pow(C_LIGHT, 2.0)); \n }\n else\n {\n *(gamma+i)=(*(r+i))/r00;\n *(pres+i)=(lumi*pow(r00, 2.0))/(12.0*M_PI*C_LIGHT*pow(C_LIGHT, 2.0)*pow(*(r+i), 4.0) ); \n }\n \n vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5);\n *(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);\n *(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);\n *(dens+i)=lumi/(4*M_PI*pow(*(r+i), 2.0)*pow(C_LIGHT, 3.0)*gamma_infinity*(*(gamma+i)));\n *(dens_lab+i)=(*(dens+i))*(*(gamma+i));\n *(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n //fprintf(fPtr,\"Gamma: %lf\\nR: %lf\\nPres: %e\\nvel %lf\\nX: %lf\\nY %lf\\nVx: %lf\\nVy: %lf\\nDens: %e\\nLab_Dens: %e\\nTemp: %lf\\n\", *(gamma+i), *(r+i), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i));\n\n }\n \n}\n\n\nvoid dirFileMerge(char dir[200], int start_frame, int last_frame, int numprocs, int angle_id, int dim_switch, int riken_switch, FILE *fPtr )\n{\n //function to merge files in mcdir produced by various threads\n int i=0, j=0, k=0, num_files=8, num_thread=8; //omp_get_max_threads() number of files is number of types of mcdata files there are\n int increment=1;\n char filename_k[2000]=\"\", file_no_thread_num[2000]=\"\", cmd[2000]=\"\", mcdata_type[200]=\"\";\n \n //printf(\"Merging files in %s\\n\", dir); \n //#pragma omp parallel for num_threads(num_thread) firstprivate( filename_k, file_no_thread_num, cmd,mcdata_type,num_files, increment ) private(i,j,k)\n // i < last frame because calculation before this function gives last_frame as the first frame of the next process set of frames to merge files for\n for (i=start_frame;i=3000))\n {\n increment=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n }\n \n for (j=0;j> \", file_no_thread_num);\n system(cmd);\n }\n \n //remove file\n snprintf(cmd, sizeof(cmd), \"%s%s\", \"rm \", filename_k);\n system(cmd);\n \n }\n \n \n }\n }\n \n if (angle_id==0)\n {\n //merge photon weight files\n for (k=0;k> \", file_no_thread_num);\n system(cmd);\n }\n \n \n //remove files\n snprintf(cmd, sizeof(cmd), \"%s%s\", \"rm \", filename_k);\n system(cmd);\n \n }\n }\n \n}\n\nvoid modifyFlashName(char flash_file[200], char prefix[200], int frame, int dim_switch)\n{\n int lim1=0, lim2=0, lim3=0;\n \n if (dim_switch==0)\n {\n //2D case\n lim1=10;\n lim2=100;\n lim3=1000;\n }\n else\n {\n //3d case\n lim1=100;\n lim2=1000;\n lim3=10000;\n }\n \n if (frame> Opening file %s\\n\", file_num);\n fflush(fPtr);\n \n snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, file_end);\n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr);\n fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr);\n fread(&r_min_index, sizeof(int)*1, 1,hydroPtr);\n fread(&r_max_index, sizeof(int)*1, 1,hydroPtr);\n fclose(hydroPtr);\n \n //fortran indexing starts @ 1, but C starts @ 0\n r_min_index--;//=r_min_index-1;\n r_max_index--;//=r_max_index-1;\n theta_min_index--;//=theta_min_index-1;\n theta_max_index--;//=theta_max_index-1;\n \n elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index); //max index is max number of elements minus 1, there add one to get total number of elements\n fprintf(fPtr,\"Elem %d\\n\", elem);\n fprintf(fPtr,\"Limits %d, %d, %d, %d, %d, %d\\n\", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); \n fflush(fPtr);\n \n //now with number of elements allocate data\n dens_unprc=malloc(elem*sizeof(float));\n vel_r_unprc=malloc(elem*sizeof(float));\n vel_theta_unprc=malloc(elem*sizeof(float));\n pres_unprc=malloc(elem*sizeof(float));\n \n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n /*\n for (i=0;i> Opening file %s\\n\", full_file);\n //fflush(fPtr);\n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n \n //elem=(r_max_index-r_min_index)*(theta_max_index-theta_min_index);\n //fprintf(fPtr,\"Elem %d\\n\", elem);\n //fprintf(fPtr,\"Limits %d, %d, %d, %d, %d, %d\\n\", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); \n //fflush(fPtr);\n\n fread(pres_unprc, sizeof(float),elem, hydroPtr); //data\n \n fclose(hydroPtr);\n \n \n /*\n for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)\n { \n for (k=0; k<(r_max_index+1-r_min_index); k++)\n {\n \n fprintf(fPtr,\"Pres %d: %e\\n\", ( j*(r_max_index+1-r_min_index)+k ), *(pres_unprc+( j*(r_max_index+1-r_min_index)+k )));\n //fprintf(fPtr,\"Pres %d: %e\\n\", ( j*(r_max_index)+k ), *(pres_unprc+( j*(r_max_index)+k )));\n fflush(fPtr);\n \n }\n }\n exit(0); \n */\n \n //R\n snprintf(hydrofile,sizeof(hydrofile),\"%s%s\",hydro_prefix,\"grid-x1.data\" );\n hydroPtr=fopen(hydrofile, \"r\");\n //fprintf(fPtr,\">> Opening file %s\\n\", hydrofile);\n //fflush(fPtr);\n \n i=0;\n while (i> Opening file %s\\n\", hydrofile);\n //fflush(fPtr);\n \n i=0;\n while (i injection radius\n elem_factor=0;\n elem=0;\n while (elem==0)\n {\n elem_factor++;\n elem=0;\n for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)\n { \n for (k=0; k<(r_max_index+1-r_min_index); k++)\n {\n i=r_min_index+k; //look at indexes of r that are included in small hydro file\n //if I have photons do selection differently than if injecting photons\n if (ph_inj_switch==0)\n {\n //if calling this function when propagating photons, choose blocks based on where the photons are\n if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (ph_rmax + elem_factor*C_LIGHT/fps) ))\n {\n // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )\n elem++;\n }\n }\n else\n {\n //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient\n if (((r_inj - C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (r_inj + C_LIGHT/fps) ))\n {\n // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )\n elem++;\n }\n \n }\n \n }\n }\n }\n fprintf(fPtr, \"Number of post restricted Elems: %d %e\\n\", elem, r_inj);\n fflush(fPtr);\n\n \n (*pres)=malloc (elem * sizeof (double ));\n (*velx)=malloc (elem * sizeof (double ));\n (*vely)=malloc (elem * sizeof (double ));\n (*dens)=malloc (elem * sizeof (double ));\n (*x)=malloc (elem * sizeof (double ));\n (*y)=malloc (elem * sizeof (double ));\n (*r)=malloc (elem * sizeof (double ));\n (*theta)=malloc (elem * sizeof (double ));\n (*gamma)=malloc (elem * sizeof (double ));\n (*dens_lab)=malloc (elem * sizeof (double ));\n //szx becomes delta r szy becomes delta theta\n (*szx)=malloc (elem * sizeof (double ));\n (*szy)=malloc (elem * sizeof (double ));\n (*temp)=malloc (elem * sizeof (double ));\n\n elem=0;\n for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)\n { \n for (k=0; k<(r_max_index+1-r_min_index); k++)\n {\n r_index=r_min_index+k; //look at indexes of r that are included in small hydro file\n theta_index=theta_min_index+j;\n \n if (ph_inj_switch==0)\n {\n if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) ))\n {\n (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));\n (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));\n (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));\n (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));\n (*r)[elem]=*(r_unprc+r_index);\n (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);\n (*szy)[elem]=(M_PI/2)/2000;\n (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis\n (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c\n (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);\n (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n elem++;\n }\n }\n else\n {\n if (((r_inj - C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + C_LIGHT/fps) ))\n {\n (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));\n (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));\n (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));\n (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));\n (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));\n (*r)[elem]=*(r_unprc+r_index);\n (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);\n (*szy)[elem]=(M_PI/2)/2000;\n (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis\n (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c\n (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);\n (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n elem++;\n \n }\n }\n }\n }\n\n (*number)=elem;\n //fprintf(fPtr, \"Number of post restricted Elems: %d %e\\n\", elem, r_inj);\n //fflush(fPtr);\n \n \n free(pres_unprc); //works when not being freed?\n //fprintf(fPtr, \"pres Done\\n\\n\");\n //fflush(fPtr);\n \n free(vel_r_unprc);\n //fprintf(fPtr, \"vel_r Done\\n\\n\");\n //fflush(fPtr);\n \n free(vel_theta_unprc);\n //fprintf(fPtr, \"vel_theta Done\\n\\n\");\n //fflush(fPtr);\n \n free(dens_unprc);\n //fprintf(fPtr, \"dens Done\\n\\n\");\n //fflush(fPtr);\n \n free(r_unprc); \n //fprintf(fPtr, \"r Done\\n\\n\");\n //fflush(fPtr);\n \n free(theta_unprc); \n //fprintf(fPtr, \"theta Done\\n\\n\");\n //fflush(fPtr);\n \n pres_unprc=NULL;\n vel_r_unprc=NULL;\n vel_theta_unprc=NULL;\n dens_unprc=NULL;\n r_unprc=NULL;\n theta_unprc=NULL;\n \n //fprintf(fPtr, \"ALL Done\\n\\n\");\n //fflush(fPtr);\n}\n\n", "meta": {"hexsha": "f87fe86a92825d0dfff0034d8dd404538f22cc4d", "size": 118236, "ext": "c", "lang": "C", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib.c", "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib.c", "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "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": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib.c", "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "avg_line_length": 42.3784946237, "max_line_length": 430, "alphanum_fraction": 0.5686085456, "num_tokens": 36050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.1709250929618526}} {"text": "#include \n#include \n#include \n#include \"chaincolln.h\"\n#include \"cokus.h\"\n#include \"chain.h\"\n#include \"config.h\"\n#include \"parameters.h\"\n#include \"irmutils.h\"\n#include \"relation.h\"\n#include \"domain.h\"\n\n#ifdef GSL\n#include \n#include \n#include \n#endif\n\n\n/*****************************************************************************\nA collection of chains. We maintain several chains in case we want to run\nMetropolis-coupled MCMC (MC^3). We also keep one spare chain so that\nsplit-merge proposals can be tried without losing the current state. \n*****************************************************************************/\n\nstruct chaincolln_str\n{ int nchains;\n chain *chains;\n chain sparechain;\n char prefix[MAXSTRING];\t/* unused right now */\n int itercount;\t\t/* iteration count */\n} chaincolln_str;\n\n/* nchains already includes one extra for sparechain */\nchaincolln chaincolln_create(int nchains, int ndomains, int nrelns, char *pref)\n{\n int i;\n chaincolln cc;\n double temp;\n cc = (chaincolln) my_malloc(sizeof(struct chaincolln_str));\n cc->chains = (chain *) my_malloc(nchains*sizeof(chain ));\n /* include spare chain */\n for (i = 0; i < nchains; i++) {\n temp = 1.0/(1+ps.temp*i);\n cc->chains[i] = chain_create(ndomains, nrelns, temp);\n }\n cc->nchains = nchains-1;\n cc->sparechain = cc->chains[nchains-1];\n strcpy(cc->prefix, pref);\n cc->itercount = 0;\n return cc;\n}\n\n/* read the configuration file and the graph */\nchaincolln chaincolln_readdata(void) {\n FILE *fileptr, *initzsfile;\n int i, j, k, ndom, nreln, d, r, nitem, dim, maxclass, initclass, relcl, ndim, \n\tdomlabel, clusterflag, itemind, nchains, cind, zind;\n int *domlabels, *participants, participant;\n double val;\n double nig[DISTSIZE];\n domain *doms;\n relation rn;\n int *initclasses, ***edgecounts, *relsizes;\n char prefix[MAXSTRING];\n\n chaincolln cc;\n chain c, c0;\n#ifdef GSL\n gsl_rng *rng;\n const gsl_rng_type *T;\n gsl_permutation *perm ;\n size_t N;\n\n gsl_rng_env_setup();\n T = gsl_rng_default;\n rng = gsl_rng_alloc(T);\n#endif \n\n fprintf(stdout,\"A\\n\");\n nchains = ps.nchains+1;\n nig[0] = ps.m; nig[1] = ps.v; nig[2] = ps.a; nig[3] = ps.b; \n \n fileptr = fopen(ps.configfile,\"r\");\n if (fileptr == NULL) {\n fprintf(stderr, \"couldn't read config file\\n\"); exit(1); \n }\n\n /* initial read of ps.configfile to get ps.maxdim, ps.maxrel, ps.maxitem, \n ps.maxclass */\n fscanf(fileptr, \"%s\", prefix);\n fscanf(fileptr, \"%d %d\", &ndom, &nreln);\n relsizes= (int *) my_malloc(nreln*sizeof(int));\n ps.maxrel = nreln;\n ps.maxitem = 0; ps.maxclass = 0;\n for (d = 0; d < ndom; d++) {\n fscanf(fileptr, \"%d %d %d %d\", &nitem, &maxclass, &initclass, &clusterflag);\n if (nitem > ps.maxitem) {\n ps.maxitem = nitem;\n }\n if (maxclass > ps.maxclass) {\n ps.maxclass= maxclass;\n }\n }\n fprintf(stdout,\"B\\n\");\n ps.maxdim = 0;\n for (r = 0; r < nreln; r++) {\n fscanf(fileptr, \"%d\", &ndim);\n relsizes[r] = ndim;\n if (ndim > ps.maxdim) {\n ps.maxdim = ndim;\n }\n for (dim=0; dim < ndim; dim++) {\n fscanf(fileptr, \"%d\", &domlabel);\n }\n }\n fclose(fileptr);\n\n fprintf(stdout,\"C\\n\");\n domlabels=\t (int *) my_malloc(ps.maxdim*sizeof(int));\n participants= (int *) my_malloc(ps.maxdim*sizeof(int));\n initclasses = (int *) my_malloc(ps.maxitem*sizeof(int));\n\n fprintf(stdout,\"D \\n\");\n /* initial read of ps.graphname to get ps.maxobjtuples */\n edgecounts = (int ***) my_malloc(ps.maxrel*sizeof(int **));\n for (i = 0; i < ps.maxrel; i++) {\n edgecounts[i] = (int **) my_malloc(ps.maxdim*sizeof(int *));\n for (j = 0; j < ps.maxdim; j++) {\n edgecounts[i][j] = (int *) my_malloc(ps.maxitem*sizeof(int));\n for (k = 0; k < ps.maxitem; k++) {\n edgecounts[i][j][k] = 0;\n }\n }\n }\n ps.maxobjtuples = 0;\n\n fprintf(stdout,\"D2 \\n\");\n fileptr = fopen(ps.graphname,\"r\");\n if (fileptr == NULL) {\n fprintf(stderr, \"couldn't read graph\\n\"); exit(1); \n }\n while( fscanf( fileptr, \" %d\", &r)!=EOF ) {\n fprintf(stdout,\"%s %d %d\\n\",__FILE__,__LINE__,r);\n ndim = relsizes[r];\n fprintf(stdout,\"%s %d %d\\n\",__FILE__,__LINE__,ndim);\n for (dim = 0; dim < ndim; dim++) {\n fscanf(fileptr, \"%d\", &participant);\n participants[dim] = participant;\n }\n fscanf(fileptr, \"%lf\", &val); \n\n for (dim = 0; dim < ndim; dim++) {\n fprintf(stdout,\"D2 %d %d %d \\n\",r,dim,participants[dim]);\n edgecounts[r][dim][participants[dim]]++;\n fprintf(stdout,\"D2 %d %d %d \\n\",r,dim,participants[dim]);\n }\n }\n fprintf(stdout,\"E\\n\");\n fclose(fileptr);\n for (i = 0; i < ps.maxrel; i++) {\n for (j = 0; j < ps.maxdim; j++) {\n for (k = 0; k < ps.maxitem; k++) {\n if (edgecounts[i][j][k] > ps.maxobjtuples) {\n ps.maxobjtuples = edgecounts[i][j][k];\n }\n edgecounts[i][j][k]= 0;\n }\n }\n }\n\n fprintf(stdout,\"F\\n\");\n free(relsizes); \n for (i = 0; i < ps.maxrel; i++) {\n for (j = 0; j < ps.maxdim; j++) {\n free(edgecounts[i][j]);\n }\n free(edgecounts[i]);\n }\n free(edgecounts);\n\n\n fprintf(stdout,\"G\\n\");\n /* second read of ps.configfile where we set up datastructures */\n\n fileptr = fopen(ps.configfile,\"r\");\n if (ps.outsideinit) {\n initzsfile= fopen(ps.initfile,\"r\");\n if (initzsfile == NULL) {\n fprintf(stderr, \"couldn't read initzsfile\\n\"); exit(1); \n }\n } else {\n initzsfile = NULL;\n }\n\n fprintf(stdout,\"H\\n\");\n fscanf(fileptr, \"%s\", prefix);\n fscanf(fileptr, \"%d %d\", &ndom, &nreln);\n\n cc = chaincolln_create(nchains, ndom, nreln, prefix);\n c0 = chaincolln_getchain(cc, 0);\n\n fprintf(stdout,\"I\\n\");\n /* read domains */\n /* input file: nitem maxclass initclass clusterflag*/\n for (d = 0; d < ndom; d++) {\n fscanf(fileptr, \"%d %d %d %d\", &nitem, &maxclass, &initclass, &clusterflag);\n#ifdef GSL\n N = nitem; \n#endif\n if (ps.outsideinit) {\n for (zind = 0; zind < nitem; zind++) {\n fscanf(initzsfile, \"%d\", &initclasses[zind]);\n }\n }\n fprintf(stdout,\"J\\n\");\n\n /* add domains and items to chains */\n for (cind = 0; cind < nchains; cind++) {\n c = chaincolln_getchain(cc, cind);\n chain_adddomain(c, d, nitem, maxclass, clusterflag, ps.alpha,\n\t\t ps.alphahyp, initclasses);\n#ifdef GSL\n perm = gsl_permutation_alloc(N);\n gsl_permutation_init(perm);\n gsl_ran_shuffle(rng, perm->data, N, sizeof(size_t)); \n#endif\n /* assign items to classes */\n relcl = 0;\n for (i = 0; i < nitem; i++) {\n if (ps.outsideinit) {\n\t chain_additemtoclass(c, d, i, initclasses[i]);\n\t} else { \n if (relcl == initclass) relcl = 0; \n\n\t /* without the GNUSL, each chain gets initialized the same way. This\n\t * is suboptimal */\n\t itemind = i;\n#ifdef GSL\n itemind = gsl_permutation_get(perm, i);\n#endif\n chain_additemtoclass(c, d, itemind, relcl);\n relcl++;\n }\n }\n#ifdef GSL\n gsl_permutation_free(perm);\n#endif\n }\n }\n#ifdef GSL\n gsl_rng_free(rng);\n#endif\n \n fprintf(stdout,\"K\\n\");\n /* read relations*/\n /* input file: ndim d0 ... dn */\n\n for (r = 0; r < nreln; r++) {\n fscanf(fileptr, \"%d\", &ndim);\n for (dim=0; dim < ndim; dim++) {\n fscanf(fileptr, \"%d\", &domlabel);\n domlabels[dim] = domlabel;\n }\n for (cind = 0; cind < nchains; cind++) {\n c = chaincolln_getchain(cc, cind);\n chain_addrelation(c, r, ndim, ps.betaprop, ps.betamag, nig, domlabels);\n }\n }\n if (ps.outsideinit) {\n fclose(initzsfile); \n }\n\n fprintf(stdout,\"L\\n\");\n fclose(fileptr);\n /* second read of ps.graphname: store edges*/\n fileptr = fopen(ps.graphname,\"r\");\n /* input file: relind p0 p1 p2 .. pn val */\n while( fscanf( fileptr, \" %d\", &r)!= EOF ) {\n ndim = relation_getdim( chain_getrelation(c0, r) );\n doms = relation_getdoms( chain_getrelation(c0, r) ); \n for (dim = 0; dim < ndim; dim++) {\n fscanf(fileptr, \"%d\", &participant);\n fprintf(stdout,\"M %d %d\\n\",dim,participant);\n participants[dim] = participant;\n domlabels[dim] = domain_getlabel(doms[dim]); \n }\n \n for (i = 0; i < ndim; i++) {\n for (j = 0; j < i; j++) {\n if (participants[i] == participants[j] && \n\t domlabels[i] == domlabels[j]) {\n\t fprintf(stderr, \"Self links not allowed.\\n\"); exit(1); \n\t}\n } \n } \n\n fscanf(fileptr, \"%lf\", &val);\n fprintf(stderr,\"%d\\n\",nchains);\n for (cind = 0; cind < nchains; cind++) {\n c = chaincolln_getchain(cc, cind);\n chain_addedge(c, r, val, participants); \n \n rn = chain_getrelation(c, r);\n \n if (doubleeq(val, 0)) {\n\trelation_setmissing(rn, 1);\t\n }\n \n if (val > 1.5 && relation_getdtype(rn) != CONT) {\n\trelation_setdtype(rn, FREQ);\t\n }\n \n if (!doubleeq(val, (int) val)) {\n\trelation_setdtype(rn, CONT);\t\n\trelation_setmissing(rn, 1); /* XXX: no sparse continuous matrices */\t\n }\t\n \n }\n }\n\n fprintf(stderr,\"N\\n\");\n fclose(fileptr);\n\n for (cind = 0; cind < nchains; cind++) {\n c = chaincolln_getchain(cc, cind);\n for (i = 0; i < chain_getndomains(c); i++) {\n chain_updatedomprobs(c, i);\n }\n }\n\n fprintf(stderr,\"O\\n\");\n free(domlabels); free(participants); free(initclasses);\n\n return cc;\n}\n\nint chaincolln_getnchain(chaincolln cc) {\n return cc->nchains;\n}\n\nchain chaincolln_getchain(chaincolln cc, int chainind) {\n return cc->chains[chainind];\n}\n\nchar *chaincolln_getprefix(chaincolln cc) {\n return cc->prefix;\n}\n\nint chaincolln_getitercount(chaincolln cc) {\n return cc->itercount;\n}\n\nvoid chaincolln_print(chaincolln cc) {\n chaincolln_printassignments(cc);\n chaincolln_printstatus(cc, NULL);\n chaincolln_printstatus(cc, stderr);\n}\n\n/* run hillclimbing with random restarts */\nvoid chaincolln_climb(chaincolln cc, int maxloops) {\n int i, j, changeflag, nrepeats; \n chain chn, schn;\n double oldscore, newscore, currscore;\n\n chn = chaincolln_getchain(cc, 0);\n schn = cc->sparechain;\n changeflag = 1; \n nrepeats = 0;\n oldscore = -MAXDOUBLE;\n currscore= -MAXDOUBLE;\n\n chaincolln_print(cc);\n for (i = 0; i < maxloops; i++) {\n if (changeflag > 0) { \n /* maximizing scan: move each object to the best class for it */\n changeflag = chain_climbscan(chn);\n }\n /*chain_print(chn); fprintf(stderr, \"splitting\\n\");*/\n changeflag = changeflag + chain_climbsplitfast(chn, schn);\n\n /*chain_print(chn); fprintf(stderr, \"merging\\n\");*/\n changeflag = changeflag + chain_climbmergefast(chn, schn);\n\n for (j = 0; j < ps.hypupdates; j++) {\n changeflag = changeflag + chaincolln_hypupdates(cc, &proposal_best);\n }\n\n cc->itercount++;\n newscore = chain_getprob(chn);\n if ( fabs(newscore - oldscore) < 0.00001 * fabs(newscore) ) {\n nrepeats++;\n if (nrepeats == 8) {\n chaincolln_print(cc);\n fprintf(stderr, \"*************** randomize\\n\");\n nrepeats = 0;\n\tchain_randomize(cc->chains[0]);\n currscore = chain_getprob(chn);\n newscore = chain_getprob(chn);\n }\n } else {\n nrepeats = 0;\n }\n oldscore = newscore;\n chaincolln_printstatus(cc, stderr);\n }\n}\n\n/* run gibbs sampler with Metropolis updates (MC^3, split-merge) */\nvoid chaincolln_mcmc(chaincolln cc, int maxloops) {\n int i, j;\n chaincolln_print(cc);\n for (i = 0; i < maxloops; i++) {\n fprintf(stderr,\"loop %d\",i);\n /* gibbs scans and split merge updates */\n chaincolln_sample(cc, 1);\n /* MC^3: try swaps between chains at different temperatures */\n chaincolln_tryswaps(cc);\n /* hyperparameter updates? */\n for (j = 0; j < ps.hypupdates; j++) {\n chaincolln_hypupdates(cc, &proposal_mcmc);\n }\n chaincolln_print(cc);\n }\n}\n\n\n/* update hyperparameters */\nint chaincolln_hypupdates(chaincolln cc, \n\tint (*proposal_choose) (double, double, double)) {\n int i, changeflag;\n changeflag = 0;\n for (i = 0; i < cc->nchains; i++) {\n chain_hypupdate(chaincolln_getchain(cc, i), proposal_choose, &changeflag);\n }\n return changeflag;\n}\n\n\nvoid chaincolln_itergibbsm(chaincolln cc) {\n int i;\n if (1) { /* regular gibbs scans */\n for (i = 0; i < cc->nchains; i++) {\n chain_itergibbs(chaincolln_getchain(cc, i));\n }\n }\n if (1) { /* split-merge updates */\n for (i = 0; i < cc->nchains; i++) {\n chain_itersm(chaincolln_getchain(cc, i), cc->sparechain);\n }\n }\n cc->itercount++;\n}\n\nvoid chaincolln_sample(chaincolln cc, int niter) {\n int i;\n for (i = 0; i < niter; i++) {\n chaincolln_itergibbsm(cc);\n }\n}\n\n/* try swapping chains at different temperatures */\nvoid chaincolln_tryswaps(chaincolln cc) {\n int nchains;\n int sw1, sw2, swcount;\n chain c1, c2; \n double t1, t2, aswap, rn;\n\n nchains = cc->nchains;\n if (nchains > 1) {\n for (swcount = 0; swcount < 1; swcount++) {\n sw1 = randomitem(nchains);\n sw2 = sw1;\n while (sw2 == sw1) { sw2 = randomitem(nchains); }\n\n c1 = cc->chains[sw1]; c2 = cc->chains[sw2]; \n t1 = chain_gettemp(c1); t2 = chain_gettemp(c2); \n aswap = exp( (t1 - t2)* (chain_getprob(c2) - chain_getprob(c1)) );\n if (aswap > 1) { aswap=1; }\n rn = myrand();\n if (rn < aswap) {\n chaincolln_swapchains(cc, sw1, sw2);\n fprintf(stderr, \"****CS: %f\\n\", aswap);\n }\n }\n }\n}\n\n/* swap chains SW1 and SW2 */\nvoid chaincolln_swapchains(chaincolln cc, int sw1, int sw2) {\n chain c1, c2;\n double t1, t2;\n c1 = chaincolln_getchain(cc, sw1);\n c2 = chaincolln_getchain(cc, sw2);\n t1 = chain_gettemp(c1); t2 = chain_gettemp(c2); \n chain_settemp(c1, t2); chain_settemp(c2, t1); \n cc->chains[sw1] = c2;\n cc->chains[sw2] = c1;\n}\n\n\nvoid chaincolln_printassignments(chaincolln cc) {\n int i;\n chain chn; \n char filename[MAXSTRING];\n FILE * domfileptr;\n\n chn = chaincolln_getchain(cc, 0);\n for (i = 0; i < chain_getndomains(chn); i++) {\n sprintf(filename, \"%s_dom%d\", ps.outroot, i);\n domfileptr = fopen(filename, \"a\"); \n if (domfileptr == NULL) {\n fprintf(stderr, \"couldn't read domain file\\n\"); \n exit(1); \n }\n domain_printassignments(domfileptr, chain_getdomain(chn, i));\n fclose(domfileptr);\n }\n}\n\n\nvoid chaincolln_printstatus(chaincolln cc, FILE *fptr) {\n int i, nchains;\n chain chn; \n char filename[MAXSTRING];\n FILE * domfileptr;\n\n nchains = chaincolln_getnchain(cc);\n if (fptr == NULL) {\n sprintf(filename, \"%s_status\", ps.outroot);\n domfileptr = fopen(filename, \"a\"); \n if (domfileptr == NULL) {\n fprintf(stderr, \"couldn't read statusfile\\n\"); \n exit(1); \n }\n } else { \n domfileptr = fptr;\n }\n fprintf(domfileptr, \"%4d: \", chaincolln_getitercount(cc));\n chn = chaincolln_getchain(cc, 0);\n chain_printdetailedstatus(chn, domfileptr);\n for (i = 1; i < nchains; i++) {\n chn = chaincolln_getchain(cc, i);\n chain_printbriefstatus(chn, domfileptr);\n }\n chn = chaincolln_getchain(cc,0);\n chain_printhyps(chn, domfileptr);\n fprintf(domfileptr, \"\\n\");\n\n\n if (fptr == NULL) {\n fclose(domfileptr);\n }\n}\n\nvoid chaincolln_free(chaincolln cc)\n{\n int i;\n /* include spare chain */\n for (i = 0; i < cc->nchains+1; i++) {\n chain_free(cc->chains[i]);\n }\n free(cc->chains);\n free(cc);\n}\n\n", "meta": {"hexsha": "c9861b4c05eacd928f095e9fc6b1bb831c853278", "size": 15133, "ext": "c", "lang": "C", "max_stars_repo_path": "HiddenCauses/irm/chaincolln.c", "max_stars_repo_name": "adamsumm/CausalMario", "max_stars_repo_head_hexsha": "93cddb9931509e90693c61a559b98c24ba8a7110", "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": "HiddenCauses/irm/chaincolln.c", "max_issues_repo_name": "adamsumm/CausalMario", "max_issues_repo_head_hexsha": "93cddb9931509e90693c61a559b98c24ba8a7110", "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": "HiddenCauses/irm/chaincolln.c", "max_forks_repo_name": "adamsumm/CausalMario", "max_forks_repo_head_hexsha": "93cddb9931509e90693c61a559b98c24ba8a7110", "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": 26.6895943563, "max_line_length": 80, "alphanum_fraction": 0.6000792969, "num_tokens": 4829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.1707319205056705}} {"text": "/* DomSelfAdaptFWD.c\n\nForward-in-time simulation of an adaptive alleles with dominance and selfing, with linked neutral fragment.\n\nThis is the BATCH version - to be used on cluster machine to produce many simulation replicates at once.\n\nBurn-in program: generates neutral background diversity for other simulations to use. See README for more information.\n\nSimulation uses routines found with the GNU Scientific Library (GSL)\n(http://www.gnu.org/software/gsl/)\nSince GSL is distributed under the GNU General Public License \n(http://www.gnu.org/copyleft/gpl.html), you must download it \nseparately from this file.\n\n*/\n\n/* Preprocessor statements */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define INITTS 1000\n\n/* Function prototypes */\nvoid Wait();\nunsigned int bitswitch(unsigned int x);\nvoid generation_BI(unsigned int N, double self, double R, unsigned int *nums, unsigned int **neutin, unsigned int **neutout, unsigned int npoly, double *polypos, const gsl_rng *r);\nvoid rec_sort(double *index, unsigned int nrow);\nvoid addpoly(unsigned int N, unsigned int **neutin, double *polyloc, unsigned int *npoly, double theta, const gsl_rng *r);\nvoid reassign2(unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int N, unsigned int aft);\nvoid popprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N, unsigned int ei, unsigned int suffix);\nvoid polyprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N);\nvoid ptrim(unsigned int size, unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int *npolyT, double *avpi);\nunsigned int uniqueH(unsigned int **neutin, unsigned int npoly, unsigned int N);\n\nvoid Wait(){\n\tprintf(\"Press Enter to Continue\");\n\twhile( getchar() != '\\n' );\n\tprintf(\"\\n\");\t\n}\n\n/* Bit-switching routine */\nunsigned int bitswitch(unsigned int x){\n\tunsigned int ret;\n\tswitch(x)\n\t{\n\t\tcase 0:\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tret = 0;\n\t\t\tbreak;\t\t\n\t\tdefault:\t/* If none of these cases chosen, exit with error message */\n\t\t\tfprintf(stderr,\"Error in bitswitch: input is not 0 or 1.\\n\");\n\t\t\texit(1);\n break;\n\t}\n\treturn ret;\n}\n\n/* Sorting rec events after choosing them */\nvoid rec_sort(double *index, unsigned int nrow){\n\tunsigned int j, i;\t\t/* Sorting indices */\n\tdouble temp0;\t\t/* For swapping */\n\t\n\tfor(j = 1; j < nrow; j++){\n\t\ti = j;\n\t\twhile( (i > 0) && ( *(index + (i - 1) ) > *(index + i) )){\n\t\t\t/* Swapping entries */\n\t\t\ttemp0 = *(index + (i - 1));\n\t\t\t*(index + (i - 1)) = *(index + (i));\n\t\t\t*(index + (i)) = temp0;\t\t\t\n\t\t\ti--;\n\t\t}\n\t}\n\t\n}\n\n/* Reproduction routine */\nvoid generation_BI(unsigned int N, double self, double R, unsigned int *nums, unsigned int **neutin, unsigned int **neutout, unsigned int npoly, double *polypos, const gsl_rng *r){\n\tunsigned int i, j, k;\t\t/* Pop counter, neutral marker counter, rec event counter */\n\tunsigned int isself = 0;\t/* Is this a selfing reproduction? */\n\tunsigned int choose1 = 0;\t/* Chromosome to be selected */\n\tunsigned int choose2 = 0;\t/* Chromosome to be selected (2nd with outcrossing) */\n\tunsigned int wc1 = 0;\t\t/* Which chrom (parent 1) */\n\tunsigned int wc2 = 0;\t\t/* Which chrom (parent 2) */\n\tunsigned int index1 = 0;\t/* Index of chosen sample 1 */\n\tunsigned int index2 = 0;\t/* Index of chosen sample 2 */\n\tunsigned int nself = 0;\t\t/* Number of selfing events */\n\tunsigned int selfix = 0;\t/* Selfing index */\n\tunsigned int recix1 = 0;\t/* Rec index chr 1 */\n\tunsigned int recix2 = 0;\t/* Rec index chr 2 */\n\tunsigned int nrec1 = 0;\t\t/* Number rec events chr 1 */\n\tunsigned int nrec2 = 0;\t\t/* Number rec events chr 2 */\n\t\n\t/* First deciding number of selfing events; creating vector of events + choosing */\n\tnself = gsl_ran_binomial(r, self, N);\n\tunsigned int *selfev = calloc(nself,sizeof(unsigned int));\n\tgsl_ran_choose(r, selfev, nself, nums, N, sizeof(unsigned int));\n\t\t\n\tfor(i = 0; i < N; i++){\t\t/* Regenerating population */\n \t\n \t/* Choosing first parent, and relevant chromosomes */\n \t/* ADJUSTED SO PURELY NEUTRAL SELECTION ONLY */\n\t\tchoose1 = gsl_rng_uniform_int(r,N);\n\t\twc1 = gsl_ran_bernoulli(r,0.5);\n\t\twc2 = gsl_ran_bernoulli(r,0.5);\n\t\tindex1 = 2*choose1 + wc1;\n\t\t\n\t\t/* Copying over selected sites, first checking if selfing occurs */\n\t\tisself = 0;\n\t\tif(nself != 0){\n\t\t\tif(*(selfev + selfix) == i){\n\t\t\t\tisself = 1;\n\t\t\t\tselfix++;\n\t\t\t}\n\t\t}\n\t\tif(isself == 1){\n\t\t\tindex2 = 2*choose1 + wc2;\n\t\t}else if(isself == 0){\n\t\t\tchoose2 = gsl_rng_uniform_int(r,N);\n\t\t\tindex2 = 2*choose2 + wc2;\n\t\t}\n\t\t\n\t\t/* Now copying over neutral fragment, accounting for recombination */\n\t\tif(R != 0){\n\t\t\t/* Choosing number of recombination events on arms 1, 2 */\n\t\t\trecix1 = 0;\n\t\t\trecix2 = 0;\n\t\t\tnrec1 = gsl_ran_poisson(r,R);\n\t\t\tnrec2 = gsl_ran_poisson(r,R);\n\t\t\tdouble *recev1 = calloc(nrec1 + 1,sizeof(double));\n\t\t\tdouble *recev2 = calloc(nrec2 + 1,sizeof(double));\n\t\t\tfor(k = 0; k < nrec1; k++){\n\t\t\t\t*(recev1 + k) = gsl_ran_flat(r,0,1);\n\t\t\t}\n\t\t\tfor(k = 0; k < nrec2; k++){\n\t\t\t\t*(recev2 + k) = gsl_ran_flat(r,0,1);\n\t\t\t}\n\t\t\t*(recev1 + nrec1) = 1.01;\n\t\t\t*(recev2 + nrec2) = 1.01;\t\t\t\n\t\t\trec_sort(recev1,nrec1 + 1);\n\t\t\trec_sort(recev2,nrec2 + 1);\n\t\t\t\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\tif( (*(polypos + j)) >= *(recev1 + recix1)){\n\t\t\t\t\twc1 = bitswitch(wc1);\n\t\t\t\t\tindex1 = 2*choose1 + wc1;\n\t\t\t\t\trecix1++;\n\t\t\t\t}\n\t\t\t\tif( (*(polypos + j)) >= *(recev2 + recix2)){\n\t\t\t\t\twc2 = bitswitch(wc2);\n\t\t\t\t\tif(isself == 1){\n\t\t\t\t\t\tindex2 = 2*choose1 + wc2;\n\t\t\t\t\t}else if(isself == 0){\n\t\t\t\t\t\tindex2 = 2*choose2 + wc2;\n\t\t\t\t\t}\n\t\t\t\t\trecix2++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t*((*(neutout + 2*i)) + j) = *((*(neutin + index1)) + j);\n\t\t\t\t*((*(neutout + 2*i + 1)) + j) = *((*(neutin + index2)) + j);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tfree(recev1);\n\t\t\tfree(recev2);\n\t\t\t\n\t\t}else if (R == 0){\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\t*((*(neutout + 2*i)) + j) = *((*(neutin + index1)) + j);\n\t\t\t\t*((*(neutout + 2*i + 1)) + j) = *((*(neutin + index2)) + j);\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfree(selfev);\n\t\n}\t/* End of reproduction routine */\n\n/* Adding neutral polymorphism routine */\nvoid addpoly(unsigned int N, unsigned int **neutin, double *polyloc, unsigned int *npoly, double theta, const gsl_rng *r){\n\tunsigned int i, j;\n\tint k;\n\tunsigned int newpoly = 0;\t\t\t/* Number of new polymorphisms added */\n\tunsigned int pchr = 0;\t\t\t\t/* Chromosome of appearance */\n\tunsigned int pfound = 0;\t\t\t/* Flag to denote if right index found */\n\tdouble ploc = 0;\t\t\t\t\t/* Location of polymorphism */\n/*\tFILE *ofp_poly;\t\t\t\t Pointer for polymorphisms output */\t\n\t\n\tnewpoly = gsl_ran_poisson(r,(0.5*theta));\n/*\tprintf(\"Add %d new polymorphisms\\n\",newpoly);*/\n\t\n\tfor(j = 0; j < newpoly; j++){\n\t\tploc = gsl_ran_flat(r,0.0,1.0);\n/*\t\tprintf(\"ploc is %lf\\n\",ploc);\t*/\n\t\tpchr = gsl_rng_uniform_int(r,2*N);\n/*\t\tprintf(\"pchr is %d\\n\",pchr);*/\n\t\t\n\t\t/* Inserting new polymorphism */\n\t\tif(*(npoly) == 0){\n/*\t\t\tprintf(\"zero entry here\\n\");\t*/\n\t\t\t*(polyloc + 0) = ploc;\n\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t*((*(neutin + i)) + 0) = 0;\n\t\t\t\t}\n\t\t\t*((*(neutin + pchr)) + 0) = 1;\n\t\t}else if(*(npoly) > 0){\n/*\t\t\tprintf(\"non-zero entry here\\n\");\t\t*/\n\t\t\tpfound = 0;\n\t\t\tfor(k = (*(npoly) - 1); k >= 0; k--){\n/*\t\t\t\tprintf(\"k is %d\\n\",k);*/\n\t\t\t\tif(*(polyloc + k) > ploc){\t\n/*\t\t\t\t\tprintf(\"is here 1\\n\");*/\n\t\t\t\t\t*(polyloc + k + 1) = *(polyloc + k);\n\t\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t\t*((*(neutin + i)) + k + 1) = *((*(neutin + i)) + k);\n\t\t\t\t\t}\n\t\t\t\t}else if(*(polyloc + k) <= ploc){\n/*\t\t\t\t\tprintf(\"is here 2\\n\");\t\t\t\t*/\n\t\t\t\t\tpfound = 1;\n\t\t\t\t\t*(polyloc + k + 1) = ploc;\n\t\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t\t*((*(neutin + i)) + k + 1) = 0;\n\t\t\t\t\t}\n\t\t\t\t\t*((*(neutin + pchr)) + k + 1) = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\n\t\t\t}\n\n\t\t\tif(pfound == 0){\t\t/* In this case polymorphism is inserted at the start */\n\t\t\t\t*(polyloc + 0) = ploc;\n\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t*((*(neutin + i)) + 0) = 0;\n\t\t\t\t}\n\t\t\t\t*((*(neutin + pchr)) + 0) = 1;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t*(npoly) += 1;\n/*\t\tprintf(\"n poly is %d\\n\",*(npoly));\t\t\t*/\n\t\tif(*(npoly) == INITTS){\n\t\t\tfprintf(stderr,\"Too many neutral polymorphisms.\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\n\t}\n}\n\n/* Reassigning new population routine (after trimming) */\nvoid reassign2(unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int N, unsigned int aft){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\t\n\tfor(i = 0; i < 2*N; i++){\n\t\tfor(j = 0; j < npoly; j++){\n\t\t\t*((*(neutout + i)) + j) = *((*(neutin + i)) + j);\n\t\t\tif(i == 0 && aft == 1){\n\t\t\t\t*(posout + j) = *(posin + j);\n\t\t\t}\n\t\t}\n\t}\n\t\n}\t/* End of reassignment routine */\n\n/* Printing population state to file */\nvoid popprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N, unsigned int ei, unsigned int suffix){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\tchar Pout[32];\t\t\t\t /* String to hold filename in (Mutations) */\n\tFILE *ofp_poly = NULL;\t\t /* Pointer for data output */\n\t\n\t/* Printing out polymorphism table */\n\tsprintf(Pout,\"Pop_%d.dat\",ei + suffix);\n\tofp_poly = fopen(Pout,\"w\");\n\tfor(j = 0; j < npoly; j++){\n\t\tfprintf(ofp_poly,\"%lf \",*(posin + j));\n\t\tfor(i = 0; i < 2*N; i++){\n\t\t\tfprintf(ofp_poly,\"%d \",*((*(neutin + i)) + j));\n\t\t}\n\t\tfprintf(ofp_poly,\"\\n\");\n\t}\n\tfclose(ofp_poly);\n\t\n}\t/* End of population printing routine */\n\n/* Printing polymorphism routines */\nvoid polyprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\t\n\tfor(j = 0; j < npoly; j++){\n\t\tprintf(\"%lf \",*(posin + j));\n\t\tfor(i = 0; i < 2*N; i++){\n\t\t\tprintf(\"%d \",*((*(neutin + i)) + j));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tWait();\n\t\n}\t/* End of reassignment routine */\n\n/* Cutting out non-polymorphic sites */\nvoid ptrim(unsigned int size, unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int *npolyT, double *avpi){\n\tunsigned int i, j;\n\tunsigned int newp = 0;\t\t/* New number of polymorphisms */\n\tunsigned int count = 0;\t\t/* Polymorphism count */\n\tdouble cumpi = 0;\t\t\t/* Cumulative pi (diversity) */\n\n/*\tprintf(\"Trimming routine activated\\n\");\t*/\n\tfor(j = 0; j < npoly; j++){\n\t\tcount = 0;\n\t\t*(posout + newp) = *(posin + j);\n\t\tfor(i = 0; i < size; i++){\n\t\t\t*((*(neutout + i)) + newp) = *((*(neutin + i)) + j);\n\t\t\tcount += *((*(neutin + i)) + j);\n\t\t}\n/*\t\tprintf(\"For poly %d, count is %d\\n\",j,count);*/\n\t\tif((count > 0) && (count < size)){\n/*\t\t\tprintf(\"Keeping poly %d at location %lf\\n\",j,*(posin + j));\t*/\n\t\t\tnewp++;\n\t\t\tcumpi += ((count*(size-count))/(1.0*size*size));\n/*\t\t\tprintf(\"Count is %d, freq is %lf, cumulative value is %lf\\n\",count,count/(1.0*size),cumpi);\t*/\n\t\t}\n\t\t\n\t\t/*\n\t\tif(count==size){\n\t\t\tprintf(\"A fixed neutral mutation here\\n\");\n\t\t}\n\t\t*/\n\t\t\n\t}\n\t\n\t*npolyT = newp;\n\t*avpi = (cumpi/(1.0*newp));\n}\n\n/* Count number of unique haplotypes */\nunsigned int uniqueH(unsigned int **neutin, unsigned int npoly, unsigned int N){\n\n\tunsigned int i, j, k;\n\tunsigned int unH = 0;\t\t\t/* Count of unique haplotypes */\n\tunsigned int nomatch = 0;\t\t/* Marker to show if sites do not match */\n\t\n\tunsigned int **UH = calloc(2*N,sizeof(unsigned int *));\n\tfor(i = 0; i < 2*N; i++){\n\t\tUH[i] = calloc(npoly,sizeof(unsigned int));\n\t}\n\t\n\t/* Assigning first unique haplotype */\n\tfor(j = 0; j < npoly; j++){\n\t\t*((*(UH + 0)) + j) = *((*(neutin + 0)) + j);\n\t}\n\tunH++;\n\t\n\t/* Now testing other haplotypes */\n\tfor(i = 0; i < 2*N; i++){\n\t\tnomatch = 0;\n\t\tfor(k = 0; k < unH; k++){\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\tif(*((*(UH + k)) + j) != *((*(neutin + i)) + j)){\n\t\t\t\t\tnomatch++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(nomatch == unH){\t\t/* If haplotype does not match ANY unique ones, then add as new */\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\t*((*(UH + unH)) + j) = *((*(neutin + i)) + j);\n\t\t\t}\n\t\t\tunH++;\n\t\t}\t\n\t}\n\t\n\tfor(i = 0; i < 2*N; i++){\n\t\tfree(UH[i]);\n\t}\n\tfree(UH);\n\t\n\treturn unH;\n\t\t\n}\n\n/* Main program */\nint main(int argc, char *argv[]){\n\n\t/* Declare variables here */\n\tunsigned int a, i;\t\t\t/* Counters */\n\tunsigned int N = 0;\t\t\t/* Population Size */\n\tunsigned int npoly = 0;\t\t/* Number of neutral alleles */\n\tunsigned int npolyT = 0;\t/* Number of neutral alleles (after cutting out fixed sites) */\t\n\tunsigned int suffix = 0;\t/* Number of times to subsample from population */\n\tunsigned int base = 0;\t\t/* Number of baseline forward-in-time simulations */\n/*\tunsigned int n = 0;\t\t\tsprintf counter */\n\tunsigned int ttot = 0;\t\t/* Total time of simulation */\n/*\tunsigned int unH = 0;\t\t Number of unique haplotypes */\n\tunsigned int tbi = 0;\t\t/* Burn-in time */\n/*\tdouble npr = 0;\t\t\t\t Number of times to print out number of stats */\n\tdouble self = 0;\t\t\t/* Selfing rate */\n\tdouble Rin = 0;\t\t\t\t/* Recombination rate (input) */\n\tdouble R = 0;\t\t\t\t/* Recombination rate (at a time) */\n\tdouble theta = 0;\t\t\t/* Rate of neutral mutation */\n\tdouble avpi = 0;\n\tchar Sout[32];\t\t\t\t/* String to hold filename in (Seed) */\t\t\n\tFILE *ofp_sd;\t\t\t\t/* Pointer for seed output */\n\t\n\t/* GSL random number definitions */\n\tconst gsl_rng_type * T;\n\tgsl_rng * r;\n\t\n\t/* Reading in data from command line */\n\tif(argc != 7){\n\t\tfprintf(stderr,\"Not enough inputs (need: N self R theta basereps suffix).\\n\");\n\t\texit(1);\n\t}\n\t\n\tN = atoi(argv[1]);\n\tif(N <= 0){\n\t\tfprintf(stderr,\"Total Population size N is zero or negative, not allowed.\\n\");\n\t\texit(1);\n\t}\n\t\n\tself = strtod(argv[2],NULL);\n\tif(self < 0 || self > 1){\n\t\tfprintf(stderr,\"Selfing rate must lie between 0 and 1 (inclusive).\\n\");\n\t\texit(1);\n\t}\n\t\n\tRin = strtod(argv[3],NULL);\n\tif(Rin < 0){\n\t\tfprintf(stderr,\"Recombination rate must be positive or zero.\\n\");\n\t\texit(1);\n\t}\n\tRin /= 2.0*N;\n\t\n\ttheta = strtod(argv[4],NULL);\n\tif(theta <= 0){\n\t\tfprintf(stderr,\"Mutation rate must be a positive value.\\n\");\n\t\texit(1);\n\t}\n\t\n\tbase = atoi(argv[5]);\n\tif(base <= 0){\n\t\tfprintf(stderr,\"Number of baseline simulations must be greater than zero.\\n\");\n\t\texit(1);\n\t}\n\t\n\tsuffix = atoi(argv[6]);\n\tif(argv[6] < 0){\n\t\tfprintf(stderr,\"File index must be greater than or equal to zero.\\n\");\n\t\texit(1);\n\t}\n\t\t\n\t/* create a generator chosen by the \n environment variable GSL_RNG_TYPE */\n \n mkdir(\"SeedsPop/\", 0777); \n\tgsl_rng_env_setup();\n\tif (!getenv(\"GSL_RNG_SEED\")) gsl_rng_default_seed = time(0);\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\tsprintf(Sout,\"SeedsPop/Seed_%d.dat\",suffix);\n\tofp_sd = fopen(Sout,\"w\");\n\tfprintf(ofp_sd,\"%lu\\n\",gsl_rng_default_seed);\n\tfclose(ofp_sd);\n\t\n\t/* Vector of 0 to (N-1) for sampling random numbers */\n\tunsigned int *nums = calloc(N,sizeof(unsigned int));\n\tunsigned int *nums2 = calloc(2*N,sizeof(unsigned int));\n\tfor(a = 0; a < 2*N; a++){\n\t\t*(nums2 + a) = a;\n\t\tif(a < N){\n\t\t\t*(nums + a) = a;\n\t\t}\n\t}\n\t\n\t/* Executing simulation */\n\tfor(i = 0; i < base; i++){\n\n/*\t\tprintf(\"Starting run %d\\n\",i);*/\n\n\t\t/* Setting up selection, neutral tables per individual */\n\t\tdouble *polypos = calloc(INITTS,sizeof(double));\t\t\t\t\t\t/* Position of neutral mutations */\n\t\tdouble *polyposF = calloc(INITTS,sizeof(double));\t\t\t\t\t\t/* Position of neutral mutations (final for polymorphism sampling) */\n\t\tunsigned int **neutindvP = calloc(2*N,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (parents) */\n\t\tunsigned int **neutindvO = calloc(2*N,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (offspring) */\n\t\tunsigned int **neutindvF = calloc(2*N,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (final for sampling) */\n\t\tfor(a = 0; a < 2*N; a++){\n\t\t\tneutindvP[a] = calloc(INITTS,sizeof(unsigned int));\t\n\t\t\tneutindvO[a] = calloc(INITTS,sizeof(unsigned int));\n\t\t\tneutindvF[a] = calloc(INITTS,sizeof(unsigned int));\n\t\t}\n\t\tnpoly = 0;\n\t\tttot = 0;\n\t\tR = Rin;\n\t\ttbi = 20*N;\n/*\t\tnpr = 20.0;\t*/\n\t\n\t\twhile(ttot < tbi){\n\t\t\t\n\t\t\t/*\n\t\t\tint tick = (tbi)/(npr);\n\t\t\tif(ttot%tick == 0){\n\t\t\t\tunH = uniqueH(neutindvP, npoly, N);\n\t\t\t\tprintf(\"Time is %d; npoly is %d; av pi is %lf, unique haps are %d\\n\",ttot,npoly,avpi,unH);\n\t\t\t}\n\t\t\t*/\n\t\t\t\n\t\t\t/* Generating new population */\n\t\t\tgeneration_BI(N,self,R,nums,neutindvP,neutindvO,npoly,polypos,r);\n\t\n\t\t\t/* Neutral Mutation phase */\n\t\t\taddpoly(N, neutindvO, polypos, &npoly, theta, r);\n\t\t\n\t\t\t/* Reassigning matrices */\n\t\t\treassign2(neutindvO, neutindvP, polyposF, polypos, npoly, N, 0);\n\n\t\t\tttot++;\n\t\t\tptrim(2*N, neutindvP, neutindvF, polypos, polyposF, npoly, &npolyT, &avpi);\n\t\t\tnpoly = npolyT;\n\t\t\treassign2(neutindvF, neutindvP, polyposF, polypos, npoly, N, 1);\n\t\t\t\n\t\t\t/*\n\t\t\tprintf(\"Number of unique haplotypes are %d\\n\",uniqueH(neutindvP, npoly, N));\n\t\t\tpolyprint(neutindvP, polypos, npoly, N);\n\t\t\t*/\n\t\t}\n/*\t\tprintf(\"End of burn-in\\n\");*/\n\t\t\n\t\t/* After burn-in, print out neutral mutants */\n\t\tpopprint(neutindvP, polypos, npoly, N, i, suffix);\n\t\t\n\t\t/*\n\t\treassign2(neutindvP, neutindvA, polypos, polyposA, npoly, N);\n\t\tnpolyA = npoly;\n\t\t*/\n\t\t\n\t\tfor(a = 0; a < 2*N; a++){\n\t\t\tfree(neutindvF[a]);\t\t\n\t\t\tfree(neutindvO[a]);\n\t\t\tfree(neutindvP[a]);\n\t\t}\t\n\t\tfree(neutindvF);\n\t\tfree(neutindvO);\n\t\tfree(neutindvP);\n\t\tfree(polyposF);\n\t\tfree(polypos);\n\t\n\t}\n\n\tfree(nums2);\t\n\tfree(nums);\n\tgsl_rng_free(r);\t\n\n\treturn 0;\n\t\n}\t/* End of main program */\n\n/* End of File */", "meta": {"hexsha": "7b998274e6f688acf475106c5547b883f99f3f75", "size": 17063, "ext": "c", "lang": "C", "max_stars_repo_path": "DomSelfAdaptFWD_BIRec.c", "max_stars_repo_name": "MattHartfield/DomSelfAdapt", "max_stars_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49", "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": "DomSelfAdaptFWD_BIRec.c", "max_issues_repo_name": "MattHartfield/DomSelfAdapt", "max_issues_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49", "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": "DomSelfAdaptFWD_BIRec.c", "max_forks_repo_name": "MattHartfield/DomSelfAdapt", "max_forks_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49", "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": 30.2, "max_line_length": 180, "alphanum_fraction": 0.602883432, "num_tokens": 5672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.30735801052067535, "lm_q1q2_score": 0.16804435066974155}} {"text": "\n#include \n#include \n#include \n#include \n#include \n\n\n#ifdef SUBFIND\n\n#include \"allvars.h\"\n#include \"proto.h\"\n#include \"subfind.h\"\n\n\n/*! Structure for communication during the density computation. Holds data that is sent to other processors.\n */\nstatic struct linkngbdata_in\n{\n MyDouble Pos[3];\n MyFloat DM_Hsml;\n int NodeList[NODELISTLENGTH];\n}\n *LinkngbDataIn, *LinkngbDataGet;\n\n\nstatic struct linkngbdata_out\n{\n int Ngb;\n}\n *LinkngbDataResult, *LinkngbDataOut;\n\n\n\nvoid subfind_find_linkngb(void)\n{\n long long ntot;\n int i, j, ndone, ndone_flag, npleft, dummy, iter = 0, save_DesNumNgb;\n MyFloat *Left, *Right;\n char *Todo;\n int ngrp, sendTask, recvTask, place, nexport, nimport;\n double dmax1, dmax2, t0, t1;\n\n\n if(ThisTask == 0)\n printf(\"Start find_linkngb (%d particles on task=%d)\\n\", NumPartGroup, ThisTask);\n\n save_DesNumNgb = All.DesNumNgb;\n All.DesNumNgb = All.DesLinkNgb;\t/* for simplicity, reset this value */\n\n\n /* allocate buffers to arrange communication */\n\n Ngblist = (int *) mymalloc(NumPartGroup * sizeof(int));\n Dist2list = (double *) mymalloc(NumPartGroup * sizeof(double));\n\n All.BunchSize =\n (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +\n\t\t\t\t\t sizeof(struct linkngbdata_in) + sizeof(struct linkngbdata_out) +\n\t\t\t\t\t sizemax(sizeof(struct linkngbdata_in),\n\t\t\t\t\t\t sizeof(struct linkngbdata_out))));\n DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));\n DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));\n\n Left = mymalloc(sizeof(MyFloat) * NumPartGroup);\n Right = mymalloc(sizeof(MyFloat) * NumPartGroup);\n Todo = mymalloc(sizeof(char) * NumPartGroup);\n\n for(i = 0; i < NumPartGroup; i++)\n {\n Left[i] = Right[i] = 0;\n Todo[i] = 1;\n }\n\n /* we will repeat the whole thing for those particles where we didn't find enough neighbours */\n do\n {\n t0 = second();\n\n i = 0;\t\t\t/* begin with this index */\n\n do\n\t{\n\t for(j = 0; j < NTask; j++)\n\t {\n\t Send_count[j] = 0;\n\t Exportflag[j] = -1;\n\t }\n\n\t /* do local particles and prepare export list */\n\n\t for(nexport = 0; i < NumPartGroup; i++)\n\t {\n\t if(Todo[i])\n\t\t{\n\t\t if(subfind_linkngb_evaluate(i, 0, &nexport, Send_count) < 0)\n\t\t break;\n\t\t}\n\t }\n\n\t qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n\n\t MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);\n\n\t for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)\n\t {\n\t Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];\n\t nimport += Recv_count[j];\n\n\t if(j > 0)\n\t\t{\n\t\t Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\t\t Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];\n\t\t}\n\t }\n\n\t LinkngbDataGet = (struct linkngbdata_in *) mymalloc(nimport * sizeof(struct linkngbdata_in));\n\t LinkngbDataIn = (struct linkngbdata_in *) mymalloc(nexport * sizeof(struct linkngbdata_in));\n\n\t /* prepare particle data for export */\n\t for(j = 0; j < nexport; j++)\n\t {\n\t place = DataIndexTable[j].Index;\n\n\t LinkngbDataIn[j].Pos[0] = P[place].Pos[0];\n\t LinkngbDataIn[j].Pos[1] = P[place].Pos[1];\n\t LinkngbDataIn[j].Pos[2] = P[place].Pos[2];\n\t LinkngbDataIn[j].DM_Hsml = P[place].DM_Hsml;\n\n\t memcpy(LinkngbDataIn[j].NodeList,\n\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\t }\n\n\t /* exchange particle data */\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t {\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t {\n\t\t /* get the particles */\n\t\t MPI_Sendrecv(&LinkngbDataIn[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct linkngbdata_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A,\n\t\t\t\t &LinkngbDataGet[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct linkngbdata_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t }\n\t\t}\n\t }\n\n\t myfree(LinkngbDataIn);\n\t LinkngbDataResult = (struct linkngbdata_out *) mymalloc(nimport * sizeof(struct linkngbdata_out));\n\t LinkngbDataOut = (struct linkngbdata_out *) mymalloc(nexport * sizeof(struct linkngbdata_out));\n\n\n\t /* now do the particles that were sent to us */\n\t for(j = 0; j < nimport; j++)\n\t subfind_linkngb_evaluate(j, 1, &dummy, &dummy);\n\n\t if(i >= NumPartGroup)\n\t ndone_flag = 1;\n\t else\n\t ndone_flag = 0;\n\n\t MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n\t /* get the result */\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t {\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t {\n\t\t /* send the results */\n\t\t MPI_Sendrecv(&LinkngbDataResult[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct linkngbdata_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B,\n\t\t\t\t &LinkngbDataOut[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct linkngbdata_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t }\n\t\t}\n\t }\n\n\t /* add the result to the local particles */\n\t for(j = 0; j < nexport; j++)\n\t {\n\t place = DataIndexTable[j].Index;\n\n\t P[place].DM_NumNgb += LinkngbDataOut[j].Ngb;\n\t }\n\n\n\t myfree(LinkngbDataOut);\n\t myfree(LinkngbDataResult);\n\t myfree(LinkngbDataGet);\n\t}\n while(ndone < NTask);\n\n /* do final operations on results */\n for(i = 0, npleft = 0; i < NumPartGroup; i++)\n\t{\n\t /* now check whether we had enough neighbours */\n\t if(Todo[i])\n\t {\n\t if(P[i].DM_NumNgb != All.DesLinkNgb &&\n\t\t ((Right[i] - Left[i]) > 1.0e-3 * Left[i] || Left[i] == 0 || Right[i] == 0))\n\t\t{\n\t\t /* need to redo this particle */\n\t\t npleft++;\n\n\t\t if(P[i].DM_NumNgb < All.DesLinkNgb)\n\t\t Left[i] = DMAX(P[i].DM_Hsml, Left[i]);\n\t\t else\n\t\t {\n\t\t if(Right[i] != 0)\n\t\t\t{\n\t\t\t if(P[i].DM_Hsml < Right[i])\n\t\t\t Right[i] = P[i].DM_Hsml;\n\t\t\t}\n\t\t else\n\t\t\tRight[i] = P[i].DM_Hsml;\n\t\t }\n\n\t\t if(iter >= MAXITER - 10)\n\t\t {\n\t\t printf\n\t\t\t(\"i=%d task=%d ID=%d DM_Hsml=%g Left=%g Right=%g Ngbs=%g Right-Left=%g\\n pos=(%g|%g|%g)\\n\",\n\t\t\t i, ThisTask, (int) P[i].ID, P[i].DM_Hsml, Left[i], Right[i],\n\t\t\t (double) P[i].DM_NumNgb, Right[i] - Left[i], P[i].Pos[0], P[i].Pos[1], P[i].Pos[2]);\n\t\t fflush(stdout);\n\t\t }\n\n\t\t if(Right[i] > 0 && Left[i] > 0)\n\t\t P[i].DM_Hsml = pow(0.5 * (pow(Left[i], 3) + pow(Right[i], 3)), 1.0 / 3);\n\t\t else\n\t\t {\n\t\t if(Right[i] == 0 && Left[i] == 0)\n\t\t\tendrun(8189);\t/* can't occur */\n\n\t\t if(Right[i] == 0 && Left[i] > 0)\n\t\t\tP[i].DM_Hsml *= 1.26;\n\n\t\t if(Right[i] > 0 && Left[i] == 0)\n\t\t\tP[i].DM_Hsml /= 1.26;\n\t\t }\n\t\t}\n\t else\n\t\tTodo[i] = 0;\n\t }\n\t}\n\n\n sumup_large_ints(1, &npleft, &ntot);\n\n t1 = second();\n\n if(ntot > 0)\n\t{\n\t iter++;\n\n\t if(iter > 0 && ThisTask == 0)\n\t {\n\t printf(\"find linkngb iteration %d: need to repeat for %d%09d particles. (took %g sec)\\n\", iter,\n\t\t (int) (ntot / 1000000000), (int) (ntot % 1000000000), timediff(t0, t1));\n\t fflush(stdout);\n\t }\n\n\t if(iter > MAXITER)\n\t {\n\t printf(\"failed to converge in neighbour iteration in density()\\n\");\n\t fflush(stdout);\n\t endrun(1155);\n\t }\n\t}\n }\n while(ntot > 0);\n\n myfree(Todo);\n myfree(Right);\n myfree(Left);\n\n myfree(DataNodeList);\n myfree(DataIndexTable);\n\n myfree(Dist2list);\n myfree(Ngblist);\n\n All.DesNumNgb = save_DesNumNgb;\t/* restore it */\n}\n\n\n/*! This function represents the core of the SPH density computation. The\n * target particle may either be local, or reside in the communication\n * buffer.\n */\nint subfind_linkngb_evaluate(int target, int mode, int *nexport, int *nsend_local)\n{\n int startnode, numngb, ngbs, listindex = 0;\n double hmax;\n double h, h2, hinv, hinv3;\n MyDouble *pos;\n\n numngb = 0;\n\n if(mode == 0)\n {\n pos = P[target].Pos;\n h = P[target].DM_Hsml;\n }\n else\n {\n pos = LinkngbDataGet[target].Pos;\n h = LinkngbDataGet[target].DM_Hsml;\n }\n\n\n h2 = h * h;\n hinv = 1.0 / h;\n hinv3 = hinv * hinv * hinv;\n\n\n if(mode == 0)\n {\n startnode = All.MaxPart;\t/* root node */\n }\n else\n {\n startnode = LinkngbDataGet[target].NodeList[0];\n startnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n }\n\n numngb = 0;\n\n while(startnode >= 0)\n {\n while(startnode >= 0)\n\t{\n\t ngbs = subfind_ngb_treefind_linkngb(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local);\n\n\t if(ngbs < 0)\n\t return -1;\n\n\t if(mode == 0 && hmax > 0)\n\t P[target].DM_Hsml = hmax;\n\n\t numngb += ngbs;\n\t}\n\n if(mode == 1)\n\t{\n\t listindex++;\n\t if(listindex < NODELISTLENGTH)\n\t {\n\t startnode = LinkngbDataGet[target].NodeList[listindex];\n\t if(startnode >= 0)\n\t\tstartnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n\t }\n\t}\n }\n\n if(mode == 0)\n {\n P[target].DM_NumNgb = numngb;\n }\n else\n {\n LinkngbDataResult[target].Ngb = numngb;\n }\n\n return 0;\n}\n\n\n\n\nint subfind_ngb_treefind_linkngb(MyDouble searchcenter[3], double hsml, int target, int *startnode, int mode,\n\t\t\t\t double *hmax, int *nexport, int *nsend_local)\n{\n int numngb, i, no, p, task, nexport_save, exported = 0;\n struct NODE *current;\n double dx, dy, dz, dist, r2;\n\n#ifdef PERIODIC\n MyDouble xtmp;\n#endif\n\n nexport_save = *nexport;\n\n *hmax = 0;\n numngb = 0;\n no = *startnode;\n\n while(no >= 0)\n {\n if(no < All.MaxPart)\t/* single particle */\n\t{\n\t p = no;\n\t no = Nextnode[no];\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(!((1 << P[p].Type) & (DENSITY_SPLIT_BY_TYPE)))\n#else\n\t if(!((1 << P[p].Type) & (FOF_PRIMARY_LINK_TYPES)))\n#endif\n\t continue;\n\n\t dist = hsml;\n\t dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist)\n\t continue;\n\n\t Dist2list[numngb] = r2;\n\t Ngblist[numngb++] = p;\n\t}\n else\n\t{\n\t if(no >= All.MaxPart + MaxNodes)\t/* pseudo particle */\n\t {\n\t if(mode == 1)\n\t\tendrun(12312);\n\n\t if(target >= 0)\t/* if no target is given, export will not occur */\n\t\t{\n\t\t exported = 1;\n\t\t if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target)\n\t\t {\n\t\t Exportflag[task] = target;\n\t\t Exportnodecount[task] = NODELISTLENGTH;\n\t\t }\n\n\t\t if(Exportnodecount[task] == NODELISTLENGTH)\n\t\t {\n\t\t if(*nexport >= All.BunchSize)\n\t\t\t{\n\t\t\t *nexport = nexport_save;\n\t\t\t if(nexport_save == 0)\n\t\t\t endrun(13004);\t/* in this case, the buffer is too small to process even a single particle */\n\t\t\t for(task = 0; task < NTask; task++)\n\t\t\t nsend_local[task] = 0;\n\t\t\t for(no = 0; no < nexport_save; no++)\n\t\t\t nsend_local[DataIndexTable[no].Task]++;\n\t\t\t return -1;\n\t\t\t}\n\t\t Exportnodecount[task] = 0;\n\t\t Exportindex[task] = *nexport;\n\t\t DataIndexTable[*nexport].Task = task;\n\t\t DataIndexTable[*nexport].Index = target;\n\t\t DataIndexTable[*nexport].IndexGet = *nexport;\n\t\t *nexport = *nexport + 1;\n\t\t nsend_local[task]++;\n\t\t }\n\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] =\n\t\t DomainNodeIndex[no - (All.MaxPart + MaxNodes)];\n\n\t\t if(Exportnodecount[task] < NODELISTLENGTH)\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1;\n\t\t}\n\n\t no = Nextnode[no - MaxNodes];\n\t continue;\n\t }\n\n\t current = &Nodes[no];\n\n\t if(mode == 1)\n\t {\n\t if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL))\t/* we reached a top-level node again, which means that we are done with the branch */\n\t\t{\n\t\t *startnode = -1;\n\t\t return numngb;\n\t\t}\n\t }\n\n\t no = current->u.d.sibling;\t/* in case the node can be discarded */\n\n\t dist = hsml + 0.5 * current->len;;\n\t dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t /* now test against the minimal sphere enclosing everything */\n\t dist += FACT1 * current->len;\n\t if(dx * dx + dy * dy + dz * dz > dist * dist)\n\t continue;\n\n\t no = current->u.d.nextnode;\t/* ok, we need to open the node */\n\t}\n }\n\n\n if(mode == 0)\t\t\t/* local particle */\n if(exported == 0)\t\t/* completely local */\n if(numngb >= All.DesNumNgb)\n\t{\n\t R2list = mymalloc(sizeof(struct r2data) * numngb);\n\t for(i = 0; i < numngb; i++)\n\t {\n\t R2list[i].index = Ngblist[i];\n\t R2list[i].r2 = Dist2list[i];\n\t }\n\n\t qsort(R2list, numngb, sizeof(struct r2data), subfind_ngb_compare_dist);\n\n\t *hmax = sqrt(R2list[All.DesNumNgb - 1].r2);\n\t numngb = All.DesNumNgb;\n\n\t for(i = 0; i < numngb; i++)\n\t {\n\t Ngblist[i] = R2list[i].index;\n\t Dist2list[i] = R2list[i].r2;\n\t }\n\n\t myfree(R2list);\n\t}\n\n\n *startnode = -1;\n return numngb;\n}\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n/*! This routine finds all neighbours `j' that can interact with\n * \\f$ r_{ij} < h_i \\f$ OR if \\f$ r_{ij} < h_j \\f$. \n */\nint subfind_ngb_treefind_linkpairs(MyDouble searchcenter[3], double hsml, int target, int *startnode,\n\t\t\t\t int mode, double *hmax, int *nexport, int *nsend_local)\n{\n int numngb, i, no, p, task, nexport_save, exported = 0;\n struct NODE *current;\n double dx, dy, dz, dist, r2, dmax1, dmax2;\n\n#ifdef PERIODIC\n MyDouble xtmp;\n#endif\n\n nexport_save = *nexport;\n\n *hmax = 0;\n numngb = 0;\n no = *startnode;\n\n while(no >= 0)\n {\n if(no < All.MaxPart)\t/* single particle */\n\t{\n\t p = no;\n\t no = Nextnode[no];\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(!((1 << P[p].Type) & (DENSITY_SPLIT_BY_TYPE)))\n#else\n\t if(!((1 << P[p].Type) & (FOF_PRIMARY_LINK_TYPES)))\n#endif\n\t continue;\n\n\t dist = DMAX(P[p].DM_Hsml, hsml);\n\t dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist)\n\t continue;\n\n\t Dist2list[numngb] = r2;\n\t Ngblist[numngb++] = p;\n\t}\n else\n\t{\n\t if(no >= All.MaxPart + MaxNodes)\t/* pseudo particle */\n\t {\n\t if(mode == 1)\n\t\tendrun(12312);\n\n\t if(target >= 0)\t/* if no target is given, export will not occur */\n\t\t{\n\t\t exported = 1;\n\t\t if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target)\n\t\t {\n\t\t Exportflag[task] = target;\n\t\t Exportnodecount[task] = NODELISTLENGTH;\n\t\t }\n\n\t\t if(Exportnodecount[task] == NODELISTLENGTH)\n\t\t {\n\t\t if(*nexport >= All.BunchSize)\n\t\t\t{\n\t\t\t *nexport = nexport_save;\n\t\t\t if(nexport_save == 0)\n\t\t\t endrun(13004);\t/* in this case, the buffer is too small to process even a single particle */\n\t\t\t for(task = 0; task < NTask; task++)\n\t\t\t nsend_local[task] = 0;\n\t\t\t for(no = 0; no < nexport_save; no++)\n\t\t\t nsend_local[DataIndexTable[no].Task]++;\n\t\t\t return -1;\n\t\t\t}\n\t\t Exportnodecount[task] = 0;\n\t\t Exportindex[task] = *nexport;\n\t\t DataIndexTable[*nexport].Task = task;\n\t\t DataIndexTable[*nexport].Index = target;\n\t\t DataIndexTable[*nexport].IndexGet = *nexport;\n\t\t *nexport = *nexport + 1;\n\t\t nsend_local[task]++;\n\t\t }\n\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] =\n\t\t DomainNodeIndex[no - (All.MaxPart + MaxNodes)];\n\n\t\t if(Exportnodecount[task] < NODELISTLENGTH)\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1;\n\t\t}\n\n\t no = Nextnode[no - MaxNodes];\n\t continue;\n\t }\n\n\t current = &Nodes[no];\n\n\t if(mode == 1)\n\t {\n\t if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL))\t/* we reached a top-level node again, which means that we are done with the branch */\n\t\t{\n\t\t *startnode = -1;\n\t\t return numngb;\n\t\t}\n\t }\n\n\t dist = DMAX(Extnodes[no].hmax, hsml) + 0.5 * current->len;\n\t no = current->u.d.sibling;\t/* in case the node can be discarded */\n\t dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t /* now test against the minimal sphere enclosing everything */\n\t dist += FACT1 * current->len;\n\t if(dx * dx + dy * dy + dz * dz > dist * dist)\n\t continue;\n\n\t no = current->u.d.nextnode;\t/* ok, we need to open the node */\n\t}\n }\n\n\n if(mode == 0)\t\t\t/* local particle */\n if(exported == 0)\t\t/* completely local */\n if(numngb >= All.DesNumNgb)\n\t{\n\t R2list = mymalloc(sizeof(struct r2data) * numngb);\n\t for(i = 0; i < numngb; i++)\n\t {\n\t R2list[i].index = Ngblist[i];\n\t R2list[i].r2 = Dist2list[i];\n\t }\n\n\t qsort(R2list, numngb, sizeof(struct r2data), subfind_ngb_compare_dist);\n\n\t *hmax = sqrt(R2list[All.DesNumNgb - 1].r2);\n\t numngb = All.DesNumNgb;\n\n\t for(i = 0; i < numngb; i++)\n\t {\n\t Ngblist[i] = R2list[i].index;\n\t Dist2list[i] = R2list[i].r2;\n\t }\n\n\t myfree(R2list);\n\t}\n\n\n *startnode = -1;\n return numngb;\n}\n#endif\n\nint subfind_ngb_compare_dist(const void *a, const void *b)\n{\n if(((struct r2data *) a)->r2 < (((struct r2data *) b)->r2))\n return -1;\n\n if(((struct r2data *) a)->r2 > (((struct r2data *) b)->r2))\n return +1;\n\n return 0;\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "0f40a5c90ffafc9d2172b27a0dae843ea803510f", "size": 17858, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_findlinkngb.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "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": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_findlinkngb.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "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": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_findlinkngb.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8027777778, "max_line_length": 144, "alphanum_fraction": 0.5960913876, "num_tokens": 5795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.2909808539178129, "lm_q1q2_score": 0.16804009026355288}} {"text": "/*\nSimulation of a network of FitzHugh-Nagumo neurons, coupled by excitatory\nchemical synapses, receiving decorrelated, random input spiketrains with\nboth excitatory and inhibitory components.\n\nThe simulation was written by Ekkehard Ullner in 2013.\n\nThis is a modified version of E.U.'s original, stand-alone program,\nfor use as a library (e.g. via the ctypes ffi in Python).\nChangelog:\n- Various simulation parameters are exposed (to allow arbitrary network topologies,\ninput patterns, neuron parameters etc.)\n- results are written to a provided buffer instead of text files\n- the non-free and problematic[0] \"Numerical Recipes\" RAN1 random number generator\nwas replaced with a Mersenne Twister rng from the GNU scientific library.\n- cosmetics and a minimum of documentation (i.e. the comments)\n\nC Korndoerfer 2014\n\n[0 \"Random Numbers in Scientific Computing: An Introduction\", Katzgraber, 2010\nhttp://arxiv.org/pdf/1005.4117.pdf]\n\n\n\nThe MIT License (MIT)\n\nCopyright (c) 2013,2014 Ekkehard Ullner, Clemens Korndörfer\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICU\nLAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nvoid sagwas(){\n puts(\"simulation version Oct 12 2016\");\n}\n\n\n/* function simulate\n * ------------------\n * Runs a single network simulation with the given parameters and writes the resulting\n * voltage traces into a given buffer.\n *\n * Parameters:\n *\n * N: Number of rows i in the simulated grid of neurons. (regardless of network topology,\n * the network is a 'grid' where each node is adressed by an (i,j) coordinate.)\n * M: number of columns j in the grid\n *\n * limit: max. simulation time\n * rec_resolution: to store only every ~'th simulation step.\n *\n * KT: maximum number of coupled neighbors of any node (degree of the network)\n * connection: function pointer, where\n * connection(i,j,l, '0' | '1') must return the first (second) coordinate of the l'th afferent to cell ij\n * connection(i,j,l, 's') must return the strength of that connection\n *\n * outputbuffer: array of shape (M,N,limit) in which simulation results will be written in row first order\n *\n * inputc: array of shape (M,N) in row-first order. modulates the rate of input pulses fed into\n * each cell, values within [0,1]. aka \"the stimulus\".\n * laminex: firing rate \"lambda_in,ex\", the base rate of excitatory input spikes modulated by inputc\n * lamini: firing rate \"lambda_in,in\", the base rate of inhibitory input spikes modulated by inputc\n *\n * double fhn_a: parameter a of the FHN neuron\n * double fhn_eps: parameter epsilon of the FHN neuron\n *\n * double con_upstr_exc: synapse conductance \"g^{up,ex}\" of the excitatory random external inputs.\n * double con_upstr_inh: synapse conductance \"g^{up,in}\" of the inhibitory random external inputs.\n *\n * seed: a random seed > 0\n *\n * delta_t : integration step width\n *\n * Return: None (simulation results are passed back as a side effect, by filling the provided output buffer)\n*/\n\nvoid simulate(int M,\n int N,\n int limit,\n int rec_resolution,\n int KT,\n double (*connection)(int,int,int,char),\n double* outputbuffer,\n double* debug_outbuf,\n double* inputc_exc,\n double* inputc_inh,\n double laminex,\n double lamini,\n double fhn_a,\n double fhn_eps,\n double con_upstr_exc,\n double con_upstr_inh,\n double taus,\n double alp,\n double bet,\n double tauni,\n double ani,\n double bni,\n double tauna,\n double ana,\n double bna,\n int seed,\n int verbose,\n double delta_t){\n\n\n\n // say hello & show the current input pattern.\n if (verbose){\n printf(\" simulation with seed %d\\n\",seed);\n printf(\"laminex: %f\\nlamini: %f\\nfhn_a: %f\\nfhn_eps: %f\\ncon_upstr_exc: %f\\ncon_upstr_inh: %f\\ntaus: %f\\nalp: %f\\\n \\nbet: %f\\ntauni: %f\\nani: %f\\nbni: %f\\ntauna: %f\\nana: %f\\nbna: %f\\n\", laminex, lamini, fhn_a, fhn_eps, con_upstr_exc,\n con_upstr_inh, taus, alp, bet, tauni, ani, bni, tauna, ana, bna);\n int i1,j1;\n int print_exc, print_inh;\n for (j1 = 0; j1 0;\n print_inh = inputc_inh[i1 + N*j1] > 0;\n if (print_exc && print_inh) printf(\" ±\");\n else if (print_exc) printf(\" +\");\n else if (print_inh) printf(\" -\");\n else printf(\" .\");\n }\n printf(\"\\n\");\n }\n }\n\n assert(seed>0);\n gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937);\n gsl_rng_set(rng, seed);\n\n // Initialisations & constant parameters:\n // neuron model:\n double xold[N][M],xh[N][M],xnew[N][M]; // activation variable (previous value, intermediate value, new value)\n double yold[N][M],yh[N][M],ynew[N][M]; // recovery variable (previous value, intermediate value, new value)\n double Isyn[N][M], Ihsyn[N][M]; // lateral input current (Ihsyn: intermediate value)\n\n // lateral synapses:\n double rold[N][M],rh[N][M],rnew[N][M]; // fraction of open receptors (previous value, intermediate value, new value).\n\n // more precisely: r[i][j] is the fraction of open receptors at synapses anywhere in the network\n // that are the target of neuron (i,j). Since all synapses have the same rise and decay constants\n // alpha and beta, the effect of a spike at neuron i,j is the same at all of its target synapses.\n // We can therefore write the fractions of open receptors of all these target synapses as a\n // single variable r[i][j], associated with the source neuron i,j.\n\n double Tl[N][M]; // spike arrival times \"T_j\" (indexing follows the same logic as r[][])\n double Hs[N][M]; // transmitter concentrations \"[T]_j\" (...here, too)\n double Vsyn = 0.0; // synaptic reversal potential\n\n // double taus = 0.01; // duration of transmitter presence after spike\n double Tm = 1.0; // maximum transmitter concentration\n\n // double alp = 8.0; // rising time constant of fraction of open receptors\n // double bet = 8.0; // decay time constant of fraction of open receptors\n\n\n // activatory external input synapses:\n double rnoa[N][M],rnha[N][M],rnna[N][M]; // fraction of open receptors\n double Tnla[N][M],Hna[N][M]; // spike arrival times and transmitter concentrations\n double Vna = 0.0; // synaptic reversal potential\n\n // double tauna = 0.01; // duration of transmitter presence after spike\n double Tna = 1.0; // maximum transmitter concentration\n\n // double ana = 8.0; // rising time constant of fraction of open receptors\n // double bna = 8.0; // decay time constant of fraction of open receptors\n\n\n // inhibitory external input synapses:\n double rnoi[N][M],rnhi[N][M],rnni[N][M]; // fraction of open receptors (previous value, intermediate value, new value)\n double Tnli[N][M],Hni[N][M]; // spike arrival times and transmitter concentrations\n double Vni = - 2.1; // synaptic reversal potential\n\n // double tauni = 0.01; // duration of transmitter presence after spike\n double Tni = 1.0; // maximum transmitter concentration\n\n // double ani = 8.0; // rising time constant of fraction of open receptors\n // double bni = 8.0; // decay time constant of fraction of open receptors\n\n\n // misc:\n double xth = 1.0; // spike detection threshold\n long step; // simulation step count\n // double delta_t = 0.001; // integration step width\n // double delta_t = 0.01; // integration step width\n double current_time = 0.0; // simulation time, in some irrelevant real - numbered unit\n\n long i,j,l; // various loop variables over network nodes. don't ask me why those were chosen as long ints.\n\n int p1[N][M][KT],p2[N][M][KT]; // lookup tables holding the first (p1) and second (p2) coordinate of the KT'th afferent to neuron N,M\n float conductance_net[N][M][KT]; // lookup table: synapse conductance of the KT'th afferent to neuron N,M\n double in_exc[N][M]; // excitatory stimulus strength (input noise rate modulation) for neuron N,M\n double in_inh[N][M]; // inhibitory ...\n\n\n // remaining initialisations:\n for (j = 0;jcurrent_time) Hs[i][j] = 1.0 * Tm;\n else Hs[i][j] = 0.0;\n\n // ..for activatory external input synapses..\n if (Tnla[i][j] + tauna>current_time) Hna[i][j] = 1.0 * Tna;\n else Hna[i][j] = 0.0;\n\n // ..and for inhibitory external input synapses.\n if (Tnli[i][j] + tauni>current_time) Hni[i][j] = 1.0 * Tni;\n else Hni[i][j] = 0.0;\n\n // collect lateral synaptic currents (for first integration step)\n Isyn[i][j] = 0.0;\n for (l = 0;l= xth){\n Tl[i][j] = current_time;\n }\n\n // sample random spike times for activatory external input\n if(gsl_rng_uniform(rng) <= (laminex * (double)in_exc[i][j]) * delta_t){\n Tnla[i][j] = current_time;\n }\n // sample random spike times for inhibitory external input\n if(gsl_rng_uniform(rng)<= (lamini * (double)in_inh[i][j]) * delta_t){\n Tnli[i][j] = current_time;\n }\n\n // swap\n xold[i][j] = xnew[i][j];\n yold[i][j] = ynew[i][j];\n rold[i][j] = rnew[i][j];\n rnoa[i][j] = rnna[i][j];\n rnoi[i][j] = rnni[i][j];\n }}\n\n\n // write the current network state into the provided output buffer.\n // This is a 3D array of shape (M,N,limit) in row first order,\n // so it has strides proportional to (N * limit, limit, 1).\n // ..and we write only every rec_resolution'th step.\n int limit_rec = limit/rec_resolution;\n if (step % rec_resolution == 0) {\n int linearind = 0;\n for(int oi = 0; oi < M; oi++ ) {\n for(int oj = 0; oj < N; oj++ ) {\n linearind = oi * limit_rec * N + oj * limit_rec + (step/rec_resolution) - 1;\n outputbuffer[linearind] = xnew[oj][oi];\n debug_outbuf[linearind] = ynew[oj][oi];\n }\n }\n }\n } // end of integration loop\n if (verbose){\n printf(\"\\033[2K\");\n fflush(stdout);\n }\n\n gsl_rng_free(rng);\n}\n\n\n\n// helper function to play with the random number generator.\nvoid rantest(long seed,int N,double * out){\n gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); // initialize a mersenne twister rng\n gsl_rng_set(rng, seed); // seed it\n double number = - 1;\n\n for(int i = 0; i\n#include \n#include \n#include \n#include \n#include \n#include \"parmt_polarity.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#else\n#include \n#endif\n#include \"ttimes.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/geodetic/geodetic.h\"\n#include \"iscl/memory/memory.h\"\n\n\n#define LDG 8\n#ifndef MAX\n#define MAX(x,y) (((x) > (y)) ? (x) : (y))\n#endif\n\nstatic void fillBasis(const double i, const double phi,\n double *__restrict__ gam,\n double *__restrict__ phat,\n double *__restrict__ phihat);\nstatic double computeContraction3x3(const double *__restrict__ a,\n const double *__restrict__ M,\n const double *__restrict__ b);\nstatic void setM3x3(const int k, double *__restrict__ M);\nstatic int computePadding64f(const int n);\nstatic int performPolaritySearch64f(const int nmt, const int ldm, \n const int nobs,\n const int blockSize, const int mblock,\n const int Mrows, const int Kcols,\n const double *__restrict__ Dmat,\n const double *__restrict__ G,\n const double *__restrict__ Sigma,\n const double *__restrict__ mts, \n double *__restrict__ phi);\n\n/*!\n * @brief Driver routine for computing the polarity Green's functions from the\n * ttimes ak135 global travel time table.\n *\n * @param[in] globalComm Global MPI communicator.\n * @param[in] parms Contains the polarity modeling parameters.\n * @param[in] data The SAC data whose header information will define\n * the polarity and channel information.\n *\n * @param[out] polarityData On exit contains the corresponding polarity Green's\n * functions that can be used by the grid-search to\n * estimate polarities from a given moment tensor.\n *\n * @result 0 indicates success.\n */\nint parmt_polarity_computeTTimesGreens(\n const MPI_Comm globalComm,\n const struct parmtPolarityParms_struct parms,\n const struct parmtData_struct data,\n struct polarityData_struct *polarityData)\n{\n char kt0[8], kcmpnm[8], stat[8];\n double G6[6], *cmpazs, *cmpincs, *deps, *evlas, *evlos,\n *GxxBuf, *GyyBuf, *GzzBuf, *GxyBuf, *GxzBuf, *GyzBuf,\n *stlas, *stlos, cmpinc, cmpincSAC, cmpaz, stla, stlo;\n int *icomps, *observation, *polarity, *waveType, icomp, ierr, ierrAll,\n iloc, iobs, ipol, it, iwav, jloc, k, kt, myid, nPolarity, nprocs;\n size_t lenos;\n const int master = 0;\n const int nTimeVars = 11;\n const enum sacHeader_enum timeVarNames[11]\n = {SAC_CHAR_KA,\n SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,\n SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,\n SAC_CHAR_KT8, SAC_CHAR_KT9};\n //------------------------------------------------------------------------//\n //\n // Initialize\n ierr = 0;\n cmpazs = NULL;\n cmpincs = NULL;\n deps = NULL;\n evlas = NULL;\n evlos = NULL;\n GxxBuf = NULL;\n GyyBuf = NULL;\n GzzBuf = NULL;\n GxyBuf = NULL;\n GxzBuf = NULL;\n GyzBuf = NULL;\n icomps = NULL;\n observation = NULL;\n polarity = NULL;\n stlas = NULL;\n stlos = NULL;\n waveType = NULL;\n memset(polarityData, 0, sizeof(struct polarityData_struct));\n // ttimes uses read-only file-io and i don't want to fix it\n MPI_Comm_rank(globalComm, &myid);\n MPI_Comm_size(globalComm, &nprocs);\n //if (myid != master){goto WAIT;}\n // Verify there is a chance for something to do\n if (data.nobs < 1 || data.nlocs < 1)\n {\n if (data.nobs < 1){fprintf(stderr, \"%s: No observations\\n\", __func__);}\n if (data.nlocs < 1){fprintf(stderr, \"%s: No locations\\n\", __func__);}\n return 0;\n }\n // Extract the depths in the grid-search from the first waveform \n iobs = 0;\n deps = memory_calloc64f(data.nlocs);\n evlas = memory_calloc64f(data.nlocs);\n evlos = memory_calloc64f(data.nlocs);\n for (iloc=0; iloc 1)\n {\n iwav = 1;\n if (kt0[0] == 'P' || kt0[0] == 'p')\n {\n iwav = 1;\n }\n else if (kt0[0] == 'S' || kt0[0] == 's')\n {\n iwav = 2;\n }\n else\n {\n // surface waves will commonly be processed and not\n // have polarities\n if (kt0[0] == 'R' || kt0[0] == 'r' ||\n kt0[0] == 'L' || kt0[0] == 'l')\n {\n continue;\n }\n fprintf(stderr, \"%s: t0 phase is not a P or S phase %s\\n\",\n __func__, kt0);\n continue;\n }\n if (kt0[lenos-1] == '+')\n {\n ipol = 1;\n }\n else if (kt0[lenos-1] == '-')\n {\n ipol =-1;\n }\n else\n {\n fprintf(stderr, \"%s: could not classify polarity %s\\n\",\n __func__, kt0);\n continue;\n }\n // let user know something happened \n sacio_getCharacterHeader(SAC_CHAR_KSTNM,\n data.data[iobs].header, stat);\n fprintf(stdout, \"%s: Polarity for %s is %d\\n\",\n __func__, stat, ipol); \n//printf(\"%f %f %f %f %d %d %d %d\\n\", stla, stlo, cmpinc, cmpaz, icomp, iobs, iwav, ipol);\n // save information for modeling\n stlas[nPolarity] = stla;\n stlos[nPolarity] = stlo;\n cmpincs[nPolarity] = cmpinc;\n cmpazs[nPolarity] = cmpaz;\n icomps[nPolarity] = icomp;\n observation[nPolarity] = iobs;\n waveType[nPolarity] = iwav;\n polarity[nPolarity] = ipol;\n nPolarity = nPolarity + 1;\n //printf(\"%d %d %f %f\\n\", iwav, ipol, cmpinc, cmpaz);\n } // End basic header info check\n } // Loop on observations\n } // End check on myid == master\n // Tell all other processes about the forward modeling information\n MPI_Bcast(&nPolarity, 1, MPI_INT, master, globalComm);\n if (nPolarity == 0)\n {\n if (myid == master)\n {\n fprintf(stdout, \"%s: There are no polarities\\n\", __func__);\n }\n ierr = 0;\n goto ERROR;\n }\n if (myid != master)\n {\n stlas = memory_calloc64f(nPolarity);\n stlos = memory_calloc64f(nPolarity);\n cmpincs = memory_calloc64f(nPolarity);\n cmpazs = memory_calloc64f(nPolarity);\n icomps = memory_calloc32i(nPolarity);\n observation = memory_calloc32i(nPolarity);\n waveType = memory_calloc32i(nPolarity);\n polarity = memory_calloc32i(nPolarity);\n }\n else\n {\n fprintf(stdout, \"%s: Warning - i'm setting wts to unity for now\\n\",\n __func__);\n }\n MPI_Bcast(stlas, nPolarity, MPI_DOUBLE, master, globalComm);\n MPI_Bcast(stlos, nPolarity, MPI_DOUBLE, master, globalComm);\n MPI_Bcast(cmpincs, nPolarity, MPI_DOUBLE, master, globalComm);\n MPI_Bcast(cmpazs, nPolarity, MPI_DOUBLE, master, globalComm);\n MPI_Bcast(icomps, nPolarity, MPI_INT, master, globalComm);\n MPI_Bcast(observation, nPolarity, MPI_INT, master, globalComm);\n MPI_Bcast(waveType, nPolarity, MPI_INT, master, globalComm);\n MPI_Bcast(polarity, nPolarity, MPI_INT, master, globalComm); \n // Set space\n ierrAll = 0;\n GxxBuf = memory_calloc64f(data.nlocs*nPolarity);\n GyyBuf = memory_calloc64f(data.nlocs*nPolarity);\n GzzBuf = memory_calloc64f(data.nlocs*nPolarity);\n GxyBuf = memory_calloc64f(data.nlocs*nPolarity);\n GxzBuf = memory_calloc64f(data.nlocs*nPolarity);\n GyzBuf = memory_calloc64f(data.nlocs*nPolarity);\n polarityData->Gxx = memory_calloc64f(data.nlocs*nPolarity);\n polarityData->Gyy = memory_calloc64f(data.nlocs*nPolarity);\n polarityData->Gzz = memory_calloc64f(data.nlocs*nPolarity);\n polarityData->Gxy = memory_calloc64f(data.nlocs*nPolarity);\n polarityData->Gxz = memory_calloc64f(data.nlocs*nPolarity);\n polarityData->Gyz = memory_calloc64f(data.nlocs*nPolarity);\n // Set the data\n polarityData->polarity = memory_calloc64f(nPolarity);\n for (ipol=0; ipolpolarity[ipol] = (double) polarity[ipol];\n }\n // Set the weights\n // TODO fix me\n polarityData->wts = array_set64f(nPolarity, 1.0, &ierr); \n // Compute the forward modeling matrix columns\n for (jloc=0; jloc= data.nlocs){continue;}\n // Compute the forward modeling matrix for this observation group\n for (ipol=0; ipolnPolarity = nPolarity;\n polarityData->nlocs = data.nlocs;\n polarityData->nobs = data.nobs;\n polarityData->obsMap = array_copy32i(nPolarity, observation, &ierr);\n MPI_Allreduce(GxxBuf, polarityData->Gxx, data.nlocs*nPolarity,\n MPI_DOUBLE, MPI_SUM, globalComm);\n MPI_Allreduce(GyyBuf, polarityData->Gyy, data.nlocs*nPolarity,\n MPI_DOUBLE, MPI_SUM, globalComm);\n MPI_Allreduce(GzzBuf, polarityData->Gzz, data.nlocs*nPolarity,\n MPI_DOUBLE, MPI_SUM, globalComm);\n MPI_Allreduce(GxyBuf, polarityData->Gxy, data.nlocs*nPolarity,\n MPI_DOUBLE, MPI_SUM, globalComm);\n MPI_Allreduce(GxzBuf, polarityData->Gxz, data.nlocs*nPolarity,\n MPI_DOUBLE, MPI_SUM, globalComm);\n MPI_Allreduce(GyzBuf, polarityData->Gyz, data.nlocs*nPolarity,\n MPI_DOUBLE, MPI_SUM, globalComm);\n // Finally assemble Green's functions into modeling matrix\n//WAIT:;\nERROR:;\n MPI_Barrier(globalComm);\n // free memory\n memory_free64f(&GxxBuf);\n memory_free64f(&GyyBuf);\n memory_free64f(&GzzBuf);\n memory_free64f(&GxyBuf);\n memory_free64f(&GxzBuf);\n memory_free64f(&GyzBuf);\n memory_free64f(&deps);\n memory_free64f(&evlas);\n memory_free64f(&evlos);\n memory_free64f(&stlas);\n memory_free64f(&stlos);\n memory_free64f(&cmpincs);\n memory_free64f(&cmpazs);\n memory_free32i(&observation);\n memory_free32i(&polarity);\n memory_free32i(&icomps);\n memory_free32i(&waveType);\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Computes the row of the Green's functions matrix for modeling\n * a polarity from the ttimes model.\n *\n * @param[in] data Contains the pick type and channel information.\n * @param[in] wavetype P_WAVE (1) indicates a P-wave.\n * @param[in] wavetype S_WAVE (2) indicates an S-wave.\n * @param[in] evdp Depth of the event in kilometers. \n * @param[in] dirnm Directory containing the iasp-tau binary files. \n * @param[in] model Name of the model, e.g., ak135.\n *\n * @param[out] G On exit contains the Green's functions so that for \n * the i'th row of G, \\f$ G_i \\cdot \\textbf{m} \\f$ \n * computes an estimate of polarity. This is packed\n * in order\n * \\f$\n * \\{m_{xx}, m_{yy}, m_{zz}, m_{xy}, m_{xz}, m_{yz} \\}\n * \\f$\n * and must have a dimension of at least [6].\n *\n * @result 0 indicates success.\n *\n * @copyright ISTI distributed under the Apache 2 license.\n *\n */\nint parmt_polarity_computeGreensRowFromData(const struct sacData_struct data,\n const int wavetype,\n const double evdp,\n const char *dirnm,\n const char *model,\n double *__restrict__ G)\n{\n char kcmpnm[16];\n double cmpaz, cmpinc, cmpincSAC, evla, evlo, stla, stlo;\n int icomp, ierr;\n size_t lenos;\n memset(kcmpnm, 16, 16*sizeof(char));\n ierr = sacio_getFloatHeader(SAC_FLOAT_CMPINC, data.header, &cmpincSAC); \n ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ, data.header, &cmpaz);\n ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA, data.header, &evla);\n ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO, data.header, &evlo);\n ierr += sacio_getFloatHeader(SAC_FLOAT_STLA, data.header, &stla);\n ierr += sacio_getFloatHeader(SAC_FLOAT_STLO, data.header, &stlo);\n ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM, data.header, kcmpnm);\n if (ierr != 0) \n {\n fprintf(stderr, \"%s: Failed to get header information\\n\", __func__);\n return -1;\n }\n // Figure out the component\n ierr = parmt_utils_getComponent(kcmpnm, cmpincSAC, &icomp);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to classify component\\n\", __func__);\n return -1;\n }\n // SAC to SEED convention\n cmpinc = cmpincSAC - 90.0;\n // Figure out the component\n lenos = MAX(1, strlen(kcmpnm));\n icomp = 1;\n if (kcmpnm[lenos-1] == 'Z' || kcmpnm[lenos-1] == '1')\n {\n icomp = 1;\n }\n else if (kcmpnm[lenos-1] == 'N' || kcmpnm[lenos-1] == '2')\n {\n icomp = 2;\n }\n else if (kcmpnm[lenos-1] == 'E' || kcmpnm[lenos-1] == '3')\n {\n icomp = 3;\n }\n else\n {\n fprintf(stderr, \"%s: Can't classify component %s\\n\", __func__, kcmpnm);\n return -1;\n }\n ierr = parmt_polarity_computeGreensRowFromTtimes(wavetype, icomp,\n evla, evlo, evdp,\n stla, stlo,\n cmpinc, cmpaz,\n dirnm, model,\n G);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to compute G\\n\", __func__);\n }\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Computes a row of the Green's functions matrix from ttimes\n *\n * @param[in] wavetype If 1 then this is a P wave.\n * @param[in] wavetype If 2 then this is an S wave.\n * @param[in] icomp If 1 then this is the vertical channel.\n * @param[in] icomp If 2 then this is the north (1 or 2) channel.\n * @param[in] icomp If 3 then this is the east (2 or 3) channel.\n * @param[in] evla Event latitude (degrees).\n * @param[in] evlo Event longitude (degrees).\n * @param[in] evdp Event depth (km).\n * @param[in] stla Station latitude (degrees).\n * @param[in] stlo Station longitude (degrees).\n * @param[in] cmpaz Component azimuth (0 north, +90 east).\n * @param[in] cmpinc Component inclination (-90 up, 0 east/north, +90 down).\n * @param[in] dirnm Directory containing the ttimes precomputed binary\n * files. If NULL then the default as dicated by the \n * ttimes configuration will be used. \n * @param[in] model Model name (e.g., ak135 or iasp91)\n *\n * @param[out] G Row of matrix s.t. G*m produces estimates the polarity\n * at the station. Here m is packed \n * \\f$ \\{m_{xx}, m_{yy}, m_{zz},\n * m_{xy}, m_{xz}, m_{yz} \\} \\f$\n * This must have dimension of at least 6.\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint parmt_polarity_computeGreensRowFromTtimes(\n const int wavetype, const int icomp,\n const double evla, const double evlo, const double evdp,\n const double stla, const double stlo,\n const double cmpinc, const double cmpaz,\n const char *dirnm, const char *model,\n double *__restrict__ G)\n{\n double aoiRec, az, azSrc, baz, bazRec, dist, delta, toaSrc;\n struct ttimesTravelTime_struct ttime;\n int ierr;\n ierr = 0;\n if (G == NULL)\n {\n fprintf(stderr, \"%s: Error G is NULL\\n\", __func__);\n return -1;\n }\n memset(G, 0, 6*sizeof(double));\n if (evdp < 0.0 || evdp > ttimes_getMaxDepth())\n {\n fprintf(stderr, \"%s: Error depth must be between [0,%f]\\n\", __func__,\n ttimes_getMaxDepth()); \n return -1;\n }\n memset(&ttime, 0, sizeof(struct ttimesTravelTime_struct));\n geodetic_gps2distanceAzimuth(evla, evlo, stla, stlo,\n &dist, &delta, &az, &baz);\n if (wavetype == 1)\n {\n ierr = ttimes_getFirstPPhase(delta, evdp, dirnm, model, &ttime);\n }\n else if (wavetype == 2)\n {\n ierr = ttimes_getFirstSPhase(delta, evdp, dirnm, model, &ttime); \n }\n else\n {\n fprintf(stderr, \"%s: Invalid phase type - must be 1 (P) or 2 (S)\\n\",\n __func__);\n return -1;\n }\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error computing theoretical traveltime info\\n\",\n __func__);\n return -1;\n }\n // Compute the column in the Green's function matrix\n toaSrc = ttime.toang;\n azSrc = az;\n bazRec = baz;\n aoiRec = ttime.aoi;\n //printf(\"%f %f %f %f %f %f %f\\n\", delta, stla, stlo, toaSrc, azSrc, aoiRec, bazRec);\n ierr = parmt_polarity_computeGreensMatrixRow(wavetype, icomp,\n azSrc, toaSrc, bazRec, aoiRec,\n cmpinc, cmpaz, G);\n \n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to compute polarity for row\\n\", __func__);\n memset(G, 0, 6*sizeof(double));\n return -1;\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Computes a column for the Green's function s.t. G*m produces an \n * estimate of polarity on the icomp'th component measured in the \n * far-field. The moment tensor which would be applied to this row\n * is packed: \n * \\f$ \\{m_{xx}, m_{yy}, m_{zz}, m_{xy}, m_{xz}, m_{yz} \\} \\f$\n * with convention North, East, Down (e.g., Jost and Herrmann).\n * For more see Quantitative Seismology - Aki and Richards 2002,\n * Eqn 4.96 on pg 111 and Source Mechanisms of Earthquakes: Theory\n * and Practice - Udias et al. pg 100..\n *\n * @param[in] wavetype =1 -> P wave\n * =2 -> S wave\n * @param[in] icomp receiver component of motion:\n * =1 -> Vertical channel\n * =2 -> 1 or North channel\n * =3 -> 2 or East channel\n * @param[in] azSrc source to receiver azimuth is measured positive from\n * north (degrees)\n * @param[in] toaSrc take-off angle (measured positive from x3 where x3 \n * points down) (degrees)\n * @param[in] bazRec receiver to source back azimuth measured positive\n * from north (degrees)\n * @param[in] aoiRec angle of incidence at receiver\n * @param[in] cmpaz component azimuth (0 north, +90 east)\n * @param[in] cmpinc component inclinantion (-90 up, 0 east/north, +90 down)\n *\n * @param[out] G row of matrix s.t. G*m produces estimates the polarity\n * at the station. Here m is packed \n * \\f$ \\{m_{xx}, m_{yy}, m_{zz},\n * m_{xy}, m_{xz}, m_{yz} \\} \\f$\n *\n * @bugs i've really only looked at the vertical p-teleseismic case - no idea\n * about other phases, wavetypes\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint parmt_polarity_computeGreensMatrixRow(const int wavetype,\n const int icomp,\n const double azSrc,\n const double toaSrc,\n const double bazRec,\n const double aoiRec,\n const double cmpinc,\n const double cmpaz,\n double *__restrict__ G)\n{\n double M[9], G63[18], up[6], ush[6], usv[6],\n gam[3], lhat[3], phat[3], phihat[3],\n cosba, cos_cmpaz, cost_rec,\n r11, r12, r13, r21, r22, r23, r31, r32, r33,\n sinba, sin_cmpaz,\n sint_rec,\n t1, t2, t3, theta, xsign, u1, u2, ue, un, uz;\n int k;\n const double pi180 = M_PI/180.0;\n const bool lrot = true;//false;\n const int P_WAVE = 1;\n const int S_WAVE = 2;\n //------------------------------------------------------------------------//\n //\n // Error check\n if (icomp < 1 || icomp > 3)\n {\n fprintf(stderr, \"%s: Invalid component\\n\", __func__);\n return -1;\n } \n if (wavetype < P_WAVE || wavetype > S_WAVE)\n {\n fprintf(stderr, \"%s: Invalid wavetype\\n\", __func__);\n return -1;\n }\n // Fill the basis at the source (Aki and Richards Eqn 4.88)\n fillBasis(toaSrc, azSrc, gam, phat, phihat);\n // Compute the contractions for u_p, u_sv, and u_sh (A&R Eqn 4.96)\n // for all 6 individual moment tensor terms\n for (k=0; k<6; k++)\n {\n // Set the moment tensor with the k'th mt term 1 others zero\n setM3x3(k, M);\n // Compute contraction\n up[k] = computeContraction3x3(gam, M, gam);\n usv[k] = computeContraction3x3(phat, M, gam);\n ush[k] = computeContraction3x3(phihat, M, gam); \n }\n // Fill the basis at the receiver - notice the basis uses the forward\n // azimuth from the receiver to the source \n fillBasis(aoiRec, (bazRec + 180.0), lhat, phat, phihat); \n // Compute geometric factors at receiver \n//printf(\"%f %f %f %f %f\\n\", toaSrc, azSrc, bazRec, aoiRec, cmpaz);\n theta = aoiRec*pi180;\n cosba = cos(bazRec*pi180);\n cost_rec = cos(theta);\n sinba = sin(bazRec*pi180);\n sint_rec = sin(theta);\n cos_cmpaz = cos(cmpaz*pi180);\n sin_cmpaz = sin(cmpaz*pi180);\n // Set 3D rotation matrix\n r11 = cost_rec;\n r21 = sint_rec;\n r31 = 0.0;\n r12 =-sint_rec*sinba;\n r22 = cost_rec*sinba;\n r32 = -cosba;\n r13 =-sint_rec*cosba;\n r23 = cost_rec*cosba;\n r33 = sinba;\n // Flip sign for receivers that acquire positive down \n xsign = 1.0; \n if (fabs(cmpinc - 90.0) < 1.e-4){xsign =-1.0;}\n // Compute 6 x 3 subforward modeling matrix with row for up (1 channel)\n if (wavetype == P_WAVE)\n {\n // Loop on mts terms\n for (k=0; k<6; k++)\n {\n // Extract the (north, east, down) component\n t3 =-up[k]*lhat[0]; // z-down -> z-up\n //t3 = up[k]*lhat[0]; // z-up\n t2 = up[k]*lhat[1]; // east\n t1 = up[k]*lhat[2]; // north \n // Not sure if i have to rotate LQT -> ZNE\n if (lrot)\n {\n uz = t1*r11 + t2*r21 + t3*r31; // Z\n ue = t1*r12 + t2*r22 + t3*r32; // E\n un = t1*r13 + t2*r23 + t3*r33; // N\n }\n else\n {\n uz = t3;\n ue = t2;\n un = t1;\n }\n // Rotate into (1, 2)\n u1 = un*cos_cmpaz + ue*sin_cmpaz;\n u2 =-un*sin_cmpaz + ue*cos_cmpaz;\n // Finish\n G63[k*3+0] = xsign*uz;\n //G63[k*3+0] =-xsign*uz;\n G63[k*3+1] = u1;\n G63[k*3+2] = u2;\n }\n }\n // SH wave\n else\n {\n // Loop on mts terms\n for (k=0; k<6; k++)\n {\n // Extract the (north, east, down) component\n t3 =-usv[k]*phat[0] - ush[k]*phihat[0]; // z-down -> z-up\n t2 = usv[k]*phat[1] + ush[k]*phihat[1]; // east\n t1 = usv[k]*phat[2] + ush[k]*phihat[2]; // north\n // Not sure if i have to rotate LQT -> ZNE\n if (lrot)\n {\n uz = t1*r11 + t2*r21 + t3*r31; // Z\n ue = t1*r12 + t2*r22 + t3*r32; // E\n un = t1*r13 + t2*r23 + t3*r33; // N\n }\n else\n {\n uz = t3;\n ue = t2;\n un = t1;\n }\n // Rotate into (1, 2)\n u1 = un*cos_cmpaz + ue*sin_cmpaz;\n u2 =-un*sin_cmpaz + ue*cos_cmpaz;\n // Finish\n G63[k*3+0] = xsign*uz;\n G63[k*3+1] = u1;\n G63[k*3+2] = u2;\n }\n }\n // Copy the result - vertical\n if (icomp == 1)\n {\n for (k=0; k<6; k++)\n {\n G[k] = G63[k*3+0];\n }\n }\n // 1 component\n else if (icomp == 2)\n {\n for (k=0; k<6; k++)\n {\n G[k] = G63[k*3+1];\n }\n }\n // 2 component\n else if (icomp == 3)\n {\n for (k=0; k<6; k++)\n {\n G[k] = G63[k*3+2];\n }\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Fills in the basis vectors - Aki and Richards pg 108 Eqn 4.88.\n *\n * @param[in] i Take-off angle (degrees).\n * @param[in] phi Azimuth angle (degrees).\n * @param[in] gam P-wave direction. This has dimension [3].\n * @param[in] phat SV-wave direction. This has dimension [3].\n * @param[in] phihat SH-wave direction. This has dimension [3].\n *\n * @copyright ISTI distributed under the Apache 2 license.\n * \n */\nstatic void fillBasis(const double i, const double phi,\n double *__restrict__ gam,\n double *__restrict__ phat,\n double *__restrict__ phihat)\n{\n double cosi, sini, cosp, sinp;\n const double pi180 = M_PI/180.0;\n cosi = cos(i*pi180);\n sini = sin(i*pi180);\n cosp = cos(phi*pi180);\n sinp = sin(phi*pi180);\n gam[0] = sini*cosp;\n gam[1] = sini*sinp;\n gam[2] = cosi;\n\n phat[0] = cosi*cosp;\n phat[1] = cosi*sinp;\n phat[2] =-sini; \n\n phihat[0] =-sinp;\n phihat[1] = cosp;\n phihat[2] = 0.0;\n}\n//============================================================================//\n/*!\n * @brief Sets the moment tensor matrix where the k'th moment tensor\n * term is 1 and others are zero. Here moment tensor terms\n * are counted {0,1,2,3,4,5} = {xx,yy,zz,xy,xz,yz}\n *\n * @param[in] k Moment tensor index. This is in the range [0,5] and follows\n * the mapping {0,1,2,3,4,5} = {xx,yy,zz,xy,xz,yz}.\n *\n * @param[out] M The 3x3 NED moment tensor. This is an array of dimension [9].\n *\n */\nstatic void setM3x3(const int k, double *__restrict__ M)\n{\n memset(M, 0, 9*sizeof(double));\n // mxx (fill mtt)\n if (k == 0)\n {\n M[4] = 1.0; //M[0][0] = 1.0;\n }\n // myy (fill mpp)\n else if (k == 1)\n {\n M[8] = 1.0; //M[1][1] = 1.0;\n }\n // mzz (fill mrr)\n else if (k == 2)\n {\n M[0] = 1.0; //M[2][2] = 1.0;\n }\n // mxy and myz (fill mtp)\n else if (k == 3)\n {\n M[5] =-1.0; //M[0][1] = 1.0;\n M[7] =-1.0; //M[1][0] = 1.0;\n }\n // mxz and mzx (fill mrp)\n else if (k == 4)\n {\n M[1] = 1.0; //M[0][2] = 1.0;\n M[3] = 1.0; //M[2][0] = 1.0;\n }\n // myz and mzy (fill mrp)\n else\n {\n M[2] =-1.0; //M[1][2] = 1.0;\n M[6] =-1.0; //M[2][1] = 1.0;\n }\n/*\n // mxx\n if (k == 0)\n {\n M[0] = 1.0; //M[0][0] = 1.0;\n }\n // myy\n else if (k == 1)\n {\n M[4] = 1.0; //M[1][1] = 1.0;\n }\n // mzz\n else if (k == 2)\n {\n M[8] = 1.0; //M[2][2] = 1.0;\n }\n // mxy and myz\n else if (k == 3)\n {\n M[1] = 1.0; //M[0][1] = 1.0;\n M[3] = 1.0; //M[1][0] = 1.0;\n }\n // mxz and mzx\n else if (k == 4)\n {\n M[2] = 1.0; //M[0][2] = 1.0;\n M[6] = 1.0; //M[2][0] = 1.0;\n }\n // myz and mzy\n else\n {\n M[5] = 1.0; //M[1][2] = 1.0;\n M[7] = 1.0; //M[2][1] = 1.0;\n }\n*/\n return;\n}\n//============================================================================//\n/*!\n * @brief Computes the contraction in Aki and Richards Eqn 4.96\n * for the given basis vectors and moment tensor.\n */\nstatic double computeContraction3x3(const double *__restrict__ a,\n const double *__restrict__ M,\n const double *__restrict__ b)\n{ \n double res;\n int i, ij, j;\n res = 0.0;\n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++) \n {\n ij = 3*i + j;\n res = res + a[i]*M[ij]*b[j];\n }\n }\n return res;\n}\n//============================================================================//\n/*!\n * @brief Tabulates the objective function over the earthquake locations.\n *\n * @param[in] locComm Location MPI communicator.\n * @param[in] blockSize Block-size for performing matrix-matrix\n * multiplications.\n * @param[in] polarityData Contains the polarity data and the Green's functions.\n * @param[in] mtloc Contains the local moment tensors in this rank's\n * grid search.\n *\n * @param[out] phi The objective function tabulated for all locations\n * and moment tensors. This is only accessed by\n * master process in locComm; and for this case has\n * dimension [nlocs x mtloc.nmtAll] with leading\n * dimension mtloc.nmtAll. Otherwise, this can be NULL.\n *\n * @result 0 indicates success. \n *\n * @copyright ISTI distributed under the Apache 2 license.\n *\n */\nint polarity_performLocationSearch64f(const MPI_Comm locComm,\n const int blockSize,\n struct polarityData_struct polarityData, \n struct localMT_struct mtloc,\n double *__restrict__ phi)\n{\n double *Dmat, *G, *Sigma, *phiLoc, *phiWork;\n int icol, ierr, ierrAll, iloc, ipol, jloc, jndx,\n kt, mylocID, nlocProcs, mblock, pad;\n const int nPolarity = polarityData.nPolarity;\n const int Mrows = nPolarity;\n const int Kcols = 6;\n const int nlocs = polarityData.nlocs;\n const int ldm = mtloc.ldm;\n const int nmt = mtloc.nmt;\n const int master = 0;\n // Initialize\n ierr = 0;\n ierrAll = 0;\n MPI_Comm_size(locComm, &nlocProcs);\n MPI_Comm_rank(locComm, &mylocID);\n // Compute padding for 64 bit data alignment in observations and mt blocks\n pad = computePadding64f(blockSize);\n mblock = blockSize + pad;\n // Set space\n phiLoc = memory_calloc64f(nmt);\n G = memory_calloc64f(nPolarity*LDG);\n Dmat = memory_calloc64f(nPolarity*mblock);\n Sigma = array_set64f(nPolarity, 1.0, &ierr); // Default to identity\n phiWork = memory_calloc64f(nlocs*mtloc.nmtAll);\n // Set the row major data matrix where each row is an observation\n for (ipol=0; ipol\n#include \n#include \n#include \n#include \n#if HAVE_NETCDF4\n#include \n#endif\n\n#include \"uvspec.h\"\n#include \"cdisort.h\"\n#include \"ckdfu.h\"\n#include \"ascii.h\"\n#if HAVE_NETCDF4\n#include \"netCDF_functions.h\"\n#endif\n#include \"numeric.h\"\n#include \"solver.h\"\n#include \"errors.h\"\n\n#if HAVE_LIBGSL\n#include \n#include \n#endif\n\n#ifndef PI\n#define PI 3.14159265358979323846264338327\n#endif\n\n#define EPSILON 1E-6\n#define s2day 3600.0 * 24.0 /* seconds to day */\n#define mW2W 1.E-3; /* mW to W */\n#define ERRCODE 2\n#define ERR(e) \\\n { \\\n printf (\"Error: %s\\n\", nc_strerror (e)); \\\n exit (ERRCODE); \\\n status++; \\\n }\n\n/* prototypes of internal functions */\nstatic int cnvlv (double* x_spec, float* y_spec, int n_spec, double* x_slit, double* y_slit, int n_slit, int std);\n\nstatic float radiance2bt (float rad, float* wvnmlo, float* wvnmhi, float* filter, int n, int processing, int ivi);\n\nstatic int output2bt (input_struct input, output_struct* output, int iv, int is_3d);\n\nstatic int read_photon_file (char* filename, float* lambda_r, int nlamdba_r, float** fraction);\n\nstatic int select_wavelength_indices (float* lambda,\n int nlambda,\n float* lambda_lower,\n float* lambda_upper,\n int start_index,\n int end_index,\n int quiet,\n int raman,\n int* lower,\n int* upper);\n\nstatic int set_raman_wl_grid (wl_inp_struct* wl_inp, wl_out_struct* wl_out, char* filename, int quiet);\nstatic int find_raman_closest_wl_in_solar_file (float* wls, float* wle, char* filename, int quiet);\nstatic int set_transmittance_wl_grid (wl_inp_struct* wl_inp, wl_out_struct* wl_out, int quiet);\nstatic int set_transmittance_wl_grid_lowtran (wl_inp_struct* wl_inp, wl_out_struct* wl_out, int quiet);\n\nstatic int\nset_transmittance_wl_grid_reptran (input_struct input, float** lambda_lower, float** lambda_upper, wl_out_struct* wl_out);\n\nstatic int set_rte_wl_grid_reptran (input_struct input, output_struct* output);\n\nstatic int write_spectral3D (input_struct input, output_struct* output);\n\nstatic int spec2rgb (input_struct input, output_struct* output);\nstatic int spec2rgb3D (input_struct input, output_struct* output);\nstatic int raman_spec2spec (input_struct input, output_struct* output);\nstatic inline int float_equal (float a, float b);\ndouble linpol (double x1, double x2, double y1, double y2, double x);\n\ndouble nm_to_inv_cm (double wavelength_nm);\ndouble inv_cm_to_nm (double wavenumber_inv_cm);\ndouble polarizability_anisotropy_N2 (double nu);\ndouble polarizability_anisotropy_O2 (double nu);\nint pfraction_reptran (wl_out_struct* wl_out);\n\n/********************************************/\n/* Setup the transmittance wavelength grid. */\n/********************************************/\nint setup_wlgrid (input_struct input, output_struct* output) {\n int iv = 0, status = 0, monochromatic = 0;\n float *lambda_lower = NULL, *lambda_upper = NULL;\n float test_lower = 0, test_upper = 0;\n char function_name[] = \"setup_wlgrid\";\n char file_name[] = \"ancillary.c\";\n\n /* Check whether representative wavelengths will be used. */\n if (input.ck_scheme == CK_REPTRAN || input.ck_scheme == CK_REPTRAN_CHANNEL)\n output->wl.use_reptran = 1;\n else\n output->wl.use_reptran = 0;\n\n /* in case of RGB conversion we need an internal wavelength grid */\n if (input.processing == PROCESS_RGB || input.processing == PROCESS_RGBNORM) {\n /* reset wavelength range */\n input.wl.start = -999;\n input.wl.end = -999;\n\n switch (input.source) {\n case SRC_SOLAR:\n case SRC_BLITZ: /* BCA */\n case SRC_LIDAR: /* BCA */\n /* and replace transmittance grid */\n strcpy (input.filename[FN_WLTRANS], input.filename[FN_PATH]);\n strcat (input.filename[FN_WLTRANS], \"solar_flux/rgb\");\n\n if (!input.quiet) {\n fprintf (stderr, \" ... ignoring user-defined wavelength range and using\\n\");\n fprintf (stderr, \" ... internal wavelength grid from %s\\n\", input.filename[FN_WLTRANS]);\n }\n\n break;\n\n case SRC_THERMAL:\n /* and replace thermal bands file */\n strcpy (input.filename[FN_WLBANDS], input.filename[FN_PATH]);\n strcat (input.filename[FN_WLBANDS], \"solar_flux/rgb_bands\");\n\n if (!input.quiet) {\n fprintf (stderr, \" ... ignoring user-defined wavelength range and using\\n\");\n fprintf (stderr, \" ... internal thermal bands from %s\\n\", input.filename[FN_WLBANDS]);\n }\n\n break;\n\n default:\n fprintf (stderr, \"Error, unsupported source %d in %s (%s)\\n\", input.source, function_name, file_name);\n return -1;\n }\n }\n\n /* set default unit for band width */\n output->bandwidth_unit = input.bandwidth_unit;\n\n if (output->bandwidth_unit == UNIT_NOT_DEFINED) {\n switch (input.source) {\n case SRC_SOLAR:\n case SRC_BLITZ: /* BCA */\n case SRC_LIDAR: /* BCA */\n output->bandwidth_unit = UNIT_PER_NM;\n break;\n case SRC_THERMAL:\n output->bandwidth_unit = UNIT_PER_CM_1;\n break;\n default:\n fprintf (stderr, \"Error, unsupported source %d in %s (%s)\\n\", input.source, function_name, file_name);\n return -1;\n }\n }\n\n if (input.raman) {\n /* Internally the lower and upper wavelengths for Raman scattering are different from */\n /* what the user specifies. This is setup in setup_wlgrid (ancillary.c). */\n /* For Raman scattering only include wavelengths that the user asked. */\n /* Internally we have to include more wavelengths to account for */\n /* Raman scattered radiation */\n /* The values 196.8269 and 194.3015 are the maximum shifts (in cm-1) for N2 and O2 */\n /* as given in report: Accounting for Raman Scattering in DOAS, J.F. de Haan, */\n /* SN-OMIE-KNMI-409, Version 1.0, May 18, 2003. See also functions: crs_raman_N2 and */\n /* crs_raman_O2. */\n\n output->wl.delta_wvl_raman_extra = 1.0;\n output->wl.delta_wvl_raman_lower = input.wl.start - inv_cm_to_nm (nm_to_inv_cm (input.wl.start) + 196.8269);\n input.wl.start = inv_cm_to_nm (nm_to_inv_cm (input.wl.start) + 196.8269) - output->wl.delta_wvl_raman_extra;\n output->wl.delta_wvl_raman_upper = inv_cm_to_nm (nm_to_inv_cm (input.wl.end) - 194.3015) - input.wl.end;\n input.wl.end = inv_cm_to_nm (nm_to_inv_cm (input.wl.end) - 194.3015) + output->wl.delta_wvl_raman_extra;\n status = find_raman_closest_wl_in_solar_file (&input.wl.start, &input.wl.end, input.filename[FN_EXTRATERRESTRIAL], input.quiet);\n }\n\n if (input.wl.start > 0 && input.wl.end > 0) {\n output->wl.start = input.wl.start;\n output->wl.end = input.wl.end;\n }\n\n output->wl.type = WLGRID_NONE;\n\n if (strlen (input.filename[FN_FILTERFUNCTION]) > 0 && input.ck_scheme == CK_REPTRAN_CHANNEL)\n fprintf (stderr, \"Error: Combining options 'mol_abs_param reptran_channel' and 'filter_function_file' is not allowed.\");\n\n if (output->wl.use_reptran || input.ck_scheme == CK_CRS || input.ck_scheme == CK_LOWTRAN ||\n input.ck_scheme == CK_RAMAN) { /* no real correlated-k */\n\n if (strlen (input.filename[FN_WLBANDS]) > 0 && input.source == SRC_THERMAL) { /* thermal_bands_file */\n\n output->wl.type = WLGRID_BANDS;\n output->wl.ignore_solar_file = 1; /* ignore solar file if FN_WLBANDS is used */\n\n if (!input.quiet)\n fprintf (stderr, \" ... reading thermal_bands_file from %s\\n\", input.filename[FN_WLBANDS]);\n\n /* read center wavelength and band limits [wavenumbers] from file */\n status = read_3c_file_float (input.filename[FN_WLBANDS],\n &(output->wl.lambda_t),\n &(lambda_lower),\n &(lambda_upper),\n &output->wl.nlambda_t);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d opening %s\\n\", status, input.filename[FN_WLBANDS]);\n return status;\n }\n\n }\n\n else if (strlen (input.filename[FN_WLTRANS]) > 0) { /* transmittance_wl_file */\n\n output->wl.type = WLGRID_USER;\n\n /* read internal wavelength grid from transmittance file */\n status = read_1c_file_float (input.filename[FN_WLTRANS], &(output->wl.lambda_t), &output->wl.nlambda_t);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d opening %s\\n\", status, input.filename[FN_WLTRANS]);\n return status;\n }\n\n if (output->wl.use_reptran) {\n\n status = set_transmittance_wl_grid_reptran (input, &lambda_lower, &lambda_upper, &output->wl);\n if (status)\n return fct_err_out (status, \"set_transmittance_wl_grid_reptran\", ERROR_POSITION);\n }\n\n }\n\n else if (strlen (input.filename[FN_MOL_TAU_ABS]) > 0) { /* moltau_file */\n\n output->wl.type = WLGRID_MOLABS;\n\n if (!input.quiet) {\n fprintf (stderr, \" ... molecular_tau_file specified but computational wavelength grid\\n\");\n fprintf (stderr, \" ... not explicitely defined; reading the wavelength grid\\n\");\n fprintf (stderr, \" ... from molecular_tau_file %s\\n\", input.filename[FN_MOL_TAU_ABS]);\n }\n status = read_molecular_absorption_lambda (input.filename[FN_MOL_TAU_ABS],\n input.quiet,\n &output->wl.lambda_t,\n &output->wl.nlambda_t,\n &monochromatic);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading wavelength grid from %s\\n\", status, input.filename[FN_MOL_TAU_ABS]);\n return -1;\n }\n }\n\n if (output->wl.type == WLGRID_MOLABS && monochromatic == 1) {\n output->wl.lambda_t[0] = input.wl.start;\n } else if (output->wl.type == WLGRID_NONE ||\n (output->wl.type == WLGRID_MOLABS && monochromatic == 0 && input.ck_scheme == CK_RAMAN)) {\n\n output->wl.type = WLGRID_UVSPEC;\n\n if (output->wl.use_reptran) {\n\n /* transmittance wavelength grid consists of band centers */\n status = set_transmittance_wl_grid_reptran (input, &lambda_lower, &lambda_upper, &output->wl);\n if (status)\n return fct_err_out (status, \"set_transmittance_wl_grid_reptran\", ERROR_POSITION);\n\n } else if (input.ck_scheme == CK_CRS) {\n\n /* set up a reasonable wavelength grid for the radiative transfer calculation */\n status = set_transmittance_wl_grid (&input.wl, &output->wl, input.quiet);\n if (status)\n return fct_err_out (status, \"set_transmittance_wl_grid\", ERROR_POSITION);\n\n } else if (input.ck_scheme == CK_RAMAN) {\n\n /* Set the internal radiative transfer grid equal to the grid specified in */\n /* the extraterrestrial spectrum, because we use the absolute value of */\n /* the solar source in all calculations. */\n status = set_raman_wl_grid (&input.wl, &output->wl, input.filename[FN_EXTRATERRESTRIAL], input.quiet);\n\n /* For Raman scattering only include wavelengths that the user asked. */\n /* Internally we have to include more wavelengths because we need */\n /* these cross sections to account for Raman scattered radiation. */\n test_lower = output->wl.lambda_t[0] + output->wl.delta_wvl_raman_lower + output->wl.delta_wvl_raman_extra;\n test_upper =\n output->wl.lambda_t[output->wl.nlambda_t - 1] - output->wl.delta_wvl_raman_upper - output->wl.delta_wvl_raman_extra;\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n if (output->wl.lambda_t[iv] < test_lower)\n output->wl.raman_start_id = iv + 1;\n if (output->wl.lambda_t[output->wl.nlambda_t - 1 - iv] > test_upper)\n output->wl.raman_end_id = output->wl.nlambda_t - iv - 2;\n }\n\n } else\n status = set_transmittance_wl_grid_lowtran (&input.wl, &output->wl, input.quiet);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d setting up wavelength grid\\n\", status);\n return status;\n }\n\n /* here we need to calculate the full wavelength range */\n output->wl.nlambda_rte_lower = 0;\n output->wl.nlambda_rte_upper = output->wl.nlambda_t - 1;\n }\n\n } else { /* correlated-k */\n\n output->wl.type = WLGRID_CK;\n\n /* read information about wavelength grid and quadrature points */\n switch (input.ck_scheme) {\n case CK_KATO:\n case CK_KATO2:\n case CK_KATO2_96:\n case CK_KATO2ANDWANDJI:\n\n /* read Kato et al. [1999] tables */\n status = kato_readtables (input.ck_scheme, &(output->ck), input.filename[FN_PATH], input.rte.mc.filename[FN_MC_PHOTONS]);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by kato_readtables() in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n break;\n\n case CK_FU:\n\n /* read Fu and Liou [1992/93] tables */\n status = fu_readtables (&(output->ck), input.filename[FN_PATH], input.rte.mc.filename[FN_MC_PHOTONS]);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by fu_readtables() in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n break;\n\n case CK_AVHRR_KRATZ:\n\n /* read Kratz [1999] tables */\n status = avhrr_kratz_readtables (&(output->ck), input.filename[FN_PATH], input.rte.mc.filename[FN_MC_PHOTONS]);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by avhrr_kratz_readtables() in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n break;\n\n case CK_FILE:\n\n /* read generic tables in CDF format */\n status = ck_generic_readtables (&(output->ck), input.ck_scheme_filename, input.rte.mc.filename[FN_MC_PHOTONS]);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by ck_generic_readtables() in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n break;\n\n default:\n fprintf (stderr, \"Error: unsupported correlated-k scheme\\n\");\n return -1;\n }\n\n /* copy center wavelengths to transmittance grid */\n /* and set wavenumber intervals */\n\n output->wl.nlambda_t = output->ck.n_wvl;\n output->wl.lambda_t = (float*)calloc (output->wl.nlambda_t, sizeof (float));\n\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n output->wl.lambda_t[iv] = output->ck.wvlc[iv + 1];\n }\n\n } /* end correlated-k */\n\n /* setup array containing the band limits */\n output->wl.wvnmlo_t = (float*)calloc (output->wl.nlambda_t, sizeof (float));\n output->wl.wvnmhi_t = (float*)calloc (output->wl.nlambda_t, sizeof (float));\n\n if (output->wl.type == WLGRID_CK) {\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n output->wl.wvnmlo_t[iv] = output->ck.wvnlo[iv + 1];\n output->wl.wvnmhi_t[iv] = output->ck.wvnhi[iv + 1];\n }\n } else if (output->wl.type == WLGRID_BANDS && input.source == SRC_THERMAL) {\n /* band limits from thermal_bands_file */\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n output->wl.wvnmlo_t[iv] = 1.0E7 / lambda_upper[iv];\n output->wl.wvnmhi_t[iv] = 1.0E7 / lambda_lower[iv];\n }\n } else {\n /* the default bandwidth is 1cm-1 to get the emittance per cm-1; */\n /* input.bandwidth can be set with thermal_bandwidth */\n if (output->bandwidth_unit == UNIT_PER_CM_1) {\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n output->wl.wvnmlo_t[iv] = 1.0E7 / output->wl.lambda_t[iv] - input.bandwidth / 2.0;\n output->wl.wvnmhi_t[iv] = output->wl.wvnmlo_t[iv] + input.bandwidth;\n }\n } else if (output->bandwidth_unit == UNIT_PER_NM) {\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n output->wl.wvnmlo_t[iv] = 1.0E7 / (output->wl.lambda_t[iv] + input.bandwidth / 2.0);\n output->wl.wvnmhi_t[iv] = 1.0E7 / (output->wl.lambda_t[iv] - input.bandwidth / 2.0);\n }\n } else {\n fprintf (stderr, \"Error, unsupported bandwidth_unit %d in %s (%s)\\n\", output->bandwidth_unit, function_name, file_name);\n return -1;\n }\n }\n\n /* free temporary wavelengths arrays */\n if (lambda_lower != NULL)\n free (lambda_lower);\n if (lambda_upper != NULL)\n free (lambda_upper);\n\n if (output->wl.type == WLGRID_CK || output->wl.type == WLGRID_BANDS || output->wl.type == WLGRID_USER ||\n (output->wl.type == WLGRID_MOLABS && monochromatic == 0)) {\n\n /* if start and end wavelength have not been set, use entire wavelength range */\n if (input.wl.start < 0 || input.wl.end < 0) {\n output->wl.start = output->wl.lambda_t[0];\n output->wl.end = output->wl.lambda_t[output->wl.nlambda_t - 1];\n if (!input.quiet)\n fprintf (stderr, \" ... setting wavelength range to %f - %fnm\\n\", output->wl.start, output->wl.end);\n }\n\n /* select wavelength range */\n status = select_wavelength_indices (output->wl.lambda_t,\n output->wl.nlambda_t,\n &(output->wl.start),\n &(output->wl.end),\n input.wl.start_index,\n input.wl.end_index,\n input.quiet,\n input.raman,\n &(output->wl.nlambda_rte_lower),\n &(output->wl.nlambda_rte_upper));\n if (status != 0) {\n fprintf (stderr, \"Error %d at no correlated-k in setup_wlgrid (ancillary.c) \\n\", status);\n return status;\n }\n\n /* check if the end wavelength is larger than 850nm in which case */\n /* we require user-selected molecular absorption properties */\n /*\n if (output->wl.lambda_t[output->wl.nlambda_rte_upper]>850 && \n\t (input.ck_scheme==CK_CRS && strlen(input.filename[FN_MOL_TAU_ABS])==0)) {\n fprintf (stderr, \"Error, you want to do a spectral calculation for wavelengths larger than 850 nm. While uvspec\\n\");\n fprintf (stderr, \" treats ozone absorption correctly, molecular absorption is NOT considered in monochromatic\\n\");\n fprintf (stderr, \" uvspec calculations, as absorption cross-section are highly variable with wavelength.\\n\");\n fprintf (stderr, \" To consider molecular absorption other than ozone you have two choices \\n\");\n fprintf (stderr, \" with uvspec:\\n\");\n fprintf (stderr, \" (1) Do a line-by-line calculation using 'molecular_tau_file' to specify\\n\");\n fprintf (stderr, \" the wavelength-dependent absorption profile; to calculate the\\n\");\n fprintf (stderr, \" latter, you need something like David Edwards' genln2.\\n\");\n fprintf (stderr, \" ATTENTION: line-by-line calculations are very time-consuming!\\n\");\n fprintf (stderr, \" (2) Use the correlated-k approximation which is the most accurate\\n\");\n fprintf (stderr, \" solution after the line-by-line calculation; use either the\\n\");\n fprintf (stderr, \" pre-defined parameterization that come with libRadtran or provide\\n\");\n fprintf (stderr, \" your own; both options are selected with 'mol_abs_param ...'\\n\");\n fprintf (stderr, \"\\n\");\n return -1;\n }\n */\n }\n\n /* now setup the ck structure for the LOWTRAN/SBDART table */\n if (input.ck_scheme == CK_LOWTRAN) {\n\n /* read LOWTRAN/SBDART tables */\n status = sbdart_readtables (&(output->ck),\n output->wl.nlambda_t,\n input.filename[FN_PATH],\n input.rte.mc.filename[FN_MC_PHOTONS],\n input.quiet);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by sbdart_readtables()\\n\", status);\n return status;\n }\n }\n\n if (output->wl.type != WLGRID_CK && output->wl.use_reptran == 0) {\n /* check if the internal grid covers the required wavelength range */\n if (output->wl.lambda_t[0] > output->wl.start || output->wl.lambda_t[output->wl.nlambda_t - 1] < output->wl.end) {\n fprintf (stderr,\n \"Error, internal wavelength grid (%f - %f nm)\\n\",\n output->wl.lambda_t[0],\n output->wl.lambda_t[output->wl.nlambda_t - 1]);\n fprintf (stderr, \"does not cover the user-defined wavelength range (%f - %f nm)\\n\", output->wl.start, output->wl.end);\n return -1;\n }\n }\n\n /* inform the user about wavelength selection */\n if (!input.quiet) {\n if (output->wl.nlambda_rte_upper != output->wl.nlambda_t - 1 || output->wl.nlambda_rte_lower != 0) {\n if (fabs (input.wl.start - NOT_DEFINED_FLOAT) > EPSILON)\n fprintf (stderr, \" user wavelength range: %f - %f nm\\n\", input.wl.start, input.wl.end);\n fprintf (stderr, \" selected wavelength indices %d - %d\\n\", output->wl.nlambda_rte_lower, output->wl.nlambda_rte_upper);\n fprintf (stderr,\n \" wavelength bands boundaries: %f - %f nm\\n\",\n output->wl.lambda_t[output->wl.nlambda_rte_lower],\n output->wl.lambda_t[output->wl.nlambda_rte_upper]);\n }\n }\n\n return 0;\n}\n\n/**********************************************************************/\n/* Setup the wavelength grid for the radiative transfer calculations. */\n/**********************************************************************/\nint setup_rte_wlgrid (input_struct input, output_struct* output) {\n\n int i, iv, status;\n\n if (output->wl.use_reptran) {\n\n /* checking compatibility of representative wavelengths with selected wavelength grid */\n if (output->wl.type == WLGRID_BANDS)\n return err_out (\"Error: Combining representative wavelengths and thermal_bands_file is not allowed.\\n\", -1);\n\n if (output->wl.type == WLGRID_MOLABS)\n return err_out (\"Error: Combining representative wavelengths and molecular_tau_file is not allowed.\\n\", -1);\n\n if (output->wl.type == WLGRID_UVSPEC || output->wl.type == WLGRID_USER) {\n\n status = set_rte_wl_grid_reptran (input, output);\n\n if (status)\n return fct_err_out (status, \"set_rte_wl_grid_reptran\", ERROR_POSITION);\n\n output->wl.nlambda_rte_lower = 0;\n output->wl.nlambda_rte_upper = output->wl.nlambda_r - 1;\n\n if (input.verbose) {\n fprintf (stderr, \" transmittance wavelength | radiative transfer wavelength | weight\\n\");\n for (iv = 0; iv < output->wl.nlambda_t; iv++)\n for (i = 0; i < output->wl.nlambda_in_reptran_band[output->wl.reptran_band_t[iv]]; i++)\n fprintf (stderr,\n \" %12.6f nm | %12.6f nm | %f \\n\",\n output->wl.lambda_t[iv],\n output->wl.lambda_r[output->wl.reptran_band[output->wl.reptran_band_t[iv]][i]],\n output->wl.weight_reptran_band[output->wl.reptran_band_t[iv]][i]);\n }\n\n } else\n return err_out (\"Error: Uncompatible wavelength grid type.\\n\", -1);\n\n } else {\n\n /* If representative wavelengths are not used, the wavelength grids for */\n /* radiative transfer and transmission are identical */\n output->wl.nlambda_r = output->wl.nlambda_t;\n output->wl.lambda_r = output->wl.lambda_t;\n output->wl.wvnmlo_r = output->wl.wvnmlo_t;\n output->wl.wvnmhi_r = output->wl.wvnmhi_t;\n }\n\n /* need to read the photons file */\n if (output->wl.use_reptran || input.ck_scheme == CK_CRS || input.ck_scheme == CK_RAMAN) {\n\n if (strlen (input.rte.mc.filename[FN_MC_PHOTONS]) > 0) {\n status =\n read_photon_file (input.rte.mc.filename[FN_MC_PHOTONS], output->wl.lambda_r, output->wl.nlambda_r, &(output->wl.pfraction));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading photon file name %s\\n\", status, input.rte.mc.filename[FN_MC_PHOTONS]);\n return status;\n }\n } else {\n output->wl.pfraction = calloc (output->wl.nlambda_r, sizeof (float));\n if (output->wl.use_reptran)\n status = pfraction_reptran (&(output->wl));\n else\n for (iv = output->wl.nlambda_rte_lower; iv <= output->wl.nlambda_rte_upper; iv++)\n output->wl.pfraction[iv] = 1.0 / (float)(output->wl.nlambda_rte_upper - output->wl.nlambda_rte_lower + 1);\n }\n }\n\n if (input.rte.mc.spectral_is) {\n if (!input.quiet)\n fprintf (stderr, \" ... using %d wavelengths for spectral importance sampling \\n\", output->wl.nlambda_r);\n output->mc.alis.nlambda_abs = output->wl.nlambda_r;\n output->mc.alis.lambda = calloc (output->mc.alis.nlambda_abs, sizeof (float));\n for (iv = 0; iv < output->mc.alis.nlambda_abs; iv++) {\n output->mc.alis.lambda[iv] = output->wl.lambda_r[iv];\n }\n\n /* Initialization for number of concentrations */\n output->mc.alis.Nc = 1;\n }\n\n if (input.rte.mc.concentration_is)\n output->mc.alis.nlambda_abs = 1;\n\n return 0;\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\n/***********************************************************************/\n/* Interpolate old_y (on the old_x grid) to new_y (on the new_x grid), */\n/* either with */\n/* natural cubic splines (linear=0), */\n/* linear (linear=1), or */\n/* logarithmic (linear=2) */\n/* interpolation methods. */\n/* The new_y must already be allocated with the right size (n_new_x)!! */\n/* If the input is sorted in descending order, */\n/* 'descend' needs to be set to 1. */\n/***********************************************************************/\n\nint arb_wvn (int n_old_x, float* old_x, float* old_y, int n_new_x, float* new_x, float* new_y, int linear, int descend) {\n int i = 0, j = 0, status = 0;\n double *a0 = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL;\n double *x = NULL, *y = NULL;\n double* tmp_y = NULL;\n double ynew = 0;\n double tst1 = 0, tst2 = 0;\n double sum = 0;\n\n x = (double*)calloc (n_old_x, sizeof (double));\n y = (double*)calloc (n_old_x, sizeof (double));\n\n if (!descend) {\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[i];\n y[i] = (double)old_y[i];\n }\n } else {\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[n_old_x - 1 - i];\n y[i] = (double)old_y[n_old_x - 1 - i];\n }\n }\n\n /* check if the array is now sorted in ascending order */\n for (i = 0; i < n_old_x - 1; i++)\n if (x[i] >= x[i + 1]) {\n fprintf (stderr, \"Error, x not sorted in ascending order (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n fprintf (stderr, \"x[%d] = %f, x[%d] = %f\\n\", i, x[i], i + 1, x[i + 1]);\n return -1;\n }\n\n /* check that range of x_new is <= range of x_old (if not checked -> segfault) */\n /* check minimum */\n for (i = 0; i < n_new_x; i++)\n if (new_x[i] < x[0]) {\n fprintf (stderr, \"Error, x_new[%d] = %f < min(x_old) = %f, arb_wvn() (in ancillary.c) \\n\", i, new_x[i], x[0]);\n return -2;\n }\n /* check maximum */\n for (i = 0; i < n_new_x; i++)\n if (new_x[i] > x[n_old_x - 1]) {\n fprintf (stderr, \"Error, x_new[%d] = %f > max(x_old) = %f, arb_wvn() (in ancillary.c) \\n\", i, new_x[i], x[n_old_x - 1]);\n return -3;\n }\n\n /* special check for log_spline interpolation */\n if (linear == 4) {\n sum = 0.0;\n for (i = 0; i < n_old_x; i++) {\n sum += y[i];\n if (y[i] < 0.0) {\n fprintf (stderr, \"Error, cannot use log_spline interpolation for profile with negative values\\n\");\n return -4;\n }\n }\n if (sum == 0.0) { /* x is zero in each layer, but grid must be changed anyway */\n free (x);\n free (y);\n for (i = 0; i < n_new_x; i++)\n new_y[i] = 0.0;\n return 0;\n } else {\n for (i = 0; i < n_old_x; i++) {\n if (y[i] > 0.0)\n y[i] = log (y[i]);\n else\n y[i] = -10.E+99; /* this is a little bit cheating, but it works */\n }\n }\n }\n\n switch (linear) {\n case 0: /* spline */\n case 4: /* log spline */\n\n status = spline_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do spline interpolation\\n\");\n fprintf (stderr, \"spline_coeffc() returned status %d\\n\", status);\n return status;\n }\n break;\n\n case 1: /* linear */\n status = linear_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do linear interpolation\\n\");\n fprintf (stderr, \"linear_coeffc() returned status %d\\n\", status);\n return status;\n }\n break;\n\n case 2: /* log */\n tmp_y = (double*)calloc (n_new_x, sizeof (double));\n for (i = 0; i < n_new_x; i++) {\n\n j = 0;\n while (new_x[i] > x[j])\n j++;\n\n if (j > 0)\n j--;\n\n /* logarithmic interpolation (if reasonable) */\n tst1 = fabs (y[j + 1] - y[j]);\n tst2 = (y[j + 1] < y[j] ? y[j + 1] : y[j]);\n if (tst1 <= 0.001 * y[j] || tst2 <= 0) /* linear */\n tmp_y[i] = y[j] + (new_x[i] - x[j]) / (x[j + 1] - x[j]) * (y[j + 1] - y[j]);\n else /* logarithmic */\n tmp_y[i] = exp (log (y[j]) + (new_x[i] - x[j]) / (x[j + 1] - x[j]) * (log (y[j + 1]) - log (y[j])));\n }\n\n /* first interpolate, then copy because then source */\n /* and target may be one and the same */\n for (i = 0; i < n_new_x; i++)\n new_y[i] = (float)tmp_y[i];\n\n free (tmp_y);\n break;\n\n case 3: /* linear mixing ratio */\n fprintf (stderr, \"Error, linear mixing interpolation not possible with arb_wvn.\\n\");\n fprintf (stderr, \"Please use interpolate_density instead. \\n\");\n return -5;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown interpolation type %d\\n\", linear);\n return -6;\n }\n\n switch (linear) {\n case 0: /* spline */\n case 1: /* linear */\n case 4: /* log spline */\n\n for (i = 0; i < n_new_x; i++) {\n\n if (linear == 1)\n status = calc_linear_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1);\n else\n status = calc_splined_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1, a2, a3);\n\n /* this check is new in 0.99-alpha-6; so far, no error */\n /* was reported if a value could not be interpolated */\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by calc_splined_value (%g)\\n\", status, new_x[i]);\n fprintf (stderr, \" %d data points, x[0] = %g, x[%d] = %g\\n\", n_old_x, x[0], n_old_x - 1, x[n_old_x - 1]);\n return status;\n }\n\n new_y[i] = (float)ynew;\n }\n\n free (a0);\n free (a1);\n free (a2);\n free (a3);\n break;\n\n case 2:\n /* no need to do anything because interpolation has already been done above */\n break;\n\n case 3: /* linear mixing ratio */\n fprintf (stderr, \"Error, linear mixing interpolation not possible with arb_wvn.\\n\");\n fprintf (stderr, \"Please use interpolate_density instead. \\n\");\n return -1;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown interpolation type %d\\n\", linear);\n return -7;\n }\n\n if (linear == 4)\n for (i = 0; i < n_new_x; i++)\n new_y[i] = exp (new_y[i]);\n\n free (x);\n free (y);\n\n return 0;\n}\n\nint arb_wvn_double (int n_old_x, double* old_x, double* old_y, int n_new_x, double* new_x, double* new_y, int linear, int descend) {\n int i = 0, j = 0, status = 0;\n double *a0 = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL;\n double *x = NULL, *y = NULL;\n double* tmp_y = NULL;\n double ynew = 0;\n double tst1 = 0, tst2 = 0;\n double sum = 0;\n\n x = (double*)calloc (n_old_x, sizeof (double));\n y = (double*)calloc (n_old_x, sizeof (double));\n\n if (!descend) {\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[i];\n y[i] = (double)old_y[i];\n }\n } else {\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[n_old_x - 1 - i];\n y[i] = (double)old_y[n_old_x - 1 - i];\n }\n }\n\n /* check if the array is now sorted in ascending order */\n for (i = 0; i < n_old_x - 1; i++)\n if (x[i] >= x[i + 1]) {\n fprintf (stderr, \"Error, x not sorted in ascending order (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n fprintf (stderr, \"x[%d] = %f, x[%d] = %f\\n\", i, x[i], i + 1, x[i + 1]);\n return -1;\n }\n\n /* check that range of x_new is <= range of x_old (if not checked -> segfault) */\n /* check minimum */\n for (i = 0; i < n_new_x; i++)\n if (new_x[i] < x[0]) {\n fprintf (stderr, \"Error, x_new[%d] = %f < min(x_old) = %f, arb_wvn() (in ancillary.c) \\n\", i, new_x[i], x[0]);\n return -2;\n }\n /* check maximum */\n for (i = 0; i < n_new_x; i++)\n if (new_x[i] > x[n_old_x - 1]) {\n fprintf (stderr, \"Error, x_new[%d] = %f > max(x_old) = %f, arb_wvn() (in ancillary.c) \\n\", i, new_x[i], x[n_old_x - 1]);\n return -3;\n }\n\n /* special check for log_spline interpolation */\n if (linear == 4) {\n sum = 0.0;\n for (i = 0; i < n_old_x; i++) {\n sum += y[i];\n if (y[i] < 0.0) {\n fprintf (stderr, \"Error, cannot use log_spline interpolation for profile with negative values\\n\");\n return -4;\n }\n }\n if (sum == 0.0) { /* x is zero in each layer, but grid must be changed anyway */\n free (x);\n free (y);\n for (i = 0; i < n_new_x; i++)\n new_y[i] = 0.0;\n return 0;\n } else {\n for (i = 0; i < n_old_x; i++) {\n if (y[i] > 0.0)\n y[i] = log (y[i]);\n else\n y[i] = -10.E+99; /* this is a little bit cheating, but it works */\n }\n }\n }\n\n switch (linear) {\n case 0: /* spline */\n case 4: /* log spline */\n\n status = spline_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do spline interpolation\\n\");\n fprintf (stderr, \"spline_coeffc() returned status %d\\n\", status);\n return status;\n }\n break;\n\n case 1: /* linear */\n status = linear_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do linear interpolation\\n\");\n fprintf (stderr, \"linear_coeffc() returned status %d\\n\", status);\n return status;\n }\n break;\n\n case 2: /* log */\n tmp_y = (double*)calloc (n_new_x, sizeof (double));\n for (i = 0; i < n_new_x; i++) {\n\n j = 0;\n while (new_x[i] > x[j])\n j++;\n\n if (j > 0)\n j--;\n\n /* logarithmic interpolation (if reasonable) */\n tst1 = fabs (y[j + 1] - y[j]);\n tst2 = (y[j + 1] < y[j] ? y[j + 1] : y[j]);\n if (tst1 <= 0.001 * y[j] || tst2 <= 0) /* linear */\n tmp_y[i] = y[j] + (new_x[i] - x[j]) / (x[j + 1] - x[j]) * (y[j + 1] - y[j]);\n else /* logarithmic */\n tmp_y[i] = exp (log (y[j]) + (new_x[i] - x[j]) / (x[j + 1] - x[j]) * (log (y[j + 1]) - log (y[j])));\n }\n\n /* first interpolate, then copy because then source */\n /* and target may be one and the same */\n for (i = 0; i < n_new_x; i++)\n new_y[i] = (float)tmp_y[i];\n\n free (tmp_y);\n break;\n\n case 3: /* linear mixing ratio */\n fprintf (stderr, \"Error, linear mixing interpolation not possible with arb_wvn.\\n\");\n fprintf (stderr, \"Please use interpolate_density instead. \\n\");\n return -5;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown interpolation type %d\\n\", linear);\n return -6;\n }\n\n switch (linear) {\n case 0: /* spline */\n case 1: /* linear */\n case 4: /* log spline */\n\n for (i = 0; i < n_new_x; i++) {\n\n if (linear == 1)\n status = calc_linear_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1);\n else\n status = calc_splined_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1, a2, a3);\n\n /* this check is new in 0.99-alpha-6; so far, no error */\n /* was reported if a value could not be interpolated */\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by calc_splined_value (%g)\\n\", status, new_x[i]);\n fprintf (stderr, \" %d data points, x[0] = %g, x[%d] = %g\\n\", n_old_x, x[0], n_old_x - 1, x[n_old_x - 1]);\n return status;\n }\n\n new_y[i] = (float)ynew;\n }\n\n free (a0);\n free (a1);\n free (a2);\n free (a3);\n break;\n\n case 2:\n /* no need to do anything because interpolation has already been done above */\n break;\n\n case 3: /* linear mixing ratio */\n fprintf (stderr, \"Error, linear mixing interpolation not possible with arb_wvn.\\n\");\n fprintf (stderr, \"Please use interpolate_density instead. \\n\");\n return -1;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown interpolation type %d\\n\", linear);\n return -7;\n }\n\n if (linear == 4)\n for (i = 0; i < n_new_x; i++)\n new_y[i] = exp (new_y[i]);\n\n free (x);\n free (y);\n\n return 0;\n}\n\n/***************************************************************/\n/* Interpolate from one wavelength grid to another, either */\n/* with natural cubic splines (linear=0) or linear (linear=1); */\n/* if the input is sorted in descending order, descend needs */\n/* to be set to 1. In contrast to arb_wvn(), values that */\n/* cannot be interpolated will be set to 0. */\n/***************************************************************/\n\nint arb_wvn_zero (int n_old_x, float* old_x, float* old_y, int n_new_x, float* new_x, float* new_y, int linear, int descend) {\n int i = 0, status = 0;\n double *a0 = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL;\n double *x = NULL, *y = NULL;\n double ynew = 0;\n\n x = (double*)calloc (n_old_x, sizeof (double));\n y = (double*)calloc (n_old_x, sizeof (double));\n\n if (!descend) {\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[i];\n y[i] = (double)old_y[i];\n }\n } else {\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[n_old_x - 1 - i];\n y[i] = (double)old_y[n_old_x - 1 - i];\n }\n }\n\n switch (linear) {\n case 0:\n status = spline_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do spline interpolation\\n\");\n fprintf (stderr, \"spline_coeffc() returned status %d\\n\", status);\n return status;\n }\n break;\n\n case 1:\n status = linear_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do linear interpolation\\n\");\n fprintf (stderr, \"linear_coeffc() returned status %d\\n\", status);\n return status;\n }\n break;\n\n case 2:\n default:\n fprintf (stderr, \"Error, unknown interpolation type %d\\n\", linear);\n return -1;\n }\n\n switch (linear) {\n case 0:\n case 1:\n for (i = 0; i < n_new_x; i++) {\n\n if (linear == 1)\n status = calc_linear_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1);\n else\n status = calc_splined_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1, a2, a3);\n\n if (status == 0)\n new_y[i] = (float)ynew;\n else\n new_y[i] = 0;\n }\n\n free (a0);\n free (a1);\n free (a2);\n free (a3);\n\n break;\n\n case 2:\n default:\n fprintf (stderr, \"Error, unknown interpolation type %d\\n\", linear);\n return -1;\n }\n\n free (x);\n free (y);\n\n return 0;\n}\n\n/***************************************************************/\n/* Interpolate from one wavelength grid to another, either */\n/* with natural cubic splines (linear=0) or linear (linear=1); */\n/* interpolate only to a selected range of the output grid */\n/* (including n_new_x_lower and n_new_x_upper) */\n/***************************************************************/\n\nint arb_wvn2 (int n_old_x,\n float* old_x,\n float* old_y,\n int n_new_x_lower,\n int n_new_x_upper,\n float* new_x,\n float* new_y,\n int linear) {\n int i = 0, status = 0;\n double *a0 = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL;\n double *x = NULL, *y = NULL;\n double ynew = 0;\n\n x = (double*)calloc (n_old_x, sizeof (double));\n y = (double*)calloc (n_old_x, sizeof (double));\n\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[i];\n y[i] = (double)old_y[i];\n }\n\n if (linear) {\n status = linear_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do linear interpolation\\n\");\n fprintf (stderr, \"linear_coeffc() returned status %d\\n\", status);\n return status;\n }\n } else {\n status = spline_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do spline interpolation\\n\");\n fprintf (stderr, \"spline_coeffc() returned status %d\\n\", status);\n return status;\n }\n }\n\n for (i = n_new_x_lower; i <= n_new_x_upper; i++) {\n\n if (linear)\n status = calc_linear_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1);\n else\n status = calc_splined_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1, a2, a3);\n\n /* this check is new in 0.99-alpha-6; so far, no error */\n /* was reported if a value could not be interpolated */\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by calc_splined_value (%g)\\n\", status, new_x[i]);\n fprintf (stderr, \" %d data points, x[0] = %g, x[%d] = %g\\n\", n_old_x, x[0], n_old_x - 1, x[n_old_x - 1]);\n return status;\n }\n\n new_y[i] = (float)ynew;\n }\n\n free (a0);\n free (a1);\n free (a2);\n free (a3);\n free (x);\n free (y);\n\n return 0;\n}\n\nint arb_wvn2_double (int n_old_x,\n double* old_x,\n double* old_y,\n int n_new_x_lower,\n int n_new_x_upper,\n double* new_x,\n double* new_y,\n int linear) {\n int i = 0, status = 0;\n double *a0 = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL;\n double *x = NULL, *y = NULL;\n double ynew = 0;\n\n x = (double*)calloc (n_old_x, sizeof (double));\n y = (double*)calloc (n_old_x, sizeof (double));\n\n for (i = 0; i < n_old_x; i++) {\n x[i] = (double)old_x[i];\n y[i] = (double)old_y[i];\n }\n\n if (linear) {\n status = linear_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do linear interpolation\\n\");\n fprintf (stderr, \"linear_coeffc() returned status %d\\n\", status);\n return status;\n }\n } else {\n status = spline_coeffc (x, y, n_old_x, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"arb_wvn: sorry cannot do spline interpolation\\n\");\n fprintf (stderr, \"spline_coeffc() returned status %d\\n\", status);\n return status;\n }\n }\n\n for (i = n_new_x_lower; i <= n_new_x_upper; i++) {\n\n if (linear)\n status = calc_linear_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1);\n else\n status = calc_splined_value ((double)new_x[i], &ynew, x, n_old_x, a0, a1, a2, a3);\n\n /* this check is new in 0.99-alpha-6; so far, no error */\n /* was reported if a value could not be interpolated */\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by calc_splined_value (%g)\\n\", status, new_x[i]);\n fprintf (stderr, \" %d data points, x[0] = %g, x[%d] = %g\\n\", n_old_x, x[0], n_old_x - 1, x[n_old_x - 1]);\n return status;\n }\n\n new_y[i] = (double)ynew;\n }\n\n free (a0);\n free (a1);\n free (a2);\n free (a3);\n free (x);\n free (y);\n\n return 0;\n}\n\n/***************************************************/\n/* Distribute the photons according to the weights */\n/* when represenative wavelengths are used */\n/***************************************************/\nint pfraction_reptran (wl_out_struct* wl_out) {\n int i, i_t, i_band;\n float weight_sum;\n\n /* calculate the sum of the weights over all bands */\n weight_sum = 0;\n for (i_t = 0; i_t < wl_out->nlambda_t; i_t++) {\n\n i_band = wl_out->reptran_band_t[i_t];\n\n /* Test if previous _t wavelength was in the same band. */\n /* If yes, go to next _t wavelength since we do not */\n /* want to add the weights for a band multiple times. */\n if (i_t > 0 && (i_band == wl_out->reptran_band_t[i_t - 1]))\n continue;\n\n for (i = 0; i < wl_out->nlambda_in_reptran_band[i_band]; i++)\n weight_sum += wl_out->weight_reptran_band[i_band][i] * wl_out->extra_reptran_r[wl_out->reptran_band[i_band][i]];\n }\n\n /* Calculate the pfraction */\n for (i_t = 0; i_t < wl_out->nlambda_t; i_t++) {\n\n i_band = wl_out->reptran_band_t[i_t];\n\n for (i = 0; i < wl_out->nlambda_in_reptran_band[i_band]; i++)\n wl_out->pfraction[wl_out->reptran_band[i_band][i]] =\n wl_out->weight_reptran_band[i_band][i] * wl_out->extra_reptran_r[wl_out->reptran_band[i_band][i]] / weight_sum;\n }\n\n return 0;\n}\n\n/**************************************************************************************************************/\n/* Calculate results at transmission grid (results_t) from results at representative wavelengths (results_r). */\n/* In case of solar source, the results are weighted with the weights (weight_reptran_band) and the */\n/* extraterrestrial spectrum (extra_reptran_r) in accordance with the approach taken during finding */\n/* the representative wavelengths. */\n/* In case of thermal source, only the weights (weight_reptran_band) are relevant */\n/* (extra_reptran_r was set to 1, it is neutral). */\n/* Set is_variance=1 for weighting variances, and is_variance=0 for weighting other quantities */\n/**************************************************************************************************************/\nint weighting_reptran (const wl_out_struct* wl_out, int is_variance, float* results_r, float* results_t) {\n int i, i_t, i_band;\n float weight;\n float sum;\n float weight_sum;\n\n for (i_t = 0; i_t < wl_out->nlambda_t; i_t++) {\n\n i_band = wl_out->reptran_band_t[i_t];\n\n sum = 0;\n weight_sum = 0;\n\n for (i = 0; i < wl_out->nlambda_in_reptran_band[i_band]; i++) {\n\n weight = wl_out->weight_reptran_band[i_band][i] * wl_out->extra_reptran_r[wl_out->reptran_band[i_band][i]];\n\n if (is_variance)\n sum += results_r[wl_out->reptran_band[i_band][i]] * weight * weight;\n else\n sum += results_r[wl_out->reptran_band[i_band][i]] * weight;\n\n weight_sum += weight;\n }\n\n if (is_variance)\n results_t[i_t] = sum / (weight_sum * weight_sum);\n else\n results_t[i_t] = sum / weight_sum;\n }\n\n return 0;\n}\n\n/************************************************************************************************/\n/* This function returns the name of the file with the representative wavelengths (if i_mol<=0) */\n/* or the name of the corresponding absorption lookup table files (if i_mol>0). */\n/************************************************************************************************/\nint reptran_filename (input_struct input, int i_mol, char* filename) {\n\n int len;\n char* gas = NULL;\n\n if (strlen (input.filename[FN_REPTRAN]) > 0)\n\n strcpy (filename, input.filename[FN_REPTRAN]);\n\n else {\n\n strcpy (filename, input.filename[FN_PATH]);\n strcat (filename, \"correlated_k/reptran/\");\n strcat (filename, \"reptran_\");\n\n if (input.source == SRC_THERMAL)\n strcat (filename, \"thermal_\");\n else if (input.source == SRC_SOLAR)\n strcat (filename, \"solar_\");\n else\n return err_out (\"Error: Unsupported source in reptran_filename().\\n\", -1);\n\n if (input.ck_scheme == CK_REPTRAN) {\n if (input.ck_reptran_option == REPTRAN_OPTION_FINE)\n strcat (filename, \"fine\");\n else if (input.ck_reptran_option == REPTRAN_OPTION_MEDIUM)\n strcat (filename, \"medium\");\n else if (input.ck_reptran_option == REPTRAN_OPTION_COARSE || input.ck_reptran_option == REPTRAN_OPTION_NONE)\n strcat (filename, \"coarse\");\n else\n return err_out (\"Error: Unknown ck_reptran_option in function reptran_filename().\\n\", -1);\n } else if (input.ck_scheme ==\n CK_REPTRAN_CHANNEL) { // reptran filename contains only first part of channel name until first underscore;\n len = strlen (input.ck_reptran_channel) - strlen (strchr (input.ck_reptran_channel, '_'));\n if (\n isdigit (\n input.ck_reptran_channel\n [len -\n 1])) // reptran filename does not contain the last or the last two characters if there are digits (e.g. sentinel3 --> sentinel or sentinel2a --> sentinel)\n len = len - 1;\n else if (isdigit (input.ck_reptran_channel[len - 2]))\n len = len - 2;\n strncat (filename, input.ck_reptran_channel, len);\n }\n }\n\n if (i_mol > 0) {\n\n strcat (filename, \".lookup.\");\n gas = gas_number2string (i_mol);\n strcat (filename, gas);\n if (filename[strlen (filename) - 1] == ' ')\n filename[strlen (filename) - 1] = '\\0'; /* remove upto two space characters from the species names */\n if (filename[strlen (filename) - 1] == ' ')\n filename[strlen (filename) - 1] = '\\0';\n\n free (gas);\n }\n\n strcat (filename, \".cdf\");\n\n return 0;\n}\n\n/**************************************************************/\n/* Interpolate a given profile (x,y) to a new grid xnew; */\n/* data are written to original array y and memory is */\n/* automatically reallocated */\n/* automatically check for negative values */\n/* */\n/* Ulrich Hamann */\n/**************************************************************/\n\nint interpolate_profile (float* x, float** y, int n, float* xnew, int nnew, int interpol_method, int quiet) {\n int status = 0;\n float* tmp = NULL;\n int lc = 0, lc2 = 0, first = 0;\n\n tmp = (float*)calloc (nnew, sizeof (float));\n\n switch (interpol_method) {\n case INTERP_METHOD_SPLINE:\n case INTERP_METHOD_LINEAR:\n case INTERP_METHOD_LOG:\n case INTERP_METHOD_LOG_SPLINE:\n status = arb_wvn (n, x, *y, nnew, xnew, tmp, interpol_method, 1);\n break;\n\n case INTERP_METHOD_LINMIX:\n fprintf (stderr, \"Error, linear mixing ratio not possible with interpolate_profile\\n\");\n fprintf (stderr, \"Please use interpolate_density instead!\\n\");\n return -1;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown interpolation method in interpolate_profile\\n\");\n return -1;\n }\n\n /* testing for negativ density values */\n\n switch (interpol_method) {\n case INTERP_METHOD_SPLINE:\n for (lc = 0; lc < nnew; lc++) {\n if (tmp[lc] < 0.0) {\n if (!quiet) {\n if (first == 0)\n fprintf (stderr, \"*** Warning: In interpolate_density, automatic correction of negative density to 0.0\\n\");\n fprintf (stderr, \"*** Warning: z[%d]= %5.1f, dens[%d]= %12.7e -> dens[%d]= 0.0\\n\", lc, x[lc], lc, tmp[lc], lc);\n tmp[lc] = 0.0;\n first = 1;\n }\n }\n }\n break;\n\n case INTERP_METHOD_LINEAR:\n case INTERP_METHOD_LOG:\n case INTERP_METHOD_LINMIX:\n case INTERP_METHOD_LOG_SPLINE:\n for (lc = 0; lc < nnew; lc++) {\n if (tmp[lc] < 0.0) {\n if (fabs (tmp[lc]) < EPSILON) {\n if (!quiet) {\n fprintf (stderr, \"*** Warning, small negative density detected during interpolate_profile!\\n\");\n fprintf (stderr, \"*** in layer = %d, dens = %e.\\n\", lc, tmp[lc]);\n fprintf (stderr, \"*** This may happen, when dens profiles contain 0.0 values.\\n\");\n fprintf (stderr, \"*** Setting to 0.0 automatically.\\n\");\n }\n tmp[lc] = 0.0;\n } else {\n fprintf (stderr, \"Error, negative density detected in interpolate_profile! lc=%d \\n\", lc);\n for (lc2 = 0; lc2 < nnew; lc2++)\n fprintf (stderr, \" ### dens[%d]=%e\\n\", lc2, tmp[lc2]);\n return -1;\n }\n }\n }\n break;\n default:\n fprintf (stderr, \"Error, unknown interpolation method in interpolate_profile\\n\");\n return -1;\n }\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating profile\\n\", status);\n return status;\n }\n\n free (*y);\n *y = tmp;\n\n return 0;\n}\n\n/**************************************************************/\n/* Interpolate a given profile (x,y) to a new grid xnew; */\n/* data are written to original array y and memory is */\n/* automatically reallocated */\n/* automatically check for negative values */\n/* */\n/* Ulrich Hamann */\n/**************************************************************/\n\nint interpolate_density (float* x,\n float** y,\n int n,\n float* xnew,\n int nnew,\n int interpol_method,\n float* dens_air_old,\n float* dens_air,\n int quiet) {\n int status = 0;\n float* tmp = calloc (nnew, sizeof (float));\n int lc = 0, lc2 = 0;\n int first = 0;\n\n switch (interpol_method) {\n case INTERP_METHOD_SPLINE:\n case INTERP_METHOD_LINEAR:\n case INTERP_METHOD_LOG:\n case INTERP_METHOD_LOG_SPLINE:\n status = arb_wvn (n, x, *y, nnew, xnew, tmp, interpol_method, 1);\n break;\n\n case INTERP_METHOD_LINMIX:\n /* convert from density to mixing ratio */\n for (lc = 0; lc < n; lc++) {\n if (dens_air_old[lc] <= 0.0) {\n fprintf (stderr, \"Error, cannot use linmix interpolation, when air density is <= 0.0\\n\");\n return -1;\n } else\n (*y)[lc] = (*y)[lc] / dens_air_old[lc];\n }\n /*linear interpolation of the mixing ratio*/\n status = arb_wvn (n, x, *y, nnew, xnew, tmp, INTERP_METHOD_LINEAR, 1);\n\n /* convert back to number density */\n for (lc = 0; lc < nnew; lc++)\n tmp[lc] = tmp[lc] * dens_air[lc];\n break;\n default:\n fprintf (stderr, \"Error, unknown interpolation method in interpolate_profile\\n\");\n return -1;\n }\n\n /* testing for negativ density values */\n\n switch (interpol_method) {\n case INTERP_METHOD_SPLINE:\n for (lc = 0; lc < nnew; lc++) {\n if (tmp[lc] < 0.0) {\n if (!quiet) {\n if (first == 0)\n fprintf (stderr, \"*** Warning: In interpolate_density, automatic correction of negative density to 0.0\\n\");\n fprintf (stderr, \"*** Warning: z[%3d]= %5.1f, dens[%3d]= %12.7e -> dens[%3d]= 0.0\\n\", lc, x[lc], lc, tmp[lc], lc);\n tmp[lc] = 0.0;\n first = 1;\n }\n }\n }\n break;\n\n case INTERP_METHOD_LINEAR:\n case INTERP_METHOD_LOG:\n case INTERP_METHOD_LINMIX:\n case INTERP_METHOD_LOG_SPLINE:\n for (lc = 0; lc < nnew; lc++) {\n if (tmp[lc] < 0.0) {\n if (fabs (tmp[lc]) < EPSILON) {\n if (!quiet) {\n fprintf (stderr, \"*** Warning, small negative density detected during interpolate_density!\\n\");\n fprintf (stderr, \"*** in layer = %d, dens = %e, abs(dens)= %e\\n\", lc, tmp[lc], fabs (tmp[lc]));\n fprintf (stderr, \"*** This may happen, when dens profiles contain 0.0 values.\\n\");\n fprintf (stderr, \"*** Setting to 0.0 automatically.\\n\");\n }\n tmp[lc] = 0.0;\n } else {\n fprintf (stderr, \"Error, negative density detected in interpolate_density!, lc=%3d \\n\", lc);\n for (lc2 = 0; lc2 < nnew; lc2++)\n fprintf (stderr, \" ### z[%3d] = %7.2f, dens[%3d] = %e\\n\", lc2, xnew[lc2], lc2, tmp[lc2]);\n return -1;\n }\n }\n }\n break;\n default:\n fprintf (stderr, \"Error, unknown interpolation method in interpolate_profile\\n\");\n return -1;\n }\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating density\\n\", status);\n return status;\n }\n\n free (*y);\n *y = tmp;\n\n return 0;\n}\n\n/*******************************************************************/\n/* Interpolate all given atmospheric profiles to a new z-grid */\n/* profiles are written to original arrays and memory is */\n/* automatically reallocated */\n/*******************************************************************/\n\nint interpolate_atmosphere (float* z,\n float**** p_p,\n float**** p_T,\n float***** p_dens,\n float**** p_Tavg,\n float***** p_densavg,\n int n,\n float* znew,\n int nnew,\n int interpol_method_press,\n int interpol_method_temper,\n int* interpol_method_gas,\n int quiet)\n\n{\n /* n is old number of levels, nnew is new number of levels */\n\n /* \"p_xxx\" here means \"pointer to xxx\" */\n\n int status = 0;\n int lc = -999, i = -999;\n /* float BOLTZMANN = 1.38065e-23; */\n float* dens_air_old = NULL;\n\n /* Pressure */\n status = 0;\n status += interpolate_profile (z, p_p[0][0], n, znew, nnew, interpol_method_press, quiet);\n\n /* Temperature */\n status += interpolate_profile (z, p_T[0][0], n, znew, nnew, interpol_method_temper, quiet);\n\n /* copy old air number density */\n dens_air_old = calloc (n, sizeof (float));\n for (lc = 0; lc < n; lc++)\n dens_air_old[lc] = (*p_dens)[MOL_AIR][0][0][lc];\n\n /* Air */\n /* this is not 100% consistent with interpolation of p and T */\n status += interpolate_profile (z, &((*p_dens)[MOL_AIR][0][0]), n, znew, nnew, interpol_method_gas[MOL_AIR], quiet);\n\n /* /\\* determine air number density from pressure and temperature *\\/ */\n /* free((*p_dens)[MOL_AIR]); */\n /* (*p_dens)[MOL_AIR] = calloc (nnew, sizeof(float)); */\n /* for (lc=0; lcstart;\n iv = 0;\n\n if (wl_inp->start != wl_inp->end) { /* non-monochromatic calculation */\n while (lambda < wl_inp->end) {\n\n lambdanew = lambda;\n\n if (lambda < 121.0) {\n lambdanew += 1.0;\n if (lambdanew > 121.0) {\n lambda = 121.0;\n lambdanew = 121.0;\n }\n }\n\n /* Lyman alpha */\n if (lambda >= 121.0 && lambda < 122.0)\n lambdanew += 0.01;\n\n /* Schumann-Runge continuum */\n if (lambda >= 122.0 && lambda < 130) {\n lambdanew += 0.1;\n if (lambdanew >= 1.0E7 / 57000.0)\n lambda += 0.1;\n }\n\n if (lambda >= 130.0 && lambda < 1.0E7 / 57000.0) {\n lambdanew += 0.5;\n if (lambdanew >= 1.0E7 / 57000.0)\n lambda += 0.5;\n }\n\n /* Schumann-Runge bands */\n if (lambda <= 1.0E7 / 49000.5 && lambda >= 1.0E7 / 57000.0) {\n if (firstsr) {\n if (iv > 0)\n lambdanew = 1.0E7 / 57000.0;\n else\n lambdanew = 1.0E7 / (floor (2.0 * 1.0E7 / lambda) / 2.0);\n\n firstsr = 0;\n } else\n lambdanew = 1.0E7 / (1.0E7 / lambda - 0.5);\n }\n\n /* Herzberg continuum, Hartley-Huggins bands */\n if (lambda > 1.0E7 / 49000.5 && lambda < 350.0) {\n if (firsthz) {\n lambdanew = ceil (2.0 * lambda) / 2.0;\n if (lambdanew == lambda)\n lambdanew += 0.5;\n firsthz = 0;\n } else\n lambdanew += 0.5;\n }\n\n if (lambda >= 350.0)\n lambdanew += 1.0;\n\n lambda = lambdanew;\n\n iv++;\n }\n }\n\n firstsr = 1;\n firsthz = 1;\n wl_out->nlambda_t = iv + 1;\n wl_out->lambda_t = (float*)calloc (wl_out->nlambda_t, sizeof (float));\n\n /* Set wavelengths for radiative transfer calculation */\n lambda = wl_inp->start;\n\n for (iv = 0; iv < wl_out->nlambda_t; iv++) {\n wl_out->lambda_t[iv] = lambda;\n lambdanew = lambda;\n\n if (lambda < 121.0) {\n lambdanew += 1.0;\n if (lambdanew > 121.0) {\n lambda = 121.0;\n lambdanew = 121.0;\n }\n }\n\n /* Lyman alpha */\n if (lambda >= 121.0 && lambda < 122.0)\n lambdanew += 0.01;\n\n /* Schumann-Runge continuum */\n if (lambda >= 122.0 && lambda < 130) {\n lambdanew += 0.1;\n if (lambdanew >= 1.0E7 / 57000.0)\n lambda += 0.1;\n }\n\n if (lambda >= 130.0 && lambda < 1.0E7 / 57000.0) {\n lambdanew += 0.5;\n if (lambdanew >= 1.0E7 / 57000.0)\n lambda += 0.5;\n }\n\n /* Schumann-Runge bands */\n if (lambda <= 1.0E7 / 49000.5 && lambda >= 1.0E7 / 57000.0) {\n if (firstsr) {\n if (iv > 0)\n lambdanew = 1.0E7 / 57000.0;\n else { /* start of spectrum */\n lambdanew = 1.0E7 / (floor (2.0 * 1.0E7 / lambda) / 2.0);\n if (lambdanew == lambda) /* avoid that we use the same wavelength twice */\n lambdanew = 1.0E7 / (1.0E7 / lambda - 0.5);\n }\n\n firstsr = 0;\n } else\n lambdanew = 1.0E7 / (1.0E7 / lambda - 0.5);\n }\n\n /* Herzberg continuum, Hartley-Huggins bands */\n if (lambda > 1.0E7 / 49000.5 && lambda < 350.0) {\n if (firsthz) {\n lambdanew = ceil (2.0 * lambda) / 2.0;\n if (lambdanew == lambda)\n lambdanew += 0.5;\n firsthz = 0;\n } else\n lambdanew += 0.5;\n }\n\n if (lambda >= 350.0)\n lambdanew += 1.0;\n\n lambda = lambdanew;\n }\n\n return 0;\n}\n\nstatic int set_raman_wl_grid (wl_inp_struct* wl_inp, wl_out_struct* wl_out, char* filename, int quiet) {\n int iv = 0, i = 0;\n int nlambda = 0, status = 0;\n int ivs = 0, ive = 0; /* Start and end indices */\n float *tmp_lambda = NULL, *tmp_fbeam = NULL;\n\n /* read extraterrestrial irradiance */\n status = read_2c_file_float (filename, &tmp_lambda, &tmp_fbeam, &nlambda);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d reading %s\\n\", status, filename);\n return status;\n }\n\n wl_out->nlambda_t = 0;\n for (iv = 0; iv < nlambda; iv++) {\n if (tmp_lambda[iv] < wl_inp->start)\n ivs = iv + 1;\n if (tmp_lambda[iv] < wl_inp->end)\n ive = iv + 1;\n if (tmp_lambda[iv] >= wl_inp->start && tmp_lambda[iv] <= wl_inp->end) {\n wl_out->nlambda_t++;\n }\n }\n wl_out->nlambda_t = ive - ivs + 1;\n wl_out->lambda_t = (float*)calloc (wl_out->nlambda_t, sizeof (float));\n i = 0;\n for (iv = ivs; iv <= ive; iv++) {\n wl_out->lambda_t[i] = tmp_lambda[iv];\n i++;\n }\n\n free (tmp_lambda);\n free (tmp_fbeam);\n\n return 0;\n}\n\nstatic int find_raman_closest_wl_in_solar_file (float* wls, float* wle, char* filename, int quiet) {\n int iv = 0;\n int nlambda = 0, status = 0;\n int ivs = 0, ive = 0; /* Start and end indices */\n float *tmp_lambda = NULL, *tmp_fbeam = NULL;\n\n /* read extraterrestrial irradiance */\n status = read_2c_file_float (filename, &tmp_lambda, &tmp_fbeam, &nlambda);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d reading %s\\n\", status, filename);\n return status;\n }\n\n for (iv = 0; iv < nlambda; iv++) {\n if (tmp_lambda[iv] < *wls)\n ivs = iv;\n if (tmp_lambda[iv] < *wle)\n ive = iv + 1;\n }\n\n *wls = tmp_lambda[ivs];\n *wle = tmp_lambda[ive];\n\n free (tmp_lambda);\n free (tmp_fbeam);\n\n return 0;\n}\n\n/******************************************************************/\n/* Define the internal wavelength grid for the radiative transfer */\n/* calculation. LOWTRAN requires much less detail, in */\n/* particular below 300nm */\n/******************************************************************/\n\nstatic int set_transmittance_wl_grid_lowtran (wl_inp_struct* wl_inp, wl_out_struct* wl_out, int quiet) {\n int iv = 0;\n float lambda = 0.0, wvn_step_t = 0.0;\n\n /* Determine number of wavelengths needed for radiative transfer calculation */\n lambda = wl_inp->start;\n iv = 1;\n while (lambda < wl_inp->end) {\n\n if (lambda < 350.0)\n wvn_step_t = 0.5;\n else\n wvn_step_t = 1.0;\n\n lambda += wvn_step_t;\n iv++;\n }\n\n wl_out->nlambda_t = iv;\n wl_out->lambda_t = (float*)calloc (wl_out->nlambda_t, sizeof (float));\n\n /* Set wavelengths for radiative transfer calculation */\n lambda = wl_inp->start;\n\n for (iv = 0; iv < wl_out->nlambda_t; iv++) {\n wl_out->lambda_t[iv] = lambda;\n\n if (lambda < 350.0)\n wvn_step_t = 0.5;\n else\n wvn_step_t = 1.0;\n\n lambda += wvn_step_t;\n }\n\n return 0;\n}\n\n/***********************************************************************************/\n/* Define the transmittance wavelength grid when using representative wavelengths. */\n/* The transmittance wavelengths are the center wavelengths of the bands. */\n/***********************************************************************************/\nstatic int\nset_transmittance_wl_grid_reptran (input_struct input, float** lambda_lower, float** lambda_upper, wl_out_struct* wl_out) {\n\n#if HAVE_NETCDF4\n int status = 0;\n int nbands = 0;\n int max_len_band_name = 0;\n\n double* wvlmin;\n double* wvlmax;\n\n char** band_name;\n\n char cdf_filename[FILENAME_MAX] = \"\";\n int ncid = 0;\n\n int idd_nbands = 0;\n int idd_max_len_band_name = 0;\n\n int id_wvlmin = 0;\n int id_wvlmax = 0;\n int id_band_name = 0;\n\n size_t dimlen = 0;\n\n int i_band;\n int i_band_start = -1;\n int i_band_end = -1;\n int it;\n\n size_t start[] = {0, 0};\n size_t count[] = {1, 1};\n\n /* determine filename with the parameterization */\n status = reptran_filename (input, -1, cdf_filename);\n\n if (input.verbose)\n fprintf (stderr, \" reading bands from %s.\\n\", cdf_filename);\n\n /* open netcdf file and read the minimum and maximum wavelengths of the bands */\n status = nc_open (cdf_filename, NC_NOWRITE, &ncid);\n if (status == NC_NOERR) {\n\n status = NC_NOERR;\n status += nc_inq_dimid (ncid, \"nbands\", &idd_nbands);\n status += nc_inq_dimid (ncid, \"max_len_band_name\", &idd_max_len_band_name);\n\n status += nc_inq_dimlen (ncid, idd_nbands, &dimlen);\n nbands = dimlen;\n status += nc_inq_dimlen (ncid, idd_max_len_band_name, &dimlen);\n max_len_band_name = dimlen;\n\n status += nc_inq_varid (ncid, \"wvlmin\", &id_wvlmin);\n status += nc_inq_varid (ncid, \"wvlmax\", &id_wvlmax);\n\n wvlmin = (double*)calloc (nbands, sizeof (double));\n wvlmax = (double*)calloc (nbands, sizeof (double));\n\n if (status != NC_NOERR)\n return err_out (\"Error %d while reading the representative wavelengths file.\\n\", status);\n\n status += nc_get_var_double (ncid, id_wvlmin, wvlmin);\n status += nc_get_var_double (ncid, id_wvlmax, wvlmax);\n\n status += nc_inq_varid (ncid, \"band_name\", &id_band_name);\n\n ASCII_calloc_char (&band_name, nbands, max_len_band_name);\n\n count[1] = max_len_band_name;\n for (i_band = 0; i_band < nbands; i_band++) {\n start[0] = i_band;\n status += nc_get_vara_text (ncid, id_band_name, start, count, band_name[i_band]);\n }\n\n if (status != NC_NOERR)\n return err_out (\"Error %d while reading the representative wavelengths file.\\n\", status);\n\n nc_close (ncid);\n\n } else {\n if (status) {\n fprintf (stderr, \"**********************************************************************************\\n\");\n fprintf (stderr, \"*Error: Data files for REPTRAN not found in directory data/correlated_k/reptran. *'\\n\");\n fprintf (stderr, \"* Please check whether you have downloaded the required REPTRAN data files *\\n\");\n fprintf (stderr, \"* from http://www.libradtran.org/doku.php?id=download and unzipped the data*\\n\");\n fprintf (stderr, \"* in the libRadtran folder. *\\n\");\n fprintf (stderr, \"**********************************************************************************\\n\");\n }\n return err_out (\"Error %d while opening the representative wavelengths file.\\n\", status);\n }\n\n if (wl_out->type == WLGRID_UVSPEC) {\n\n if (input.ck_scheme == CK_REPTRAN_CHANNEL) { /* channel is searched here in the netcdf file */\n\n for (i_band = 0; i_band < nbands; i_band++)\n\n if (strncasecmp (input.ck_reptran_channel, band_name[i_band], strlen (input.ck_reptran_channel)) == 0) {\n\n i_band_start = i_band;\n i_band_end = i_band;\n\n /* setting the wavelength range to the wavelength range required for selected channel */\n wl_out->start = wvlmin[i_band];\n wl_out->end = wvlmax[i_band];\n }\n\n if (i_band_start < 0 || i_band_end < 0)\n return err_out (\"Error: Channel not found in reptran_file.\\n\", -1);\n\n } else if (input.wl.start > 0) {\n\n /* select bands required for user-specified wavelength range */\n i_band_start = nbands;\n for (i_band = nbands - 1; i_band >= 0; i_band--)\n if (input.wl.start < (float)wvlmax[i_band])\n i_band_start = i_band;\n\n i_band_end = -1;\n for (i_band = 0; i_band < nbands; i_band++)\n if (input.wl.end > (float)wvlmin[i_band])\n i_band_end = i_band;\n\n if (input.wl.start == input.wl.end &&\n i_band_start >\n i_band_end) /* special case when a) only a single wavelength was specified and b) this wavelength is a band boundary */\n i_band_end = i_band_start;\n\n if (i_band_start == nbands || i_band_end == -1 || input.wl.end > (float)wvlmax[nbands - 1] ||\n input.wl.start < (float)wvlmin[0]) {\n fprintf (stderr, \"*****************************************************************\\n\");\n fprintf (stderr, \"Error: User-specified wavelength range not covered by REPTRAN.\\n\");\n fprintf (stderr, \" Wavelength range covered by REPTRAN is from %f nm to %f nm\\n\", wvlmin[0], wvlmax[nbands - 1]);\n fprintf (stderr, \"*****************************************************************\\n\");\n return err_out (\"Error: User-specified wavelength range not covered by the representative wavelengths parameterization.\\n\",\n -1);\n }\n } else if (input.wl.start_index > 0) {\n\n i_band_start = input.wl.start_index - 1;\n i_band_end = input.wl.end_index - 1;\n\n if (i_band_end > nbands - 1)\n return err_out (\"Error: Wavelength index too large for activated representative wavelengths parameterization.\\n\", -1);\n\n wl_out->start = wvlmin[i_band_start];\n wl_out->end = wvlmax[i_band_end];\n\n } else {\n\n fprintf (stderr, \"***************************************************************************************\\n\");\n fprintf (stderr, \"Error: No wavelength range selected. Please use options wavelength or wavelength_index.\\n\");\n fprintf (stderr, \"***************************************************************************************\\n\");\n return err_out (\"Error: No wavelength range selected.\\n\", -1);\n\n /*\n\ti_band_start=0;\n\ti_band_end=nbands-1;\n\twl_out->start=wvlmin[i_band_start];\n\twl_out->end=wvlmax[i_band_end];\n */\n }\n\n if (wl_out->start < 1.0e7 / 49000.5) {\n fprintf (stderr, \"**************************************************************************************\\n\");\n fprintf (stderr, \"Warning: The wavelength resolution of REPTRAN at wavelength < 204.1nm might be too low\\n\");\n fprintf (stderr, \" for fully resolving the spectral absorption features.\\n\");\n fprintf (stderr, \" Use 'mol_abs_param crs' if you need higher spectral resolution.\\n\");\n fprintf (stderr, \"**************************************************************************************\\n\");\n }\n\n wl_out->nlambda_t = i_band_end - i_band_start + 1;\n wl_out->lambda_t = (float*)calloc (wl_out->nlambda_t, sizeof (float));\n\n *lambda_lower = (float*)calloc (wl_out->nlambda_t, sizeof (float));\n *lambda_upper = (float*)calloc (wl_out->nlambda_t, sizeof (float));\n\n wl_out->reptran_band_t = (int*)calloc (wl_out->nlambda_t, sizeof (int));\n\n for (i_band = i_band_start; i_band <= i_band_end; i_band++) {\n\n wl_out->lambda_t[i_band - i_band_start] = (wvlmin[i_band] + wvlmax[i_band]) / 2;\n\n (*lambda_lower)[i_band - i_band_start] = wvlmin[i_band];\n (*lambda_upper)[i_band - i_band_start] = wvlmax[i_band];\n wl_out->reptran_band_t[i_band - i_band_start] = i_band;\n }\n\n } else if (wl_out->type == WLGRID_USER) {\n\n if (input.wl.start > 0)\n return err_out (\"Error: Combination of 'mol_abs_param reptran' and 'wavelength_grid_file' with 'wavelength' not supported.\\n\",\n -1);\n\n /* only need to find suitable bands for the transmission wavelengths given by the user */\n wl_out->reptran_band_t = (int*)calloc (wl_out->nlambda_t, sizeof (int));\n for (it = 0; it < wl_out->nlambda_t; it++) {\n\n wl_out->reptran_band_t[it] = -1;\n\n for (i_band = 0; i_band < nbands; i_band++)\n if (wl_out->lambda_t[it] >= wvlmin[i_band] && wl_out->lambda_t[it] < wvlmax[i_band])\n wl_out->reptran_band_t[it] = i_band;\n\n if (wl_out->reptran_band_t[it] == -1)\n return err_out (\n \"Error: Wavelengths in wavelength_grid_file not covered by range of representative wavelengths parameterization.\\n\",\n -1);\n }\n }\n\n if (input.verbose)\n fprintf (stderr, \" %d wavelengths set by set_transmittance_wl_grid_reptran().\\n\", wl_out->nlambda_t);\n\n ASCII_free_char (band_name, nbands);\n free (wvlmin);\n free (wvlmax);\n\n return 0;\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any netCDF option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/*****************************************************************************/\n/* Define the rte wavelength grid when using the representative wavelengths. */\n/*****************************************************************************/\nstatic int set_rte_wl_grid_reptran (input_struct input, output_struct* output) {\n#if HAVE_NETCDF4\n\n int status = 0;\n int nbands = 0;\n int nwvl = 0;\n int max_nwvl_in_band = 0;\n\n char cdf_filename[FILENAME_MAX] = \"\";\n int ncid = 0;\n\n int idd_nwvl = 0;\n int idd_nbands = 0;\n int idd_max_nwvl_in_band = 0;\n int id_wvl = 0;\n int id_iwvl = 0;\n int id_weight_wvl = 0;\n int id_nwvl_in_band = 0;\n int id_extra = 0;\n int id_wvl_integral = 0;\n\n size_t dimlen = 0;\n\n double* wvl;\n int* wvl_active;\n int n_active;\n int i_wvl;\n int* index_in_lambda_r;\n double* extra;\n\n int no_extra;\n\n int i_band;\n int i;\n\n int* i_wvl_tmp;\n double* weight_wvl_tmp;\n\n int isp;\n int add_tau_wvl_to_lambda_r;\n\n double wvl_min_tmp;\n double wvl_max_tmp;\n double tau_wvl;\n\n /* determine file with the parameterization */\n status = reptran_filename (input, -1, cdf_filename);\n\n /* open this file for reading */\n status = nc_open (cdf_filename, NC_NOWRITE, &ncid);\n if (status == NC_NOERR) {\n\n /* read dimensions */\n status = 0;\n status += nc_inq_dimid (ncid, \"nwvl\", &idd_nwvl);\n status += nc_inq_dimid (ncid, \"nbands\", &idd_nbands);\n status += nc_inq_dimid (ncid, \"max_nwvl_in_band\", &idd_max_nwvl_in_band);\n\n status += nc_inq_dimlen (ncid, idd_nwvl, &dimlen);\n nwvl = dimlen;\n status += nc_inq_dimlen (ncid, idd_nbands, &dimlen);\n nbands = dimlen;\n status += nc_inq_dimlen (ncid, idd_max_nwvl_in_band, &dimlen);\n max_nwvl_in_band = dimlen;\n\n if (status != 0) {\n fprintf (stderr, \"Error %d reading dimensions from %s\\n\", status, cdf_filename);\n return status;\n }\n\n status = nc_inq_varid (ncid, \"wvl\", &id_wvl);\n wvl = (double*)calloc (nwvl, sizeof (double));\n status = nc_get_var_double (ncid, id_wvl, wvl);\n\n status = nc_inq_varid (ncid, \"nwvl_in_band\", &id_nwvl_in_band);\n output->wl.nlambda_in_reptran_band = (int*)calloc (nbands, sizeof (int));\n status = nc_get_var_int (ncid, id_nwvl_in_band, (output->wl.nlambda_in_reptran_band));\n\n status = nc_inq_varid (ncid, \"iwvl\", &id_iwvl);\n status = nc_inq_varid (ncid, \"iwvl_weight\", &id_weight_wvl);\n status = ASCII_calloc_int (&(output->wl.reptran_band), nbands, max_nwvl_in_band);\n status = ASCII_calloc_double (&(output->wl.weight_reptran_band), nbands, max_nwvl_in_band);\n i_wvl_tmp = (int*)calloc (nbands * max_nwvl_in_band, sizeof (int));\n weight_wvl_tmp = (double*)calloc (nbands * max_nwvl_in_band, sizeof (double));\n status = nc_get_var_int (ncid, id_iwvl, i_wvl_tmp);\n status = nc_get_var_double (ncid, id_weight_wvl, weight_wvl_tmp);\n for (i_band = 0; i_band < nbands; i_band++) {\n for (i_wvl = 0; i_wvl < max_nwvl_in_band; i_wvl++) {\n output->wl.reptran_band[i_band][i_wvl] = i_wvl_tmp[(i_band + i_wvl * nbands)];\n output->wl.weight_reptran_band[i_band][i_wvl] = weight_wvl_tmp[(i_band + i_wvl * nbands)];\n }\n }\n free (i_wvl_tmp);\n free (weight_wvl_tmp);\n\n status = nc_inq_varid (ncid, \"extra\", &id_extra);\n if (status != 0) {\n no_extra = 1; /* representative wavelengths for thermal calculations */\n if (input.source != SRC_THERMAL) {\n fprintf (stderr, \"Error: Representative wavelengths file %s was created for\\n\", cdf_filename);\n fprintf (stderr, \" thermal source, but in the input file 'source' is not set to 'thermal'.\");\n return -4;\n }\n } else {\n no_extra = 0; /* representative wavelengths for solar calculations */\n if (input.source != SRC_SOLAR) {\n fprintf (stderr, \"Error: Representative wavelengths file %s was created for\\n\", cdf_filename);\n fprintf (stderr, \" solar source, but in the input file 'source' is not set to 'solar'.\");\n return -5;\n }\n }\n extra = (double*)calloc (nwvl, sizeof (double));\n\n if (no_extra) {\n status = 0;\n for (i_wvl = 0; i_wvl < nwvl; i_wvl++)\n extra[i_wvl] = 1; /* In case of thermal calculations extra is set to 1 */\n } else\n status = nc_get_var_double (ncid, id_extra, extra);\n\n status += nc_inq_varid (ncid, \"wvl_integral\", &id_wvl_integral);\n output->wl.width_of_reptran_band = (double*)calloc (nbands, sizeof (double));\n status += nc_get_var_double (ncid, id_wvl_integral, output->wl.width_of_reptran_band);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d reading %s\\n\", status, cdf_filename);\n return status;\n }\n\n nc_close (ncid);\n\n } else\n return status;\n\n /* find required ('active') representative wavelengths */\n wvl_active = (int*)calloc (nwvl, sizeof (int));\n for (i = 0; i < nwvl; i++)\n wvl_active[i] = 0;\n\n /* go through transmission wavelength grid */\n for (i_wvl = 0; i_wvl < output->wl.nlambda_t; i_wvl++)\n for (i = 0; i < output->wl.nlambda_in_reptran_band[output->wl.reptran_band_t[i_wvl]]; i++)\n wvl_active[output->wl.reptran_band[output->wl.reptran_band_t[i_wvl]][i] - 1] = 1;\n\n /* count active wavelengths */\n n_active = 0;\n for (i_wvl = 0; i_wvl < nwvl; i_wvl++)\n if (wvl_active[i_wvl] == 1)\n n_active++;\n\n /* find out wavelength for tau scaling*/\n tau_wvl = -1;\n\n if (input.aer.modify[MODIFY_VAR_TAU550][MODIFY_TYPE_SET] >= 0) {\n if (input.aer.tau_wvl_lambda > 0)\n tau_wvl = input.aer.tau_wvl_lambda;\n else\n tau_wvl = 550;\n }\n\n for (isp = 0; isp < input.n_caoth; isp++) {\n if (input.caoth[isp].modify[MODIFY_VAR_TAU550][MODIFY_TYPE_SET] >= 0)\n tau_wvl = 550;\n }\n\n /* find out if tau_wvl needs to be added to wavelength grid */\n add_tau_wvl_to_lambda_r = 0;\n if (tau_wvl > 0) {\n\n /* find out wavelength range */\n wvl_min_tmp = 1e12;\n wvl_max_tmp = 0;\n for (i_wvl = 0; i_wvl < nwvl; i_wvl++) {\n if (wvl_active[i_wvl] == 1) {\n if (wvl_min_tmp > wvl[i_wvl])\n wvl_min_tmp = wvl[i_wvl];\n if (wvl_max_tmp < wvl[i_wvl])\n wvl_max_tmp = wvl[i_wvl];\n }\n }\n\n /* check if tau_wvl is outside the wavelength range */\n if (wvl_max_tmp < tau_wvl || wvl_min_tmp > tau_wvl) {\n add_tau_wvl_to_lambda_r = 1;\n n_active += 1;\n }\n }\n\n /* allocate required arrays */\n output->wl.nlambda_r = n_active;\n output->wl.lambda_r = (float*)calloc (output->wl.nlambda_r, sizeof (float));\n output->wl.iwvl_in_reptran_file_r = (int*)calloc (output->wl.nlambda_r, sizeof (int));\n output->wl.extra_reptran_r = (float*)calloc (output->wl.nlambda_r, sizeof (float));\n output->wl.wvnmlo_r = (float*)calloc (output->wl.nlambda_r, sizeof (float));\n output->wl.wvnmhi_r = (float*)calloc (output->wl.nlambda_r, sizeof (float));\n index_in_lambda_r = (int*)calloc (nwvl, sizeof (int));\n\n /* reset counter */\n n_active = 0;\n\n /* if tau_wvl needs to be added before the representative wavelengths */\n if (add_tau_wvl_to_lambda_r == 1 && wvl_min_tmp > tau_wvl) {\n output->wl.lambda_r[n_active] = tau_wvl;\n output->wl.iwvl_in_reptran_file_r[n_active] = -1;\n output->wl.extra_reptran_r[n_active] = 0;\n n_active++;\n if (input.verbose)\n fprintf (stderr, \" Added the hidden wavelength %f nm at which the aerosol/cloud amount is scaled.\\n\", tau_wvl);\n }\n\n /* add the required representative wavelengths */\n for (i_wvl = 0; i_wvl < nwvl; i_wvl++) {\n if (wvl_active[i_wvl] == 1) {\n output->wl.lambda_r[n_active] = wvl[i_wvl];\n output->wl.iwvl_in_reptran_file_r[n_active] = i_wvl;\n output->wl.extra_reptran_r[n_active] = extra[i_wvl];\n index_in_lambda_r[i_wvl] = n_active;\n n_active++;\n } else\n index_in_lambda_r[i_wvl] = -1;\n }\n\n /* if tau_wvl needs to be added after the representative wavelengths */\n if (add_tau_wvl_to_lambda_r == 1 && wvl_max_tmp < tau_wvl) {\n output->wl.lambda_r[n_active] = tau_wvl;\n output->wl.iwvl_in_reptran_file_r[n_active] = -1;\n output->wl.extra_reptran_r[n_active] = 0;\n n_active++;\n if (input.verbose)\n fprintf (stderr, \" Added the hidden wavelength %f nm at which the aerosol amount is scaled.\\n\", tau_wvl);\n }\n\n /* calculate wavenumbers according to given bandwidth */\n if (output->bandwidth_unit == UNIT_PER_CM_1) {\n for (i_wvl = 0; i_wvl < n_active; i_wvl++) {\n output->wl.wvnmlo_r[i_wvl] = 1.0E7 / output->wl.lambda_r[i_wvl] - input.bandwidth / 2.0;\n output->wl.wvnmhi_r[i_wvl] = output->wl.wvnmlo_r[i_wvl] + input.bandwidth;\n }\n } else if (output->bandwidth_unit == UNIT_PER_NM) {\n for (i_wvl = 0; i_wvl < n_active; i_wvl++) {\n output->wl.wvnmlo_r[i_wvl] = 1.0E7 / (output->wl.lambda_r[i_wvl] + input.bandwidth / 2.0);\n output->wl.wvnmhi_r[i_wvl] = 1.0E7 / (output->wl.lambda_r[i_wvl] - input.bandwidth / 2.0);\n }\n } else {\n fprintf (stderr, \"Error, unsupported bandwidth_unit %d in while setting up rte_wavelength_grid.\\n\", output->bandwidth_unit);\n return -1;\n }\n\n /* change reptran_band from pointing to wvl (netcdf variable) to pointing to lambda_r (internal grid) */\n for (i_band = 0; i_band < nbands; i_band++)\n for (i = 0; i < output->wl.nlambda_in_reptran_band[i_band]; i++)\n if (output->wl.reptran_band[i_band][i] > -1)\n output->wl.reptran_band[i_band][i] = index_in_lambda_r[output->wl.reptran_band[i_band][i] - 1];\n\n if (input.verbose)\n fprintf (stderr, \" %d wavelengths set by set_rte_wl_grid_reptran().\\n\", output->wl.nlambda_r);\n\n free (wvl);\n free (wvl_active);\n free (extra);\n free (index_in_lambda_r);\n\n return 0;\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any netCDF option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/**************************************************************/\n/* Convolve the spectrum with a user-defined slit function */\n/**************************************************************/\n\nint convolve (input_struct input, output_struct* output) {\n int is = 0, js = 0, ks = 0, iv = 0, iu = 0, ip = 0, ic = 0, j = 0, lev = 0;\n int status = 0;\n double* x_data = NULL;\n\n int n_slit = 0;\n double *x_slit = NULL, *y_slit = NULL;\n int nstokes = 0;\n\n nstokes = input.rte.mc.nstokes;\n\n /* read slit function from file */\n status = read_2c_file (input.filename[FN_SLITFUNCTION], &x_slit, &y_slit, &n_slit);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d reading file %s\\n\", status, input.filename[FN_SLITFUNCTION]);\n return status;\n }\n\n x_data = calloc (output->wl.nlambda_h, sizeof (double));\n\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n x_data[iv] = (double)output->wl.lambda_h[iv];\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* Convolve up_flux and down_flux*/\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n status = cnvlv (x_data, output->up_flux[lev][is], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting up_flux\\n\", status);\n return status;\n }\n\n status = cnvlv (x_data, output->down_flux[lev][is], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting down_flux\\n\", status);\n return status;\n }\n\n /* Convolve up_rad and down_rad*/\n for (j = 0; j < input.rte.nphi; j++) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = cnvlv (x_data, output->down_rad[lev][j][iu][is], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting down_rad\\n\", status);\n return status;\n }\n\n status = cnvlv (x_data, output->up_rad[lev][j][iu][is], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting up_rad\\n\", status);\n return status;\n }\n }\n }\n }\n }\n } else {\n\n /* convolve albmed and trnmed */\n\n /* albmed */\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = cnvlv (x_data, output->albmed[iu], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting albmed\\n\", status);\n return status;\n }\n }\n\n /* trnmed */\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = cnvlv (x_data, output->trnmed[iu], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting trnmed\\n\", status);\n return status;\n }\n }\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* Convolve rfldir, rfldn, flup and uavg for all cases */\n\n /* rfldir */\n status = cnvlv (x_data, output->rfldir[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting rfldir\\n\", status);\n return status;\n }\n\n /* rfldn */\n status = cnvlv (x_data, output->rfldn[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting rfldn\\n\", status);\n return status;\n }\n\n /* flup */\n status = cnvlv (x_data, output->flup[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting flup\\n\", status);\n return status;\n }\n\n /* uavg */\n status = cnvlv (x_data, output->uavg[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavg\\n\", status);\n return status;\n }\n\n /* 3D fields */\n if (output->mc.sample.passback3D)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n /* rfldir3d */\n status = cnvlv (x_data, output->rfldir3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting rfldir3d\\n\", status);\n return status;\n }\n\n /* rfldn3d */\n status = cnvlv (x_data, output->rfldn3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting rfldn3d\\n\", status);\n return status;\n }\n\n /* flup3d */\n status = cnvlv (x_data, output->flup3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting flup3d\\n\", status);\n return status;\n }\n\n /* uavgso3d */\n status = cnvlv (x_data, output->uavgso3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgso3d\\n\", status);\n return status;\n }\n\n /* uavgdn3d */\n status = cnvlv (x_data, output->uavgdn3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgdn3d\\n\", status);\n return status;\n }\n\n /* uavgup3d */\n status = cnvlv (x_data, output->uavgup3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgup3d\\n\", status);\n return status;\n }\n\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n /* fl3d_is */\n status = cnvlv (x_data, output->fl3d_is[lev][is][js][ic], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting fl3d_is\\n\", status);\n return status;\n }\n }\n\n for (ip = 0; ip < nstokes; ip++) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n /* radiance3d */\n status = cnvlv (x_data, output->radiance3d[lev][is][js][ip][ic], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting radiance3d\\n\", status);\n return status;\n }\n }\n }\n\n /* absback3d */\n if (input.rte.mc.backward.absorption) {\n status = cnvlv (x_data, output->absback3d[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting absback3d\\n\", status);\n return status;\n }\n }\n\n /* variances */\n if (input.rte.mc.std) {\n\n /* rfldir3d_var */\n status = cnvlv (x_data, output->rfldir3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting rfldir3d_var\\n\", status);\n return status;\n }\n\n /* rfldn3d_var */\n status = cnvlv (x_data, output->rfldn3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting rfldn3d_var\\n\", status);\n return status;\n }\n\n /* flup3d_var */\n status = cnvlv (x_data, output->flup3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting flup3d_var\\n\", status);\n return status;\n }\n\n /* uavgso3d_var */\n status = cnvlv (x_data, output->uavgso3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgso3d_var\\n\", status);\n return status;\n }\n\n /* uavgdn3d_var */\n status = cnvlv (x_data, output->uavgdn3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgdn3d_var\\n\", status);\n return status;\n }\n\n /* uavgup3d_var */\n status = cnvlv (x_data, output->uavgup3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgup3d_var\\n\", status);\n return status;\n }\n\n for (ip = 0; ip < nstokes; ip++) {\n\n /* radiance3d_var */\n status = cnvlv (x_data, output->radiance3d_var[lev][is][js][ip], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting radiance3d_var\\n\", status);\n return status;\n }\n }\n\n /* absback3d_var */\n if (input.rte.mc.backward.absorption) {\n status = cnvlv (x_data, output->absback3d_var[lev][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting absback3d_var\\n\", status);\n return status;\n }\n }\n }\n }\n\n if (input.rte.solver != SOLVER_FTWOSTR) {\n\n /* Convolve uavgso, uavgdn, uavgup */\n\n /* uavgso */\n status = cnvlv (x_data, output->uavgso[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgso\\n\", status);\n return status;\n }\n\n /* uavgdn */\n status = cnvlv (x_data, output->uavgdn[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgdn\\n\", status);\n return status;\n }\n\n /* uavgup */\n status = cnvlv (x_data, output->uavgup[lev], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting uavgup\\n\", status);\n return status;\n }\n\n /* Convolve u0u */\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = cnvlv (x_data, output->u0u[lev][iu], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting u0u\\n\", status);\n return status;\n }\n }\n\n if (output->print_phi > 0) {\n\n /* Convolve uu */\n for (j = 0; j < input.rte.nphi; j++) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = cnvlv (x_data, output->uu[lev][j][iu], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting u0u\\n\", status);\n return status;\n }\n }\n }\n }\n }\n }\n\n /* 3D absorption */\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks])\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++) {\n\n status = cnvlv (x_data, output->abs3d[ks][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (input.rte.mc.std) /* **CK added for forward mc_std */\n status = cnvlv (x_data, output->abs3d_var[ks][is][js], output->wl.nlambda_h, x_slit, y_slit, n_slit, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d convoluting abs3d\\n\", status);\n return status;\n }\n }\n }\n\n free (x_slit);\n free (y_slit);\n free (x_data);\n\n return 0;\n}\n\n/**************************************************************/\n/* Convolve a spectrum with a slit function. */\n/* Internal function, used by convolve(). */\n/**************************************************************/\n\nstatic int cnvlv (double* x_spec, float* y_spec, int n_spec, double* x_slit, double* y_slit, int n_slit, int std) {\n int iv = 0, status = 0;\n double* y_data = calloc (n_spec, sizeof (double));\n double* tmp = NULL;\n\n for (iv = 0; iv < n_spec; iv++)\n y_data[iv] = (double)y_spec[iv];\n\n status = int_convolute (x_spec, y_data, n_spec, x_slit, y_slit, n_slit, &tmp, std);\n if (status != 0)\n return status;\n\n for (iv = 0; iv < n_spec; iv++)\n y_spec[iv] = (float)tmp[iv];\n\n free (y_data);\n free (tmp);\n\n return 0;\n}\n\n/**************************************************************/\n/* Interpolate the high resolution spectrum *_h */\n/* to a user-defined wavelength grid. *_s */\n/**************************************************************/\n\nint spline_interpolate (input_struct input, output_struct* output) {\n int is = 0, js = 0, ks = 0, iu = 0, iv = 0, ip = 0, ic = 0, j = 0, lev = 0;\n int status = 0;\n double* x_user = NULL;\n int linear = 0;\n\n if (strlen (input.filename[FN_SPLINE]) > 0) {\n\n /* read file with user x values */\n status = read_1c_file (input.filename[FN_SPLINE], &x_user, &output->wl.nlambda_s);\n if (status != 0) {\n fprintf (stderr,\n \"Error %d reading spline_interpolate file %s (line %d, function %s in %s)\\n\",\n status,\n input.filename[FN_SPLINE],\n __LINE__,\n __func__,\n __FILE__);\n return (status);\n }\n\n output->wl.lambda_s = (float*)calloc (output->wl.nlambda_s, sizeof (float));\n\n for (iv = 0; iv < output->wl.nlambda_s; iv++)\n output->wl.lambda_s[iv] = (float)x_user[iv];\n\n /* Check wavelength ranges */\n status = 0;\n if (output->wl.start > output->wl.lambda_s[0]) {\n fprintf (stderr, \"Error, spline wavelength %f is smaller than wvn %f\\n\", output->wl.lambda_s[0], output->wl.start);\n status--;\n }\n\n if (output->wl.end < output->wl.lambda_s[output->wl.nlambda_s - 1]) {\n fprintf (stderr,\n \"Error, spline wavelength %f is greater than wvn %f\\n\",\n output->wl.lambda_s[output->wl.nlambda_s - 1],\n output->wl.end);\n status--;\n }\n\n if (status != 0)\n return status;\n } else {\n output->wl.nlambda_s = (int)((input.spline_lambda_1 - input.spline_lambda_0) / input.spline_lambda_step + 1);\n\n output->wl.lambda_s = (float*)calloc (output->wl.nlambda_s, sizeof (float));\n\n for (iv = 0; iv < output->wl.nlambda_s; iv++)\n output->wl.lambda_s[iv] = input.spline_lambda_0 + (float)iv * input.spline_lambda_step;\n }\n\n /* Allocation of the solar zenith angle */\n if ((output->sza_s = calloc (output->wl.nlambda_s, sizeof (float))) == NULL) {\n fprintf (stderr, \"Error: Allocation of sza_s in spline_interpolate (ancillary.c)\\n\");\n return -1;\n }\n\n /* Interpolation of the solar zenith angle to output wavelength grid */\n status += arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->sza_h,\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->sza_s,\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by arb_wvn()\\n\", status);\n return status;\n }\n\n /* copy to sza_h for print_output */\n free (output->sza_h);\n output->sza_h = (float*)calloc (output->wl.nlambda_s, sizeof (float));\n for (iv = 0; iv < output->wl.nlambda_s; iv++)\n output->sza_h[iv] = (float)output->sza_s[iv];\n\n /* Interpolation to output wavelength grid */\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* Spline interpolate up_flux and down_flux*/\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->up_flux[lev][is],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->up_flux[lev][is],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating up_flux\\n\", status);\n return status;\n }\n\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->down_flux[lev][is],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->down_flux[lev][is],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating down_flux\\n\", status);\n return status;\n }\n\n /* Spline interpolate up_rad and down_rad */\n for (j = 0; j < input.rte.nphi; j++) {\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->down_rad[lev][j][iu][is],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->down_rad[lev][j][iu][is],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating down_rad\\n\", status);\n return status;\n }\n\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->up_rad[lev][j][iu][is],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->up_rad[lev][j][iu][is],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating up_rad\\n\", status);\n return status;\n }\n }\n }\n }\n\n /* Spline interpolate heating rate */\n if (input.heating != HEAT_NONE) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->heat[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->heat[lev],\n linear,\n 0);\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->emis[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->emis[lev],\n linear,\n 0);\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->w_zout[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->w_zout[lev],\n linear,\n 0);\n }\n }\n } else {\n\n /* albmed */\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->albmed[iu],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->albmed[iu],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating albmed\\n\", status);\n return status;\n }\n }\n\n /* trnmed */\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->trnmed[iu],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->trnmed[iu],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating trnmed\\n\", status);\n return status;\n }\n }\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* Spline interpolate rfldir, rfldn, flup, uavg and heat for all cases */\n\n /* rfldir */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldir[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->rfldir[lev],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating rfldir\\n\", status);\n return status;\n }\n\n /* rfldn */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldn[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->rfldn[lev],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating rfldn\\n\", status);\n return status;\n }\n\n /* flup */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->flup[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->flup[lev],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating flup\\n\", status);\n return status;\n }\n\n /* uavg */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavg[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavg[lev],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavg\\n\", status);\n return status;\n }\n\n /* heating rates */\n if (input.heating != HEAT_NONE) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->heat[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->heat[lev],\n linear,\n 0);\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->emis[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->emis[lev],\n linear,\n 0);\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->w_zout[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->w_zout[lev],\n linear,\n 0);\n }\n\n /* 3D fields */\n if (output->mc.sample.passback3D)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n /* rfldir3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldir3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->rfldir3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating rfldir3d\\n\", status);\n return status;\n }\n\n /* rfldn3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldn3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->rfldn3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating rfldn3d\\n\", status);\n return status;\n }\n\n /* rflup3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->flup3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->flup3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating flup3d\\n\", status);\n return status;\n }\n\n /* uavgso3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgso3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgso3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgso3d\\n\", status);\n return status;\n }\n\n /* uavgdn3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgdn3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgdn3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgdn3d\\n\", status);\n return status;\n }\n\n /* uavgup3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgup3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgup3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgup3d\\n\", status);\n return status;\n }\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->fl3d_is[lev][is][js][ic],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->fl3d_is[lev][is][js][ic],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating fl3d_is\\n\", status);\n return status;\n }\n }\n }\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n /* radiance3d */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->radiance3d[lev][is][js][ip][ic],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->radiance3d[lev][is][js][ip][ic],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating radiance3d\\n\", status);\n return status;\n }\n }\n }\n\n /* absback3d */\n if (input.rte.mc.backward.absorption) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->absback3d[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->absback3d[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating absback3d\\n\", status);\n return status;\n }\n }\n\n /* variances */\n if (input.rte.mc.std) {\n\n /* rfldir3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldir3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->rfldir3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating rfldir3d_var\\n\", status);\n return status;\n }\n\n /* rfldn3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldn3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->rfldn3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating rfldn3d_var\\n\", status);\n return status;\n }\n\n /* rflup3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->flup3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->flup3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating flup3d_var\\n\", status);\n return status;\n }\n\n /* uavgso3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgso3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgso3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgso3d_var\\n\", status);\n return status;\n }\n\n /* uavgdn3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgdn3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgdn3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgdn3d_var\\n\", status);\n return status;\n }\n\n /* uavgup3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgup3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgup3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgup3d_var\\n\", status);\n return status;\n }\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n\n /* radiance3d_var */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->radiance3d_var[lev][is][js][ip],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->radiance3d_var[lev][is][js][ip],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating radiance3d_var\\n\", status);\n return status;\n }\n }\n\n /* absback3d_var */\n if (input.rte.mc.backward.absorption) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->absback3d_var[lev][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->absback3d_var[lev][is][js],\n linear,\n 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating absback3d_var\\n\", status);\n return status;\n }\n }\n }\n }\n\n if (input.rte.solver != SOLVER_FTWOSTR) {\n\n /* Spline interpolate uavgso, uavgdn, uavgup */\n\n /* uavgso */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgso[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgso[lev],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgso\\n\", status);\n return status;\n }\n\n /* uavgdn */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgdn[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgdn[lev],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgdn\\n\", status);\n return status;\n }\n\n /* uavgup */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgup[lev],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uavgup[lev],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uavgup\\n\", status);\n return status;\n }\n\n /* Spline interpolate u0u */\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->u0u[lev][iu],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->u0u[lev][iu],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating u0u\\n\", status);\n return status;\n }\n }\n\n if (output->print_phi > 0) {\n\n /* Spline interpolate uu */\n for (j = 0; j < input.rte.nphi; j++) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uu[lev][j][iu],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->uu[lev][j][iu],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating uu\\n\", status);\n return status;\n }\n }\n }\n }\n }\n }\n\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks])\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++) {\n\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->abs3d[ks][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->abs3d[ks][is][js],\n linear,\n 0);\n\n if (input.rte.mc.std) /* **CK added for forward mc_std */\n status = arb_wvn (output->wl.nlambda_h,\n output->wl.lambda_h,\n output->abs3d_var[ks][is][js],\n output->wl.nlambda_s,\n output->wl.lambda_s,\n output->abs3d_var[ks][is][js],\n linear,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d interpolating abs3d\\n\", status);\n return status;\n }\n }\n }\n\n free (output->wl.lambda_h);\n\n output->wl.nlambda_h = output->wl.nlambda_s;\n\n output->wl.lambda_h = (float*)calloc (output->wl.nlambda_s, sizeof (float));\n\n for (iv = 0; iv < output->wl.nlambda_s; iv++)\n output->wl.lambda_h[iv] = (float)output->wl.lambda_s[iv];\n\n return status;\n}\n\n/****************************************************************************************************************/\n/* Transfer radiative transfer results from radiative transfer wavelength grid to transmittance wavelength grid */\n/****************************************************************************************************************/\nint internal_to_transmittance_grid (input_struct input, output_struct* output) {\n int status = 0;\n int lu = 0, is = 0, js = 0, ks = 0, iu = 0, ip = 0, ic = 0, j = 0;\n int isp = 0, i = 0, lc = 0;\n\n double ffactor = 0.0, rfactor = 0.0, hfactor = 0.0;\n int iv = 0;\n\n double unit_factor;\n char function_name[] = \"internal_to_transmittance_grid\";\n char file_name[] = \"ancillary.c\";\n\n /* Pointers to results are just copied, if no representative wavelengths are used */\n if (output->wl.use_reptran == 0) {\n\n if (input.rte.solver != SOLVER_POLRADTRAN) {\n output->albmed_t = output->albmed_r;\n output->trnmed_t = output->trnmed_r;\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n output->up_flux_t = output->up_flux_r;\n output->down_flux_t = output->down_flux_r;\n output->down_rad_t = output->down_rad_r;\n output->up_rad_t = output->up_rad_r;\n\n if (input.heating != HEAT_NONE) {\n output->heat_t = output->heat_r;\n output->emis_t = output->emis_r;\n output->w_zout_t = output->w_zout_r;\n }\n } else {\n output->flup_t = output->flup_r;\n output->rfldir_t = output->rfldir_r;\n output->rfldn_t = output->rfldn_r;\n output->uavg_t = output->uavg_r;\n output->uavgdn_t = output->uavgdn_r;\n output->uavgso_t = output->uavgso_r;\n output->uavgup_t = output->uavgup_r;\n output->sslidar_nphot_t = output->sslidar_nphot_r;\n output->sslidar_nphot_q_t = output->sslidar_nphot_q_r;\n output->sslidar_ratio_t = output->sslidar_ratio_r;\n if (input.heating != HEAT_NONE) {\n output->heat_t = output->heat_r;\n output->emis_t = output->emis_r;\n output->w_zout_t = output->w_zout_r;\n }\n\n /* radiances */\n output->u0u_t = output->u0u_r;\n output->uu_t = output->uu_r;\n\n /* 3D fields */\n if (output->mc.sample.passback3D) {\n output->rfldir3d_t = output->rfldir3d_r;\n output->rfldn3d_t = output->rfldn3d_r;\n output->flup3d_t = output->flup3d_r;\n output->uavgso3d_t = output->uavgso3d_r;\n output->uavgdn3d_t = output->uavgdn3d_r;\n output->uavgup3d_t = output->uavgup3d_r;\n output->radiance3d_t = output->radiance3d_r;\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is)\n output->fl3d_is_t = output->fl3d_is_r;\n\n if (input.rte.mc.jacobian[DIM_1D])\n output->jacobian_t = output->jacobian_r;\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_t = output->absback3d_r;\n\n /* variances */\n if (input.rte.mc.std) {\n\n output->rfldir3d_var_t = output->rfldir3d_var_r;\n output->rfldn3d_var_t = output->rfldn3d_var_r;\n output->flup3d_var_t = output->flup3d_var_r;\n output->uavgso3d_var_t = output->uavgso3d_var_r;\n output->uavgdn3d_var_t = output->uavgdn3d_var_r;\n output->uavgup3d_var_t = output->uavgup3d_var_r;\n output->radiance3d_var_t = output->radiance3d_var_r;\n if (input.rte.mc.backward.absorption)\n output->absback3d_var_t = output->absback3d_var_r;\n }\n }\n }\n\n /* absorption is defined on the 3D caoth grid, not on the user-defined grid */\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE) { /* **CK added bracket */\n output->abs3d_t = output->abs3d_r;\n if (input.rte.mc.std) /* **CK added for forward mc_std */\n output->abs3d_var_t = output->abs3d_var_r;\n }\n\n /* copy solar zenith angle */\n output->atm.sza_t = output->atm.sza_r;\n\n output->triangle_results_t = output->triangle_results_r;\n } else { /* if representative wavelengths are used, the results at the radiative transfer wavelength grid need to be weighted */\n\n output->atm.sza_t = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 0, output->atm.sza_r, output->atm.sza_t);\n\n if (input.rte.solver != SOLVER_POLRADTRAN) {\n\n output->albmed_t = calloc (input.rte.numu, sizeof (float*));\n output->trnmed_t = calloc (input.rte.numu, sizeof (float*));\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->albmed_t[iu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->trnmed_t[iu] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 0, output->albmed_r[iu], output->albmed_t[iu]);\n status += weighting_reptran (&output->wl, 0, output->trnmed_r[iu], output->trnmed_t[iu]);\n }\n }\n\n if (input.heating != HEAT_NONE) {\n output->heat_t = calloc (output->atm.nzout, sizeof (float*));\n output->emis_t = calloc (output->atm.nzout, sizeof (float*));\n output->w_zout_t = calloc (output->atm.nzout, sizeof (float*));\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n output->down_flux_t = calloc (output->atm.nzout, sizeof (float**));\n output->up_flux_t = calloc (output->atm.nzout, sizeof (float**));\n } else {\n output->flup_t = calloc (output->atm.nzout, sizeof (float*));\n output->rfldir_t = calloc (output->atm.nzout, sizeof (float*));\n output->rfldn_t = calloc (output->atm.nzout, sizeof (float*));\n output->uavg_t = calloc (output->atm.nzout, sizeof (float*));\n output->uavgdn_t = calloc (output->atm.nzout, sizeof (float*));\n output->uavgso_t = calloc (output->atm.nzout, sizeof (float*));\n output->uavgup_t = calloc (output->atm.nzout, sizeof (float*));\n output->sslidar_nphot_t = calloc (output->atm.nzout, sizeof (float*));\n output->sslidar_nphot_q_t = calloc (output->atm.nzout, sizeof (float*));\n output->sslidar_ratio_t = calloc (output->atm.nzout, sizeof (float*));\n\n if (output->mc.sample.passback3D) {\n output->rfldir3d_t = calloc (output->atm.nzout, sizeof (float***));\n output->rfldn3d_t = calloc (output->atm.nzout, sizeof (float***));\n output->flup3d_t = calloc (output->atm.nzout, sizeof (float***));\n output->uavgso3d_t = calloc (output->atm.nzout, sizeof (float***));\n output->uavgdn3d_t = calloc (output->atm.nzout, sizeof (float***));\n output->uavgup3d_t = calloc (output->atm.nzout, sizeof (float***));\n\n output->radiance3d_t = calloc (output->atm.nzout, sizeof (float****));\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n if ((status = ASCII_calloc_float_5D (&output->fl3d_is_t,\n output->atm.nzout,\n output->mc.sample.Nx,\n output->mc.sample.Ny,\n output->mc.alis.Nc,\n output->wl.nlambda_t)) != 0)\n return status;\n }\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n if ((status = ASCII_calloc_float_7D (&output->jacobian_t,\n output->atm.nzout,\n 1,\n 1,\n input.n_caoth + 2,\n 2,\n output->atm.nlev - 1,\n output->wl.nlambda_t)) != 0)\n return status;\n }\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_t = calloc (output->atm.nzout, sizeof (float***));\n\n if (input.rte.mc.std) {\n output->rfldir3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n output->rfldn3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n output->flup3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n output->uavgso3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n output->uavgdn3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n output->uavgup3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n\n output->radiance3d_var_t = calloc (output->atm.nzout, sizeof (float****));\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var_t = calloc (output->atm.nzout, sizeof (float***));\n }\n }\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n output->down_rad_t = calloc (output->atm.nzout, sizeof (float****));\n output->up_rad_t = calloc (output->atm.nzout, sizeof (float****));\n } else {\n output->u0u_t = calloc (output->atm.nzout, sizeof (float**));\n output->uu_t = calloc (output->atm.nzout, sizeof (float***));\n }\n\n for (lu = 0; lu < output->atm.nzout; lu++) {\n\n if (input.heating != HEAT_NONE) {\n\n output->heat_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->emis_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->w_zout_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n\n status += weighting_reptran (&output->wl, 0, output->heat_r[lu], output->heat_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->emis_r[lu], output->emis_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->w_zout_r[lu], output->w_zout_t[lu]);\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n\n output->down_flux_t[lu] = calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (float*));\n output->up_flux_t[lu] = calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (float*));\n\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n output->down_flux_t[lu][is] = calloc (output->wl.nlambda_t, sizeof (float));\n output->up_flux_t[lu][is] = calloc (output->wl.nlambda_t, sizeof (float));\n\n status += weighting_reptran (&output->wl, 0, output->down_flux_r[lu][is], output->down_flux_t[lu][is]);\n status += weighting_reptran (&output->wl, 0, output->up_flux_r[lu][is], output->up_flux_t[lu][is]);\n }\n\n } else {\n\n output->flup_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->rfldir_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->rfldn_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavg_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgdn_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgso_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgup_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->sslidar_nphot_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->sslidar_nphot_q_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n output->sslidar_ratio_t[lu] = calloc (output->wl.nlambda_t, sizeof (float));\n\n status += weighting_reptran (&output->wl, 0, output->flup_r[lu], output->flup_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->rfldir_r[lu], output->rfldir_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->rfldn_r[lu], output->rfldn_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->uavg_r[lu], output->uavg_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->uavgdn_r[lu], output->uavgdn_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->uavgso_r[lu], output->uavgso_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->uavgup_r[lu], output->uavgup_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->sslidar_nphot_r[lu], output->sslidar_nphot_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->sslidar_nphot_q_r[lu], output->sslidar_nphot_q_t[lu]);\n status += weighting_reptran (&output->wl, 0, output->sslidar_ratio_r[lu], output->sslidar_ratio_t[lu]);\n\n /* 3D fields */\n if (output->mc.sample.passback3D) {\n\n output->rfldir3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->rfldn3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->flup3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->uavgso3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->uavgdn3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->uavgup3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n\n output->radiance3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float****));\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n\n if (input.rte.mc.std) {\n output->rfldir3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->rfldn3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->flup3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->uavgso3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->uavgdn3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n output->uavgup3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n\n output->radiance3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float***));\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var_t[lu] = calloc (output->mc.sample.Nx, sizeof (float**));\n }\n\n for (is = output->islower; is <= output->isupper; is += output->isstep) {\n\n output->rfldir3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->rfldn3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->flup3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->uavgso3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->uavgdn3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->uavgup3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n\n output->radiance3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float***));\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n\n if (input.rte.mc.std) {\n output->rfldir3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->rfldn3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->flup3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->uavgso3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->uavgdn3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n output->uavgup3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n\n output->radiance3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float**));\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var_t[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*));\n }\n\n for (js = output->jslower; js <= output->jsupper; js++) {\n\n output->rfldir3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->rfldn3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->flup3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgso3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgdn3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgup3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n\n status += weighting_reptran (&output->wl, 0, output->rfldir3d_r[lu][is][js], output->rfldir3d_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 0, output->rfldn3d_r[lu][is][js], output->rfldn3d_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 0, output->flup3d_r[lu][is][js], output->flup3d_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 0, output->uavgso3d_r[lu][is][js], output->uavgso3d_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 0, output->uavgdn3d_r[lu][is][js], output->uavgdn3d_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 0, output->uavgup3d_r[lu][is][js], output->uavgup3d_t[lu][is][js]);\n\n output->radiance3d_t[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float**));\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n status +=\n weighting_reptran (&output->wl, 0, output->fl3d_is_r[lu][is][js][ic], output->fl3d_is_t[lu][is][js][ic]);\n }\n }\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n output->radiance3d_t[lu][is][js][ip] = calloc (output->mc.alis.Nc, sizeof (float*));\n\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n output->radiance3d_t[lu][is][js][ip][ic] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl,\n 0,\n output->radiance3d_r[lu][is][js][ip][ic],\n output->radiance3d_t[lu][is][js][ip][ic]);\n }\n }\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n\n for (isp = 0; isp < input.n_caoth + 2; isp++) {\n\n for (i = 0; i < 2; i++) {\n\n for (lc = 0; lc < output->atm.nlev - 1; lc++) {\n\n status += weighting_reptran (&output->wl,\n 0,\n output->jacobian_r[lu][is][js][isp][i][lc],\n output->jacobian_t[lu][is][js][isp][i][lc]);\n }\n }\n }\n }\n\n if (input.rte.mc.backward.absorption) {\n output->absback3d_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 0, output->absback3d_r[lu][is][js], output->absback3d_t[lu][is][js]);\n }\n\n /* variances */\n if (input.rte.mc.std) {\n\n output->rfldir3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->rfldn3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->flup3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgso3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgdn3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n output->uavgup3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n\n status +=\n weighting_reptran (&output->wl, 1, output->rfldir3d_var_r[lu][is][js], output->rfldir3d_var_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 1, output->rfldn3d_var_r[lu][is][js], output->rfldn3d_var_t[lu][is][js]);\n status += weighting_reptran (&output->wl, 1, output->flup3d_var_r[lu][is][js], output->flup3d_var_t[lu][is][js]);\n status +=\n weighting_reptran (&output->wl, 1, output->uavgso3d_var_r[lu][is][js], output->uavgso3d_var_t[lu][is][js]);\n status +=\n weighting_reptran (&output->wl, 1, output->uavgdn3d_var_r[lu][is][js], output->uavgdn3d_var_t[lu][is][js]);\n status +=\n weighting_reptran (&output->wl, 1, output->uavgup3d_var_r[lu][is][js], output->uavgup3d_var_t[lu][is][js]);\n\n output->radiance3d_var_t[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float*));\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n output->radiance3d_var_t[lu][is][js][ip] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl,\n 1,\n output->radiance3d_var_r[lu][is][js][ip],\n output->radiance3d_var_t[lu][is][js][ip]);\n }\n\n if (input.rte.mc.backward.absorption) {\n output->absback3d_var_t[lu][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n status +=\n weighting_reptran (&output->wl, 1, output->absback3d_var_r[lu][is][js], output->absback3d_var_t[lu][is][js]);\n }\n }\n }\n }\n }\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n\n output->down_rad_t[lu] = calloc (input.rte.nphi, sizeof (float***));\n output->up_rad_t[lu] = calloc (input.rte.nphi, sizeof (float***));\n\n for (j = 0; j < input.rte.nphi; j++) {\n\n output->down_rad_t[lu][j] = calloc (input.rte.numu, sizeof (float**));\n output->up_rad_t[lu][j] = calloc (input.rte.numu, sizeof (float**));\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n\n output->down_rad_t[lu][j][iu] = calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (float*));\n output->up_rad_t[lu][j][iu] = calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (float*));\n\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n output->down_rad_t[lu][j][iu][is] = calloc (output->wl.nlambda_t, sizeof (float));\n output->up_rad_t[lu][j][iu][is] = calloc (output->wl.nlambda_t, sizeof (float));\n\n status += weighting_reptran (&output->wl, 0, output->down_rad_r[lu][j][iu][is], output->down_rad_t[lu][j][iu][is]);\n status += weighting_reptran (&output->wl, 0, output->up_rad_r[lu][j][iu][is], output->up_rad_t[lu][j][iu][is]);\n }\n }\n }\n } else {\n\n output->u0u_t[lu] = calloc (input.rte.numu, sizeof (float*));\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->u0u_t[lu][iu] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 0, output->u0u_r[lu][iu], output->u0u_t[lu][iu]);\n }\n\n output->uu_t[lu] = calloc (input.rte.nphi, sizeof (float**));\n for (j = 0; j < input.rte.nphi; j++) {\n output->uu_t[lu][j] = calloc (input.rte.numu, sizeof (float*));\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->uu_t[lu][j][iu] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 0, output->uu_r[lu][j][iu], output->uu_t[lu][j][iu]);\n }\n }\n }\n } /* end of loop over layers */\n\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE) {\n output->abs3d_t = calloc (output->atm.Nzcld, sizeof (float***));\n for (ks = 0; ks < output->atm.Nzcld; ks++) {\n if (output->atm.threed[ks]) {\n output->abs3d_t[ks] = calloc (output->atm.Nxcld, sizeof (float**));\n for (is = 0; is < output->atm.Nxcld; is++) {\n output->abs3d_t[ks][is] = calloc (output->atm.Nycld, sizeof (float*));\n for (js = 0; js < output->atm.Nycld; js++) {\n\n output->abs3d_t[ks][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 0, output->abs3d_r[ks][is][js], output->abs3d_t[ks][is][js]);\n\n if (input.rte.mc.std) { /* **CK added for forward mc_std */\n output->abs3d_var_t[ks][is][js] = calloc (output->wl.nlambda_t, sizeof (float));\n status += weighting_reptran (&output->wl, 1, output->abs3d_var_r[ks][is][js], output->abs3d_var_t[ks][is][js]);\n }\n }\n }\n }\n }\n }\n\n { // copy (and weight) triangle_result_r -> triangle_results_t\n int ierr;\n ierr = init_spectral_triangular_surface_result_struct (output->wl.nlambda_t,\n output->mc.triangular_surface.N_triangles,\n &(output->triangle_results_t));\n CHKERR (ierr);\n\n // because the triangle_result output does not have wavelength as leading dimension\n // we have this wrapper here to copy and weight triangle_result_r -> triangle_results_t\n for (size_t id = 0; id < output->mc.triangular_surface.N_triangles; ++id) {\n const size_t Nvar = 6;\n float var_r[Nvar][output->wl.nlambda_r];\n float var_t[Nvar][output->wl.nlambda_t];\n for (size_t iv_r = 0; iv_r < output->wl.nlambda_r; ++iv_r) {\n var_r[0][iv_r] = output->triangle_results_r[iv_r]->ndir[id];\n var_r[1][iv_r] = output->triangle_results_r[iv_r]->ndn[id];\n var_r[2][iv_r] = output->triangle_results_r[iv_r]->nup[id];\n var_r[3][iv_r] = output->triangle_results_r[iv_r]->edir[id];\n var_r[4][iv_r] = output->triangle_results_r[iv_r]->edn[id];\n var_r[5][iv_r] = output->triangle_results_r[iv_r]->eup[id];\n }\n for (size_t ivar = 0; ivar < Nvar; ++ivar) {\n const int ierr = weighting_reptran (&output->wl, 0, var_r[ivar], var_t[ivar]);\n CHKERR (ierr);\n }\n for (size_t iv_t = 0; iv_t < output->wl.nlambda_t; ++iv_t) {\n output->triangle_results_t[iv_t]->ndir[id] = var_t[0][iv_t];\n output->triangle_results_t[iv_t]->ndn[id] = var_t[1][iv_t];\n output->triangle_results_t[iv_t]->nup[id] = var_t[2][iv_t];\n output->triangle_results_t[iv_t]->edir[id] = var_t[3][iv_t];\n output->triangle_results_t[iv_t]->edn[id] = var_t[4][iv_t];\n output->triangle_results_t[iv_t]->eup[id] = var_t[5][iv_t];\n }\n }\n }\n\n /* scale output to user-requested output unit (when no representative wavelengths are used, this was already done in solve_rte()) */\n for (iv = 0; iv < output->wl.nlambda_t; iv++) {\n\n if (input.source == SRC_THERMAL && output->spectrum_unit == UNIT_PER_CM_1) {\n\n switch (input.output_unit) {\n case UNIT_PER_CM_1:\n unit_factor = 1;\n break;\n case UNIT_PER_NM:\n unit_factor = 1.0e+7 / (output->wl.lambda_t[iv] * output->wl.lambda_t[iv]);\n break;\n case UNIT_PER_BAND:\n unit_factor = output->wl.width_of_reptran_band[output->wl.reptran_band_t[iv]];\n break;\n case UNIT_NOT_DEFINED:\n unit_factor = 1.0;\n break;\n default:\n fprintf (stderr,\n \"Error: Program bug, unsupported output unit %d in %s (%s). \\n\",\n input.output_unit,\n function_name,\n file_name);\n return -1;\n }\n\n } else if (input.source == SRC_SOLAR && output->spectrum_unit == UNIT_PER_NM) {\n switch (input.output_unit) {\n case UNIT_PER_CM_1:\n unit_factor = (output->wl.lambda_t[iv] * output->wl.lambda_t[iv]) / 1.0e+7;\n break;\n case UNIT_PER_NM:\n unit_factor = 1;\n break;\n case UNIT_PER_BAND:\n unit_factor = output->wl.width_of_reptran_band[output->wl.reptran_band_t[iv]];\n break;\n case UNIT_NOT_DEFINED:\n unit_factor = 1.0;\n break;\n default:\n fprintf (stderr,\n \"Error: Program bug, unsupported output unit %d in %s (%s). \\n\",\n input.output_unit,\n function_name,\n file_name);\n return -1;\n }\n\n } else {\n\n fprintf (stderr,\n \"Error: Program bug, unsupported comination of spectrum unit %d with source %d in %s (%s). \\n\",\n input.spectrum_unit,\n input.source,\n function_name,\n file_name);\n return -1;\n }\n\n ffactor = unit_factor;\n rfactor = unit_factor;\n hfactor = unit_factor;\n status = scale_output (input,\n &(output->rfldir_t),\n &(output->rfldn_t),\n &(output->flup_t),\n &(output->albmed_t),\n &(output->trnmed_t),\n &(output->uavgso_t),\n &(output->uavgdn_t),\n &(output->uavgup_t),\n &(output->uavg_t),\n &(output->u0u_t),\n &(output->uu_t),\n &(output->heat_t),\n &(output->emis_t),\n &(output->w_zout_t),\n &(output->down_flux_t),\n &(output->up_flux_t),\n &(output->down_rad_t),\n &(output->up_rad_t),\n &(output->rfldir3d_t),\n &(output->rfldn3d_t),\n &(output->flup3d_t),\n &(output->fl3d_is_t),\n &(output->uavgso3d_t),\n &(output->uavgdn3d_t),\n &(output->uavgup3d_t),\n &(output->radiance3d_t),\n &(output->jacobian_t),\n &(output->absback3d_t),\n &(output->rfldir3d_var_t),\n &(output->rfldn3d_var_t),\n &(output->flup3d_var_t),\n &(output->uavgso3d_var_t),\n &(output->uavgdn3d_var_t),\n &(output->uavgup3d_var_t),\n &(output->radiance3d_var_t),\n &(output->abs3d_var_t),\n &(output->absback3d_var_t),\n output->atm.nzout,\n output->atm.Nxcld,\n output->atm.Nycld,\n output->atm.Nzcld,\n output->mc.alis.Nc,\n output->atm.nlev - 1,\n output->atm.threed,\n output->mc.sample.passback3D,\n output->islower,\n output->isupper,\n output->jslower,\n output->jsupper,\n output->isstep,\n output->jsstep,\n &(output->abs3d_t),\n output->triangle_results_t,\n ffactor,\n rfactor,\n hfactor,\n iv); /* in ancillary.c */\n CHKERR (status);\n }\n }\n\n return status;\n}\n\nint closest (float lambda, float* lambda_raw, int n_crs) {\n int iv = 0;\n\n float min_delta = FLT_MAX;\n\n int result = -1;\n\n for (iv = 0; iv < n_crs; iv++) {\n if (fabs (lambda - lambda_raw[iv]) < min_delta) {\n min_delta = fabs (lambda - lambda_raw[iv]);\n result = iv;\n }\n }\n return result;\n}\n\n/*****************************************************************************/\n/* Interpolate the transmittance from the transmission wavelength grid to */\n/* high resolution grid. */\n/*****************************************************************************/\n\nint interpolate_transmittance (input_struct input, output_struct* output) {\n int lu = 0, is = 0, js = 0, ks = 0, iv = 0, ivh = 0, iu = 0, ip = 0, j = 0, ic = 0;\n int isp = 0, i = 0, lc = 0;\n int linear = 1, status = 0;\n\n /* If only one wavelength is required, or in correlated-k mode, */\n /* arrays are not interpolated but copied */\n /* ??? need to add the condition that the extraterrestrial ??? */\n /* ??? spectrum was not read from file but set to 1 ??? */\n\n if (output->wl.nlambda_t == 1 || output->wl.use_reptran == 1 ||\n (output->wl.use_reptran == 0 && input.ck_scheme != CK_CRS && input.ck_scheme != CK_RAMAN && input.ck_scheme != CK_LOWTRAN)) {\n\n for (ivh = 0; ivh < output->wl.nlambda_h; ivh++) {\n\n if (output->wl.nlambda_t == 1)\n iv = ivh;\n else if (output->wl.use_reptran == 1)\n iv = closest (output->wl.lambda_h[ivh], output->wl.lambda_t, output->wl.nlambda_t);\n else\n iv = output->wl.map_e2h[ivh];\n\n if (input.rte.solver != SOLVER_POLRADTRAN) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->albmed[iu][ivh] = output->albmed_t[iu][iv];\n output->trnmed[iu][ivh] = output->trnmed_t[iu][iv];\n }\n }\n\n for (lu = 0; lu < output->atm.nzout; lu++) {\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n output->up_flux[lu][is][ivh] = output->up_flux_t[lu][is][iv];\n output->down_flux[lu][is][ivh] = output->down_flux_t[lu][is][iv];\n }\n\n for (j = 0; j < input.rte.nphi; j++)\n for (iu = 0; iu < input.rte.numu; iu++)\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n output->down_rad[lu][j][iu][is][ivh] = output->down_rad_t[lu][j][iu][is][iv];\n output->up_rad[lu][j][iu][is][ivh] = output->up_rad_t[lu][j][iu][is][iv];\n }\n if (input.heating != HEAT_NONE) {\n output->heat[lu][ivh] = output->heat_t[lu][iv];\n output->emis[lu][ivh] = output->emis_t[lu][iv];\n output->w_zout[lu][ivh] = output->w_zout_t[lu][iv];\n }\n } else {\n output->flup[lu][ivh] = output->flup_t[lu][iv];\n output->rfldir[lu][ivh] = output->rfldir_t[lu][iv];\n output->rfldn[lu][ivh] = output->rfldn_t[lu][iv];\n output->uavg[lu][ivh] = output->uavg_t[lu][iv];\n output->uavgdn[lu][ivh] = output->uavgdn_t[lu][iv];\n output->uavgso[lu][ivh] = output->uavgso_t[lu][iv];\n output->uavgup[lu][ivh] = output->uavgup_t[lu][iv];\n output->sslidar_nphot[lu][ivh] = output->sslidar_nphot_t[lu][iv];\n output->sslidar_nphot_q[lu][ivh] = output->sslidar_nphot_q_t[lu][iv];\n output->sslidar_ratio[lu][ivh] = output->sslidar_ratio_t[lu][iv];\n if (input.heating != HEAT_NONE) {\n output->heat[lu][ivh] = output->heat_t[lu][iv];\n output->emis[lu][ivh] = output->emis_t[lu][iv];\n output->w_zout[lu][ivh] = output->w_zout_t[lu][iv];\n }\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->u0u[lu][iu][ivh] = output->u0u_t[lu][iu][iv];\n\n for (j = 0; j < input.rte.nphi; j++)\n output->uu[lu][j][iu][ivh] = output->uu_t[lu][j][iu][iv];\n }\n\n /* 3D fields */\n if (output->mc.sample.passback3D)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n output->rfldir3d[lu][is][js][ivh] = output->rfldir3d_t[lu][is][js][iv];\n output->rfldn3d[lu][is][js][ivh] = output->rfldn3d_t[lu][is][js][iv];\n output->flup3d[lu][is][js][ivh] = output->flup3d_t[lu][is][js][iv];\n output->uavgso3d[lu][is][js][ivh] = output->uavgso3d_t[lu][is][js][iv];\n output->uavgdn3d[lu][is][js][ivh] = output->uavgdn3d_t[lu][is][js][iv];\n output->uavgup3d[lu][is][js][ivh] = output->uavgup3d_t[lu][is][js][iv];\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n output->radiance3d[lu][is][js][ip][ic][ivh] = output->radiance3d_t[lu][is][js][ip][ic][iv];\n }\n }\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n output->fl3d_is[lu][is][js][ic][ivh] = output->fl3d_is_t[lu][is][js][ic][iv];\n }\n }\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < output->atm.nlev - 1; lc++) {\n output->jacobian[lu][is][js][isp][i][lc][ivh] = output->jacobian_t[lu][is][js][isp][i][lc][iv];\n }\n }\n\n if (input.rte.mc.backward.absorption)\n output->absback3d[lu][is][js][ivh] = output->absback3d_t[lu][is][js][iv];\n\n /* variances */\n if (input.rte.mc.std) {\n\n output->rfldir3d_var[lu][is][js][ivh] = output->rfldir3d_var_t[lu][is][js][iv];\n output->rfldn3d_var[lu][is][js][ivh] = output->rfldn3d_var_t[lu][is][js][iv];\n output->flup3d_var[lu][is][js][ivh] = output->flup3d_var_t[lu][is][js][iv];\n output->uavgso3d_var[lu][is][js][ivh] = output->uavgso3d_var_t[lu][is][js][iv];\n output->uavgdn3d_var[lu][is][js][ivh] = output->uavgdn3d_var_t[lu][is][js][iv];\n output->uavgup3d_var[lu][is][js][ivh] = output->uavgup3d_var_t[lu][is][js][iv];\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n output->radiance3d_var[lu][is][js][ip][ivh] = output->radiance3d_var_t[lu][is][js][ip][iv];\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var[lu][is][js][ivh] = output->absback3d_var_t[lu][is][js][iv];\n }\n }\n }\n }\n\n /* absorption is defined on the 3D caoth grid, not on the user-defined grid */\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks])\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++) { /* **CK added bracket */\n output->abs3d[ks][is][js][ivh] = output->abs3d_t[ks][is][js][iv];\n if (input.rte.mc.std) /* **CK added for forward mc_std */\n output->abs3d_var[ks][is][js][ivh] = output->abs3d_var_t[ks][is][js][iv];\n }\n\n /* copy solar zenith angle */\n output->sza_h[ivh] = output->atm.sza_t[iv];\n\n if (output->triangle_results_t) { // link triangle_results_t -> triangle_results_h\n if (!output->triangle_results_o)\n output->triangle_results_o = malloc (output->wl.nlambda_h * sizeof (t_triangle_radiation_field*));\n output->triangle_results_o[ivh] = output->triangle_results_t[iv];\n }\n }\n } else { /* interpolation to different wavelengths required */\n\n /* interpolate solar zenith angle */\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->atm.sza_t,\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->sza_h,\n linear,\n 0);\n CHKERR (status);\n\n if (input.rte.solver != SOLVER_POLRADTRAN) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->albmed_t[iu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->albmed[iu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->trnmed_t[iu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->trnmed[iu],\n linear,\n 0);\n CHKERR (status);\n }\n }\n\n for (lu = 0; lu < output->atm.nzout; lu++) {\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->down_flux_t[lu][is],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->down_flux[lu][is],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->up_flux_t[lu][is],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->up_flux[lu][is],\n linear,\n 0);\n CHKERR (status);\n /* ??? */\n /* ??? is it not nessesary to interpolate here also: down_rad and up_rad ??? */\n /* ??? */\n if (input.heating != HEAT_NONE) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->heat_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->heat[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->emis_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->emis[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->w_zout_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->w_zout[lu],\n linear,\n 0);\n CHKERR (status);\n }\n }\n } else {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->flup_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->flup[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->rfldir_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldir[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->rfldn_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldn[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavg_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavg[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgdn_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgdn[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgso_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgso[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgup_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgup[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->sslidar_nphot_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->sslidar_nphot[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->sslidar_nphot_q_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->sslidar_nphot_q[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->sslidar_ratio_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->sslidar_ratio[lu],\n linear,\n 0);\n CHKERR (status);\n if (input.heating != HEAT_NONE) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->heat_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->heat[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->emis_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->emis[lu],\n linear,\n 0);\n CHKERR (status);\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->w_zout_t[lu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->w_zout[lu],\n linear,\n 0);\n CHKERR (status);\n }\n\n /* 3D fields */\n if (output->mc.sample.passback3D)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->rfldir3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldir3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->rfldn3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldn3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->flup3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->flup3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgso3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgso3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgdn3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgdn3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgup3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgup3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->radiance3d_t[lu][is][js][ip][ic],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->radiance3d[lu][is][js][ip][ic],\n linear,\n 0);\n CHKERR (status);\n }\n }\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->fl3d_is_t[lu][is][js][ic],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->fl3d_is[lu][is][js][ic],\n linear,\n 0);\n }\n }\n\n if (input.rte.mc.jacobian[DIM_1D])\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < output->atm.nlev - 1; lc++) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->jacobian_t[lu][is][js][isp][i][lc],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->jacobian[lu][is][js][isp][i][lc],\n linear,\n 0);\n CHKERR (status);\n }\n\n if (input.rte.mc.backward.absorption) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->absback3d_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->absback3d[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n }\n\n /* variances */\n if (input.rte.mc.std) {\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->rfldir3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldir3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->rfldn3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->rfldn3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->flup3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->flup3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgso3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgso3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgdn3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgdn3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uavgup3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uavgup3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->radiance3d_var_t[lu][is][js][ip],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->radiance3d_var[lu][is][js][ip],\n linear,\n 0);\n CHKERR (status);\n }\n\n if (input.rte.mc.backward.absorption) {\n status += arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->absback3d_var_t[lu][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->absback3d_var[lu][is][js],\n linear,\n 0);\n CHKERR (status);\n }\n }\n }\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n\n for (j = 0; j < input.rte.nphi; j++) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n status = arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->down_rad_t[lu][j][iu][is],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->down_rad[lu][j][iu][is],\n linear,\n 0);\n CHKERR (status);\n\n status = arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->up_rad_t[lu][j][iu][is],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->up_rad[lu][j][iu][is],\n linear,\n 0);\n CHKERR (status);\n }\n }\n }\n } else {\n for (iu = 0; iu < input.rte.numu; iu++) {\n status = arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->u0u_t[lu][iu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->u0u[lu][iu],\n linear,\n 0);\n CHKERR (status);\n }\n\n for (j = 0; j < input.rte.nphi; j++) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n\n status = arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->uu_t[lu][j][iu],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->uu[lu][j][iu],\n linear,\n 0);\n CHKERR (status);\n }\n }\n }\n }\n\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks])\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++) {\n\n status = arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->abs3d_t[ks][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->abs3d[ks][is][js],\n linear,\n 0);\n CHKERR (status);\n\n if (input.rte.mc.std) { /* **CK added for forward mc_std */\n status = arb_wvn (output->wl.nlambda_t,\n output->wl.lambda_t,\n output->abs3d_var_t[ks][is][js],\n output->wl.nlambda_h,\n output->wl.lambda_h,\n output->abs3d_var[ks][is][js],\n linear,\n 0);\n CHKERR (status);\n }\n }\n }\n\n return 0;\n}\n\n/**************************************************************/\n/* Multiply the transmittance with the extraterrestrial */\n/* irradiance. */\n/**************************************************************/\n\nint multiply_extraterrestrial (input_struct input, output_struct* output) {\n int iv = 0, status = 0;\n double ffactor = 0, rfactor = 0, hfactor = 0;\n double watt_factor = 1.0;\n double hfactor2 = 0.0;\n\n /* Figure out if we have to convert from mW to W. This should */\n /* cover the input stuff that comes with uvspec. Now, if the user */\n /* decides to change the input solar flux it may get interesting... */\n\n /* THIS mW to W CONVERTION IS USED FOR HEATING RATES, SHOULD IT BECOME DEFAULT? */\n switch (input.ck_scheme) {\n case CK_FU:\n case CK_KATO:\n case CK_KATO2:\n case CK_KATO2_96:\n case CK_KATO2ANDWANDJI:\n case CK_AVHRR_KRATZ:\n watt_factor = 1.0;\n break;\n case CK_LOWTRAN:\n case CK_FILE:\n case CK_CRS:\n case CK_REPTRAN:\n case CK_REPTRAN_CHANNEL:\n case CK_RAMAN:\n switch (input.source) {\n case SRC_SOLAR:\n case SRC_BLITZ: /* BCA */\n case SRC_LIDAR: /* BCA */\n watt_factor = mW2W;\n break;\n case SRC_THERMAL:\n watt_factor = 1.0;\n break;\n default:\n fprintf (stderr, \"Error, unknown source %d\\n\", input.source);\n return -1;\n }\n break;\n default:\n fprintf (stderr, \"Error: unsupported correlated-k scheme %d\\n\", input.ck_scheme);\n return -1;\n break;\n }\n\n hfactor = watt_factor * s2day;\n hfactor2 = hfactor;\n\n /* multiply with extraterrestrial irradiance */\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n\n switch (input.source) {\n case SRC_THERMAL:\n ffactor = output->wl.filter[iv];\n rfactor = output->wl.filter[iv];\n break;\n\n case SRC_SOLAR:\n case SRC_BLITZ: /* BCA */\n case SRC_LIDAR: /* BCA */\n switch (input.processing) {\n case PROCESS_INT:\n case PROCESS_SUM:\n case PROCESS_RGB:\n case PROCESS_RGBNORM:\n ffactor = output->wl.fbeam[iv] * output->sunshine_fraction * output->wl.filter[iv];\n rfactor = output->wl.fbeam[iv] * output->sunshine_fraction * output->wl.filter[iv];\n break;\n\n case PROCESS_NONE:\n case PROCESS_RAMAN:\n switch (input.calibration) {\n case OUTCAL_ABSOLUTE:\n ffactor = output->wl.fbeam[iv] * output->sunshine_fraction * output->wl.filter[iv];\n rfactor = output->wl.fbeam[iv] * output->sunshine_fraction * output->wl.filter[iv];\n break;\n\n case OUTCAL_TRANSMITTANCE:\n ffactor = 1.0 * output->wl.filter[iv];\n rfactor = 1.0 * output->wl.filter[iv];\n break;\n\n case OUTCAL_REFLECTIVITY:\n ffactor = 1.0 / cos (output->sza_h[iv] * PI / 180.0) * output->wl.filter[iv];\n rfactor = PI / cos (output->sza_h[iv] * PI / 180.0) * output->wl.filter[iv];\n break;\n\n default:\n fprintf (stderr, \"Error, unknown output calibration %d\\n\", input.calibration);\n return -1;\n }\n\n break;\n\n default:\n fprintf (stderr, \"Error, unknown output processing %d\\n\", input.processing);\n return -1;\n }\n\n break;\n\n default:\n fprintf (stderr, \"Error, unknown source %d\\n\", input.source);\n return -1;\n }\n\n switch (input.source) {\n case SRC_SOLAR:\n case SRC_LIDAR: /* BCA */\n case SRC_BLITZ: /* BCA */\n hfactor = output->wl.fbeam[iv] * output->sunshine_fraction * hfactor2;\n break;\n case SRC_THERMAL:\n break;\n default:\n fprintf (stderr, \"Error, unknown source %d\\n\", input.source);\n return -1;\n }\n\n /*****************************************************************************************/\n /* now scale irradiances with ffactor, radiances with rfactor, heating rate with hfactor */\n /*****************************************************************************************/\n status = scale_output (input,\n &(output->rfldir),\n &(output->rfldn),\n &(output->flup),\n &(output->albmed),\n &(output->trnmed),\n &(output->uavgso),\n &(output->uavgdn),\n &(output->uavgup),\n &(output->uavg),\n &(output->u0u),\n &(output->uu),\n &(output->heat),\n &(output->emis),\n &(output->w_zout),\n &(output->down_flux),\n &(output->up_flux),\n &(output->down_rad),\n &(output->up_rad),\n &(output->rfldir3d),\n &(output->rfldn3d),\n &(output->flup3d),\n &(output->fl3d_is),\n &(output->uavgso3d),\n &(output->uavgdn3d),\n &(output->uavgup3d),\n &(output->radiance3d),\n &(output->jacobian),\n &(output->absback3d),\n &(output->rfldir3d_var),\n &(output->rfldn3d_var),\n &(output->flup3d_var),\n &(output->uavgso3d_var),\n &(output->uavgdn3d_var),\n &(output->uavgup3d_var),\n &(output->radiance3d_var),\n &(output->abs3d_var),\n &(output->absback3d_var),\n output->atm.nzout,\n output->atm.Nxcld,\n output->atm.Nycld,\n output->atm.Nzcld,\n output->mc.alis.Nc,\n output->atm.nlyr,\n output->atm.threed,\n output->mc.sample.passback3D,\n output->islower,\n output->isupper,\n output->jslower,\n output->jsupper,\n output->isstep,\n output->jsstep,\n &(output->abs3d),\n output->triangle_results_o,\n ffactor,\n rfactor,\n hfactor,\n iv);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by scale_output()\\n\", status);\n return status;\n }\n }\n\n return 0;\n}\n\n// helper function to convert a caoth3d to consecutive memory and write it to a netcdf file\nstatic int dump_caoth3d_var (int ncid, int isp, char* caothname, caoth3d_out_struct caoth3d, char* varname, float*** caoth_data) {\n const size_t Nx = caoth3d.Nx;\n const size_t Ny = caoth3d.Ny;\n const size_t Nz = caoth3d.nthreed;\n float data[Nz][Nx][Ny];\n int retval;\n int status = 0;\n if (Nz == 0)\n return status; // nothing to do\n\n char varprefix[FILENAME_MAX];\n char ncvarname[FILENAME_MAX];\n char xlabel[FILENAME_MAX];\n char ylabel[FILENAME_MAX];\n char zlabel[FILENAME_MAX];\n char isp_char[11];\n\n sprintf (isp_char, \"%d\", isp);\n strcpy (varprefix, \"caoth3d_\");\n strcat (varprefix, isp_char);\n strcat (varprefix, \"_\");\n strcat (varprefix, caothname);\n\n strcpy (ncvarname, varprefix);\n strcat (ncvarname, varname);\n strcat (strcpy (xlabel, varprefix), \"_nlyr\");\n strcat (strcpy (ylabel, varprefix), \"_Nx\");\n strcat (strcpy (zlabel, varprefix), \"_Ny\");\n\n size_t kk = 0;\n for (size_t k = 0; k < caoth3d.nlyr; ++k) {\n if (caoth3d.threed[k]) {\n for (size_t i = 0; i < Nx; ++i) {\n for (size_t j = 0; j < Ny; ++j) {\n data[kk][i][j] = caoth_data[k][i][j];\n }\n }\n ++kk;\n }\n }\n\n if ((retval = write_netcdf_3D_contiguous_float (ncid, (float*)data, Nz, Nx, Ny, ncvarname, xlabel, ylabel, zlabel)))\n ERR (retval);\n return status;\n}\n\n/***********************************************************************************/\n/* Function: optical_properties @61_30i@ */\n/* Description: */\n/* Calculates optical depth, single scattering albedo and */\n/* phase function from absorption and scattering cross sections */\n/* corresponding gas and particulate matter concentrations for */\n/* one wavelength. */\n/* Parameters: */\n/* Return value: */\n/* Example: */\n/* Files: */\n/* Known bugs: */\n/* Author: */\n/* @i61_30@ */\n/***********************************************************************************/\n\nint optical_properties (input_struct input,\n output_struct* output,\n double wvl,\n int ir,\n int iv1,\n int iv2,\n int iq,\n int verbose,\n int skip_optical_properties) {\n\n static int first = 1; //TODO: Is this good, static int? in function interpolate_profile same variable first\n int k = 0, lc = 0, ip = 0, ips = 0, iv = 0, iv1r = 0, iv2r = 0, isp = 0, ispo = 0;\n int status = 0;\n\n /* vectors for ALL caoths; 0 is reserved for MOL, 1 for AER */\n double *babs_s = NULL, babs_tot = 0.0;\n double *bsca_s = NULL, bsca_tot = 0.0;\n\n double babs_mol_md = 0.0, babs_tot_md = 0.0;\n double bext_tot_md = 0.0; /* The absorption of gases minus the one specified with a \n\t\t\t matrix using the dens_file command (for airmass factor calculations). */\n\n double *ssa_s_unsc = NULL, *bsca_s_unsc = NULL, *babs_s_unsc = NULL;\n double *bsca_s_unsc_int = NULL, *babs_s_unsc_int = NULL;\n double* gg_s_unsc = NULL;\n\n double* babs_s_int = NULL;\n double* bsca_s_int = NULL;\n\n double tau_babs_sum = 0.0; /* ulrike: to add up the dtau's of babsa,... for all layers above the level considered*/\n\n double** mom_s = NULL;\n double bext_tot = 0.0;\n double p_mom[6] = {0, 0, 0, 0, 0, 0};\n FILE* fpol = NULL;\n int nphamat = 0;\n\n /* Output Extinction; needed for ARLEM */\n char extfilename[FILENAME_MAX] = \"\";\n FILE* extfile = NULL;\n\n int nlev = output->atm.nlev_common;\n\n int nlyr = nlev - 1;\n int n_caoth = input.n_caoth + 2; /* mol and aer included */\n int n_caoth_alloc = 0;\n int i_wc = 0, i_ic = 0;\n int i_wcn = 0, i_wck = 0;\n int i_icn = 0, i_ick = 0;\n\n double *mom_s_g1 = NULL, *mom_s_g2 = NULL;\n\n double rayleigh_mom2 = 0;\n double Delta = 0, Deltap = 0;\n\n double rayleigh_depol = 0.0, momk = 0.0;\n double *ssa_s = NULL, *dscale_s = NULL, *f_s = NULL, *ff_s = NULL, *g1_s = NULL, *g2_s = NULL, *dtau_s = NULL, *mom0_s = NULL;\n double wvl1 = 0, wvl2 = 0;\n\n int* tmp_ntheta_in = 0;\n float ** tmp_theta_in = NULL, *tmp_theta_new = NULL;\n double **tmp_mu_in = NULL, *tmp_mu_new = NULL;\n float ** tmp_phase_in = NULL, *tmp_phase_new = NULL;\n int n_in = 0, n_tot = 0, i = 0, ntheta_new = 0;\n double* interp_optprop_weight = NULL;\n int* phase_calloced = NULL;\n\n double one = 1.0;\n\n /* phase matrix element indices for polradtran */\n int ip_simp[6] = {0, 0, 0, 0, 0, 0};\n int ip_full[6] = {0, 1, 2, 3, 4, 5};\n int ip_red[6] = {0, 1, 2, 3, 0, 2};\n int** ip_act = NULL;\n\n n_caoth_alloc = n_caoth;\n i_wc = input.i_wc + 2;\n i_ic = input.i_ic + 2;\n /* in case either wc or ic is not existent, allocate a dummy */\n /* caoth, which is zero, and can be used for verbose output */\n if (i_ic == 1 || i_wc == 1)\n n_caoth_alloc++;\n /* set index of wc/ic to dummy caoth */\n if (i_wc == 1)\n i_wc = n_caoth_alloc - 1;\n if (i_ic == 1)\n i_ic = n_caoth_alloc - 1;\n\n /* allocate caoth arrays */\n babs_s = calloc (n_caoth_alloc, sizeof (double));\n bsca_s = calloc (n_caoth_alloc, sizeof (double));\n ssa_s = calloc (n_caoth_alloc, sizeof (double));\n babs_s_int = calloc (n_caoth_alloc, sizeof (double));\n bsca_s_int = calloc (n_caoth_alloc, sizeof (double));\n\n mom_s = calloc (n_caoth_alloc, sizeof (double*));\n mom_s_g1 = calloc (n_caoth_alloc, sizeof (double));\n mom_s_g2 = calloc (n_caoth_alloc, sizeof (double));\n dscale_s = calloc (n_caoth_alloc, sizeof (double));\n f_s = calloc (n_caoth_alloc, sizeof (double));\n ff_s = calloc (n_caoth_alloc, sizeof (double));\n g1_s = calloc (n_caoth_alloc, sizeof (double));\n g2_s = calloc (n_caoth_alloc, sizeof (double));\n dtau_s = calloc (n_caoth_alloc, sizeof (double));\n mom0_s = calloc (n_caoth_alloc, sizeof (double));\n\n babs_s_unsc = calloc (n_caoth_alloc, sizeof (double));\n bsca_s_unsc = calloc (n_caoth_alloc, sizeof (double));\n ssa_s_unsc = calloc (n_caoth_alloc, sizeof (double));\n babs_s_unsc_int = calloc (n_caoth_alloc, sizeof (double));\n bsca_s_unsc_int = calloc (n_caoth_alloc, sizeof (double));\n gg_s_unsc = calloc (n_caoth_alloc, sizeof (double));\n\n ip_act = calloc (n_caoth_alloc, sizeof (int*));\n\n /* */\n\n if (input.rte.polradtran[POLRADTRAN_NSTOKES] == 1)\n nphamat = 1;\n else if (input.rte.polradtran[POLRADTRAN_NSTOKES] > 1 && input.rte.polradtran[POLRADTRAN_NSTOKES] < 5)\n nphamat = 6;\n else\n fprintf (stderr, \"Input variable pol_nstokes is wrong! \\n\");\n\n output->nphamat = nphamat;\n\n if (nphamat == 6) {\n /* phase matrix element indices for last two elements in\n case of spherical symmetric particles */\n if (output->aer.optprop.nphamat == 4)\n ip_act[CAOTH_AER] = ip_red;\n else\n ip_act[CAOTH_AER] = ip_full;\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n /* phase matrix element indices for last two elements in\n\t case of spherical symmetric particles */\n if (output->caoth[ispo].optprop.nphamat == 4)\n ip_act[isp] = ip_red;\n else\n ip_act[isp] = ip_full;\n }\n\n } /* end if nphamat == 6 */\n else\n for (isp = CAOTH_AER; isp < n_caoth; isp++)\n ip_act[isp] = ip_simp;\n\n for (isp = 0; isp < n_caoth; isp++)\n mom_s[isp] = calloc (nphamat, sizeof (double));\n\n iv = iv1; /* iv needed both for Raman and not Raman when calculating phase function moments */\n if (input.raman) {\n iv1r = iv1 + output->wl.nlambda_rte_lower;\n iv2r = iv2 + output->wl.nlambda_rte_lower;\n }\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1)) {\n wvl1 = output->wl.lambda_r[iv1];\n wvl2 = output->wl.lambda_r[iv2];\n rayleigh_depol = linpol (wvl1, wvl2, output->rayleigh_depol[iv1r], output->rayleigh_depol[iv2r], wvl);\n } else {\n rayleigh_depol = output->rayleigh_depol[iv];\n }\n\n /* 2nd moment for Rayleigh scattering, including depolarization */\n rayleigh_mom2 = 0.2 * (1.0 - rayleigh_depol) / (2.0 + rayleigh_depol);\n\n /* Deltas in Eq. 2.16, Hansen and Travis, Space Science Rev., 16, 527-610, 1974.*/\n Delta = (1.0 - rayleigh_depol) / (1.0 + 0.5 * rayleigh_depol);\n Deltap = (1.0 + 2.0 * rayleigh_depol) / (1.0 - rayleigh_depol);\n\n if (verbose) {\n fprintf (stderr, \"... second moment for Rayleigh scattering: %f\\n\", rayleigh_mom2);\n fprintf (stderr, \"*** optical_properties()\\n\");\n if (output->cf.nlev == 0 || input.rte.solver == SOLVER_TWOMAXRND || input.rte.solver == SOLVER_TWOMAXRND3C ||\n input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) {\n fprintf (stderr,\n \" ------------------------------------------------------------------------------------------------------------------\"\n \"------------------------------------------------\\n\");\n fprintf (stderr,\n \" lc | z[km] | Rayleigh | Aerosol | Water cloud | Ice cloud \"\n \" | Molecular \\n\");\n fprintf (stderr,\n \" | | dtau | scatter. abs. asy. | scatter. abs. asy. | scatter. \"\n \"abs. asy. ff g1 g2 f | absorption \\n\");\n fprintf (stderr,\n \" ------------------------------------------------------------------------------------------------------------------\"\n \"------------------------------------------------\\n\");\n } else {\n fprintf (stderr,\n \" ------------------------------------------------------------------------------------------------------------------\"\n \"---------------------------\\n\");\n fprintf (stderr,\n \" lc | z[km] | Rayleigh | Aerosol | effective cloud (water and ice) \"\n \" | Molecular | Cloud \\n\");\n fprintf (stderr,\n \" | | dtau | scatter. abs. asy. | scatter. abs. asy. ff g1 g2 f \"\n \" | absorption | fraction\\n\");\n fprintf (stderr,\n \" ------------------------------------------------------------------------------------------------------------------\"\n \"---------------------------\\n\");\n }\n }\n\n if (first != 0) {\n first = 0;\n\n /* allocate memory for profiles */\n\n output->dtauc = (float*)calloc (nlyr, sizeof (float));\n output->dtauc_md = (float*)calloc (nlyr, sizeof (float));\n output->ssalb = (float*)calloc (nlyr, sizeof (float));\n\n output->dtauc_clr = (float*)calloc (nlyr, sizeof (float));\n output->ssalb_clr = (float*)calloc (nlyr, sizeof (float));\n\n output->dtauc_cldk = (float*)calloc (nlyr, sizeof (float));\n output->ssalb_cldk = (float*)calloc (nlyr, sizeof (float));\n\n output->dtauc_cldn = (float*)calloc (nlyr, sizeof (float));\n output->ssalb_cldn = (float*)calloc (nlyr, sizeof (float));\n\n if (input.tipa == TIPA_DIR)\n output->tausol = (float*)calloc (nlyr, sizeof (float)); /* ulrike: for tipa dir */\n if (input.raman) { //TODO: Delete this, never used\n output->ssalbR = (float*)calloc (nlyr, sizeof (float));\n output->ssalbRL = (float*)calloc (nlyr, sizeof (float));\n }\n\n if (input.rte.solver == SOLVER_MONTECARLO) {\n output->mc.z = (float*)calloc (nlev, sizeof (float));\n\n if (!input.atmosphere3d)\n ASCII_calloc_float_3D (&output->mc.temper,\n 1,\n 1,\n nlyr + 1); /* CE: temper is defined on levels, so cahnged nlyr -> nlyr+1 ??*/\n\n /* alternative: output->mc.caoth = calloc (n_caoth, sizeof(mc_caoth_struct)); */\n output->mc.dt = (float**)calloc (n_caoth, sizeof (float*));\n output->mc.om = (float**)calloc (n_caoth, sizeof (float*));\n output->mc.g1 = (float**)calloc (n_caoth, sizeof (float*));\n output->mc.g2 = (float**)calloc (n_caoth, sizeof (float*));\n output->mc.ff = (float**)calloc (n_caoth, sizeof (float*));\n output->mc.ds = (float**)calloc (n_caoth, sizeof (float*));\n output->mc.re = (float**)calloc (n_caoth, sizeof (float*));\n\n for (isp = 0; isp < n_caoth; isp++) {\n output->mc.dt[isp] = (float*)calloc (nlev, sizeof (float));\n output->mc.om[isp] = (float*)calloc (nlev, sizeof (float));\n output->mc.g1[isp] = (float*)calloc (nlev, sizeof (float));\n output->mc.g2[isp] = (float*)calloc (nlev, sizeof (float));\n output->mc.ff[isp] = (float*)calloc (nlev, sizeof (float));\n output->mc.ds[isp] = (float*)calloc (nlev, sizeof (float));\n output->mc.re[isp] = (float*)calloc (nlev, sizeof (float));\n }\n\n output->mc.refind = (float*)calloc (nlev, sizeof (float));\n\n /* SBCA clean this later */\n output->mc.nmomaer = (int*)calloc (nlev, sizeof (int));\n output->mc.momaer = (float***)calloc (nlev, sizeof (float**));\n\n //TODO: size: nlyr , nphamat, ntheta, Speicherzugriffsfehler, wenn nlev\n output->mc.nthetaaer = calloc (nlev, sizeof (int*));\n output->mc.thetaaer = calloc (nlev, sizeof (float**));\n output->mc.muaer = calloc (nlev, sizeof (double**));\n output->mc.phaseaer = calloc (nlev, sizeof (float**));\n\n for (isp = 0; isp < n_caoth; isp++) {\n for (lc = 0; lc < nlev; lc++) {\n output->mc.ff[isp][lc] = 1.0;\n }\n }\n }\n\n /* output->atm.nmom+1 stores the maximum number of moments */\n /* for all wavelengths and layers, minus 1 */\n\n status = ASCII_calloc_float_3D (&output->pmom, nlyr, nphamat, output->atm.nmom + 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d allocating memory for output->pmom\\n\", status);\n return status;\n }\n\n output->pmom01_clr = calloc (nlyr, sizeof (float));\n output->pmom01_cldk = calloc (nlyr, sizeof (float));\n output->pmom01_cldn = calloc (nlyr, sizeof (float));\n\n output->ntheta = calloc (nlyr, sizeof (int*));\n output->theta = calloc (nlyr, sizeof (float**));\n output->mu = calloc (nlyr, sizeof (double**));\n output->phase = calloc (nlyr, sizeof (float**));\n } /* end if first */\n else {\n if (!skip_optical_properties) {\n /* need to free mu theta phase */\n for (lc = 0; lc < nlyr; lc++) {\n if (output->ntheta[lc] != NULL) {\n for (ip = 0; ip < nphamat; ip++) {\n if (output->theta[lc][ip] != NULL)\n free (output->theta[lc][ip]);\n if (output->mu[lc][ip] != NULL)\n free (output->mu[lc][ip]);\n if (output->phase[lc][ip] != NULL)\n free (output->phase[lc][ip]);\n }\n free (output->ntheta[lc]);\n free (output->theta[lc]);\n free (output->mu[lc]);\n free (output->phase[lc]);\n }\n }\n }\n }\n\n if (!skip_optical_properties) {\n\n /* identify indices of \"wcn\" and \"wck\" CAOTHs (thiN and thicK clouds) for twomaxrnd3c */\n if (input.rte.solver == SOLVER_TWOMAXRND3C) {\n i_wcn = -1;\n i_wck = -1;\n i_icn = -1;\n i_ick = -1;\n\n for (isp = 0; isp < input.n_caoth; isp++) {\n if (strcasecmp (output->caoth[isp].name, \"wcn\") == 0)\n i_wcn = isp;\n\n if (strcasecmp (output->caoth[isp].name, \"wck\") == 0)\n i_wck = isp;\n\n if (strcasecmp (output->caoth[isp].name, \"ick\") == 0)\n i_ick = isp;\n\n if (strcasecmp (output->caoth[isp].name, \"icn\") == 0)\n i_icn = isp;\n }\n\n if (i_wcn < 0 || i_wck < 0) {\n fprintf (stderr, \"Error. Please define wck and wcn profiles for solver twomaxrnd3c!\\n\");\n return -1;\n }\n\n if ((i_icn >= 0 && i_ick < 0) || (i_ick >= 0 && i_icn < 0)) {\n fprintf (stderr, \"Error, please define both thin and thick ice clouds, icn and ick!\\n\");\n return -1;\n }\n\n if (!input.quiet)\n if (i_icn >= 0 && i_ick >= 0)\n fprintf (stderr, \" ... ice clouds for twomaxrnd3c found!\\n\");\n\n /* add offset CAOTH_FIR because elements 0 and 1 are reserved for MOL and AER */\n i_wcn += CAOTH_FIR;\n i_wck += CAOTH_FIR;\n\n if (i_icn > 0)\n i_icn += CAOTH_FIR;\n\n if (i_ick > 0)\n i_ick += CAOTH_FIR;\n\n if (input.verbose)\n fprintf (stderr, \" ... twomaxrnd3c(): i_wcn=%d, i_wck=%d\\n\", i_wcn, i_wck);\n\n if (!input.quiet)\n if (i_icn > 0 && i_ick > 0)\n fprintf (stderr, \" ... twomaxrnd3c(): i_icn=%d, i_ick=%d\\n\", i_icn, i_ick);\n }\n\n for (isp = 0; isp < n_caoth; isp++) {\n babs_s_int[isp] = 0.0;\n bsca_s_int[isp] = 0.0;\n }\n\n if (input.write_ext_to_file) {\n strcpy (extfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcat (extfilename, \".ext_r\");\n if ((extfile = fopen (extfilename, \"w\")) == NULL)\n return -1;\n }\n\n for (lc = 0; lc < nlyr; lc++) {\n\n switch (input.rte.solver) {\n case SOLVER_SSSI:\n /* special treatment for SOLVER_SSSI: caoth single scattering albedo is */\n /* set to 0 because caoth scattering is treated explicitely */\n /* through the tabulated caoth reflectivity; caoth then only */\n /* reduce radiance through Lambert-Beer */\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n output->caoth[ispo].optprop.ssa[iv][lc] = 0;\n }\n\n break;\n\n default:\n break;\n }\n\n /* only in the Fu and Liou case, the Rayleigh scattering */\n /* cross section depends on the subband */\n switch (input.ck_scheme) {\n case CK_FU:\n bsca_s[CAOTH_MOL] = output->atm.optprop.tau_rayleigh_r[0][0][lc][iv][iq];\n break;\n\n case CK_KATO:\n case CK_KATO2:\n case CK_KATO2_96:\n case CK_KATO2ANDWANDJI:\n case CK_AVHRR_KRATZ:\n case CK_FILE:\n case CK_LOWTRAN:\n case CK_CRS:\n case CK_REPTRAN:\n case CK_REPTRAN_CHANNEL:\n bsca_s[CAOTH_MOL] = output->atm.optprop.tau_rayleigh_r[0][0][lc][iv][0];\n break;\n\n case CK_RAMAN:\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n bsca_s[CAOTH_MOL] = linpol (wvl1,\n wvl2,\n output->atm.optprop.tau_rayleigh_r[0][0][lc][iv1r][0],\n output->atm.optprop.tau_rayleigh_r[0][0][lc][iv2r][0],\n wvl);\n else\n bsca_s[CAOTH_MOL] = output->atm.optprop.tau_rayleigh_r[0][0][lc][iq][0];\n break;\n\n default:\n fprintf (stderr, \"Error: unsupported correlated-k scheme %d\\n\", input.ck_scheme);\n return -1;\n\n break;\n }\n switch (output->atm.molabs) {\n case MOLABS_CALC:\n case MOLABS_LOOKUP:\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n babs_s[CAOTH_MOL] = linpol (wvl1,\n wvl2,\n output->atm.optprop.tau_molabs_r[0][0][lc][iv1r][0],\n output->atm.optprop.tau_molabs_r[0][0][lc][iv2r][0],\n wvl);\n else if (input.raman_fast && ir == 0)\n babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_r[0][0][lc][iv][0];\n else\n babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_r[0][0][lc][iv][iq];\n if (input.rte.solver == SOLVER_SDISORT)\n babs_mol_md = output->atm.optprop.tau_molabs_md_r[0][0][lc][iv][iq];\n else\n babs_mol_md = 0.0;\n break;\n\n case MOLABS_FILE_MONO:\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n babs_s[CAOTH_MOL] = linpol (wvl1,\n wvl2,\n output->atm.optprop.tau_molabs_r[0][0][lc][iv1r][0],\n output->atm.optprop.tau_molabs_r[0][0][lc][iv2r][0],\n wvl);\n else if (input.raman_fast && ir == 0)\n babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_r[0][0][lc][iv][0];\n else\n /* babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_user[lc]; */\n babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_r[0][0][lc][iv][iq];\n\n babs_mol_md = 0;\n break;\n\n case MOLABS_FILE_SPEC:\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n babs_s[CAOTH_MOL] = linpol (wvl1,\n wvl2,\n output->atm.optprop.tau_molabs_r[0][0][lc][iv1r][0],\n output->atm.optprop.tau_molabs_r[0][0][lc][iv2r][0],\n wvl);\n else if (input.raman_fast && ir == 0)\n babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_r[0][0][lc][iq][0];\n else\n babs_s[CAOTH_MOL] = output->atm.optprop.tau_molabs_r[0][0][lc][iv][iq];\n\n babs_mol_md = 0;\n break;\n\n case MOLABS_NONE:\n babs_s[CAOTH_MOL] = 0;\n babs_mol_md = 0;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown molecular absorption option %d\\n\", output->atm.molabs);\n return -1;\n }\n\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1)) {\n ssa_s[CAOTH_AER] = linpol (wvl1, wvl2, output->aer.optprop.ssa[iv1r][lc], output->aer.optprop.ssa[iv2r][lc], wvl);\n f_s[CAOTH_AER] = linpol (wvl1, wvl2, output->aer.optprop.f[iv1r][lc], output->aer.optprop.f[iv2r][lc], wvl);\n ff_s[CAOTH_AER] = linpol (wvl1, wvl2, output->aer.optprop.ff[iv1r][lc], output->aer.optprop.ff[iv2r][lc], wvl);\n g1_s[CAOTH_AER] = linpol (wvl1, wvl2, output->aer.optprop.g1[iv1r][lc], output->aer.optprop.g1[iv2r][lc], wvl);\n g2_s[CAOTH_AER] = linpol (wvl1, wvl2, output->aer.optprop.g2[iv1r][lc], output->aer.optprop.g2[iv2r][lc], wvl);\n dtau_s[CAOTH_AER] = linpol (wvl1, wvl2, output->aer.optprop.dtau[iv1r][lc], output->aer.optprop.dtau[iv2r][lc], wvl);\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n ssa_s[isp] =\n linpol (wvl1, wvl2, output->caoth[ispo].optprop.ssa[iv1r][lc], output->caoth[ispo].optprop.ssa[iv2r][lc], wvl);\n f_s[isp] = linpol (wvl1, wvl2, output->caoth[ispo].optprop.f[iv1r][lc], output->caoth[ispo].optprop.f[iv2r][lc], wvl);\n ff_s[isp] = linpol (wvl1, wvl2, output->caoth[ispo].optprop.ff[iv1r][lc], output->caoth[ispo].optprop.ff[iv2r][lc], wvl);\n g1_s[isp] = linpol (wvl1, wvl2, output->caoth[ispo].optprop.g1[iv1r][lc], output->caoth[ispo].optprop.g1[iv2r][lc], wvl);\n g2_s[isp] = linpol (wvl1, wvl2, output->caoth[ispo].optprop.g2[iv1r][lc], output->caoth[ispo].optprop.g2[iv2r][lc], wvl);\n dtau_s[isp] =\n linpol (wvl1, wvl2, output->caoth[ispo].optprop.dtau[iv1r][lc], output->caoth[ispo].optprop.dtau[iv2r][lc], wvl);\n dscale_s[isp] =\n linpol (wvl1, wvl2, output->caoth[ispo].optprop.dscale[iv1r][lc], output->caoth[ispo].optprop.dscale[iv2r][lc], wvl);\n }\n\n //20120816ak refind is not used, commented\n //\trefind = linpol( wvl1, wvl2, output->atm.microphys.refind[iv1r][lc],\n //\t\t\t output->atm.microphys.refind[iv2r][lc], wvl);\n } else {\n ssa_s[CAOTH_AER] = output->aer.optprop.ssa[iv][lc];\n f_s[CAOTH_AER] = output->aer.optprop.f[iv][lc];\n ff_s[CAOTH_AER] = output->aer.optprop.ff[iv][lc];\n g1_s[CAOTH_AER] = output->aer.optprop.g1[iv][lc];\n g2_s[CAOTH_AER] = output->aer.optprop.g2[iv][lc];\n dtau_s[CAOTH_AER] = output->aer.optprop.dtau[iv][lc];\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (output->caoth[ispo].optprop.ssa != NULL) {\n ssa_s[isp] = output->caoth[ispo].optprop.ssa[iv][lc];\n f_s[isp] = output->caoth[ispo].optprop.f[iv][lc];\n ff_s[isp] = output->caoth[ispo].optprop.ff[iv][lc];\n g1_s[isp] = output->caoth[ispo].optprop.g1[iv][lc];\n g2_s[isp] = output->caoth[ispo].optprop.g2[iv][lc];\n dtau_s[isp] = output->caoth[ispo].optprop.dtau[iv][lc];\n dscale_s[isp] = output->caoth[ispo].optprop.dscale[iv][lc];\n /* ?????????? */\n }\n }\n\n //20120816ak refind is not used, commented\n //\trefind = output->atm.microphys.refind[iv][lc];\n }\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++)\n ssa_s_unsc[isp] = ssa_s[isp] / (1.0 + f_s[isp] * (ssa_s[isp] - 1.0));\n\n /* absorption by aerosols and caoths */\n if (input.absorption) {\n for (isp = CAOTH_AER; isp < n_caoth; isp++)\n babs_s[isp] = (1.0 - ssa_s[isp]) * dtau_s[isp];\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++)\n babs_s_unsc[isp] = (1.0 - ssa_s_unsc[isp]) * dtau_s[isp] / (1.0 - ssa_s_unsc[isp] * f_s[isp]);\n\n babs_tot = 0.0;\n for (isp = 0; isp < n_caoth; isp++)\n babs_tot += babs_s[isp];\n\n babs_tot_md = babs_tot - babs_s[CAOTH_MOL] + babs_mol_md;\n\n if (babs_tot > FLT_MAX)\n babs_tot = FLT_MAX;\n if (babs_tot_md > FLT_MAX)\n babs_tot_md = FLT_MAX;\n } else {\n for (isp = 0; isp < n_caoth; isp++)\n babs_s[isp] = 0.0;\n\n babs_tot = 0.0;\n babs_tot_md = 0.0;\n babs_mol_md = 0.0;\n }\n\n /* scattering by non-molecules */\n for (isp = CAOTH_AER; isp < n_caoth; isp++)\n bsca_s[isp] = ssa_s[isp] * dtau_s[isp];\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++)\n bsca_s_unsc[isp] = ssa_s_unsc[isp] * dtau_s[isp] / (1.0 - ssa_s_unsc[isp] * f_s[isp]);\n\n /* switch scattering off, if user wants so */\n if (input.aer.no_scattering) {\n bsca_s[CAOTH_AER] = 0.0;\n bsca_s_unsc[CAOTH_AER] = 0.0;\n ssa_s[CAOTH_AER] = 0.0;\n }\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (input.caoth[ispo].no_scattering) {\n bsca_s[isp] = 0.0;\n bsca_s_unsc[isp] = 0.0;\n ssa_s[isp] = 0.0;\n }\n }\n\n /* Scattering coefficient */\n if (input.scattering) {\n bsca_tot = 0.0;\n for (isp = 0; isp < n_caoth; isp++)\n bsca_tot += bsca_s[isp];\n if (bsca_tot > FLT_MAX)\n bsca_tot = FLT_MAX;\n if (bsca_tot < FLT_MIN)\n bsca_tot = FLT_MIN;\n } else {\n for (isp = 0; isp < n_caoth; isp++) {\n bsca_s[isp] = 0.0;\n bsca_s_unsc[isp] = 0.0;\n ssa_s[isp] = 0.0;\n }\n bsca_tot = FLT_MIN;\n }\n\n /* Extinction coefficient */\n bext_tot = babs_tot + bsca_tot;\n if (bext_tot > FLT_MAX)\n bext_tot = FLT_MAX;\n if (bext_tot < FLT_MIN)\n bext_tot = FLT_MIN;\n\n bext_tot_md = babs_tot_md + bsca_tot;\n if (bext_tot_md > FLT_MAX)\n bext_tot_md = FLT_MAX;\n if (bext_tot_md < FLT_MIN)\n bext_tot_md = FLT_MIN;\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++)\n gg_s_unsc[isp] = g1_s[isp] * (1.0 - f_s[isp]) + f_s[isp];\n\n if (input.write_ext_to_file) {\n if (verbose && lc == 0)\n printf (\"...saving Extinction Data\\n\");\n\n /* ??? do we need this here: */\n /* if (output->cf.nlev == 0) { */\n\n /*\tfprintf (extfile, \"%5d %8.4f %9.6f %9.6f %9.6f %5.3f %11.6f %11.6f %5.3f %11.6f %11.6f %5.3f %5.3f %5.3f %6.3f %5.3f %11.6f\\n\", */\n fprintf (extfile,\n \"%5d %8.4f %11.6e %11.6e %11.6e %5.3f %11.6e %11.6e %5.3f %11.6e %11.6e %5.3f %5.3f %5.3f %6.3f %5.3f %11.6e\\n\",\n lc,\n output->atm.zd[lc + 1] + output->alt.altitude,\n /* Rayleigh */\n bsca_s[CAOTH_MOL],\n /* Aerosol, averaging of delta scaling factors for mixture of aerosol types not yet implemented !!!*/\n bsca_s[CAOTH_AER],\n babs_s[CAOTH_AER],\n g1_s[CAOTH_AER] * ff_s[CAOTH_AER] + (1.0 - ff_s[CAOTH_AER]) * g2_s[CAOTH_AER],\n /* Water cloud */\n bsca_s_unsc[i_wc],\n babs_s_unsc[i_wc],\n gg_s_unsc[i_wc] * ff_s[i_wc] + (1.0 - ff_s[i_wc]) * g2_s[i_wc],\n /* ice cloud */\n bsca_s_unsc[i_ic],\n babs_s_unsc[i_ic],\n gg_s_unsc[i_ic] * ff_s[i_ic] + (1.0 - ff_s[i_ic]) * g2_s[i_ic],\n ff_s[i_ic],\n gg_s_unsc[i_ic],\n g2_s[i_ic],\n f_s[i_ic],\n /* Molecules */\n babs_s[CAOTH_MOL]);\n }\n\n /* CE: Modified verbose output. Un-deltascaled optical properties are printed.*/\n if (verbose) {\n if (output->cf.nlev == 0 || input.rte.solver == SOLVER_TWOMAXRND || input.rte.solver == SOLVER_TWOMAXRND3C ||\n input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) {\n fprintf (stderr,\n \"%5d | %8.4f | %9.6e | %9.6f %9.6f %5.3f | %11.6f %11.6f %5.3f | %11.6f %11.6f %5.3f %5.3f %5.3f %6.3f %5.3f | \"\n \"%11.6e\\n\",\n lc,\n output->atm.zd[lc + 1] + output->alt.altitude,\n /* Rayleigh */\n bsca_s[CAOTH_MOL],\n /* Aerosol, averaging of delta scaling factors for mixture of aerosol types not yet implemented !!!*/\n bsca_s[CAOTH_AER],\n babs_s[CAOTH_AER],\n g1_s[CAOTH_AER] * ff_s[CAOTH_AER] + (1.0 - ff_s[CAOTH_AER]) * g2_s[CAOTH_AER],\n /* Water cloud */\n bsca_s_unsc[i_wc],\n babs_s_unsc[i_wc],\n gg_s_unsc[i_wc] * ff_s[i_wc] + (1.0 - ff_s[i_wc]) * g2_s[i_wc],\n /* ice cloud */\n bsca_s_unsc[i_ic],\n babs_s_unsc[i_ic],\n gg_s_unsc[i_ic] * ff_s[i_ic] + (1.0 - ff_s[i_ic]) * g2_s[i_ic],\n ff_s[i_ic],\n gg_s_unsc[i_ic],\n g2_s[i_ic],\n f_s[i_ic],\n /* Molecules */\n babs_s[CAOTH_MOL]);\n } else {\n fprintf (stderr,\n \"%5d | %8.4f | %9.6e | %9.6f %9.6f %5.3f | %11.6f %11.6f %5.3f %5.3f %5.3f %6.3f %5.3f | %11.6e | %.3f\\n\",\n lc,\n output->atm.zd[lc + 1] + output->alt.altitude,\n /* Rayleigh */\n bsca_s[CAOTH_MOL],\n /* Aerosol, averaging of delta scaling factors for mixture of aerosol types not yet implemented !!!*/\n bsca_s[CAOTH_AER],\n babs_s[CAOTH_AER],\n g1_s[CAOTH_AER] * ff_s[CAOTH_AER] + (1.0 - ff_s[CAOTH_AER]) * g2_s[CAOTH_AER],\n /* effective cloud, both */\n bsca_s_unsc[i_wc],\n babs_s_unsc[i_wc],\n gg_s_unsc[i_wc] * ff_s[i_wc] + (1.0 - ff_s[i_wc]) * g2_s[i_wc],\n ff_s[i_wc],\n gg_s_unsc[i_ic],\n g2_s[i_wc],\n f_s[i_ic], /* question to CE: does this make sense??? mixing wc and ic properties! */\n /* Molecules, Cloudfraction */\n babs_s[CAOTH_MOL],\n output->cf.cf[lc]);\n }\n }\n\n /* open polradtran input file and write extinction and scattering coefficients; */\n /* Legendre moments of the scattering phase function is added later - */\n /* therefore don't close yet! */\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n if ((fpol = fopen (&output->atm.pol_scat_files[lc * 64], \"w\")) == NULL)\n return 1;\n fprintf (fpol, \"%e\\n\", bext_tot);\n fprintf (fpol, \"%e\\n\", bsca_tot);\n fprintf (fpol, \"%e\\n\", bsca_tot / bext_tot);\n\n fprintf (fpol, \"%d\\n\", input.rte.nstr);\n }\n\n for (isp = 0; isp < n_caoth; isp++) {\n mom_s_g1[isp] = bsca_s[isp];\n mom_s_g2[isp] = bsca_s[isp];\n }\n\n output->pmom[lc][0][0] = 1.0;\n\n /* zero'th moment of of the scattering matrix */\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n /* Initialization */\n p_mom[0] = 1.0;\n for (ip = 1; ip < 6; ip++)\n p_mom[ip] = 0.0;\n\n if (nphamat == 6) {\n if (output->aer.optprop.nmom[iv][lc] > 0) {\n /* include polarization by aerosols */\n for (ip = 1; ip < 6; ip++)\n p_mom[ip] = mom_s_g1[CAOTH_AER] / bsca_tot * output->aer.optprop.moment[iv][lc][ip_act[CAOTH_AER][ip]][0];\n }\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (output->caoth[ispo].optprop.nmom[iv][lc] > 0) {\n /* include polarization by caoth */\n for (ip = 1; ip < 6; ip++)\n p_mom[ip] += mom_s_g1[isp] / bsca_tot * output->caoth[ispo].optprop.moment[iv][lc][ip_act[isp][ip]][0];\n }\n }\n\n /* Rayleigh depolarization */\n if (output->atm.rayleigh) { /* if statement should not be necessary */\n p_mom[1] += mom_s_g1[CAOTH_MOL] / bsca_tot * -0.5 * Delta;\n p_mom[4] += mom_s_g1[CAOTH_MOL] / bsca_tot * Delta;\n }\n } /* end if nphamat == 6 */\n\n fprintf (fpol, \"%d\", 0);\n for (ip = 0; ip < 6; ip++)\n fprintf (fpol, \" %f\", p_mom[ip]);\n fprintf (fpol, \"\\n\");\n }\n\n /* check that raman interpolation can work */\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1)) {\n if (output->aer.optprop.nmom[iv1r][lc] != output->aer.optprop.nmom[iv2r][lc]) {\n status = -1;\n fprintf (stderr, \"Number of aerosol moments must be equal for all wavelengths\\n\");\n fprintf (stderr, \"when Raman scattering is included.\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (output->caoth[ispo].optprop.nmom[iv1][lc] != output->caoth[ispo].optprop.nmom[iv2][lc]) {\n status = -1;\n fprintf (stderr, \"Number of %s moments must be equal for all wavelengths\\n\", output->caoth[ispo].fullname);\n fprintf (stderr, \"when Raman scattering is included.\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n }\n }\n\n /* zeroth moment needed for normalization */\n if (output->aer.optprop.nmom[iv][lc] > 0) {\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n mom0_s[CAOTH_AER] =\n linpol (wvl1, wvl2, output->aer.optprop.moment[iv1][lc][0][0], output->aer.optprop.moment[iv2][lc][0][0], wvl);\n else\n mom0_s[CAOTH_AER] = output->aer.optprop.moment[iv][lc][0][0];\n }\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (output->caoth[ispo].optprop.nmom != NULL) { /* rather ask if !montecarlo,\n\t\t\t\t\t\t\t or if mom0_s needed, SBCA */\n if (output->caoth[ispo].optprop.nmom[iv][lc] > 0) {\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n mom0_s[isp] = linpol (wvl1,\n wvl2,\n output->caoth[ispo].optprop.moment[iv1][lc][0][0],\n output->caoth[ispo].optprop.moment[iv2][lc][0][0],\n wvl);\n else\n mom0_s[isp] = output->caoth[ispo].optprop.moment[iv][lc][0][0];\n }\n }\n }\n\n for (k = 1; k <= output->atm.nmom; k++) {\n /* aerosol */\n if (output->aer.optprop.nmom[iv][lc] > 0) {\n if (k < output->aer.optprop.nmom[iv][lc]) {\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n momk =\n linpol (wvl1, wvl2, output->aer.optprop.moment[iv1r][lc][0][k], output->aer.optprop.moment[iv2r][lc][0][k], wvl);\n else\n momk = output->aer.optprop.moment[iv][lc][0][k];\n\n mom_s[CAOTH_AER][0] = bsca_s[CAOTH_AER] * momk / mom0_s[CAOTH_AER];\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n for (ip = 1; ip < nphamat; ip++)\n mom_s[CAOTH_AER][ip] = bsca_s[CAOTH_AER] * output->aer.optprop.moment[iv][lc][ip_act[CAOTH_AER][ip]][k];\n }\n } else {\n mom_s[CAOTH_AER][0] = 0;\n if (input.rte.solver == SOLVER_POLRADTRAN)\n for (ip = 0; ip < nphamat; ip++)\n mom_s[CAOTH_AER][ip] = 0;\n }\n } else { /* double Henyey-Greenstein */\n mom_s_g1[CAOTH_AER] *= g1_s[CAOTH_AER];\n mom_s_g2[CAOTH_AER] *= g2_s[CAOTH_AER];\n\n mom_s[CAOTH_AER][0] = (mom_s_g1[CAOTH_AER] * ff_s[CAOTH_AER] + (1.0 - ff_s[CAOTH_AER]) * mom_s_g2[CAOTH_AER]);\n }\n\n /* caoth */\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (output->caoth[ispo].optprop.nmom != NULL) { /* dito, SBCA */\n if (output->caoth[ispo].optprop.nmom[iv][lc] > 0) {\n if (k < output->caoth[ispo].optprop.nmom[iv][lc]) {\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1))\n momk = linpol (wvl1,\n wvl2,\n output->caoth[ispo].optprop.moment[iv1r][lc][0][k],\n output->caoth[ispo].optprop.moment[iv2r][lc][0][k],\n wvl);\n else\n momk = output->caoth[ispo].optprop.moment[iv][lc][0][k];\n\n mom_s[isp][0] = bsca_s[isp] * momk / mom0_s[isp];\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n for (ip = 1; ip < output->caoth[ispo].optprop.nphamat; ip++)\n mom_s[isp][ip] = bsca_s[isp] * output->caoth[ispo].optprop.moment[iv][lc][ip_act[isp][ip]][k];\n }\n } else {\n mom_s[isp][0] = 0;\n if (input.rte.solver == SOLVER_POLRADTRAN)\n for (ip = 1; ip < nphamat; ip++)\n mom_s[isp][ip] = 0;\n }\n } else { /* double Henyey-Greenstein */\n mom_s_g1[isp] *= g1_s[isp];\n mom_s_g2[isp] *= g2_s[isp];\n\n mom_s[isp][0] = (mom_s_g1[isp] * ff_s[isp] + (1.0 - ff_s[isp]) * mom_s_g2[isp]);\n }\n }\n }\n\n if (k == 2) /* Rayleigh scattering, including depolarization */\n mom_s[CAOTH_MOL][0] = bsca_s[CAOTH_MOL] * rayleigh_mom2;\n else\n mom_s[CAOTH_MOL][0] = 0.0;\n\n /* sum all moments, and normalize with bsca_tot */\n output->pmom[lc][0][k] = 0.0;\n if (k == 1) {\n output->pmom01_clr[lc] = 0.0;\n output->pmom01_cldk[lc] = 0.0;\n output->pmom01_cldn[lc] = 0.0;\n }\n\n for (isp = 0; isp < n_caoth; isp++) {\n output->pmom[lc][0][k] += mom_s[isp][0];\n\n if (input.rte.solver == SOLVER_TWOMAXRND || input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM ||\n input.rte.solver == SOLVER_DYNAMIC_TENSTREAM)\n if (isp != i_wc && isp != i_ic && k == 1)\n output->pmom01_clr[lc] += mom_s[isp][0];\n\n if (input.rte.solver == SOLVER_TWOMAXRND3C) {\n\n // clear := everything except thin and thick water and ice clouds\n if (k == 1)\n if (isp != i_wcn && isp != i_wck && isp != i_icn && isp != i_ick)\n output->pmom01_clr[lc] += mom_s[isp][0];\n\n // wck := everything except wcn and icn\n if (k == 1)\n if (isp != i_wcn && isp != i_icn)\n output->pmom01_cldk[lc] += mom_s[isp][0];\n\n // wcn := everything except wck and ick\n if (k == 1)\n if (isp != i_wck && isp != i_ick)\n output->pmom01_cldn[lc] += mom_s[isp][0];\n }\n }\n\n output->pmom[lc][0][k] /= bsca_tot;\n\n if (input.rte.solver == SOLVER_TWOMAXRND || input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM ||\n input.rte.solver == SOLVER_DYNAMIC_TENSTREAM)\n if (k == 1) {\n if (bsca_tot - bsca_s[i_wc] - bsca_s[i_ic] > 0)\n output->pmom01_clr[lc] /= (bsca_tot - bsca_s[i_wc] - bsca_s[i_ic]);\n else\n output->pmom01_clr[lc] = 0.0;\n }\n\n if (input.rte.solver == SOLVER_TWOMAXRND3C)\n if (k == 1) {\n double bsca_clr = bsca_tot - bsca_s[i_wck] - bsca_s[i_wcn];\n double bsca_cldk = bsca_tot - bsca_s[i_wcn];\n double bsca_cldn = bsca_tot - bsca_s[i_wck];\n\n if (i_icn > 0 && i_ick > 0) {\n bsca_clr -= (bsca_s[i_ick] - bsca_s[i_icn]);\n bsca_cldn -= bsca_s[i_ick];\n bsca_cldk -= bsca_s[i_icn];\n }\n\n if (bsca_clr > 0)\n output->pmom01_clr[lc] /= bsca_clr;\n else\n output->pmom01_clr[lc] = 0.0;\n\n if (bsca_cldk > 0)\n output->pmom01_cldk[lc] /= bsca_cldk;\n else\n output->pmom01_cldk[lc] = 0.0;\n\n if (bsca_cldn > 0)\n output->pmom01_cldn[lc] /= bsca_cldn;\n else\n output->pmom01_cldn[lc] = 0.0;\n }\n\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n for (ip = 0; ip < 6; ip++)\n p_mom[ip] = 0.0;\n /* already contains ip=0 element for rayleigh scattering (k==2) */\n for (ip = 0; ip < nphamat; ip++) {\n for (isp = 0; isp < n_caoth; isp++)\n p_mom[ip] += mom_s[isp][ip];\n p_mom[ip] *= (2 * k + 1) / bsca_tot;\n }\n\n /* add rayleigh depol for ip>0 */\n if (output->atm.rayleigh && nphamat == 6) { /* if statement (atm.rayleigh) should not be necessary */\n if (k == 1) {\n p_mom[2] += bsca_s[CAOTH_MOL] / bsca_tot * 1.5 * Delta;\n p_mom[5] += bsca_s[CAOTH_MOL] / bsca_tot * 1.5 * Delta * Deltap;\n }\n if (k == 2) {\n p_mom[1] += bsca_s[CAOTH_MOL] / bsca_tot * 0.5 * Delta;\n p_mom[4] += bsca_s[CAOTH_MOL] / bsca_tot * 0.5 * Delta;\n }\n }\n\n fprintf (fpol, \"%d\", k);\n for (ip = 0; ip < 6; ip++)\n fprintf (fpol, \" %f\", p_mom[ip]);\n fprintf (fpol, \"\\n\");\n }\n } /* end loop k */\n\n if (input.rte.solver == SOLVER_POLRADTRAN)\n fclose (fpol);\n\n /* phase functions */\n /* this should NOT be performed in case of MYSTIC solver!\n\t Basically, this should ONLY be done in case of\n\t SOLVER_FDISORT2/SOLVER_DISORT with new ICM, or with SOLVER_SSLIDAR */\n if (((input.rte.solver == SOLVER_FDISORT2 || input.rte.solver == SOLVER_DISORT) &&\n input.rte.disort_icm == DISORT_ICM_PHASE) ||\n input.rte.solver == SOLVER_SSLIDAR) {\n /* the following has strong resemblance with the function\n\t sort_and_add_weighted_phase in phasetable.c */\n\n n_in = 99; /* maximal possible number of n_ins to be defined */\n\n tmp_ntheta_in = calloc (n_in, sizeof (int));\n tmp_theta_in = calloc (n_in, sizeof (float*));\n tmp_mu_in = calloc (n_in, sizeof (double*));\n tmp_phase_in = calloc (n_in, sizeof (float*));\n phase_calloced = calloc (n_in, sizeof (int));\n interp_optprop_weight = calloc (n_in, sizeof (double));\n\n output->ntheta[lc] = calloc (nphamat, sizeof (int));\n output->theta[lc] = calloc (nphamat, sizeof (float*));\n output->mu[lc] = calloc (nphamat, sizeof (double*));\n output->phase[lc] = calloc (nphamat, sizeof (float*));\n\n /* for sslidar, we want this not only for P_11, but also for\n\t P_12 and P_22 */\n for (ip = 0; ip < nphamat; ip++) {\n\n /* find out number of phase functions already existent */\n n_in = 0;\n n_tot = 0;\n if (bsca_s[CAOTH_AER] > 0.0) {\n ips = ip_act[CAOTH_AER][ip];\n\n if (output->aer.optprop.ntheta[iv][lc][ips] > 0) {\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1)) {\n /* for raman, FIXME, THIS MAY NEEDED TO BE IMPROVED AKY20111605 */\n tmp_ntheta_in[n_in] = output->aer.optprop.ntheta[iv1r][lc][ips];\n tmp_theta_in[n_in] = output->aer.optprop.theta[iv1r][lc][ips];\n tmp_mu_in[n_in] = output->aer.optprop.mu[iv1r][lc][ips];\n tmp_phase_in[n_in] = output->aer.optprop.phase[iv1r][lc][ips];\n interp_optprop_weight[n_in] = bsca_s[CAOTH_AER] / bsca_tot * (wvl2 - wvl) / (wvl2 - wvl1);\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n } else {\n tmp_ntheta_in[n_in] = output->aer.optprop.ntheta[iv][lc][ips];\n tmp_theta_in[n_in] = output->aer.optprop.theta[iv][lc][ips];\n tmp_mu_in[n_in] = output->aer.optprop.mu[iv][lc][ips];\n tmp_phase_in[n_in] = output->aer.optprop.phase[iv][lc][ips];\n interp_optprop_weight[n_in] = bsca_s[CAOTH_AER] / bsca_tot;\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n }\n } else {\n if (output->aer.optprop.nmom[iv][lc] > 0) {\n /* only moments defined */\n fprintf (stderr,\n \"Error, you need to specify 'disort_intcor moments' in order to use these aerosol phase functions !\\n\");\n return -1;\n } else {\n if (ip > 0) {\n fprintf (stderr,\n \"Error, you are trying to combine aerosol Henyey-Greenstein with polarisation! This does not work!\\n\");\n return -1;\n }\n\n /* HG */\n status = create_phase_from_HG (g1_s[CAOTH_AER],\n &(tmp_ntheta_in[n_in]),\n &(tmp_theta_in[n_in]),\n &(tmp_mu_in[n_in]),\n &(tmp_phase_in[n_in]),\n input.rte.solver == SOLVER_SSLIDAR);\n if (status)\n return fct_err_out (status, \"create_phase_from_HG\", ERROR_POSITION);\n\n phase_calloced[n_in] = 1;\n\n interp_optprop_weight[n_in] = bsca_s[CAOTH_AER] / bsca_tot * ff_s[CAOTH_AER];\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n\n /* double HG */\n if (ff_s[CAOTH_AER] < 1.) {\n status = create_phase_from_HG (g2_s[CAOTH_AER],\n &(tmp_ntheta_in[n_in]),\n &(tmp_theta_in[n_in]),\n &(tmp_mu_in[n_in]),\n &(tmp_phase_in[n_in]),\n input.rte.solver == SOLVER_SSLIDAR);\n if (status)\n return fct_err_out (status, \"create_phase_from_HG\", ERROR_POSITION);\n\n phase_calloced[n_in] = 1;\n\n interp_optprop_weight[n_in] = bsca_s[CAOTH_AER] / bsca_tot * (1. - ff_s[CAOTH_AER]);\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n }\n }\n }\n } /* if bsca_s[CAOTH_AER] > 0 */\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (bsca_s[isp] > 0.0) {\n ips = ip_act[isp][ip];\n if (output->caoth[ispo].optprop.ntheta[iv][lc][ips] > 0) {\n if ((input.raman && !input.raman_fast) || (input.raman_fast && ir == 1)) {\n /* for raman, FIXME, THIS MAY NEEDED TO BE IMPROVED AKY20111605 */\n tmp_ntheta_in[n_in] = output->caoth[ispo].optprop.ntheta[iv1r][lc][ips];\n tmp_theta_in[n_in] = output->caoth[ispo].optprop.theta[iv1r][lc][ips];\n tmp_mu_in[n_in] = output->caoth[ispo].optprop.mu[iv1r][lc][ips];\n tmp_phase_in[n_in] = output->caoth[ispo].optprop.phase[iv1r][lc][ips];\n interp_optprop_weight[n_in] = bsca_s[isp] / bsca_tot * (wvl2 - wvl) / (wvl2 - wvl1);\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n } else {\n tmp_ntheta_in[n_in] = output->caoth[ispo].optprop.ntheta[iv][lc][ips];\n tmp_theta_in[n_in] = output->caoth[ispo].optprop.theta[iv][lc][ips];\n tmp_mu_in[n_in] = output->caoth[ispo].optprop.mu[iv][lc][ips];\n tmp_phase_in[n_in] = output->caoth[ispo].optprop.phase[iv][lc][ips];\n interp_optprop_weight[n_in] = bsca_s[isp] / bsca_tot;\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n }\n } else {\n if (output->caoth[ispo].optprop.nmom[iv][lc] > 0) {\n /* only moments defined */\n fprintf (stderr,\n \"Error, you need to specify 'disort_intcor moments' in order to use these %s phase functions !\\n\",\n output->caoth[ispo].fullname);\n return -1;\n } else {\n if (ip > 0) {\n fprintf (stderr,\n \"Error, you are trying to combine %s Henyey-Greenstein with polarisation! This does not work!\\n\",\n output->caoth[ispo].fullname);\n return -1;\n }\n\n /* HG */\n status = create_phase_from_HG (g1_s[isp],\n &(tmp_ntheta_in[n_in]),\n &(tmp_theta_in[n_in]),\n &(tmp_mu_in[n_in]),\n &(tmp_phase_in[n_in]),\n input.rte.solver == SOLVER_SSLIDAR);\n if (status)\n return fct_err_out (status, \"create_phase_from_HG\", ERROR_POSITION);\n\n phase_calloced[n_in] = 1;\n\n interp_optprop_weight[n_in] = bsca_s[isp] / bsca_tot * ff_s[isp];\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n\n /* double HG */\n if (ff_s[isp] < 1.) {\n status = create_phase_from_HG (g2_s[isp],\n &(tmp_ntheta_in[n_in]),\n &(tmp_theta_in[n_in]),\n &(tmp_mu_in[n_in]),\n &(tmp_phase_in[n_in]),\n input.rte.solver == SOLVER_SSLIDAR);\n if (status)\n return fct_err_out (status, \"create_phase_from_HG\", ERROR_POSITION);\n\n phase_calloced[n_in] = 1;\n\n interp_optprop_weight[n_in] = bsca_s[isp] / bsca_tot * (1. - ff_s[isp]);\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n }\n }\n }\n } /* end if (bsca_s[isp] > 0.0) */\n } /* end for isp */\n\n /* rayleigh */\n if (bsca_s[CAOTH_MOL] > 0.0) {\n status = create_phase_from_Rayleigh (rayleigh_depol,\n &(tmp_ntheta_in[n_in]),\n &(tmp_theta_in[n_in]),\n &(tmp_mu_in[n_in]),\n &(tmp_phase_in[n_in]),\n input.rte.solver == SOLVER_SSLIDAR,\n ip);\n phase_calloced[n_in] = 1;\n\n interp_optprop_weight[n_in] = bsca_s[CAOTH_MOL] / bsca_tot;\n n_tot += tmp_ntheta_in[n_in];\n n_in++;\n }\n\n if (input.rte.solver == SOLVER_SSLIDAR) {\n\n /* allocate theta dimension */\n output->theta[lc][ip] = calloc (1, sizeof (float));\n output->mu[lc][ip] = calloc (1, sizeof (double));\n output->phase[lc][ip] = calloc (1, sizeof (float));\n\n /* set trivial values for \"phase function\" */\n output->ntheta[lc][ip] = 1;\n output->theta[lc][ip][0] = 0.0;\n output->mu[lc][ip][0] = -1.0;\n\n /* interpolate backscatter direction */\n output->phase[lc][ip][0] = 0.0;\n for (i = 0; i < n_in; i++)\n output->phase[lc][ip][0] += interp_optprop_weight[i] * tmp_phase_in[i][0];\n\n } else {\n tmp_theta_new = calloc (n_tot, sizeof (float));\n tmp_mu_new = calloc (n_tot, sizeof (double));\n\n output->ntheta[lc][ip] = sort_theta_and_mu (n_in, tmp_ntheta_in, tmp_theta_in, tmp_theta_new, tmp_mu_in, tmp_mu_new);\n\n if (output->ntheta[lc][ip] == -1)\n return fct_err_out (-1, \"sort_theta_and_mu\", ERROR_POSITION);\n\n /* allocate theta dimension */\n output->theta[lc][ip] = calloc (output->ntheta[lc][ip], sizeof (float));\n output->mu[lc][ip] = calloc (output->ntheta[lc][ip], sizeof (double));\n output->phase[lc][ip] = calloc (output->ntheta[lc][ip], sizeof (float));\n\n /* copy new theta grid into target */\n for (i = 0; i < output->ntheta[lc][ip]; i++) {\n output->theta[lc][ip][i] = tmp_theta_new[i];\n output->mu[lc][ip][i] = tmp_mu_new[i];\n }\n\n /* interpolate phase */\n status = interpolate_phase_weighted (n_in,\n tmp_ntheta_in,\n tmp_mu_in,\n tmp_phase_in,\n interp_optprop_weight,\n output->ntheta[lc][ip],\n output->mu[lc][ip],\n output->phase[lc][ip],\n 0);\n\n if (status)\n return fct_err_out (status, \"interpolate_phase_weighted\", ERROR_POSITION);\n\n free (tmp_theta_new);\n free (tmp_mu_new);\n\n for (i = 0; i < n_in; i++) {\n if (phase_calloced[i]) {\n free (tmp_theta_in[i]);\n free (tmp_mu_in[i]);\n free (tmp_phase_in[i]);\n }\n }\n } /* end else (SOLVER_SSLIDAR) */\n } /* end for ip */\n\n free (tmp_ntheta_in);\n free (tmp_theta_in);\n free (tmp_mu_in);\n free (tmp_phase_in);\n free (interp_optprop_weight);\n free (phase_calloced);\n\n if (input.rte.solver != SOLVER_SSLIDAR)\n normalize_phase (output->mu[lc], output->phase[lc], NULL, output->ntheta[lc], 1, 0);\n\n } /* end (disort && disort_icm phase) || sslidar */\n\n /* total column for verbose output */\n /* CE: print un-deltascaled optical thickness. \n For Aerosol the averaging of the delta scaling\n factor is not yet implemented !!! */\n for (isp = 0; isp < n_caoth; isp++) {\n babs_s_int[isp] += babs_s[isp];\n bsca_s_int[isp] += bsca_s[isp];\n }\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n babs_s_unsc_int[isp] += babs_s_unsc[isp];\n bsca_s_unsc_int[isp] += bsca_s_unsc[isp];\n }\n\n /* Optical properties for the mc model */\n if (input.rte.solver == SOLVER_MONTECARLO) {\n for (isp = 0; isp < n_caoth; isp++)\n output->mc.dt[isp][nlyr - 1 - lc] = bsca_s[isp] + babs_s[isp];\n\n if (bsca_s[CAOTH_MOL] + babs_s[CAOTH_MOL] > 0.0)\n output->mc.om[CAOTH_MOL][nlyr - 1 - lc] = bsca_s[CAOTH_MOL] / (bsca_s[CAOTH_MOL] + babs_s[CAOTH_MOL]);\n else\n output->mc.om[CAOTH_MOL][nlyr - 1 - lc] = 0.0;\n\n /* in case absorption is turned off, molecular absorption is\n\t turned off somewhere else. Look for input.molabs */\n if (input.absorption)\n for (isp = CAOTH_AER; isp < n_caoth; isp++)\n output->mc.om[isp][nlyr - 1 - lc] = ssa_s[isp];\n else\n for (isp = CAOTH_AER; isp < n_caoth; isp++)\n output->mc.om[isp][nlyr - 1 - lc] = 1.0;\n\n for (isp = CAOTH_AER; isp < n_caoth; isp++) {\n output->mc.g1[isp][nlyr - 1 - lc] = g1_s[isp];\n output->mc.g2[isp][nlyr - 1 - lc] = g2_s[isp];\n output->mc.ff[isp][nlyr - 1 - lc] = ff_s[isp];\n }\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n /* effective droplet radius */\n output->mc.ds[isp][nlyr - 1 - lc] = dscale_s[isp];\n if (output->caoth[ispo].microphys.effr_layer != NULL)\n output->mc.re[isp][nlyr - 1 - lc] = output->caoth[ispo].microphys.effr_layer[lc];\n }\n\n /* ??? consequently, one should apply input.atm.interpol_method_refind; for reasons */\n /* ??? of lazyness we simply average the refractive index at the adjacent levels */\n /* ??? to get the layer property for MYSTIC */\n output->mc.refind[nlyr - 1 - lc] = 0.5 * (output->atm.microphys.refind[iv][lc] + output->atm.microphys.refind[iv][lc + 1]);\n\n if (input.rte.mc.spectral_is) {\n for (isp = 0; isp < n_caoth; isp++) {\n output->mc.alis.dt[iv][isp][nlyr - 1 - lc] = output->mc.dt[isp][nlyr - 1 - lc];\n output->mc.alis.om[iv][isp][nlyr - 1 - lc] = output->mc.om[isp][nlyr - 1 - lc];\n }\n }\n }\n\n /* Set optical depth and single scattering albedo */\n output->dtauc[lc] = bext_tot;\n output->dtauc_md[lc] = bext_tot_md;\n output->ssalb[lc] = bsca_tot / bext_tot;\n\n if (input.rte.solver == SOLVER_TWOMAXRND || input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM ||\n input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) {\n output->dtauc_clr[lc] = bext_tot - bsca_s[i_wc] - babs_s[i_wc] - bsca_s[i_ic] - babs_s[i_ic];\n\n if (output->dtauc_clr[lc] > 0)\n output->ssalb_clr[lc] = (bsca_tot - bsca_s[i_wc] - bsca_s[i_ic]) / output->dtauc_clr[lc];\n else\n output->ssalb_clr[lc] = 1.0;\n }\n\n if (input.rte.solver == SOLVER_TWOMAXRND3C) {\n double bsca_clr = 0;\n double bsca_cldn = 0;\n double bsca_cldk = 0;\n\n // clear := everything except thin and thick water and ice clouds\n output->dtauc_clr[lc] = bext_tot - bsca_s[i_wcn] - babs_s[i_wcn] - bsca_s[i_wck] - babs_s[i_wck];\n if (i_icn > 0 && i_ick > 0)\n output->dtauc_clr[lc] -= (bsca_s[i_icn] + babs_s[i_icn] + bsca_s[i_ick] + babs_s[i_ick]);\n\n bsca_clr = bsca_tot - bsca_s[i_wcn] - bsca_s[i_wck];\n if (i_icn > 0 && i_ick > 0)\n bsca_clr -= (bsca_s[i_icn] + bsca_s[i_ick]);\n\n if (output->dtauc_clr[lc] > 0)\n output->ssalb_clr[lc] = bsca_clr / output->dtauc_clr[lc];\n else\n output->ssalb_clr[lc] = 1.0;\n\n // wck := everything except thin water and ice clouds\n output->dtauc_cldk[lc] = bext_tot - bsca_s[i_wcn] - babs_s[i_wcn];\n if (i_icn > 0 && i_ick > 0)\n output->dtauc_cldk[lc] -= (bsca_s[i_icn] - babs_s[i_icn]);\n\n bsca_cldk = bsca_tot - bsca_s[i_wcn];\n if (i_icn > 0 && i_ick > 0)\n bsca_cldk -= bsca_s[i_icn];\n\n if (output->dtauc_cldk[lc] > 0)\n output->ssalb_cldk[lc] = bsca_cldk / output->dtauc_cldk[lc];\n else\n output->ssalb_cldk[lc] = 1.0;\n\n // wcn := everything except thick water and ice clouds\n output->dtauc_cldn[lc] = bext_tot - bsca_s[i_wck] - babs_s[i_wck];\n if (i_icn > 0 && i_ick > 0)\n output->dtauc_cldn[lc] -= (bsca_s[i_ick] + babs_s[i_ick]);\n\n bsca_cldn = bsca_tot - bsca_s[i_wck];\n if (i_icn > 0 && i_ick > 0)\n bsca_cldn -= bsca_s[i_ick];\n\n if (output->dtauc_cldn[lc] > 0)\n output->ssalb_cldn[lc] = bsca_cldn / output->dtauc_cldn[lc];\n else\n output->ssalb_cldn[lc] = 1.0;\n }\n\n /* ulrike: add dtau_mol, dtau_aer and tau_wc and tau_ic (the\n latter two are obtained from tipa (dir), see\n solve_rte.c (tipa_calcdtau); With tausol[lc] the\n direct radiation is then calculated and used for the\n calculation of the diffuse radiation */\n /* note: tausol is the SUM over all dtau's in layers above the\n\t level (lc) considered!!!*/\n if (input.tipa == TIPA_DIR) {\n if (!input.quiet && lc == 0)\n fprintf (stderr, \" ... (tipa dir) calculate total tau(sol) for every level\\n\");\n\n for (isp = CAOTH_FIR; isp < n_caoth; isp++)\n tau_babs_sum += babs_s[isp];\n\n output->tausol[lc] = tau_babs_sum;\n\n /* add dtau for caoth at the levels where caoth\n\t (due to tipa dir) contribute */\n /* output->caoth.tipa.taudircld is the tau of caoth along\n\t the beam, i.e. a sum over all layers up to 'caoth top' */\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if ((nlyr - lc) <= output->caoth[ispo].tipa.nztilt && output->caoth[ispo].tipa.nztilt > 0)\n output->tausol[lc] += output->caoth[ispo].tipa.taudircld[iv][nlyr - lc - 1];\n }\n }\n\n if (1.0 - output->ssalb[lc] < FLT_MIN)\n output->ssalb[lc] = 1.0 - FLT_MIN;\n\n } /* endfor (lc=0; lcntheta[lc][0] > 0) {\n n_tot += output->ntheta[lc][0];\n tmp_ntheta_in[n_in] = output->ntheta[lc][0];\n tmp_theta_in[n_in] = output->theta[lc][0];\n tmp_mu_in[n_in] = output->mu[lc][0];\n n_in++;\n }\n }\n\n tmp_theta_new = calloc (n_tot, sizeof (float));\n tmp_mu_new = calloc (n_tot, sizeof (double));\n\n /* find common mu grid */\n ntheta_new = sort_theta_and_mu (n_in, tmp_ntheta_in, tmp_theta_in, tmp_theta_new, tmp_mu_in, tmp_mu_new);\n if (ntheta_new == -1)\n return fct_err_out (-1, \"sort_theta_and_mu\", ERROR_POSITION);\n\n if (verbose)\n fprintf (stderr, \"The phase function for SOLVER_FDISORT2/cdisort is using %d grid points ...\\n\", output->ntheta[0][0]);\n\n for (lc = 0; lc < nlyr; lc++) {\n /* interpolate phase */\n tmp_phase_new = calloc (ntheta_new, sizeof (float));\n\n status = interpolate_phase_weighted (1,\n &(output->ntheta[lc][0]),\n &(output->mu[lc][0]),\n &(output->phase[lc][0]),\n &one,\n ntheta_new,\n tmp_mu_new,\n tmp_phase_new,\n 0);\n if (status)\n return fct_err_out (-1, \"interpolate_phase_weighted\", ERROR_POSITION);\n\n free (output->phase[lc][0]);\n output->phase[lc][0] = tmp_phase_new;\n }\n\n /* actually, only lc=0 is used from now on, but to avoid\n\t programming errors, we redefine all ntheta's, theta's, and\n\t mu's */\n for (lc = 0; lc < nlyr; lc++) {\n output->ntheta[lc][0] = ntheta_new;\n\n free (output->theta[lc][0]);\n free (output->mu[lc][0]);\n\n /* allocate theta dimension */\n output->theta[lc][0] = calloc (output->ntheta[0][0], sizeof (float));\n output->mu[lc][0] = calloc (output->ntheta[0][0], sizeof (double));\n\n /* copy new theta grid into target */\n for (i = 0; i < output->ntheta[0][0]; i++) {\n output->theta[lc][0][i] = tmp_theta_new[i];\n output->mu[lc][0][i] = tmp_mu_new[i];\n }\n }\n\n free (tmp_ntheta_in);\n free (tmp_theta_in);\n free (tmp_mu_in);\n free (tmp_theta_new);\n free (tmp_mu_new);\n\n /* phase function needs to be renormalized */\n for (lc = 0; lc < nlyr; lc++)\n normalize_phase (output->mu[0], output->phase[lc], NULL, output->ntheta[0], 1, 0);\n } /* end if disort && disort_icm phase */\n\n if (input.rte.solver == SOLVER_MONTECARLO) {\n\n for (isp = 0; isp < n_caoth; isp++) {\n output->mc.dt[isp][nlyr] = 0.0;\n output->mc.om[isp][nlyr] = 0.0;\n }\n\n /* loop includes nlyr because altitude and temperature */\n /* are defined per level */\n\n for (lc = 0; lc <= nlyr; lc++) {\n output->mc.z[nlyr - lc] = output->atm.zd[lc];\n if (!input.atmosphere3d)\n output->mc.temper[0][0][nlyr - lc] = output->atm.microphys.temper[0][0][lc];\n }\n\n /* loop stops at nlyr-1 because aerosol properties */\n /* are defined per layer*/\n output->mc.nphamataer = output->aer.optprop.nphamat;\n\n for (lc = 0; lc < nlyr; lc++) {\n\n output->mc.nmomaer[nlyr - lc - 1] = output->aer.optprop.nmom[iv][lc];\n output->mc.momaer[nlyr - lc - 1] = calloc (output->aer.optprop.nphamat, sizeof (float*));\n\n for (ip = 0; ip < output->aer.optprop.nphamat; ip++) {\n\n output->mc.momaer[nlyr - lc - 1][ip] = calloc (output->mc.nmomaer[nlyr - lc - 1], sizeof (float));\n\n /* ??? should free this memory later ??? */\n\n for (k = 0; k < output->mc.nmomaer[nlyr - lc - 1]; k++) {\n output->mc.momaer[nlyr - lc - 1][ip][k] =\n output->aer.optprop.moment[iv][lc][ip][k] / output->aer.optprop.moment[iv][lc][0][0];\n }\n }\n }\n\n /* we need to copy phase functions too */\n if (output->aer.optprop.ntheta[iv] != NULL) {\n for (lc = 0; lc < nlyr; lc++) {\n output->mc.nthetaaer[nlyr - lc - 1] = output->aer.optprop.ntheta[iv][lc];\n output->mc.thetaaer[nlyr - lc - 1] = output->aer.optprop.theta[iv][lc]; //TODO: Wird nicht benutzt?\n output->mc.muaer[nlyr - lc - 1] = output->aer.optprop.mu[iv][lc];\n output->mc.phaseaer[nlyr - lc - 1] = output->aer.optprop.phase[iv][lc];\n }\n }\n }\n\n#if HAVE_SSSI\n if (input.rte.solver == SOLVER_SSSI) {\n /* Total caoth optical thickness and top caoth level */\n /* for the SOLVER_SSSI approximation */\n output->sssi.tautot = 0.0;\n for (isp = 0; isp < n_caoth; isp++)\n output->sssi.tautot += bsca_s_int[isp];\n for (lc = 0; lc < nlyr; lc++) {\n for (isp = CAOTH_FIR; isp < n_caoth; isp++) {\n ispo = isp - CAOTH_FIR;\n if (output->caoth[ispo].optprop.dtau[iv][lc] > 0.0)\n break;\n }\n if (isp != n_caoth)\n break;\n }\n\n output->sssi.lctop = lc;\n\n /* the uppermost layer determines cloud phase */\n output->sssi.type =\n (output->caoth[i_wc].optprop.dtau[iv][lc] > output->caoth[i_ic].optprop.dtau[iv][lc] ? ISCCP_WATER : ISCCP_ICE);\n }\n#endif\n\n /* output vertical (total) sum */\n if (verbose) {\n if (output->cf.nlev == 0 || input.rte.solver == SOLVER_TWOMAXRND || input.rte.solver == SOLVER_TWOMAXRND3C ||\n input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) {\n fprintf (stderr,\n \" ----------------------------------------------------------------------------------------------------------------\"\n \"-------------------------------------------------\\n\");\n fprintf (stderr,\n \"%5s | %7.3f | %12.6e | %9.6f %9.6f %5.3f | %11.6f %11.6f %5.3f | %11.6f %11.6f %5.3f %5.3f %5.3f %6.3f %5.3f | \"\n \"%11.6f\\n\",\n \"sum\",\n 0.0 / 0.0,\n bsca_s_int[CAOTH_MOL],\n bsca_s_int[CAOTH_AER],\n babs_s_int[CAOTH_AER],\n 0.0 / 0.0,\n bsca_s_unsc_int[i_wc],\n babs_s_unsc_int[i_wc],\n 0.0 / 0.0,\n bsca_s_unsc_int[i_ic],\n babs_s_unsc_int[i_ic],\n 0.0 / 0.0,\n 0.0 / 0.0,\n 0.0 / 0.0,\n 0.0 / 0.0,\n 0.0 / 0.0,\n babs_s_int[CAOTH_MOL]);\n fprintf (stderr,\n \" ----------------------------------------------------------------------------------------------------------------\"\n \"-------------------------------------------------\\n\");\n } else {\n fprintf (stderr,\n \" ----------------------------------------------------------------------------------------------------------------\"\n \"----------------------\\n\");\n fprintf (stderr,\n \"%5s | %7.3f | %12.6e | %9.6f %9.6f %5.3f | %11.6f %11.6f %5.3f %5.3f %5.3f %6.3f %5.3f | %11.6f\\n\",\n \"sum\",\n 0.0 / 0.0,\n bsca_s_int[CAOTH_MOL],\n bsca_s_int[CAOTH_AER],\n babs_s_int[CAOTH_AER],\n 0.0 / 0.0,\n bsca_s_unsc_int[i_wc],\n babs_s_unsc_int[i_wc],\n 0.0 / 0.0,\n 0.0 / 0.0,\n 0.0 / 0.0,\n 0.0 / 0.0,\n 0.0 / 0.0,\n babs_s_int[CAOTH_MOL]);\n fprintf (stderr,\n \" ----------------------------------------------------------------------------------------------------------------\"\n \"---------------------\\n\");\n }\n }\n } /* if (!skip_optical_properties) { */\n else {\n if (verbose)\n fprintf (stderr, \" *** skip calculation of optical properties! iv = %4d, iq = %4d \\n\", iv, iq);\n }\n\n /* print only integrated optical properties to stderr */\n /* fprintf (stderr, \"%.0f %7.3f %12.6e %9.6f %9.6f %5.3f %11.6f %11.6f %5.3f %11.6f %11.6f %5.3f %5.3f %5.3f %6.3f %5.3f %11.6f\\n\", */\n /* 0.0, 0.0/0.0, */\n /* bsca_s_int[CAOTH_MOL], */\n /* bsca_s_int[CAOTH_AER], babs_s_int[CAOTH_AER], 0.0/0.0, */\n /* bsca_s_unsc_int[i_wc], babs_s_unsc_int[i_wc], 0.0/0.0, */\n /* bsca_s_unsc_int[i_ic], babs_s_unsc_int[i_ic], 0.0/0.0, */\n /* 0.0/0.0, 0.0/0.0, 0.0/0.0, 0.0/0.0, */\n /* babs_s_int[CAOTH_MOL]); */\n\n for (isp = 0; isp < n_caoth; isp++)\n free (mom_s[isp]);\n\n free (babs_s);\n free (bsca_s);\n free (ssa_s);\n free (babs_s_int);\n free (bsca_s_int);\n\n free (mom_s);\n free (mom_s_g1);\n free (mom_s_g2);\n free (dscale_s);\n free (f_s);\n free (ff_s);\n free (g1_s);\n free (g2_s);\n free (dtau_s);\n free (mom0_s);\n\n free (babs_s_unsc);\n free (bsca_s_unsc);\n free (ssa_s_unsc);\n free (babs_s_unsc_int);\n free (bsca_s_unsc_int);\n free (gg_s_unsc);\n\n free (ip_act);\n#if HAVE_NETCDF4\n\n // write optical properties to file for test suite //\n if (input.test_optical_properties) {\n status = 0;\n\n int ncid, retval;\n\n /********** Create netcdf file **********/\n if ((retval = nc_create (\"test.optical_properties.nc\", NC_CLOBBER, &ncid)))\n ERR (retval);\n if ((retval = nc_enddef (ncid)))\n ERR (retval);\n\n if ((retval = write_netcdf_3Dfloat (ncid,\n output->pmom,\n nlyr,\n nphamat,\n output->atm.nmom + 1,\n \"output_pmom\",\n \"nlyr\",\n \"nphamat\",\n \"nmom+1\")))\n ERR (retval);\n if (((input.rte.solver == SOLVER_FDISORT2 || input.rte.solver == SOLVER_DISORT) && input.rte.disort_icm == DISORT_ICM_PHASE) ||\n input.rte.solver == SOLVER_SSLIDAR) {\n if ((retval = write_netcdf_2Dint (ncid, output->ntheta, nlyr, nphamat, \"output_ntheta\", \"nlyr\", \"nphamat\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirrfloat (ncid,\n output->phase,\n nlyr,\n nphamat,\n output->ntheta,\n \"output_phase\",\n \"nlyr\",\n \"nphamat\",\n \"output_ntheta\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirrfloat (ncid,\n output->theta,\n nlyr,\n nphamat,\n output->ntheta,\n \"output_theta\",\n \"nlyr\",\n \"nphamat\",\n \"output_ntheta\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirrdouble (ncid,\n output->mu,\n nlyr,\n nphamat,\n output->ntheta,\n \"output_mu\",\n \"nlyr\",\n \"nphamat\",\n \"output_ntheta\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dfloat (ncid, output->dtauc, nlyr, \"output_dtauc\", \"nlyr\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dfloat (ncid, output->dtauc_md, nlyr, \"output_dtauc_md\", \"nlyr\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dfloat (ncid, output->ssalb, nlyr, \"output_ssalb\", \"nlyr\")))\n ERR (retval);\n }\n if (input.tipa == TIPA_DIR) {\n if ((retval = write_netcdf_1Dfloat (ncid, output->tausol, nlyr, \"output_tausol\", \"nlyr\")))\n ERR (retval);\n }\n#if HAVE_SSSI\n if (input.rte.solver == SOLVER_SSSI) {\n if ((retval = write_netcdf_float (ncid, output->sssi.tautot, \"output_sssi.tautot\")))\n ERR (retval);\n if ((retval = write_netcdf_int (ncid, output->sssi.lctop, \"output_sssi.lctop\")))\n ERR (retval);\n if ((retval = write_netcdf_int (ncid, output->sssi.type, \"output_sssi.type\")))\n ERR (retval);\n }\n#endif\n if (input.rte.solver == SOLVER_MONTECARLO) {\n if (output->mc.alis.dt != NULL) {\n if ((retval =\n write_netcdf_2Ddouble (ncid, output->mc.alis.dt[iv], n_caoth, nlev, \"output_mc.alis.dt[iv]\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n }\n if (output->mc.alis.om != NULL) {\n if ((retval =\n write_netcdf_2Ddouble (ncid, output->mc.alis.om[iv], n_caoth, nlev, \"output_mc.alis.om[iv]\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n }\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.dt, n_caoth, nlev, \"output_dt\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.om, n_caoth, nlev, \"output_om\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.g1, n_caoth, nlev, \"output_g1\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.g2, n_caoth, nlev, \"output_g2\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.ff, n_caoth, nlev, \"output_ff\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.ds, n_caoth, nlev, \"output_ds\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_2Dfloat (ncid, output->mc.re, n_caoth, nlev, \"output_re\", \"ncaoth\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dfloat (ncid, output->mc.refind, nlev, \"output_mc.refind\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dfloat (ncid, output->mc.z, nlev, \"output_mc.z\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dfloat (ncid, output->mc.temper[0][0], nlev, \"output_mc.temper\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_int (ncid, output->mc.nphamataer, \"output_mc.nphamataer\")))\n ERR (retval);\n if ((retval = write_netcdf_1Dint (ncid, output->mc.nmomaer, nlev, \"output_mc.nmomaer\", \"nlev\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirr_row_float (ncid,\n output->mc.momaer,\n nlev,\n output->aer.optprop.nphamat,\n output->mc.nmomaer,\n \"output_mc.momaer\",\n \"nlev\",\n \"output_aer.optprop.nphamat\",\n \"output_mc.nmomaer\")))\n ERR (retval);\n if (output->mc.nthetaaer != NULL) {\n if ((retval = write_netcdf_2Dint (ncid,\n output->mc.nthetaaer,\n nlyr,\n output->aer.optprop.nphamat,\n \"output_mc.nthetaaer\",\n \"nlyr\",\n \"output_aer.optprop.nphamat\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirrfloat (ncid,\n output->mc.thetaaer,\n nlyr,\n output->aer.optprop.nphamat,\n output->mc.nthetaaer,\n \"output_mc.thetaaer\",\n \"nlyr\",\n \"output_aer.optprop.nphamat\",\n \"output_mc.nthetaaer\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirrdouble (ncid,\n output->mc.muaer,\n nlyr,\n output->aer.optprop.nphamat,\n output->mc.nthetaaer,\n \"output_mc.muaer\",\n \"nlyr\",\n \"output_aer.optprop.nphamat\",\n \"output_mc.nthetaaer\")))\n ERR (retval);\n if ((retval = write_netcdf_3Dirrfloat (ncid,\n output->mc.phaseaer,\n nlyr,\n output->aer.optprop.nphamat,\n output->mc.nthetaaer,\n \"output_mc.phaseaer\",\n \"nlyr\",\n \"output_aer.optprop.nphamat\",\n \"output_mc.nthetaaer\")))\n ERR (retval);\n }\n }\n CHKERR (status);\n\n // Dump 3D optical properties in caoths\n for (isp = 0; isp < input.n_caoth; isp++) {\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_lwc\", output->caoth3d[isp].lwc);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_reff\", output->caoth3d[isp].reff);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_ext\", output->caoth3d[isp].ext);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_ssa\", output->caoth3d[isp].ssa);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_g1\", output->caoth3d[isp].g1);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_g2\", output->caoth3d[isp].g2);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_ff\", output->caoth3d[isp].ff);\n CHKERR (status);\n status = dump_caoth3d_var (ncid, isp, input.caoth[isp].name, output->caoth3d[isp], \"_f\", output->caoth3d[isp].f);\n CHKERR (status);\n } // end Dump 3D optical properties in caoths\n\n /********** Close the file. This frees up any internal netCDF resources\n * associated with the file, and flushes any buffers. **********/\n if ((retval = nc_close (ncid)))\n ERR (retval);\n }\n // finish writing optical properties to file for test suite //\n\n return 0;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any netCDF option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/***************************************/\n/* Post - processing of the output */\n/* sum or integration over wavelength, */\n/* calculation of heating rates or */\n/* conversion to RGB */\n/***************************************/\n\nint processing1D (input_struct input, output_struct* output) {\n int status = 0, iv = 0;\n char function_name[] = \"processing1D\";\n char file_name[] = \"ancillary.c\";\n\n switch (input.processing) {\n\n case PROCESS_NONE:\n if (input.calibration == OUTCAL_BRIGHTNESS) {\n if (!input.quiet)\n fprintf (stderr, \" ... converting radiances to brightness temperatures\\n\");\n\n /* convert irradiances / radiances to brightness temperatures */\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n status = output2bt (input, output, iv, 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by output2bt()\\n\", status);\n return status;\n }\n }\n break;\n\n case PROCESS_SUM:\n status = sum1D (input, output); /* multiply with extraterrestrial and sum up (function in ancillary.c) */\n if (status != 0) {\n fprintf (stderr, \"Error %d summing 1D output over wavelength in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n break;\n\n case PROCESS_INT:\n status = integrate1D (input, output); /* multiply with extraterrestrial and integrate (function in ancillary.c) */\n if (status != 0) {\n fprintf (stderr, \"Error %d integrating 1D output over wavelength in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n break;\n\n case PROCESS_RGB:\n case PROCESS_RGBNORM:\n status = spec2rgb (input, output); /* convert spectrum to red,green,blue space (function in ancillary.c) */\n if (status != 0) {\n fprintf (stderr, \"Error %d converting spectral output to RGB in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n break;\n\n case PROCESS_RAMAN:\n status = raman_spec2spec (input, output); /* convert Raman spectrum with extra wavelengths to user spectrum */\n if (status != 0) {\n fprintf (stderr, \"Error %d converting Ra manspectral output to user spectrum in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n break;\n\n default:\n fprintf (stderr, \"Error, unknown processing scheme %d in %s (%s)\\n\", input.processing, function_name, file_name);\n return -1;\n }\n\n return 0;\n}\n\n/***********************************************************************************/\n/* Sum the 1D results over wavelength and write data to the first array element */\n/***********************************************************************************/\n\nint sum1D (input_struct input, output_struct* output) {\n int lev = 0, iv = 0, iu = 0, j = 0, is = 0;\n int status = 0;\n\n /* calculate incident flux (output->incident) and sum extraterrestrial irradiance (wl.fbeam[0]) */\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n output->incident += output->wl.filter[iv] * output->wl.fbeam[iv] * cos (output->sza_h[iv] * PI / 180.0);\n if (iv != 0)\n output->wl.fbeam[0] += output->wl.filter[iv] * output->wl.fbeam[iv];\n else /* iv == 0 */\n output->wl.fbeam[0] = output->wl.filter[0] * output->wl.fbeam[0];\n }\n\n /* callocate integrated values */\n status = calloc_int_values (input, output);\n if (status != 0) {\n fprintf (stderr, \"error allocating integrated values, status %d\\n\", status);\n return status;\n }\n\n /* fluxes and radiances */\n for (lev = 0; lev < output->atm.nzout; lev++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n\n output->rfldir_int[lev] += (double)output->rfldir[lev][iv];\n output->rfldn_int[lev] += (double)output->rfldn[lev][iv];\n output->flup_int[lev] += (double)output->flup[lev][iv];\n output->uavg_int[lev] += (double)output->uavg[lev][iv];\n output->uavgso_int[lev] += (double)output->uavgso[lev][iv];\n output->uavgdn_int[lev] += (double)output->uavgdn[lev][iv];\n output->uavgup_int[lev] += (double)output->uavgup[lev][iv];\n if (input.heating != HEAT_NONE) {\n output->heat_int[lev] += (double)output->heat[lev][iv];\n output->emis_int[lev] += (double)output->emis[lev][iv];\n output->w_zout_int[lev] += (double)output->w_zout[lev][iv];\n }\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->u0u_int[lev][iu] += output->u0u[lev][iu][iv];\n\n for (j = 0; j < input.rte.nphi; j++)\n output->uu_int[lev][j][iu] += output->uu[lev][j][iu][iv];\n }\n }\n }\n\n /* polarized fluxes and radiances */\n if (input.rte.solver == SOLVER_POLRADTRAN)\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n for (lev = 0; lev < output->atm.nzout; lev++)\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n output->down_flux_int[lev][is] += output->down_flux[lev][is][iv];\n output->up_flux_int[lev][is] += output->up_flux[lev][is][iv];\n\n for (iu = 0; iu < input.rte.numu; iu++)\n for (j = 0; j < input.rte.nphi; j++) {\n output->down_rad_int[lev][j][iu][is] += output->down_rad[lev][j][iu][is][iv];\n output->up_rad_int[lev][j][iu][is] += output->up_rad[lev][j][iu][is][iv];\n }\n }\n }\n\n /* albedo, transmittance of total atmosphere */\n for (iu = 0; iu < input.rte.numu; iu++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n output->albmed_int[iu] += (double)output->albmed[iu][iv];\n output->trnmed_int[iu] += (double)output->trnmed[iu][iv];\n }\n }\n\n /* store integrated values in the first entry of the wavelength index, if any result fields are defined */\n if (output->wl.nlambda_h > 0)\n status += double2float_integrated_values (input, output);\n\n if (status != 0) {\n fprintf (stderr, \"Error, conversion from double to float not possible\");\n fprintf (stderr, \"sum1D(), ancillary.c, status %d\\n\", status);\n return status;\n }\n\n status += scaling_integrated_values (input, output);\n if (status != 0) {\n fprintf (stderr, \"Error, scaling integrated values.\\n\");\n fprintf (stderr, \"scaling_integrated_values(), in ancillary.c, status %d\\n\", status);\n return status;\n }\n\n return status;\n}\n\n/**************************************************************************************/\n/* Integrate the 1D results over wavelength and write data to the first array element */\n/**************************************************************************************/\n\nint integrate1D (input_struct input, output_struct* output) {\n int lev = 0, iv = 0, iu = 0, j = 0, is = 0;\n int status = 0, used_unit = 0;\n double *xint = NULL, *yint = NULL;\n double* cos_SZA = NULL;\n char function_name[] = \"integrate1D\";\n char file_name[] = \"ancillary.c\";\n\n /* callocate integrated values */\n status = calloc_int_values (input, output);\n if (status != 0) {\n fprintf (stderr, \"error allocating integrated values, status %d\\n\", status);\n return status;\n }\n\n /* calculate incident flux */\n xint = (double*)calloc (output->wl.nlambda_h, sizeof (double));\n if (xint == NULL)\n error_calloc (\"xint\", \"integrate1D\", &(status));\n yint = (double*)calloc (output->wl.nlambda_h, sizeof (double));\n if (yint == NULL)\n error_calloc (\"yint\", \"integrate1D\", &(status));\n\n if ((cos_SZA = calloc (output->wl.nlambda_h, sizeof (double))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for cos_SZA in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n switch (input.source) {\n case SRC_SOLAR:\n case SRC_LIDAR: /* BCA */\n case SRC_BLITZ: /* BCA */\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n cos_SZA[iv] = cos (output->sza_h[iv] * PI / 180.0);\n break;\n case SRC_THERMAL:\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n cos_SZA[iv] = 1.0;\n break;\n default:\n fprintf (stderr, \"Error, unknown source %d in %s (%s)\\n\", input.source, function_name, file_name);\n return -1;\n }\n\n used_unit = input.output_unit;\n if (used_unit == UNIT_NOT_DEFINED) /* if no output unit is specified, assume the same units as the input spectrum */\n used_unit = output->spectrum_unit;\n\n switch (used_unit) {\n case UNIT_PER_NM:\n if (input.verbose)\n fprintf (stderr, \" *** integration in wavelength space \\n\");\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n xint[iv] = (double)output->wl.lambda_h[iv];\n yint[iv] = output->wl.filter[iv] * output->wl.fbeam[iv] * cos_SZA[iv];\n }\n break;\n case UNIT_PER_CM_1:\n /* integration over wavenumber k, minus in order to get ascending wavenumbers */\n if (input.verbose)\n fprintf (stderr, \" *** integration in wavenumber space \\n\");\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n xint[iv] = -(double)1.0e+7 / output->wl.lambda_h[iv]; /* k = 10**7 / lambda */ /* 10**7 == nm -> cm */\n yint[iv] = output->wl.filter[iv] * output->wl.fbeam[iv] * cos_SZA[iv];\n }\n break;\n case UNIT_PER_BAND:\n fprintf (stderr, \"Error, combination 'output_process integrate' and 'output_process per_band',\\n\");\n fprintf (stderr, \" or combination 'output_process integrate' and an input spectrum defined in \\n\");\n fprintf (stderr, \" (wavelength or wavenumber) bands does not make sense \\n\");\n fprintf (stderr, \" please use 'output_process sum', when dealing with band parametrisations. \\n\\n\");\n return -1;\n break;\n case UNIT_NOT_DEFINED:\n fprintf (stderr, \"Error, in order to use 'output_process integrate' it is nessesary to specify the \\n\");\n fprintf (stderr, \" unit of the extraterrestrial spectrum with 'source solar filename unit' or\\n\");\n fprintf (stderr, \" unit of the output with 'output_process per_nm' or 'output_process per_cm-1' \\n\\n\");\n return -1;\n break;\n default:\n fprintf (stderr,\n \"Error: Program bug, unsupported unit of extraterrestial flux %d or output unit %d\\n\",\n output->spectrum_unit,\n input.output_unit);\n return -1;\n }\n\n output->incident = integrate (xint, yint, output->wl.nlambda_h);\n\n /* sum extraterrestrial irradiance */\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->wl.filter[iv] * output->wl.fbeam[iv];\n /* unit factor should alway be 1 here == output always in W/(m2 nm) */\n /* therefore it is not included here in the code */\n\n output->wl.fbeam[0] = (float)integrate (xint, yint, output->wl.nlambda_h);\n\n /* fluxes and radiances */\n for (iu = 0; iu < input.rte.numu; iu++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->albmed[iu][iv];\n output->albmed_int[iu] = integrate (xint, yint, output->wl.nlambda_h);\n }\n for (iu = 0; iu < input.rte.numu; iu++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->trnmed[iu][iv];\n output->trnmed_int[iu] = integrate (xint, yint, output->wl.nlambda_h);\n }\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->rfldir[lev][iv];\n output->rfldir_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->rfldn[lev][iv];\n output->rfldn_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->flup[lev][iv];\n output->flup_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->uavg[lev][iv];\n output->uavg_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->uavgso[lev][iv];\n output->uavgso_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->uavgdn[lev][iv];\n output->uavgdn_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->uavgup[lev][iv];\n output->uavgup_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n if (input.heating != HEAT_NONE) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->heat[lev][iv];\n output->heat_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->emis[lev][iv];\n output->emis_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->w_zout[lev][iv];\n output->w_zout_int[lev] = integrate (xint, yint, output->wl.nlambda_h);\n }\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = (double)output->u0u[lev][iu][iv];\n output->u0u_int[lev][iu] = integrate (xint, yint, output->wl.nlambda_h);\n\n for (j = 0; j < input.rte.nphi; j++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = (double)output->uu[lev][j][iu][iv];\n output->uu_int[lev][j][iu] = integrate (xint, yint, output->wl.nlambda_h);\n }\n }\n }\n\n /* polarized fluxes and radiances */\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->down_flux[lev][is][iv];\n output->down_flux_int[lev][is] = (float)integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->up_flux[lev][is][iv];\n output->up_flux_int[lev][is] = (float)integrate (xint, yint, output->wl.nlambda_h);\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n for (j = 0; j < input.rte.nphi; j++) {\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->down_rad[lev][j][iu][is][iv];\n output->down_rad_int[lev][j][iu][is] = (float)integrate (xint, yint, output->wl.nlambda_h);\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->up_rad[lev][j][iu][is][iv];\n output->up_rad_int[lev][j][iu][is] = (float)integrate (xint, yint, output->wl.nlambda_h);\n }\n }\n }\n }\n }\n\n free (xint);\n free (yint);\n\n /* store integrated values in the first entry of the wavelength index */\n if (output->wl.nlambda_h > 0)\n status += double2float_integrated_values (input, output);\n\n if (status != 0) {\n fprintf (stderr, \"Error, conversion from double to float not possible\");\n fprintf (stderr, \"integrate1D(), ancillary.c, status %d\\n\", status);\n return status;\n }\n\n status += scaling_integrated_values (input, output);\n if (status != 0) {\n fprintf (stderr, \"Error, scaling integrated values.\\n\");\n fprintf (stderr, \"integrate1D(), in ancillary.c, status %d\\n\", status);\n return status;\n }\n\n return status;\n}\n\nstatic int write_triangular_surface_results (const input_struct input, const output_struct* output) {\n if (!output->triangle_results_o)\n return 0;\n if (!output->triangle_results_o[0]->N_triangles)\n return 0;\n const t_triangle_radiation_field* out = output->triangle_results_o[0];\n\n const int ldebug = 0;\n if (ldebug) {\n for (size_t i = 0; i < out->N_triangles; ++i) {\n fprintf (stderr, \"Surface fluxes on triangle %lu => %f %f %f\\n\", i, out->edir[i], out->edn[i], out->eup[i]);\n }\n }\n\n { // write netcdf\n int ierr;\n int ncid;\n char filename[FILENAME_MAX] = \"\";\n strcpy (filename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcat (filename, \".flx.triangle.nc\");\n // Create the file. overwrite this file, if it already exists\n if ((ierr = nc_create (filename, NC_CLOBBER, &ncid)))\n CHKERR (ierr);\n if ((ierr = nc_enddef (ncid)))\n CHKERR (ierr);\n\n if ((ierr = write_netcdf_1Dsize_t (ncid, out->ndir, out->N_triangles, \"count_edir\", \"Ntriangles\")))\n CHKERR (ierr);\n if ((ierr = write_netcdf_1Dsize_t (ncid, out->ndn, out->N_triangles, \"count_edn\", \"Ntriangles\")))\n CHKERR (ierr);\n if ((ierr = write_netcdf_1Dsize_t (ncid, out->nup, out->N_triangles, \"count_eup\", \"Ntriangles\")))\n CHKERR (ierr);\n\n if ((ierr = write_netcdf_1Ddouble (ncid, out->edir, out->N_triangles, \"edir\", \"Ntriangles\")))\n CHKERR (ierr);\n if ((ierr = write_netcdf_1Ddouble (ncid, out->edn, out->N_triangles, \"edn\", \"Ntriangles\")))\n CHKERR (ierr);\n if ((ierr = write_netcdf_1Ddouble (ncid, out->eup, out->N_triangles, \"eup\", \"Ntriangles\")))\n CHKERR (ierr);\n if ((ierr = nc_close (ncid)))\n CHKERR (ierr);\n }\n return 0;\n}\n\n/***************************************/\n/* Post - processing of the output */\n/* sum or integration over wavelength, */\n/* calculation of heating rates or */\n/* conversion to RGB */\n/***************************************/\n\nint processing3D (input_struct input, output_struct* output) {\n int status = 0;\n\n int is = 0, js = 0, ks = 0, iv = 0, lc = 0;\n float scale_factor_abs3d = 1.0;\n float dz = NOT_DEFINED_FLOAT;\n float c_p = NOT_DEFINED_FLOAT;\n float rho_air = NOT_DEFINED_FLOAT;\n\n char function_name[] = \"processing3D\";\n char file_name[] = \"ancillary.c\";\n\n if (input.rte.mc.locest)\n return 0;\n\n output->wl.nlambda_h_print3D = output->wl.nlambda_h;\n\n switch (input.processing) {\n\n case PROCESS_NONE:\n if (input.calibration == OUTCAL_BRIGHTNESS) {\n if (!input.quiet)\n fprintf (stderr, \" ... converting radiances to brightness temperatures\\n\");\n\n /* convert irradiances / radiances to brightness temperatures */\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n status = output2bt (input, output, iv, 1);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by output2bt()\\n\", status);\n return status;\n }\n }\n break;\n\n case PROCESS_SUM:\n status = sum3D (input, output);\n if (status != 0) {\n fprintf (stderr, \"Error %d summing 3D output over wavelength in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n output->wl.nlambda_h_print3D = 1;\n break;\n\n case PROCESS_INT:\n status = integrate3D (input, output);\n if (status != 0) {\n fprintf (stderr, \"Error %d integrating 3D output over wavelength in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n output->wl.nlambda_h_print3D = 1;\n break;\n\n case PROCESS_RGB:\n case PROCESS_RGBNORM:\n status = spec2rgb3D (input, output); /* convert spectrum to red,green,blue space (function in ancillary.c) */\n if (status != 0) {\n fprintf (stderr, \"Error %d converting spectral output to RGB in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n output->wl.nlambda_h_print3D = 3;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown processing scheme %d in %s (%s)\\n\", input.processing, function_name, file_name);\n return -1;\n }\n\n /* convert unit of absorbed irradiance */\n\n switch (input.rte.mc.abs_unit) {\n case MCABS_UNIT_W_PER_M2_AND_DZ:\n /* default -> no change */\n break;\n\n case MCABS_UNIT_W_PER_M3:\n case MCABS_UNIT_K_PER_DAY:\n\n if (input.rte.mc.absorption != MCFORWARD_ABS_NONE) {\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks]) { /* only for 3D layers, BM07122005 */\n\n scale_factor_abs3d = 1.0;\n\n /* find model level corresponding to the user level - there must be a better way to do that! */\n if (input.rte.mc.abs_unit == MCABS_UNIT_K_PER_DAY) {\n\n rho_air = output->atm.microphys.dens_avg[MOL_AIR][0][0][output->atm.Nzcld - 1 - ks] * 1.e+6 * 1.e-3 *\n input.atm.mol_mass[MOL_AIR] / AVOGADRO;\n\n /* 1.e+6: convert from cm-3 to m-3; 1.e-3: convert g -> kg */\n status = specific_heat_capacity_moist_air (output->atm.microphys.temper_avg[0][0][output->atm.Nzcld - 1 - ks],\n output->atm.microphys.dens_avg[MOL_AIR][0][0][output->atm.Nzcld - 1 - ks],\n output->atm.microphys.dens_avg[MOL_H2O][0][0][output->atm.Nzcld - 1 - ks],\n &(c_p),\n input.quiet);\n if (status != 0) {\n fprintf (stderr, \"Error, calculating 'c_p' of moist air in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n scale_factor_abs3d = scale_factor_abs3d * s2day / (c_p * rho_air);\n }\n\n dz = (output->atm.zd[output->atm.Nzcld - ks - 1] - output->atm.zd[output->atm.Nzcld - ks]) * 1000.0; /* 1000 == km -> m */\n scale_factor_abs3d = scale_factor_abs3d / dz;\n\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++)\n for (iv = 0; iv < output->wl.nlambda_h_print3D; iv++) { /* **CK added bracket */\n output->abs3d[ks][is][js][iv] *= scale_factor_abs3d;\n if (input.rte.mc.std) /* **CK for forward mc_std */\n output->abs3d_var[ks][is][js][iv] *= (scale_factor_abs3d * scale_factor_abs3d);\n }\n }\n }\n\n if (input.rte.mc.backward.absorption) {\n for (ks = 0; ks < output->atm.nzout; ks++) {\n\n scale_factor_abs3d = 1.0;\n\n /* determine the model layer corresponding to our zout layer; */\n /* there must be a better way? */\n for (lc = 0; lc < output->atm.nlev; lc++)\n if (float_equal (output->atm.zd[lc], output->atm.zout_sur[ks]))\n break;\n\n if (lc >= output->atm.nlev)\n lc = output->atm.nlev - 1;\n\n if (input.rte.mc.abs_unit == MCABS_UNIT_K_PER_DAY) {\n rho_air = output->atm.microphys.dens_avg[MOL_AIR][0][0][lc - 1] * 1.e+6 * 1.e-3 * input.atm.mol_mass[MOL_AIR] / AVOGADRO;\n\n /* 1.e+6: convert from cm-3 to m-3; 1.e-3: convert g -> kg */\n status = specific_heat_capacity_moist_air (output->atm.microphys.temper_avg[0][0][lc - 1],\n output->atm.microphys.dens_avg[MOL_AIR][0][0][lc - 1],\n output->atm.microphys.dens_avg[MOL_H2O][0][0][lc - 1],\n &(c_p),\n input.quiet);\n if (status != 0) {\n fprintf (stderr, \"Error, calculating 'c_p' of moist air in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n scale_factor_abs3d = scale_factor_abs3d * s2day / (c_p * rho_air);\n }\n\n dz = (output->atm.zd[lc - 1] - output->atm.zd[lc]) * 1000.0; /* 1000 == km -> m */\n scale_factor_abs3d = scale_factor_abs3d / dz;\n\n if (!input.quiet && input.ipa3d != 1) /*ulrike added && input.ipa3d!=1*/\n fprintf (stderr,\n \"converting to heating rate, level %d %.3f - %.3f km, dens=%g, temper=%.3f, scale_factor %f\\n\",\n lc,\n output->atm.zd[lc],\n output->atm.zd[lc - 1],\n output->atm.microphys.dens_avg[MOL_AIR][0][0][lc - 1],\n output->atm.microphys.temper_avg[0][0][lc - 1],\n scale_factor_abs3d);\n\n /* ulrike 4.5.2010: absback3d is used to save the heating rates in case of ipa3d and \n\t absback3d is written into mc.abs.spc when mc_backward_output heat K_per_day\n\t is specified in the input-file; however, no further scaling of absback3d is necessary\n\t (scaling of absback3d was done in scale_output in ancillary.c) */\n if (input.ipa3d != 1)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep)\n for (iv = 0; iv < output->wl.nlambda_h_print3D; iv++) {\n output->absback3d[ks][is][js][iv] *= scale_factor_abs3d;\n /* 27.02.2013 **CK **BM: for thermal backward heating rates std */\n if (input.rte.mc.std)\n output->absback3d_var[ks][is][js][iv] *= (scale_factor_abs3d * scale_factor_abs3d);\n }\n } /* endfor (ks=0; ksatm.nzout; ks++) */\n } /* endif (input.rte.mc.backward.absorption) */\n\n break;\n default:\n fprintf (stderr, \"Error, unknown abs_unit %d in %s (%s)\\n\", input.rte.mc.abs_unit, function_name, file_name);\n return -1;\n }\n\n /* write 3D data to files */\n status = write_spectral3D (input, output);\n if (status != 0) {\n fprintf (stderr, \"Error %d writing spectral 3D output in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n status = write_triangular_surface_results (input, output);\n CHKERR (status);\n\n return 0;\n}\n\n/***********************************************************************************/\n/* Sum the 3D results over wavelength and print data to mc.sum */\n/***********************************************************************************/\n\nstatic int write_spectral3D (input_struct input, output_struct* output) {\n int status = 0;\n\n int doflx = 1; /* switch that turns off writing of flx files. Should be determined automatically */\n int is = 0, js = 0, ks = 0, iv = 0, ip = 0, ic = 0, isp = 0, kc = 0, ivs = 0;\n\n char flxfilename[FILENAME_MAX] = \"\";\n char radfilename[FILENAME_MAX] = \"\";\n char absfilename[FILENAME_MAX] = \"\";\n char jacfilename[FILENAME_MAX] = \"\";\n char flxisfilename[FILENAME_MAX] = \"\";\n\n char flxvarfilename[FILENAME_MAX] = \"\";\n char radvarfilename[FILENAME_MAX] = \"\";\n char absvarfilename[FILENAME_MAX] = \"\"; /* 27.02.2013 **CK **BM: add new variable for thermal backward heating rates std */\n\n FILE *fflx = NULL, *fflxvar = NULL, *fabs = NULL, *fabsvar = NULL, *frad = NULL, *fradvar = NULL, *fjac = NULL,\n *fflxis = NULL; /* 27.02.2013 **CK **BM: add *fabsvar=NULL for thermal backward heating rates std */\n\n char function_name[] = \"write_spectral3D\";\n char file_name[] = \"ancillary.c\";\n\n /* generate output file names */\n strcpy (flxfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcpy (absfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcpy (radfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n\n strcpy (flxvarfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcpy (radvarfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcpy (absvarfilename,\n input.rte.mc.filename[FN_MC_BASENAME]); /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n\n strcat (flxfilename, \".flx.spc\");\n strcat (radfilename, \".rad.spc\");\n\n strcat (flxvarfilename, \".flx.std.spc\");\n strcat (radvarfilename, \".rad.std.spc\");\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n strcpy (jacfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcat (jacfilename, \".jac.spc\");\n }\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n strcpy (flxisfilename, input.rte.mc.filename[FN_MC_BASENAME]);\n strcat (flxisfilename, \".flx.is.spc\");\n }\n\n /* extension for absorption/heating/actinic etc. file */\n switch (input.rte.mc.absorption) {\n case MCFORWARD_ABS_ACTINIC:\n strcat (absfilename, \".act.spc\");\n strcat (absvarfilename, \".act.std.spc\"); /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n break;\n\n case MCFORWARD_ABS_ABSORPTION:\n case MCFORWARD_ABS_EMISSION:\n case MCFORWARD_ABS_HEATING:\n case MCFORWARD_ABS_NONE:\n strcat (absfilename, \".abs.spc\");\n strcat (absvarfilename, \".abs.std.spc\"); /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n break;\n\n default:\n fprintf (stderr, \"Error, unknown absorption type %d\\n\", input.rte.mc.absorption);\n break;\n }\n\n if (doflx == 1) {\n if ((fflx = fopen (flxfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", flxfilename, function_name, file_name);\n return -1;\n }\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n if ((fflxis = fopen (flxisfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", flxisfilename, function_name, file_name);\n return -1;\n }\n }\n }\n\n if ((frad = fopen (radfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", radfilename, function_name, file_name);\n return -1;\n }\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n if ((fjac = fopen (jacfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", jacfilename, function_name, file_name);\n return -1;\n }\n }\n\n /* variances */\n if (input.rte.mc.std) {\n if (doflx == 1) {\n if ((fflxvar = fopen (flxvarfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", flxvarfilename, function_name, file_name);\n return -1;\n }\n }\n\n if ((fradvar = fopen (radvarfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", radvarfilename, function_name, file_name);\n return -1;\n }\n }\n\n for (iv = 0; iv < output->wl.nlambda_h_print3D; iv++)\n for (ks = 0; ks < output->atm.nzout; ks++)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n if (doflx == 1) {\n fprintf (fflx,\n \"%9.5f %4d %4d %4d %.8e %.8e %.8e %.8e %.8e %.8e\\n\",\n output->wl.lambda_h[iv],\n is,\n js,\n ks,\n output->rfldir3d[ks][is][js][iv],\n output->rfldn3d[ks][is][js][iv],\n output->flup3d[ks][is][js][iv],\n output->uavgso3d[ks][is][js][iv],\n output->uavgdn3d[ks][is][js][iv],\n output->uavgup3d[ks][is][js][iv]);\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n fprintf (fflxis,\n \"%9.5f %4d %4d %4d %4d %g\\n\",\n output->wl.lambda_h[iv],\n ic,\n is,\n js,\n ks,\n output->fl3d_is[ks][is][js][ic][iv]);\n }\n }\n }\n\n /* FIXCE reformat output for concentration_is ???? */\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n fprintf (frad,\n \"%9.5f %4d %4d %4d %g\\n\",\n output->wl.lambda_h[iv],\n is,\n js,\n ks,\n output->radiance3d[ks][is][js][ip][ic][iv]);\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n for (kc = 0; kc < output->atm.nlev - 1; kc++) {\n fprintf (fjac, \"%9.5f %4d %4d %4d %4d \", output->wl.lambda_h[iv], is, js, ks, kc);\n for (isp = 0; isp < input.n_caoth + 2; isp++) {\n fprintf (fjac,\n \"%.6e %.6e \",\n output->jacobian[ks][is][js][isp][0][kc][iv],\n output->jacobian[ks][is][js][isp][1][kc][iv]);\n }\n fprintf (fjac, \"\\n\");\n }\n }\n\n /* variances */\n if (input.rte.mc.std) {\n\n if (doflx == 1)\n fprintf (fflxvar,\n \"%9.5f %4d %4d %4d %.8e %.8e %.8e %.8e %.8e %.8e\\n\",\n output->wl.lambda_h[iv],\n is,\n js,\n ks,\n sqrt (output->rfldir3d_var[ks][is][js][iv]),\n sqrt (output->rfldn3d_var[ks][is][js][iv]),\n sqrt (output->flup3d_var[ks][is][js][iv]),\n sqrt (output->uavgso3d_var[ks][is][js][iv]),\n sqrt (output->uavgdn3d_var[ks][is][js][iv]),\n sqrt (output->uavgup3d_var[ks][is][js][iv]));\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n fprintf (fradvar,\n \"%9.5f %4d %4d %4d %g\\n\",\n output->wl.lambda_h[iv],\n is,\n js,\n ks,\n sqrt (output->radiance3d_var[ks][is][js][ip][iv]));\n }\n }\n\n if (doflx == 1)\n fclose (fflx);\n fclose (frad);\n\n if (input.rte.mc.concentration_is)\n fclose (fflxis);\n\n if (input.rte.mc.jacobian[DIM_1D])\n fclose (fjac);\n\n if (input.rte.mc.std) {\n if (doflx == 1)\n fclose (fflxvar);\n fclose (fradvar);\n }\n\n if (output->mc.sample.passback3D && (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.rte.mc.backward.absorption)) {\n\n if ((fabs = fopen (absfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", absfilename, function_name, file_name);\n return -1;\n }\n\n /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n if (input.rte.mc.std)\n if ((fabsvar = fopen (absvarfilename, \"w\")) == NULL) {\n fprintf (stderr, \"Error opening %s for writing in %s (%s)\\n\", radvarfilename, function_name, file_name);\n return -1;\n }\n\n if (input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks]) /* only for 3D layers, BM07122005 */\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++)\n for (iv = 0; iv < output->wl.nlambda_h_print3D; iv++) {\n fprintf (fabs, \"%9.5f %4d %4d %4d %.8e\\n\", output->wl.lambda_h[iv], is, js, ks, output->abs3d[ks][is][js][iv]);\n\n /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n if (input.rte.mc.std) {\n fprintf (fabsvar,\n \"%9.5f %4d %4d %4d %.8e\\n\",\n output->wl.lambda_h[iv],\n is,\n js,\n ks,\n sqrt (output->abs3d_var[ks][is][js][iv]));\n }\n }\n\n if (input.rte.mc.backward.absorption)\n for (iv = 0; iv < output->wl.nlambda_h_print3D; iv++)\n for (ks = 0; ks < output->atm.nzout; ks++)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n fprintf (fabs, \"%9.5f %4d %4d %4d %.8e\\n\", output->wl.lambda_h[iv], is, js, ks, output->absback3d[ks][is][js][iv]);\n\n /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n if (input.rte.mc.std) {\n fprintf (fabsvar,\n \"%9.5f %4d %4d %4d %.8e\\n\",\n output->wl.lambda_h[iv],\n is,\n js,\n ks,\n sqrt (output->absback3d_var[ks][is][js][iv]));\n }\n }\n\n fclose (fabs);\n\n /* 27.02.2013 **CK **BM: added for thermal backward heating rates std */\n if (input.rte.mc.std)\n fclose (fabsvar);\n }\n\n return status;\n}\n\n/***********************************************************************************/\n/* Sum the 3D results over wavelength and write data to the first array element */\n/***********************************************************************************/\n\nint sum3D (input_struct input, output_struct* output) {\n int iv = 0, is = 0, js = 0, ks = 0, ip = 0, ic = 0, isp = 0, i = 0, lc = 0;\n double ffactor = 0, ffactor2 = 0, rfactor = 0, rfactor2 = 0;\n float incident = 0, fbeam = 0;\n int status = 0;\n\n /* calculate incident flux (incident) and sum extraterrestrial irradiance (fbeam) */\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n incident += output->wl.filter[iv] * output->wl.fbeam[iv] * cos (output->sza_h[iv] * PI / 180.0);\n fbeam += output->wl.filter[iv] * output->wl.fbeam[iv];\n }\n\n /* default scaling factors */\n ffactor = 1.0; /* irradiance multiplicator */\n rfactor = 1.0; /* radiance multiplicator */\n\n /* if transmittance, then divide by the extraterrestrial flux */\n if (input.source != SRC_THERMAL) {\n switch (input.calibration) {\n case OUTCAL_ABSOLUTE:\n break;\n\n case OUTCAL_TRANSMITTANCE:\n case OUTCAL_BRIGHTNESS:\n ffactor = 1.0 / fbeam; /* irradiance multiplicator */\n rfactor = 1.0 / fbeam; /* radiance multiplicator */\n break;\n\n case OUTCAL_REFLECTIVITY:\n\n ffactor = 1.0 / incident;\n rfactor = PI / incident;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown output calibration %d\\n\", input.calibration);\n return -1;\n }\n }\n\n /* fluxes and radiances */\n for (ks = 0; ks < output->atm.nzout; ks++)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n for (iv = 1; iv < output->wl.nlambda_h; iv++) {\n output->rfldir3d[ks][is][js][0] += output->rfldir3d[ks][is][js][iv];\n output->rfldn3d[ks][is][js][0] += output->rfldn3d[ks][is][js][iv];\n output->flup3d[ks][is][js][0] += output->flup3d[ks][is][js][iv];\n output->uavgso3d[ks][is][js][0] += output->uavgso3d[ks][is][js][iv];\n output->uavgdn3d[ks][is][js][0] += output->uavgdn3d[ks][is][js][iv];\n output->uavgup3d[ks][is][js][0] += output->uavgup3d[ks][is][js][iv];\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->radiance3d[ks][is][js][ip][ic][0] += output->radiance3d[ks][is][js][ip][ic][iv];\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is)\n for (ic = 0; ic < output->mc.alis.Nc; ic++) {\n /* fprintf(stderr, \"sum3D %f is %f \\n\", output->rfldn3d[ks][is][js][iv], output->fl3d_is [ks][is][js][ic][iv]); */\n output->fl3d_is[ks][is][js][ic][0] += output->fl3d_is[ks][is][js][ic][iv];\n }\n\n if (input.rte.mc.jacobian[DIM_1D])\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < output->atm.nlev - 1; lc++) {\n /* fprintf(stderr, \"sum3D %f \\n\", output->jacobian [ks][is][js][isp][i][lc][iv]); */\n output->jacobian[ks][is][js][isp][i][lc][0] += output->jacobian[ks][is][js][isp][i][lc][iv];\n }\n\n if (input.rte.mc.backward.absorption)\n output->absback3d[ks][is][js][0] += output->absback3d[ks][is][js][iv];\n\n /* variances */\n if (input.rte.mc.std) {\n\n output->rfldir3d_var[ks][is][js][0] += output->rfldir3d_var[ks][is][js][iv];\n output->rfldn3d_var[ks][is][js][0] += output->rfldn3d_var[ks][is][js][iv];\n output->flup3d_var[ks][is][js][0] += output->flup3d_var[ks][is][js][iv];\n output->uavgso3d_var[ks][is][js][0] += output->uavgso3d_var[ks][is][js][iv];\n output->uavgdn3d_var[ks][is][js][0] += output->uavgdn3d_var[ks][is][js][iv];\n output->uavgup3d_var[ks][is][js][0] += output->uavgup3d_var[ks][is][js][iv];\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n output->radiance3d_var[ks][is][js][ip][0] += output->radiance3d_var[ks][is][js][ip][iv];\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var[ks][is][js][0] += output->absback3d_var[ks][is][js][iv];\n }\n }\n\n /* calibrate */\n if (output->wl.nlambda_h > 0) {\n output->rfldir3d[ks][is][js][0] *= ffactor;\n output->rfldn3d[ks][is][js][0] *= ffactor;\n output->flup3d[ks][is][js][0] *= ffactor;\n output->uavgso3d[ks][is][js][0] *= ffactor;\n output->uavgdn3d[ks][is][js][0] *= ffactor;\n output->uavgup3d[ks][is][js][0] *= ffactor;\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->fl3d_is[ks][is][js][ic][0] *= ffactor;\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->radiance3d[ks][is][js][ip][ic][0] *= rfactor;\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < output->atm.nlev - 1; lc++)\n if (input.rte.mc.backward.output == MCBACKWARD_EDN || input.rte.mc.backward.output == MCBACKWARD_EDNPV ||\n input.rte.mc.backward.output == MCBACKWARD_EUP)\n output->jacobian[ks][is][js][isp][i][lc][0] *= ffactor;\n else // radiance\n output->jacobian[ks][is][js][isp][i][lc][0] *= rfactor;\n }\n\n if (input.rte.mc.backward.absorption)\n output->absback3d[ks][is][js][0] *= ffactor;\n\n /* variances */\n if (input.rte.mc.std) {\n\n ffactor2 = ffactor * ffactor;\n rfactor2 = rfactor * rfactor;\n\n output->rfldir3d_var[ks][is][js][0] *= ffactor2;\n output->rfldn3d_var[ks][is][js][0] *= ffactor2;\n output->flup3d_var[ks][is][js][0] *= ffactor2;\n output->uavgso3d_var[ks][is][js][0] *= ffactor2;\n output->uavgdn3d_var[ks][is][js][0] *= ffactor2;\n output->uavgup3d_var[ks][is][js][0] *= ffactor2;\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n output->radiance3d_var[ks][is][js][ip][0] *= rfactor2;\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var[ks][is][js][0] *= ffactor2;\n }\n }\n }\n\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks]) /* only for 3D layers, BM07122005 */\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++) {\n\n for (iv = 1; iv < output->wl.nlambda_h; iv++) { /* **CK added bracket and var-line for forward mc_std */\n output->abs3d[ks][is][js][0] += output->abs3d[ks][is][js][iv];\n if (input.rte.mc.std)\n output->abs3d_var[ks][is][js][0] += output->abs3d_var[ks][is][js][iv];\n }\n output->abs3d[ks][is][js][0] *= ffactor;\n if (input.rte.mc.std)\n output->abs3d_var[ks][is][js][0] *= ffactor2; /* **CK added for forward mc_std */\n }\n\n /* finally, convert to brightness temperature if requested */\n if (input.source == SRC_THERMAL && input.calibration == OUTCAL_BRIGHTNESS) {\n\n if (!input.quiet)\n fprintf (stderr, \" ... converting 3D radiances and fluxes to brightness temperatures\\n\");\n\n /* convert irradiances / radiances to brightness temperatures */\n iv = 0;\n status = output2bt (input, output, iv, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by output2bt()\\n\", status);\n return status;\n }\n }\n\n if (output->triangle_results_o) { // sum up triangle_results\n for (iv = 1; iv < output->wl.nlambda_h; iv++) {\n status = add_triangular_surface_result (ffactor, output->triangle_results_o[iv], output->triangle_results_o[0]);\n CHKERR (status);\n }\n }\n return status;\n}\n\n/**************************************************************************************/\n/* Integrate the 3D results over wavelength and write data to the first array element */\n/**************************************************************************************/\n\nint integrate3D (input_struct input, output_struct* output) {\n int iv = 0, is = 0, js = 0, ks = 0, ip = 0, ic = 0, isp = 0, i = 0, lc = 0;\n int status = 0, used_unit = 0;\n double* cos_SZA = NULL;\n double ffactor = 0, ffactor2 = 0, rfactor = 0, rfactor2 = 0;\n float * xint = NULL, *yint = NULL;\n float incident = 0, fbeam = 0;\n char function_name[] = \"integrate3D\";\n char file_name[] = \"ancillary.c\";\n\n /* calculate integrated incident flux */\n if ((xint = (float*)calloc (output->wl.nlambda_h, sizeof (float))) == NULL)\n error_calloc (\"xint\", \"integrate3D\", &(status));\n if ((yint = (float*)calloc (output->wl.nlambda_h, sizeof (float))) == NULL)\n error_calloc (\"yint\", \"integrate3D\", &(status));\n\n if ((cos_SZA = calloc (output->wl.nlambda_h, sizeof (double))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for cos_SZA in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n switch (input.source) {\n case SRC_SOLAR:\n case SRC_LIDAR: /* BCA */\n case SRC_BLITZ: /* BCA */\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n cos_SZA[iv] = cos (output->sza_h[iv] * PI / 180.0);\n break;\n case SRC_THERMAL:\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n cos_SZA[iv] = 1.0;\n break;\n default:\n fprintf (stderr, \"Error, unknown source %d in %s (%s)\\n\", input.source, function_name, file_name);\n return -1;\n }\n\n used_unit = input.output_unit;\n if (used_unit == UNIT_NOT_DEFINED) /* if no output unit is specified, assume the same units as the input spectrum */\n used_unit = output->spectrum_unit;\n\n switch (used_unit) {\n case UNIT_PER_NM:\n if (input.verbose)\n fprintf (stderr, \" *** integration in wavelength space \\n\");\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n xint[iv] = (double)output->wl.lambda_h[iv];\n yint[iv] = output->wl.filter[iv] * output->wl.fbeam[iv] * cos_SZA[iv];\n }\n break;\n case UNIT_PER_CM_1:\n /* integration over wavenumber k, minus in order to get ascending wavenumbers */\n if (input.verbose)\n fprintf (stderr, \" *** integration in wavenumber space \\n\");\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n xint[iv] = -(double)1.0e+7 / output->wl.lambda_h[iv]; /* k = 10**7 / lambda */ /* 10**7 == nm -> cm */\n yint[iv] = output->wl.filter[iv] * output->wl.fbeam[iv] * cos_SZA[iv];\n }\n break;\n case UNIT_PER_BAND:\n fprintf (stderr, \"Error, combination 'output_process integrate' and 'output_process per_band',\\n\");\n fprintf (stderr, \" or combination 'output_process integrate' and an input spectrum defined in \\n\");\n fprintf (stderr, \" (wavelength or wavenumber) bands does not make sense \\n\");\n fprintf (stderr, \" please use 'output_process sum', when dealing with band parametrisations. \\n\\n\");\n return -1;\n break;\n case UNIT_NOT_DEFINED:\n fprintf (stderr, \"Error, in order to use 'output_process integrate' it is nessesary to specify the \\n\");\n fprintf (stderr, \" unit of the extraterrestrial spectrum with 'source solar filename unit' or\\n\");\n fprintf (stderr, \" unit of the output with 'output_process per_nm' or 'output_process per_cm-1' \\n\\n\");\n return -1;\n break;\n default:\n fprintf (stderr,\n \"Error: Program bug, unsupported unit of extraterrestrial flux %d or output unit %d\\n\",\n output->spectrum_unit,\n input.output_unit);\n return -1;\n }\n\n incident = integrate_float (xint, yint, output->wl.nlambda_h);\n\n /* calculate integrated extraterrestrial irradiance */\n for (iv = 0; iv < output->wl.nlambda_h; iv++)\n yint[iv] = output->wl.filter[iv] * output->wl.fbeam[iv];\n\n fbeam = integrate_float (xint, yint, output->wl.nlambda_h);\n\n /* default scaling factors */\n ffactor = 1.0; /* irradiance multiplicator */\n rfactor = 1.0; /* radiance multiplicator */\n\n /* if transmittance, then divide by the extraterrestrial flux */\n if (input.source != SRC_THERMAL) {\n switch (input.calibration) {\n case OUTCAL_ABSOLUTE:\n break;\n\n case OUTCAL_TRANSMITTANCE:\n case OUTCAL_BRIGHTNESS:\n ffactor = 1.0 / fbeam; /* irradiance multiplicator */\n rfactor = 1.0 / fbeam; /* radiance multiplicator */\n break;\n\n case OUTCAL_REFLECTIVITY:\n\n ffactor = 1.0 / incident;\n rfactor = PI / incident;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown output calibration %d\\n\", input.calibration);\n return -1;\n }\n }\n\n /* fluxes and radiances */\n for (ks = 0; ks < output->atm.nzout; ks++)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n output->rfldir3d[ks][is][js][0] = integrate_float (xint, output->rfldir3d[ks][is][js], output->wl.nlambda_h);\n\n output->rfldn3d[ks][is][js][0] = integrate_float (xint, output->rfldn3d[ks][is][js], output->wl.nlambda_h);\n\n output->flup3d[ks][is][js][0] = integrate_float (xint, output->flup3d[ks][is][js], output->wl.nlambda_h);\n\n output->uavgso3d[ks][is][js][0] = integrate_float (xint, output->uavgso3d[ks][is][js], output->wl.nlambda_h);\n\n output->uavgdn3d[ks][is][js][0] = integrate_float (xint, output->uavgdn3d[ks][is][js], output->wl.nlambda_h);\n\n output->uavgup3d[ks][is][js][0] = integrate_float (xint, output->uavgup3d[ks][is][js], output->wl.nlambda_h);\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->fl3d_is[ks][is][js][ic][0] = integrate_float (xint, output->fl3d_is[ks][is][js][ic], output->wl.nlambda_h);\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->radiance3d[ks][is][js][ip][ic][0] =\n integrate_float (xint, output->radiance3d[ks][is][js][ip][ic], output->wl.nlambda_h);\n\n if (input.rte.mc.jacobian[DIM_1D])\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < output->atm.nlev - 1; lc++)\n output->jacobian[ks][is][js][isp][i][lc][0] =\n integrate_float (xint, output->jacobian[ks][is][js][isp][i][lc], output->wl.nlambda_h);\n\n if (input.rte.mc.backward.absorption)\n output->absback3d[ks][is][js][0] = integrate_float (xint, output->absback3d[ks][is][js], output->wl.nlambda_h);\n\n /* variances */\n if (input.rte.mc.std) {\n\n output->rfldir3d_var[ks][is][js][0] = integrate_float (xint, output->rfldir3d_var[ks][is][js], output->wl.nlambda_h);\n\n output->rfldn3d_var[ks][is][js][0] = integrate_float (xint, output->rfldn3d_var[ks][is][js], output->wl.nlambda_h);\n\n output->flup3d_var[ks][is][js][0] = integrate_float (xint, output->flup3d_var[ks][is][js], output->wl.nlambda_h);\n\n output->uavgso3d_var[ks][is][js][0] = integrate_float (xint, output->uavgso3d_var[ks][is][js], output->wl.nlambda_h);\n\n output->uavgdn3d_var[ks][is][js][0] = integrate_float (xint, output->uavgdn3d_var[ks][is][js], output->wl.nlambda_h);\n\n output->uavgup3d_var[ks][is][js][0] = integrate_float (xint, output->uavgup3d_var[ks][is][js], output->wl.nlambda_h);\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n output->radiance3d_var[ks][is][js][ip][0] =\n integrate_float (xint, output->radiance3d_var[ks][is][js][ip], output->wl.nlambda_h);\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var[ks][is][js][0] = integrate_float (xint, output->absback3d_var[ks][is][js], output->wl.nlambda_h);\n }\n\n /* calibrate */\n if (output->wl.nlambda_h > 0) {\n output->rfldir3d[ks][is][js][0] *= ffactor;\n output->rfldn3d[ks][is][js][0] *= ffactor;\n output->flup3d[ks][is][js][0] *= ffactor;\n output->uavgso3d[ks][is][js][0] *= ffactor;\n output->uavgdn3d[ks][is][js][0] *= ffactor;\n output->uavgup3d[ks][is][js][0] *= ffactor;\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->fl3d_is[ks][is][js][ic][0] *= ffactor;\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->radiance3d[ks][is][js][ip][ic][0] *= rfactor;\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < output->atm.nlev - 1; lc++)\n if (input.rte.mc.backward.output == MCBACKWARD_EDN || input.rte.mc.backward.output == MCBACKWARD_EDNPV ||\n input.rte.mc.backward.output == MCBACKWARD_EUP)\n output->jacobian[ks][is][js][isp][i][lc][0] *= ffactor;\n else\n output->jacobian[ks][is][js][isp][i][lc][0] *= rfactor;\n }\n\n if (input.rte.mc.backward.absorption)\n output->absback3d[ks][is][js][0] *= ffactor;\n\n /* variances */\n if (input.rte.mc.std) {\n ffactor2 = ffactor * ffactor;\n rfactor2 = rfactor * rfactor;\n\n output->rfldir3d_var[ks][is][js][0] *= ffactor2;\n output->rfldn3d_var[ks][is][js][0] *= ffactor2;\n output->flup3d_var[ks][is][js][0] *= ffactor2;\n output->uavgso3d_var[ks][is][js][0] *= ffactor2;\n output->uavgdn3d_var[ks][is][js][0] *= ffactor2;\n output->uavgup3d_var[ks][is][js][0] *= ffactor2;\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n output->radiance3d_var[ks][is][js][ip][0] *= rfactor2;\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var[ks][is][js][0] *= ffactor2;\n }\n }\n }\n\n if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n for (ks = 0; ks < output->atm.Nzcld; ks++)\n if (output->atm.threed[ks]) /* only for 3D layers, BM07122005 */\n for (is = 0; is < output->atm.Nxcld; is++)\n for (js = 0; js < output->atm.Nycld; js++) {\n\n for (iv = 1; iv < output->wl.nlambda_h; iv++) { /* **CK added bracket and var-line for forward mc_std */\n output->abs3d[ks][is][js][0] = integrate_float (xint, output->abs3d[ks][is][js], output->wl.nlambda_h);\n output->abs3d_var[ks][is][js][0] = integrate_float (xint, output->abs3d_var[ks][is][js], output->wl.nlambda_h);\n }\n\n if (output->wl.nlambda_h > 0) { /* **CK added bracket and var-line for forward mc_std */\n output->abs3d[ks][is][js][0] *= ffactor;\n output->abs3d_var[ks][is][js][0] *= ffactor2;\n }\n }\n\n /* finally, convert to brightness temperature if requested */\n if (input.source == SRC_THERMAL && input.calibration == OUTCAL_BRIGHTNESS) {\n\n if (!input.quiet)\n fprintf (stderr, \" ... converting 3D radiances and fluxes to brightness temperatures\\n\");\n\n /* convert irradiances / radiances to brightness temperatures */\n status = output2bt (input, output, 0, 1);\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by output2bt()\\n\", status);\n return status;\n }\n }\n\n if (output->triangle_results_o)\n CHKERROUT (-1, \"Integrate not yet implemented for triangles\");\n\n return status;\n}\n\n/*********************************/\n/* used by integrate1D and sum1D */\n/*********************************/\nint calloc_int_values (input_struct input, output_struct* output) {\n int status = 0;\n int lev = 0, j = 0, iu = 0;\n\n /* callocate wavelength integrated fluxes and radiances */\n output->rfldir_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->rfldir_int == NULL)\n error_calloc (\"output->rfldir_int\", \"calloc_int_values\", &(status));\n output->rfldn_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->rfldn_int == NULL)\n error_calloc (\"output->rfldn_int\", \"calloc_int_values\", &(status));\n output->flup_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->flup_int == NULL)\n error_calloc (\"output->flup_int\", \"calloc_int_values\", &(status));\n output->uavg_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->uavg_int == NULL)\n error_calloc (\"output->uavg_int\", \"calloc_int_values\", &(status));\n output->uavgso_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->uavgso_int == NULL)\n error_calloc (\"output->uavgso_int\", \"calloc_int_values\", &(status));\n output->uavgdn_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->uavgdn_int == NULL)\n error_calloc (\"output->uavgdn_int\", \"calloc_int_values\", &(status));\n output->uavgup_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->uavgup_int == NULL)\n error_calloc (\"output->uavgup_int\", \"calloc_int_values\", &(status));\n if (input.heating != HEAT_NONE) {\n output->heat_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->heat_int == NULL)\n error_calloc (\"output->heat_int\", \"calloc_int_values\", &(status));\n output->emis_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->emis_int == NULL)\n error_calloc (\"output->emis_int\", \"calloc_int_values\", &(status));\n output->w_zout_int = (double*)calloc (output->atm.nzout, sizeof (double));\n if (output->w_zout_int == NULL)\n error_calloc (\"output->w_zout_int\", \"calloc_int_values\", &(status));\n }\n\n output->u0u_int = (double**)calloc (output->atm.nzout, sizeof (double*));\n if (output->u0u_int == NULL)\n error_calloc (\"output->u0u_int\", \"calloc_int_values\", &(status));\n for (lev = 0; lev < output->atm.nzout; lev++)\n output->u0u_int[lev] = (double*)calloc (input.rte.numu, sizeof (double));\n\n output->uu_int = (double***)calloc (output->atm.nzout, sizeof (double*));\n if (output->uu_int == NULL)\n error_calloc (\"output->uu_int\", \"calloc_int_values\", &(status));\n for (lev = 0; lev < output->atm.nzout; lev++) {\n output->uu_int[lev] = (double**)calloc (input.rte.nphi, sizeof (double*));\n for (j = 0; j < input.rte.nphi; j++)\n output->uu_int[lev][j] = (double*)calloc (input.rte.numu, sizeof (double));\n }\n\n output->albmed_int = (double*)calloc (input.rte.numu, sizeof (double));\n output->trnmed_int = (double*)calloc (input.rte.numu, sizeof (double));\n\n /* callocate wavelength integrated PolRadtran flux and intensities on the output grid */\n if (input.rte.solver == SOLVER_POLRADTRAN) {\n output->down_flux_int = (double**)calloc (output->atm.nzout, sizeof (double*));\n if (output->down_flux_int == NULL)\n error_calloc (\"output->down_flux_int\", \"calloc_int_values\", &(status));\n for (lev = 0; lev < output->atm.nzout; lev++)\n output->down_flux_int[lev] = (double*)calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double));\n\n output->up_flux_int = (double**)calloc (output->atm.nzout, sizeof (double*));\n if (output->up_flux_int == NULL)\n error_calloc (\"output->up_flux_int\", \"calloc_int_values\", &(status));\n for (lev = 0; lev < output->atm.nzout; lev++)\n output->up_flux_int[lev] = (double*)calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double));\n\n output->down_rad_int = (double****)calloc (output->atm.nzout, sizeof (double*));\n if (output->down_rad_int == NULL)\n error_calloc (\"output->down_rad_int\", \"calloc_int_values\", &(status));\n for (lev = 0; lev < output->atm.nzout; lev++) {\n output->down_rad_int[lev] = (double***)calloc (input.rte.nphi, sizeof (double*));\n for (j = 0; j < input.rte.nphi; j++) {\n output->down_rad_int[lev][j] = (double**)calloc (input.rte.numu, sizeof (double*));\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->down_rad_int[lev][j][iu] = (double*)calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double));\n }\n }\n }\n\n output->up_rad_int = (double****)calloc (output->atm.nzout, sizeof (double*));\n if (output->up_rad_int == NULL)\n error_calloc (\"output->up_rad_int\", \"calloc_int_values\", &(status));\n for (lev = 0; lev < output->atm.nzout; lev++) {\n output->up_rad_int[lev] = (double***)calloc (input.rte.nphi, sizeof (double*));\n for (j = 0; j < input.rte.nphi; j++) {\n output->up_rad_int[lev][j] = (double**)calloc (input.rte.numu, sizeof (double*));\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->up_rad_int[lev][j][iu] = (double*)calloc (input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double));\n }\n }\n }\n }\n\n return status;\n}\n\nvoid error_calloc (char* variable, char* function, int* status) {\n fprintf (stderr, \"Error allocating memory for (%s) in %s (ancillary.c)\\n\", variable, function);\n fflush (stderr);\n *status = *status - 1;\n}\n\n/***************************************************************************/\n/* abuse first entry of the wavelength index to store the integrated value */\n/* and to convert double (nessesary for heating rates) to floats */\n/* entry (n+1) or entry (-1) would be nicer */\n/***************************************************************************/\n\nint double2float_integrated_values (input_struct input, output_struct* output) {\n int lev, is = 0, j = 0, iu = 0;\n int status = 0;\n\n if (input.rte.solver == SOLVER_POLRADTRAN) { /* polRadtran output */\n for (lev = 0; lev < output->atm.nzout; lev++)\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n /* irradiances */\n output->down_flux[lev][is][0] = (float)output->down_flux_int[lev][is];\n output->up_flux[lev][is][0] = (float)output->up_flux_int[lev][is];\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++)\n for (j = 0; j < input.rte.nphi; j++) {\n output->down_rad[lev][j][iu][is][0] = (float)output->down_rad_int[lev][j][iu][is];\n output->up_rad[lev][j][iu][is][0] = (float)output->up_rad_int[lev][j][iu][is];\n }\n }\n } else { /* unpolarized output */\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n\n output->albmed[iu][0] = (float)output->albmed_int[iu];\n output->trnmed[iu][0] = (float)output->trnmed_int[iu];\n }\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* irradiance / actinic flux */\n output->rfldir[lev][0] = (float)output->rfldir_int[lev];\n output->rfldn[lev][0] = (float)output->rfldn_int[lev];\n output->flup[lev][0] = (float)output->flup_int[lev];\n output->uavg[lev][0] = (float)output->uavg_int[lev];\n output->uavgso[lev][0] = (float)output->uavgso_int[lev];\n output->uavgdn[lev][0] = (float)output->uavgdn_int[lev];\n output->uavgup[lev][0] = (float)output->uavgup_int[lev];\n if (input.heating != HEAT_NONE) {\n output->heat[lev][0] = (float)output->heat_int[lev];\n output->emis[lev][0] = (float)output->emis_int[lev];\n output->w_zout[lev][0] = (float)output->w_zout_int[lev];\n }\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->u0u[lev][iu][0] = (float)output->u0u_int[lev][iu];\n\n for (j = 0; j < input.rte.nphi; j++)\n output->uu[lev][j][iu][0] = (float)output->uu_int[lev][j][iu];\n }\n }\n }\n\n return status;\n}\n\n/*********************************/\n/* used by integrate1D and sum1D */\n/*********************************/\n\nint scaling_integrated_values (input_struct input, output_struct* output) {\n double ffactor = 0, rfactor = 0, hfactor = 1;\n int status = 0;\n\n /* if transmittance, then divide by the extraterrestrial flux */\n if (input.source != SRC_THERMAL) {\n switch (input.calibration) {\n case OUTCAL_ABSOLUTE:\n ffactor = 1.0; /* irradiance multiplicator */\n rfactor = 1.0; /* radiance multiplicator */\n break;\n\n case OUTCAL_TRANSMITTANCE:\n case OUTCAL_BRIGHTNESS:\n ffactor = 1.0 / output->wl.fbeam[0]; /* irradiance multiplicator */\n rfactor = 1.0 / output->wl.fbeam[0]; /* radiance multiplicator */\n break;\n\n case OUTCAL_REFLECTIVITY:\n ffactor = 1.0 / output->incident;\n rfactor = PI / output->incident;\n break;\n\n default:\n fprintf (stderr, \"Error, unknown output calibration %d\\n\", input.calibration);\n return -1;\n }\n\n /**************************************************************/\n /* now scale irradiances with ffactor, radiances with rfactor */\n /**************************************************************/\n\n if (output->wl.nlambda_h > 0) {\n /* in iv==0 the integrated values are stored */\n status = scale_output (input,\n &(output->rfldir),\n &(output->rfldn),\n &(output->flup),\n &(output->albmed),\n &(output->trnmed),\n &(output->uavgso),\n &(output->uavgdn),\n &(output->uavgup),\n &(output->uavg),\n &(output->u0u),\n &(output->uu),\n &(output->heat),\n &(output->emis),\n &(output->w_zout),\n &(output->down_flux),\n &(output->up_flux),\n &(output->down_rad),\n &(output->up_rad),\n &(output->rfldir3d),\n &(output->rfldn3d),\n &(output->flup3d),\n &(output->fl3d_is),\n &(output->uavgso3d),\n &(output->uavgdn3d),\n &(output->uavgup3d),\n &(output->radiance3d),\n &(output->jacobian),\n &(output->absback3d),\n &(output->rfldir3d_var),\n &(output->rfldn3d_var),\n &(output->flup3d_var),\n &(output->uavgso3d_var),\n &(output->uavgdn3d_var),\n &(output->uavgup3d_var),\n &(output->radiance3d_var),\n &(output->abs3d_var),\n &(output->absback3d_var),\n output->atm.nzout,\n output->atm.Nxcld,\n output->atm.Nycld,\n output->atm.Nzcld,\n output->mc.alis.Nc,\n output->atm.nlyr,\n output->atm.threed,\n output->mc.sample.passback3D,\n output->islower,\n output->isupper,\n output->jslower,\n output->jsupper,\n output->isstep,\n output->jsstep,\n &(output->abs3d),\n output->triangle_results_o,\n ffactor,\n rfactor,\n hfactor,\n 0);\n\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by scale_output()\\n\", status);\n return status;\n }\n }\n } else {\n if (input.calibration == OUTCAL_BRIGHTNESS) {\n\n if (!input.quiet)\n fprintf (stderr, \" ... converting radiances to brightness temperatures\\n\");\n\n /* convert irradiances / radiances to brightness temperatures */\n /* the first element (iv==0) stores the spectrally integrated quantities; */\n status = output2bt (input, output, 0, 0);\n if (status != 0) {\n fprintf (stderr, \"Error %d returned by output2bt()\\n\", status);\n return status;\n }\n }\n }\n\n /* abuse first entry to store the integrated value, this is not so nice programmed */\n if (output->wl.nlambda_h > 0)\n output->wl.nlambda_h = 1;\n\n return 0;\n}\n\n/***********************************************************************************/\n/* Convert Raman spectrum to user spectum */\n/***********************************************************************************/\n\nstatic int raman_spec2spec (input_struct input, output_struct* output) {\n int lev = 0, iu = 0, j = 0, status = 0, iv = 0;\n int start_id = 0, end_id = 0;\n float test_lower = 0, test_upper = 0;\n\n test_lower = output->wl.lambda_h[0] + output->wl.delta_wvl_raman_lower + output->wl.delta_wvl_raman_extra;\n test_upper = output->wl.lambda_h[output->wl.nlambda_h - 1] - output->wl.delta_wvl_raman_upper - output->wl.delta_wvl_raman_extra;\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n if (output->wl.lambda_h[iv] < test_lower)\n start_id = iv + 1;\n if (output->wl.lambda_h[output->wl.nlambda_h - 1 - iv] > test_upper)\n end_id = output->wl.nlambda_h - iv - 2;\n }\n\n /* The old nlambda_h is always larger than what we are going to output. Furthermore, */\n /* start_id is always > 0 and end_id always < nlambda_h, so we just shift and */\n /* arys decrease nlambda_h */\n\n output->wl.nlambda_h = end_id - start_id + 1;\n\n for (iv = 0; iv < output->wl.nlambda_h; iv++) {\n output->wl.lambda_h[iv] = output->wl.lambda_h[iv + start_id];\n for (lev = 0; lev < output->atm.nzout; lev++) {\n output->rfldir[lev][iv] = output->rfldir[lev][iv + start_id];\n output->rfldn[lev][iv] = output->rfldn[lev][iv + start_id];\n output->flup[lev][iv] = output->flup[lev][iv + start_id];\n output->uavgso[lev][iv] = output->uavgso[lev][iv + start_id];\n output->uavgdn[lev][iv] = output->uavgdn[lev][iv + start_id];\n output->uavgup[lev][iv] = output->uavgup[lev][iv + start_id];\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->u0u[lev][iu][iv] = output->u0u[lev][iu][iv + start_id];\n for (j = 0; j < input.rte.nphi; j++)\n output->uu[lev][j][iu][iv] = output->uu[lev][j][iu][iv + start_id];\n }\n }\n }\n\n return status;\n}\n\n/***********************************************************************************/\n/* Convert spectra to RGB and write data to the first three array elements */\n/***********************************************************************************/\n\nstatic int spec2rgb (input_struct input, output_struct* output) {\n int lev = 0, iu = 0, j = 0, is = 0, status = 0, norm = 0;\n\n if (output->wl.nlambda_h < 3) {\n fprintf (stderr, \"Fatal error, need at least 3 wavelengths to store RGB\\n\");\n return -1;\n }\n\n /* normalized or weighted with brightness */\n norm = 1;\n if (input.processing == PROCESS_RGB)\n norm = 0;\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n status += spectrum_to_rgb_overwrite (output->rfldir[lev], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->rfldn[lev], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->flup[lev], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->uavgso[lev], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->uavgdn[lev], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->uavgup[lev], output->wl.nlambda_h, norm);\n\n for (iu = 0; iu < input.rte.numu; iu++) {\n status += spectrum_to_rgb_overwrite (output->u0u[lev][iu], output->wl.nlambda_h, norm);\n\n for (j = 0; j < input.rte.nphi; j++)\n status += spectrum_to_rgb_overwrite (output->uu[lev][j][iu], output->wl.nlambda_h, norm);\n }\n }\n\n /* polarized fluxes and radiances */\n if (input.rte.solver == SOLVER_POLRADTRAN)\n\n for (lev = 0; lev < output->atm.nzout; lev++)\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n status += spectrum_to_rgb_overwrite (output->down_flux[lev][is], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->up_flux[lev][is], output->wl.nlambda_h, norm);\n\n for (iu = 0; iu < input.rte.numu; iu++)\n for (j = 0; j < input.rte.nphi; j++) {\n status += spectrum_to_rgb_overwrite (output->down_rad[lev][j][iu][is], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->up_rad[lev][j][iu][is], output->wl.nlambda_h, norm);\n }\n }\n\n if (input.verbose)\n fprintf (stderr, \"LEAVING spec2rgb()\\n\");\n\n if (output->wl.nlambda_h > 0)\n output->wl.nlambda_h = 3;\n\n output->wl.lambda_h[0] = 600;\n output->wl.lambda_h[1] = 500;\n output->wl.lambda_h[2] = 400;\n\n return 0;\n}\n\n/***********************************************************************************/\n/* Convert 3D spectra to RGB and write data to the first three array elements */\n/***********************************************************************************/\n\nstatic int spec2rgb3D (input_struct input, output_struct* output) {\n int is = 0, js = 0, ks = 0, status = 0, norm = 0;\n\n if (output->wl.nlambda_h < 3) {\n fprintf (stderr, \"Fatal error, need at least 3 wavelengths to store RGB\\n\");\n return -1;\n }\n\n /* normalized or weighted with brightness */\n norm = 1;\n if (input.processing == PROCESS_RGB)\n norm = 0;\n\n for (ks = 0; ks < output->atm.nzout; ks++)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n if (input.verbose)\n fprintf (stderr, \"R3D = %f\\n\", output->radiance3d[ks][is][js][0][0][0]);\n status += spectrum_to_rgb_overwrite (output->rfldir3d[ks][is][js], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->rfldn3d[ks][is][js], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->flup3d[ks][is][js], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->uavgso3d[ks][is][js], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->uavgdn3d[ks][is][js], output->wl.nlambda_h, norm);\n status += spectrum_to_rgb_overwrite (output->uavgup3d[ks][is][js], output->wl.nlambda_h, norm);\n /* ignore polarization for rgb output */\n status += spectrum_to_rgb_overwrite (output->radiance3d[ks][is][js][0][0], output->wl.nlambda_h, norm);\n /* ignore variances for rgb output */\n\n if (input.verbose) {\n fprintf (stderr, \"SPEC2RGB %d %d %d %d\\n\", ks, is, js, output->wl.nlambda_h);\n fprintf (stderr, \"R3D = %f\\n\", output->radiance3d[ks][is][js][0][0][0]);\n }\n }\n\n if (status != 0) {\n fprintf (stderr, \"Error converting 3D fields to colors with spec2rgb3D()\\n\");\n return status;\n }\n\n /* don't adjust lambda_h and nlambda_h here - we need the */\n /* original numbers for processing1D()! */\n /*\n if (output->wl.nlambda_h>0)\n output->wl.nlambda_h = 3;\n\n output->wl.lambda_h[0] = 600;\n output->wl.lambda_h[1] = 500;\n output->wl.lambda_h[2] = 400;\n */\n\n if (input.verbose)\n fprintf (stderr, \"LEAVING spec2rgb3D()\\n\");\n\n if (output->triangle_results_o)\n CHKERROUT (-1, \"Integrate not yet implemented for triangles\");\n\n return 0;\n}\n\n/***********************************************************************************/\n/* Scale uvspec output fields with a given factor; ffactor is the scaling factor */\n/* for irradiances/actinic fluxes and rfactor is the scaling factor for radiances */\n/***********************************************************************************/\n\nint scale_output (input_struct input,\n float*** p_rfldir,\n float*** p_rfldn,\n float*** p_flup,\n float*** p_albmed,\n float*** p_trnmed,\n float*** p_uavgso,\n float*** p_uavgdn,\n float*** p_uavgup,\n float*** p_uavg,\n float**** p_u0u,\n float***** p_uu,\n float*** p_heat,\n float*** p_emis,\n float*** p_w_zout,\n float**** p_down_flux,\n float**** p_up_flux,\n float****** p_down_rad,\n float****** p_up_rad,\n float***** p_rfldir3d,\n float***** p_rfldn3d,\n float***** p_flup3d,\n float****** p_fl3d_is,\n float***** p_uavgso3d,\n float***** p_uavgdn3d,\n float***** p_uavgup3d,\n float******* p_radiance3d,\n float******** p_jacobian,\n float***** p_absback3d,\n float***** p_rfldir3d_var,\n float***** p_rfldn3d_var,\n float***** p_flup3d_var,\n float***** p_uavgso3d_var,\n float***** p_uavgdn3d_var,\n float***** p_uavgup3d_var,\n float****** p_radiance3d_var,\n float***** p_abs3d_var,\n float***** p_absback3d_var,\n int nzout,\n int Nx,\n int Ny,\n int Nz,\n int Nc,\n int Nlyr,\n int* threed,\n int passback3D,\n int islower,\n int isupper,\n int jslower,\n int jsupper,\n int isstep,\n int jsstep,\n float***** p_abs3d,\n t_triangle_radiation_field** triangle_result,\n double ffactor,\n double rfactor,\n double hfactor,\n int iv)\n\n/* changed output_struc to a bunch of pointers, as this function is also used in solve_rte() with different arguements, UH, 2006-02 */\n{\n double ffactor2 = 0, rfactor2 = 0, hfactor2 = 0; /* 27.02.2013 **CK **BM: add hfactor2 for thermal backward heating rate std */\n int lev = 0, iu = 0, j = 0, is = 0, js = 0, ks = 0, ic = 0, ip = 0, isp = 0, i = 0, lc = 0;\n\n if (input.rte.solver == SOLVER_POLRADTRAN) { /* polRadtran output */\n for (lev = 0; lev < nzout; lev++) {\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n /* irradiances */\n (*p_down_flux)[lev][is][iv] *= ffactor;\n (*p_up_flux)[lev][is][iv] *= ffactor;\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++)\n for (j = 0; j < input.rte.nphi; j++) {\n (*p_down_rad)[lev][j][iu][is][iv] *= rfactor;\n (*p_up_rad)[lev][j][iu][is][iv] *= rfactor;\n }\n }\n /* heating rate */\n if (input.heating != HEAT_NONE) {\n (*p_heat)[lev][iv] *= hfactor;\n (*p_emis)[lev][iv] *= hfactor;\n (*p_w_zout)[lev][iv] *= hfactor;\n }\n }\n } else { /* unpolarized output */\n\n /* Arve 20160121: spherical albedo and transmittance should not be scaled \n if disort_spherical_albedo is set. */\n if (!input.rte.ibcnd) {\n for (iu = 0; iu < input.rte.numu; iu++) {\n (*p_albmed)[iu][iv] *= ffactor;\n (*p_trnmed)[iu][iv] *= ffactor;\n }\n }\n\n for (lev = 0; lev < nzout; lev++) {\n\n /* irradiance / actinic flux / heating rate */\n (*p_rfldir)[lev][iv] *= ffactor;\n (*p_rfldn)[lev][iv] *= ffactor;\n (*p_flup)[lev][iv] *= ffactor;\n (*p_uavg)[lev][iv] *= ffactor;\n (*p_uavgso)[lev][iv] *= ffactor;\n (*p_uavgdn)[lev][iv] *= ffactor;\n (*p_uavgup)[lev][iv] *= ffactor;\n if (input.heating != HEAT_NONE) {\n (*p_heat)[lev][iv] *= hfactor;\n (*p_emis)[lev][iv] *= hfactor;\n (*p_w_zout)[lev][iv] *= hfactor;\n }\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++) {\n (*p_u0u)[lev][iu][iv] *= rfactor;\n\n for (j = 0; j < input.rte.nphi; j++)\n (*p_uu)[lev][j][iu][iv] *= rfactor;\n }\n\n /* 3D irradiances and radiances */\n if (passback3D)\n for (is = islower; is <= isupper; is += isstep)\n for (js = jslower; js <= jsupper; js += jsstep) {\n (*p_rfldir3d)[lev][is][js][iv] *= ffactor;\n (*p_rfldn3d)[lev][is][js][iv] *= ffactor;\n (*p_flup3d)[lev][is][js][iv] *= ffactor;\n (*p_uavgso3d)[lev][is][js][iv] *= ffactor;\n (*p_uavgdn3d)[lev][is][js][iv] *= ffactor;\n (*p_uavgup3d)[lev][is][js][iv] *= ffactor;\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is) {\n for (ic = 0; ic < Nc; ic++)\n (*p_fl3d_is)[lev][is][js][ic][iv] *= ffactor;\n }\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++) {\n for (ic = 0; ic < Nc; ic++)\n (*p_radiance3d)[lev][is][js][ip][ic][iv] *= rfactor;\n }\n\n if (input.rte.mc.jacobian[DIM_1D]) {\n for (isp = 0; isp < input.n_caoth + 2; isp++)\n for (i = 0; i < 2; i++)\n for (lc = 0; lc < Nlyr; lc++) {\n if (input.rte.mc.backward.output == MCBACKWARD_EDN || input.rte.mc.backward.output == MCBACKWARD_EDNPV ||\n input.rte.mc.backward.output == MCBACKWARD_EUP)\n (*p_jacobian)[lev][is][js][isp][i][lc][iv] *= ffactor;\n else\n (*p_jacobian)[lev][is][js][isp][i][lc][iv] *= rfactor;\n }\n }\n\n if (input.rte.mc.backward.absorption && input.ipa3d != 1) /*ulrike: added && input.ipa3d!=1*/\n (*p_absback3d)[lev][is][js][iv] *= ffactor;\n\n /* ulrike 3.5.2010: if we have ipa3d\n\t then we use absback3d to save the heating rate; thus, p_absback3d should not be multiplied\n\t with the ffactor, but with the hfactor, which is the heating rate factor*/\n if (input.rte.mc.backward.absorption && input.ipa3d)\n (*p_absback3d)[lev][is][js][iv] *= hfactor;\n\n /* variances */\n if (input.rte.mc.std) {\n\n ffactor2 = ffactor * ffactor;\n rfactor2 = rfactor * rfactor;\n hfactor2 = hfactor * hfactor; /* 27.02.2013 **CK **BM: add hfactor2 for thermal backward heating rate std */\n\n (*p_rfldir3d_var)[lev][is][js][iv] *= ffactor2;\n (*p_rfldn3d_var)[lev][is][js][iv] *= ffactor2;\n (*p_flup3d_var)[lev][is][js][iv] *= ffactor2;\n (*p_uavgso3d_var)[lev][is][js][iv] *= ffactor2;\n (*p_uavgdn3d_var)[lev][is][js][iv] *= ffactor2;\n (*p_uavgup3d_var)[lev][is][js][iv] *= ffactor2;\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n (*p_radiance3d_var)[lev][is][js][ip][iv] *= rfactor2;\n\n if (input.rte.mc.backward.absorption &&\n input.ipa3d != 1) /* 27.02.2013 **CK **BM: add \"&&\" for thermal backward heating rate std */\n (*p_absback3d_var)[lev][is][js][iv] *= ffactor2;\n\n /* 27.02.2013 **CK **BM: add hfactor2 for thermal backward heating rate std */\n if (input.rte.mc.backward.absorption && input.ipa3d)\n (*p_absback3d_var)[lev][is][js][iv] *= hfactor2;\n }\n }\n }\n\n /* 3D absorption fields; here the loop goes over all 3D boxes */\n if (passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE)\n\n for (ks = 0; ks < Nz; ks++)\n if (threed[ks]) /* only for 3D layers, BM07122005 */\n for (is = 0; is < Nx; is++)\n for (js = 0; js < Ny; js++) { /* **CK added bracket */\n (*p_abs3d)[ks][is][js][iv] *= ffactor;\n if (\n input.rte.mc\n .std) /* **CK added for forward mc_std */ /* ??????????????? **CK shouldn't we also switch between ffactor und hfactor for ipa3d/not ipa3d as in backward mode? */\n (*p_abs3d_var)[ks][is][js][iv] *= ffactor2;\n }\n\n if (triangle_result) {\n const int ierr = scale_output_triangle_surface (ffactor, triangle_result[iv]);\n CHKERR (ierr);\n }\n }\n\n return 0;\n}\n\nint scale_output_triangle_surface (const double ffactor, t_triangle_radiation_field* result) {\n for (size_t i = 0; i < result->N_triangles; ++i) {\n result->edir[i] *= ffactor;\n result->edn[i] *= ffactor;\n result->eup[i] *= ffactor;\n }\n return 0;\n}\n\n/***********************************************************************************/\n/* Convert radiance to brightness temperature for a given filter function. */\n/***********************************************************************************/\n\nfloat radiance2bt (float rad, float* wvnmlo, float* wvnmhi, float* filter, int n, int processing, int ivi) {\n int iv = 0, it = 0;\n double t1 = 0, t2 = 0, plkrad1 = 0, plkrad2 = 0, r = 0, wvlmlo = 0, wvlmhi = 0;\n double *xint = NULL, *yint1 = NULL, *yint2 = NULL;\n\n /* careful: if accuracy is set too small, it may not be reachable because */\n /* the difference between two neighbouring floats may be larger! */\n /* Should better tie this to the actual numerical precision */\n double accur = 5e-5;\n double dt = 0.001;\n\n /* special treatment of NaN */\n if (rad != rad)\n return rad;\n\n t1 = 273;\n t2 = t1 + dt;\n\n if (rad <= 0)\n return 0;\n\n plkrad1 = 0;\n plkrad2 = 0;\n\n if (processing == PROCESS_INT) {\n\n xint = (double*)calloc (n, sizeof (double));\n yint1 = (double*)calloc (n, sizeof (double));\n yint2 = (double*)calloc (n, sizeof (double));\n\n for (iv = 0; iv < n; iv++) {\n\n wvlmlo = wvnmlo[iv];\n wvlmhi = wvnmhi[iv];\n\n // wavenumber is multiplied by -1 since the integrate()-function assumes increasing x-values\n xint[iv] = -(wvnmlo[iv] + wvnmhi[iv]) / 2.0;\n\n // the difference between wvlmlo and wvlmhi is assumed to be 1 cm^-1, otherwise the integrated value is probably wrong\n r = c_planck_func1 (wvlmlo, wvlmhi, t1);\n yint1[iv] = filter[iv] * r;\n r = c_planck_func1 (wvlmlo, wvlmhi, t2);\n yint2[iv] = filter[iv] * r;\n }\n\n plkrad1 = integrate (xint, yint1, n);\n plkrad2 = integrate (xint, yint2, n);\n\n } else if (processing == PROCESS_SUM) {\n for (iv = 0; iv < n; iv++) {\n\n wvlmlo = wvnmlo[iv];\n wvlmhi = wvnmhi[iv];\n r = c_planck_func1 (wvlmlo, wvlmhi, t1);\n plkrad1 += (double)filter[iv] * r;\n r = c_planck_func1 (wvlmlo, wvlmhi, t2);\n plkrad2 += (double)filter[iv] * r;\n }\n } else {\n\n wvlmlo = wvnmlo[ivi];\n wvlmhi = wvnmhi[ivi];\n plkrad1 = c_planck_func1 (wvlmlo, wvlmhi, t1);\n plkrad2 = c_planck_func1 (wvlmlo, wvlmhi, t2);\n }\n\n it = 0;\n while (fabs ((plkrad1 - rad) / rad) > accur) {\n\n t1 = t1 + (rad - plkrad1) / (plkrad2 - plkrad1) * dt;\n t2 = t1 + dt;\n\n plkrad1 = 0;\n plkrad2 = 0;\n if (processing == PROCESS_INT) {\n\n for (iv = 0; iv < n; iv++) {\n\n wvlmlo = wvnmlo[iv];\n wvlmhi = wvnmhi[iv];\n\n r = c_planck_func1 (wvlmlo, wvlmhi, t1);\n yint1[iv] = filter[iv] * r;\n r = c_planck_func1 (wvlmlo, wvlmhi, t2);\n yint2[iv] = filter[iv] * r;\n }\n\n plkrad1 = integrate (xint, yint1, n);\n plkrad2 = integrate (xint, yint2, n);\n\n } else if (processing == PROCESS_SUM) {\n for (iv = 0; iv < n; iv++) {\n\n wvlmlo = wvnmlo[iv];\n wvlmhi = wvnmhi[iv];\n r = c_planck_func1 (wvlmlo, wvlmhi, t1);\n plkrad1 += (double)filter[iv] * r;\n r = c_planck_func1 (wvlmlo, wvlmhi, t2);\n plkrad2 += (double)filter[iv] * r;\n }\n } else {\n\n wvlmlo = wvnmlo[ivi];\n wvlmhi = wvnmhi[ivi];\n plkrad1 = c_planck_func1 (wvlmlo, wvlmhi, t1);\n plkrad2 = c_planck_func1 (wvlmlo, wvlmhi, t2);\n }\n if (it > 999) {\n fprintf (stderr, \"While loop in function %s, file %s, did not converge.\\n\", __func__, __FILE__);\n fprintf (stderr, \"Continuing anyway, but be careful with results.\\n\");\n fprintf (stderr, \"The relevant variables in %s have the following values:\\n\", __func__);\n fprintf (stderr, \"t1 = %12.6f\\n\", t1);\n fprintf (stderr, \"t2 = %12.6f\\n\", t2);\n fprintf (stderr, \"plkrad1 = %12.6e\\n\", plkrad1);\n fprintf (stderr, \"plkrad2 = %12.6e\\n\", plkrad2);\n fprintf (stderr, \"rad = %12.6e\\n\", rad);\n fprintf (stderr, \"accur = %12.6e\\n\", accur);\n fprintf (stderr, \"fabs((plkrad1 - rad)/rad) = %12.6e\\n\", fabs ((plkrad1 - rad) / rad));\n break;\n }\n it++;\n }\n\n if (processing == PROCESS_INT) {\n\n free (xint);\n free (yint1);\n free (yint2);\n }\n\n return t1;\n}\n\n/***********************************************************************************/\n/* Convert uvspec output to brightness temperatures; currently it is assumed that */\n/* the first element (iv==0) stores the spectrally integrated quantities; */\n/* only these will be considered. */\n/***********************************************************************************/\n\nstatic int output2bt (input_struct input, output_struct* output, int iv, int is_3d) {\n int lev = 0, iu = 0, j = 0, is = 0, ih = 0, js = 0, ic = 0, ip = 0;\n\n float *wvnmlo, *wvnmhi, *weight;\n int nlambda;\n\n int processing;\n\n processing = input.processing;\n\n /* Use the representative wavelengths (_r-grid) only when no integration or summation was requested by the user */\n if (output->wl.use_reptran && input.processing == PROCESS_NONE) {\n\n processing = PROCESS_SUM;\n\n nlambda = output->wl.nlambda_in_reptran_band[output->wl.reptran_band_t[output->wl.map_e2h[iv]]];\n\n wvnmlo = calloc (nlambda, sizeof (float));\n wvnmhi = calloc (nlambda, sizeof (float));\n weight = calloc (nlambda, sizeof (float));\n\n for (ih = 0; ih < nlambda; ih++) {\n\n wvnmlo[ih] = output->wl.lambda_r[output->wl.reptran_band[output->wl.reptran_band_t[output->wl.map_e2h[iv]]][ih]];\n wvnmlo[ih] = 1.0E7 / wvnmlo[ih] - input.bandwidth / 2.0;\n wvnmhi[ih] = wvnmlo[ih] + input.bandwidth;\n weight[ih] = output->wl.weight_reptran_band[output->wl.reptran_band_t[output->wl.map_e2h[iv]]][ih];\n }\n\n } else {\n\n wvnmlo = output->wl.wvnmlo_h;\n wvnmhi = output->wl.wvnmhi_h;\n weight = output->wl.filter;\n nlambda = output->wl.nlambda_h;\n }\n\n if (is_3d) { /* 3D processing */\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* 3D fields */\n if (output->mc.sample.passback3D)\n for (is = output->islower; is <= output->isupper; is += output->isstep)\n for (js = output->jslower; js <= output->jsupper; js += output->jsstep) {\n\n output->rfldir3d[lev][is][js][iv] =\n radiance2bt (output->rfldir3d[lev][is][js][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->rfldn3d[lev][is][js][iv] =\n radiance2bt (output->rfldn3d[lev][is][js][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->flup3d[lev][is][js][iv] =\n radiance2bt (output->flup3d[lev][is][js][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavgso3d[lev][is][js][iv] =\n radiance2bt (output->uavgso3d[lev][is][js][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavgdn3d[lev][is][js][iv] =\n radiance2bt (output->uavgdn3d[lev][is][js][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavgup3d[lev][is][js][iv] =\n radiance2bt (output->uavgup3d[lev][is][js][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n if (input.rte.mc.concentration_is || input.rte.mc.spectral_is)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->fl3d_is[lev][is][js][ic][iv] =\n radiance2bt (output->fl3d_is[lev][is][js][ic][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n for (ic = 0; ic < output->mc.alis.Nc; ic++)\n output->radiance3d[lev][is][js][ip][ic][iv] =\n radiance2bt (output->radiance3d[lev][is][js][ip][ic][iv], wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n /* it would certainly be nonsense to convert standard deviations to */\n /* brightness temperature; therefore set to NaN */\n\n /* variances */\n if (input.rte.mc.std) {\n\n output->rfldir3d_var[lev][is][js][iv] = 0.0 / 0.0;\n output->rfldn3d_var[lev][is][js][iv] = 0.0 / 0.0;\n output->flup3d_var[lev][is][js][iv] = 0.0 / 0.0;\n output->uavgso3d_var[lev][is][js][iv] = 0.0 / 0.0;\n output->uavgdn3d_var[lev][is][js][iv] = 0.0 / 0.0;\n output->uavgup3d_var[lev][is][js][iv] = 0.0 / 0.0;\n\n for (ip = 0; ip < input.rte.mc.nstokes; ip++)\n output->radiance3d_var[lev][is][js][ip][iv] = 0.0 / 0.0;\n\n if (input.rte.mc.backward.absorption)\n output->absback3d_var[lev][is][js][iv] = 0.0 / 0.0;\n }\n }\n }\n\n /* conversion of 3D absorption to BT is probably useless, hence we don't do it */\n\n } else { /* 1D processing */\n\n if (input.rte.solver == SOLVER_POLRADTRAN) { /* polRadtran output */\n for (lev = 0; lev < output->atm.nzout; lev++)\n for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) {\n\n output->down_flux[lev][is][iv] =\n radiance2bt (output->down_flux[lev][is][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->up_flux[lev][is][iv] =\n radiance2bt (output->up_flux[lev][is][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++)\n for (j = 0; j < input.rte.nphi; j++) {\n\n output->down_rad[lev][j][iu][is][iv] =\n radiance2bt (output->down_rad[lev][j][iu][is][iv], wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->up_rad[lev][j][iu][is][iv] =\n radiance2bt (output->up_rad[lev][j][iu][is][iv], wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n }\n }\n } else { /* unpolarized output */\n\n for (lev = 0; lev < output->atm.nzout; lev++) {\n\n /* irradiance / actinic flux */\n output->rfldir[lev][iv] = radiance2bt (output->rfldir[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->rfldn[lev][iv] = radiance2bt (output->rfldn[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->flup[lev][iv] = radiance2bt (output->flup[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavg[lev][iv] = radiance2bt (output->uavg[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavgso[lev][iv] = radiance2bt (output->uavgso[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavgdn[lev][iv] = radiance2bt (output->uavgdn[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n output->uavgup[lev][iv] = radiance2bt (output->uavgup[lev][iv] / PI, wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n /* radiances */\n for (iu = 0; iu < input.rte.numu; iu++) {\n output->u0u[lev][iu][iv] = radiance2bt (output->u0u[lev][iu][iv], wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n\n for (j = 0; j < input.rte.nphi; j++)\n output->uu[lev][j][iu][iv] = radiance2bt (output->uu[lev][j][iu][iv], wvnmlo, wvnmhi, weight, nlambda, processing, iv);\n }\n }\n }\n }\n\n if (output->wl.use_reptran && input.processing == PROCESS_NONE) {\n free (wvnmlo);\n free (wvnmhi);\n free (weight);\n }\n\n return 0;\n}\n\nstatic int read_photon_file (char* filename, float* lambda_r, int nlambda_r, float** fraction) {\n float* wvl = NULL;\n int iv = 0, n = 0, status = 0;\n\n status = read_2c_file_float (filename, &wvl, fraction, &n);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading %s\\n\", status, filename);\n return status;\n }\n\n /* compare wavelength grids */\n if (nlambda_r != n) {\n fprintf (stderr, \"Error, number of wavelengths in %s differing from\\n\", filename);\n fprintf (stderr, \"internal wavelength grid\\n\");\n return -1;\n }\n\n for (iv = 0; iv < n; iv++)\n if (lambda_r[iv] != wvl[iv]) {\n fprintf (stderr,\n \"Error, wavelengths in %s differ from internal wavelength grid: %f vs. %f\\n\",\n filename,\n lambda_r[iv],\n wvl[iv]);\n return -1;\n }\n\n return 0;\n}\n\n/******************************************************************************/\n/* select the required wavelength range from an array of wavelengths (lambda) */\n/******************************************************************************/\n\nstatic int select_wavelength_indices (float* lambda,\n int nlambda,\n float* lambda_lower,\n float* lambda_upper,\n int start_index,\n int end_index,\n int quiet,\n int raman,\n int* lower,\n int* upper) {\n int iv = 0, tmp = 0;\n if (start_index > 0 && end_index > 0) {\n /* if wavelength indices are defined */\n\n /* check if start_index and end_index sorted; if not, sort */\n if (start_index > end_index) {\n tmp = start_index;\n start_index = end_index;\n end_index = tmp;\n }\n\n /* check if we are out of range */\n if (end_index > nlambda) {\n fprintf (stderr, \"Error, selected wavelength index %d is out of range \\n\", end_index);\n return -1;\n }\n\n /* the selected range is valid */\n *lower = start_index - 1;\n *upper = end_index - 1;\n\n *lambda_lower = lambda[*lower];\n *lambda_upper = lambda[*upper];\n\n } else {\n /* if wavelength is specified search for suitable indices */\n\n while (lambda[iv] <= *lambda_lower)\n if (++iv == nlambda)\n break;\n\n if (iv > 0)\n iv -= 1;\n\n *lower = iv;\n\n iv = 0;\n while (lambda[iv] < *lambda_upper) {\n if (++iv == nlambda)\n break;\n }\n\n /* Need to include larger wavelength range if Raman scattering is included */\n if (raman) {\n iv = 0;\n\n while (lambda[iv] <= *lambda_lower)\n if (++iv == nlambda)\n break;\n if (iv > 0)\n iv -= 1;\n *lower = iv;\n\n iv = 0;\n while (lambda[iv] < *lambda_upper) {\n if (++iv == nlambda)\n break;\n }\n\n if (iv == nlambda)\n iv -= 1;\n\n *upper = iv;\n }\n\n if (iv == nlambda)\n iv -= 1;\n\n *upper = iv;\n }\n\n return 0;\n}\n\n/**************************************************************************/\n/* average return the average density per layer in the array **y_average */\n/* **y_average will be automatically callocated */\n/* OUTPUT: dens_avg */\n/**************************************************************************/\n\nint average_dens (float* dens, float* dens_air, float* zd, int nlev, int interpol_method, float** dens_avg, int allocate) {\n int status = 0;\n int n_layer;\n float* mix; /* mixing ratio*/\n int lc;\n\n n_layer = nlev - 1;\n\n if (allocate)\n if (((*dens_avg) = (float*)calloc (n_layer, sizeof (float))) == NULL) {\n fprintf (stderr, \"Error allocating memory for (*dens_avg) in average (ancillary.c)\\n\");\n return -1;\n }\n\n switch (interpol_method) {\n case INTERP_METHOD_SPLINE:\n status = spline_average (zd, dens, nlev, dens_avg);\n break;\n case INTERP_METHOD_LINEAR:\n for (lc = 0; lc < n_layer; lc++)\n (*dens_avg)[lc] = 0.5 * (dens[lc] + dens[lc + 1]);\n break;\n case INTERP_METHOD_LOG:\n for (lc = 0; lc < n_layer; lc++) {\n (*dens_avg)[lc] = log_average (dens[lc], dens[lc + 1]);\n }\n break;\n case INTERP_METHOD_LINMIX: /* linear mixing ratio integration */\n case INTERP_METHOD_LOG_SPLINE: /* no log_spline intergration implemented jet !!! */\n mix = (float*)calloc (nlev, sizeof (float));\n if (mix == NULL) {\n fprintf (stderr, \"Error allocating memory for mixing_ratio in average (ancillary.c)\\n\");\n return -1;\n }\n for (lc = 0; lc < nlev; ++lc)\n mix[lc] = dens[lc] / dens_air[lc]; /* calculating to mixing ratio */\n\n for (lc = 0; lc < n_layer; lc++) {\n (*dens_avg)[lc] = linmix_average (mix[lc], mix[lc + 1], dens_air[lc], dens_air[lc + 1]);\n }\n free (mix);\n break;\n default:\n fprintf (stderr, \"Error, unknown interpolation method input.\");\n return -1;\n }\n\n if (status != 0) {\n fprintf (stderr, \"Error %d calculating average concentration (average, in ancillary.c)\\n\", status);\n return status;\n }\n\n return status;\n}\n\n/****************************************************************/\n/* log_average returns the logarithmic average density between */\n/* two layers with d[ens]1 und d[ens]2 */\n/* assuming logarithmic variation with hight */\n/****************************************************************/\n\nfloat log_average (float d1, float d2)\n/* small function to calculate the average density */\n/* assuming a function d=exp(-kx) */\n{\n float avg = 0;\n float test1 = -666., test2 = -666.0;\n\n test1 = (d1 < d2 ? d1 : d2);\n test2 = fabs (d2 - d1);\n\n if (test1 <= 0 || test2 <= 0.001 * d1) /* in this case numerically unstable => */\n avg = 0.5 * (d1 + d2); /* use linear interpolation instead */\n else\n avg = (d2 - d1) / log (d2 / d1);\n\n return avg;\n}\n\ndouble dlog_average (double d1, double d2)\n/* small function to calculate the average density */\n/* assuming a function d=exp(-kx) */\n{\n double avg = 0;\n double test1 = -666., test2 = -666.0;\n\n test1 = (d1 < d2 ? d1 : d2);\n test2 = fabs (d2 - d1);\n\n if (test1 <= 0 || test2 <= 0.001 * d1) /* in this case numerically unstable => */\n avg = 0.5 * (d1 + d2); /* use linear interpolation instead */\n else\n avg = (d2 - d1) / log (d2 / d1);\n\n return avg;\n}\n\n/*************************************************************************/\n/* linmix_average returns the linear mixing ratio average density n_bar */\n/* between two layers with m[ixing ratio]1 and m2 and */\n/* air number density n1 and n2 */\n/* assuming linear variation of the mix ratio with height */\n/* and logarithmic variation of the air number dens with height */\n/*************************************************************************/\n\nfloat linmix_average (float mmr1, float mmr2, float n1, float n2) {\n float avg = 0;\n float test1 = -666., test2 = -666.0;\n float log_n = 0;\n\n test1 = (n1 < n2 ? n1 : n2);\n test2 = fabs (n1 - n2);\n\n if (test1 <= 0 || test2 <= 0.001 * n1) /* in this case numerically unstable => */\n avg = 0.5 * (mmr1 * n1 + mmr2 * n2); /* use linear interpolation instead */\n else {\n log_n = log (n2 / n1);\n avg = 1 / (log_n * log_n) * ((n2 * mmr2 - n1 * mmr1) * log_n - (mmr2 - mmr1) * (n2 - n1));\n }\n\n return avg;\n}\n\n/***********************************************************************/\n/* mass_weighted_average returns the mass weighted average of x */\n/* between two layers with properties x1,n1 and x2,n2 */\n/* air number density n1 and n2 */\n/* assuming linear variation of the x with height */\n/* and logarithmic variation of the air number dens with height */\n/***********************************************************************/\n\nfloat mass_weighted_average (float x1, float x2, float n1, float n2) {\n float avg = 0;\n float test1 = -666., test2 = -666.0;\n\n test1 = (n1 < n2 ? n1 : n2);\n test2 = fabs (n1 - n2);\n\n if (test1 <= 0 || test2 <= 0.001 * n1) /* in this case numerically unstable => */\n avg = (n1 * x1 + n2 * x2) / (n1 + n2); /* use simple mass weighte average instead */\n else {\n avg = (n2 * x2 - n1 * x1) / (n2 - n1) - (x2 - x1) / log (n2 / n1);\n }\n\n return avg;\n}\n\n/************************************************************/\n/* small function to calculate the average density */\n/* assuming cubic spline variation */\n/* returns an array instead of number as previous functions */\n/************************************************************/\n\nint spline_average (float* x, float* y, int n, float** y_average)\n\n{\n double *a0 = NULL, *a1 = NULL, *a2 = NULL, *a3 = NULL;\n int m;\n int i;\n double dx, dx2, dx3;\n int status;\n int descend = 0;\n double *x_sort = NULL, *y_sort = NULL;\n double* y_average_d;\n\n x_sort = (double*)calloc (n, sizeof (double));\n y_sort = (double*)calloc (n, sizeof (double));\n\n if (x[1] <= x[0])\n descend = 1;\n\n /* number of layers = number of level - 1 */\n m = n - 1;\n\n if (!descend) {\n for (i = 0; i < n; i++) {\n x_sort[i] = (double)x[i];\n y_sort[i] = (double)y[i];\n }\n } else {\n for (i = 0; i < n; i++) {\n x_sort[i] = (double)x[n - 1 - i];\n y_sort[i] = (double)y[n - 1 - i];\n }\n }\n\n status = spline_coeffc (x_sort, y_sort, n, &a0, &a1, &a2, &a3);\n if (status != 0) {\n fprintf (stderr, \"Error %d during execution of 'spline_coeffc'\\n\", status);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n y_average_d = (double*)calloc (m, sizeof (double));\n\n for (i = 0; i < m; i++) {\n dx = (double)(x_sort[i + 1] - x_sort[i]);\n dx2 = (double)(dx * dx);\n dx3 = (double)(dx * dx2);\n y_average_d[i] = ((double)0.25) * a3[i] * dx3 + ((double)1. / 3.) * a2[i] * dx2 + ((double)0.5) * a1[i] * dx + a0[i];\n }\n\n if (!descend)\n for (i = 0; i < m; i++)\n (*y_average)[i] = (float)y_average_d[i];\n else\n for (i = 0; i < m; i++)\n (*y_average)[i] = (float)y_average_d[m - 1 - i];\n\n return 0;\n}\n\n/****************************************************************/\n/* alloc_and_read_netCDF_1D_double */\n/* allocate and */\n/* read an 1D array direct from netCDF file */\n/* ncid input input id_number of the file */\n/* dimension input name of dimension number in netCDF file */\n/* dim output number of elements */\n/* variable input name of data in netCDF file */\n/* data output pointer to data (double) */\n/* January 2007 Ulrich Hamann */\n/****************************************************************/\n\nint alloc_and_read_netCDF_1D_double (int ncid, char* dimension, size_t* dim, char* variable, double** data)\n\n{\n int status = 0;\n\n#if HAVE_NETCDF4\n\n int id_dim = 0;\n int id_var = 0;\n\n /* get dimension id for \"dimension\" */\n status = nc_inq_dimid (ncid, dimension, &id_dim);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s' locating '%s' from netCDF file\\n\", nc_strerror (status), dimension);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* get dimension length for \"dimension\" */\n status = nc_inq_dimlen (ncid, id_dim, dim);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s' while reading '%s' from netCDF file\\n\", nc_strerror (status), dimension);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* fprintf (stderr, \"reading %s, dim=%u \\n\", variable, *dim); */\n\n /* allocate data */\n if ((*(data) = calloc (*(dim), sizeof (double))) == NULL) {\n fprintf (stderr, \"Error allocating memory for 'lat' (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* get id number for variable */\n status = nc_inq_varid (ncid, variable, &id_var);\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s' while getting id for '%s' (line %d, function %s in %s) \\n\",\n nc_strerror (status),\n variable,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n /* read variable (double) */\n status = nc_get_var_double (ncid, id_var, *(data));\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s' while reading '%s' from netCDF file (line %d, function %s in %s) \\n\",\n nc_strerror (status),\n variable,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n#endif\n\n return status;\n}\n\n/**********************************************************/\n/* get_grid_index */\n/* */\n/* small function that searches the index */\n/* where \"number\" is closest to an element of \"array\" */\n/* periodic takes care of 360 degree periodic boundaries */\n/* */\n/* Ulrich Hamann, Mai 2007 */\n/**********************************************************/\n\nint get_grid_index (float number, double* array, int n_array, int periodic) {\n\n int index = NOT_DEFINED_INTEGER;\n int i = 0;\n float min_dist = NOT_DEFINED_FLOAT;\n float dist = NOT_DEFINED_FLOAT;\n float grid_dist_1 = NOT_DEFINED_FLOAT;\n float grid_dist_2 = NOT_DEFINED_FLOAT;\n\n /* if we have only one entry than choose the first and only entry */\n if (n_array == 1) {\n index = 0;\n return index;\n }\n\n if (periodic) {\n /* initialisation with periodic boundary considering periodicity */\n min_dist = fabs (array[n_array - 1] - 360.0 - number);\n index = n_array - 1;\n if (fabs (array[n_array - 1] + 360.0 - number) < min_dist)\n min_dist = fabs (array[n_array - 1] + 360.0 - number);\n } else {\n /* initialisation with boundary */\n min_dist = fabs (array[n_array - 1] - number);\n index = n_array - 1;\n }\n\n /* find minimum distance between number and grid elements */\n for (i = 0; i < n_array; i++) {\n dist = fabs (array[i] - number);\n if (dist < min_dist) {\n min_dist = dist;\n index = i;\n }\n }\n\n /* check 1: index must be defined */\n if (index == NOT_DEFINED_INTEGER) {\n fprintf (stderr, \"Error, did NOT find pixel index for pixel %6.0f !!! \\n\", number);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -2;\n }\n\n /* check 2: min_dist should be smaller than distance to next neighbour */\n if (index != 0) {\n grid_dist_1 = fabs (array[index] - array[index - 1]);\n }\n if (index != n_array - 1) {\n grid_dist_2 = fabs (array[index] - array[index + 1]);\n /* choose the largest grid space distance (more relaxed constraint) */\n if (grid_dist_2 > grid_dist_1)\n grid_dist_1 = grid_dist_2;\n }\n if (index == 0 && index == n_array - 1)\n grid_dist_1 = 0;\n\n if (min_dist > grid_dist_1) {\n fprintf (stderr, \"Error while searching grid index, minimum distance (%f) between element %8.2f and grid \\n\", number, min_dist);\n fprintf (stderr, \" is larger than one grid spacing! (grid spacing = %f) \\n\", grid_dist_1);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* correct periodic behaviour at the eastern boundary */\n if (periodic) {\n if (fabs (array[0] + 360.0 - number) < min_dist || fabs (array[0] - 360.0 - number) < min_dist) {\n min_dist = fabs (array[n_array - 1] + 360.0 - number);\n index = 0;\n }\n }\n\n return index;\n}\n\n/****************************************************************/\n/* get_all_netCDF_indices */\n/* */\n/* Purpose: */\n/* get size and index for lat, lon, time */\n/* */\n/* input: */\n/* ------ */\n/* ncid id_number of the open netCDF file */\n/* lat latitude */\n/* lon longitude */\n/* UTC universal time correlated */\n/* time_interpolate switch for time interpolation */\n/* verbose additional verbose output */\n/* quiet no verbose output */\n/* */\n/* output: */\n/* ------- */\n/* ilat index for latitude */\n/* nlat size of latitude in netCDF file */\n/* ilon index for longitude */\n/* nlon size of longitude in netCDF file */\n/* nt number of time steps (2 if time interpolation) */\n/* itime1 first index for time */\n/* itime2 second index for time */\n/* dt time step fraction where time */\n/* is in between time1 and time2 */\n/* */\n/* September 2007 by Ulrich Hamann */\n/****************************************************************/\n\nint get_all_netCDF_indices (char* filename,\n float lat,\n float lon,\n int* ncid,\n long* ilat,\n size_t* nlat,\n long* ilon,\n size_t* nlon,\n double** lat_grid,\n double** lon_grid,\n struct tm UTC,\n int time_interpolate,\n int* nt,\n int* itime1,\n int* itime2,\n float* dt,\n int verbose,\n int quiet) {\n\n#if HAVE_NETCDF4\n\n int status = 0;\n\n int i = 0, j = 0;\n\n float lon_tmp = NOT_DEFINED_FLOAT;\n float lat_min = NOT_DEFINED_FLOAT, lat_max = NOT_DEFINED_FLOAT;\n float lon_min = NOT_DEFINED_FLOAT, lon_max = NOT_DEFINED_FLOAT;\n\n char function_name[] = \"get_all_netCDF_indices\";\n char file_name[] = \"ancillary.c\";\n\n if (lat < -90.0 || 90.0 < lat) {\n fprintf (stderr,\n \"Error, latitude %f outside range, maybe not specified (if == -999) in %s (%s)\\n\",\n lat,\n function_name,\n file_name);\n return -1;\n }\n\n if (lon < -360.0 || 360.0 < lon) {\n fprintf (stderr,\n \"Error, longitude %f outside range, maybe not specified (if == -999) in %s (%s)\\n\",\n lon,\n function_name,\n file_name);\n return -1;\n }\n\n /* open netcdf file */\n status = nc_open (filename, NC_NOWRITE, ncid);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error %d opening netCDF file %s in %s (%s)\\n\", status, filename, function_name, file_name);\n return status;\n }\n\n /* read latitude array */\n status = alloc_and_read_netCDF_1D_double ((*ncid), \"lat\", nlat, \"lat\", lat_grid);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading latitude in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n /* search correct latitude index */\n (*ilat) = get_grid_index (lat, *lat_grid, (*nlat), FALSE);\n if (ilat < 0) {\n fprintf (stderr, \"Error -1 finding index for lat=%5.2f in %s, %s (%s)\\n\", lat, filename, function_name, file_name);\n return -1;\n }\n\n /* get range of latitude */\n lat_min = (*lat_grid)[0];\n lat_max = (*lat_grid)[0];\n for (i = 1; i < (*nlat); i++) {\n if ((*lat_grid)[i] > lat_max)\n lat_max = (*lat_grid)[i];\n if ((*lat_grid)[i] < lat_min)\n lat_min = (*lat_grid)[i];\n }\n\n /* read longitude */\n status = alloc_and_read_netCDF_1D_double ((*ncid), \"lon\", nlon, \"lon\", lon_grid);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading longitude in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n /* get range of longitude */\n lon_min = (*lon_grid)[0];\n lon_max = (*lon_grid)[0];\n for (j = 1; j < (*nlon); j++) {\n if ((*lon_grid)[j] > lon_max)\n lon_max = (*lon_grid)[j];\n if ((*lon_grid)[j] < lon_min)\n lon_min = (*lon_grid)[j];\n }\n\n lon_tmp = lon;\n\n /* longitude periodicity */\n /* correct periodicity of latitude so, that longitude is inside the range of the map */\n if (lon_tmp < lon_min)\n lon_tmp += 360.0;\n if (lon_tmp > lon_max)\n lon_tmp -= 360.0;\n\n /* search correct longitude index */\n (*ilon) = get_grid_index (lon_tmp, *lon_grid, (*nlon), TRUE);\n if (ilon < 0) {\n fprintf (stderr, \"Error -2 finding index for lon=%5.2f in %s, %s (%s)\\n\", lon, filename, function_name, file_name);\n return -2;\n }\n\n if (verbose)\n fprintf (stderr, \" found %zd x %zd data points\\n\", (*nlat), (*nlon));\n\n if (verbose) {\n fprintf (stderr,\n \" map size = [%8.3f (South),%8.3f (North)] x [%8.3f (West),%8.3f (East)]\\n\",\n lat_min,\n lat_max,\n lon_min,\n lon_max);\n }\n\n /* get time index */\n status = get_time_index ((*ncid), UTC, time_interpolate, nt, itime1, itime2, dt, verbose, quiet);\n if (status != 0) {\n fprintf (stderr, \"Error %d, during get_time_index in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n if (verbose) {\n if (UTC.tm_mday > 0 && (*nt) == 2)\n fprintf (stderr,\n \" read data at: lat =%7.2f (%7.2f), lon =%7.2f (%7.2f), time = %s\",\n (*lat_grid)[(*ilat)],\n lat,\n (*lon_grid)[(*ilon)],\n lon_tmp,\n asctime (&UTC));\n else\n fprintf (stderr,\n \" read data at: lat =%7.2f (%7.2f), lon =%7.2f (%7.2f), \\n\",\n (*lat_grid)[(*ilat)],\n lat,\n (*lon_grid)[(*ilon)],\n lon_tmp);\n\n if ((*nt) == 1)\n fprintf (stderr, \" element: i=%6ld (lon), j=%6ld (lat), t=%6d (time)\\n\", (*ilon), (*ilat), (*itime1));\n if ((*nt) == 2)\n fprintf (stderr,\n \" element: i=%6ld (lon), j=%6ld (lat), (%4d/%4d) (time1/time2)\\n\",\n (*ilon),\n (*ilat),\n (*itime1),\n (*itime2));\n }\n\n return status;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any netCDF option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/****************************************************************/\n/* read_p_T_z_from_ECMWF_file */\n/* */\n/* Purpose: */\n/* read pressure, temperature from ECMWF file */\n/* interpolate data with respect to time if wanted */\n/* calculate z-grid for the layers */\n/* */\n/* input: */\n/* ------ */\n/* ncid id_number of the open netCDF file */\n/* ilat index for latitude */\n/* nlat size of latitude in netCDF file */\n/* ilon index for longitude */\n/* nlon size of longitude in netCDF file */\n/* nt number of time steps (2 if time interpolation) */\n/* itime1 first index for time */\n/* itime2 second index for time */\n/* dt time step fraction where time */\n/* is in between time1 and time2 */\n/* time_interpolate switch for time interpolation */\n/* verbose additional verbose output */\n/* quiet no verbose output */\n/* */\n/* output: */\n/* ------- */\n/* nlay number of layers + 1 for surface */\n/* p_layer layer averaged pressure */\n/* T_layer layer averaged temperature */\n/* z_layer z-levels for layer midpoints */\n/* */\n/* September 2007 by Ulrich Hamann */\n/****************************************************************/\n\nint read_p_T_z_from_ECMWF_file (int ncid,\n long ilat,\n size_t nlat,\n long ilon,\n size_t nlon,\n int nt,\n int itime1,\n int itime2,\n float dt,\n size_t* nlay,\n size_t* nlev,\n float altitude,\n float** p_layer,\n float** T_layer,\n float** z_layer,\n int verbose,\n int quiet) {\n int status = 0;\n\n float** tmp_p_level = NULL;\n float** tmp_p_layer = NULL;\n float** tmp_T_layer = NULL;\n\n int itime = 0;\n int t = NOT_DEFINED_INTEGER;\n float SP = -999.0;\n float dx = NOT_DEFINED_FLOAT;\n\n int lc = 0;\n\n char function_name[] = \"read_p_T_z_from_ECMWF_file\";\n char file_name[] = \"ancillary.c\";\n\n /* alloc nt timesteps for pressure */\n if ((tmp_p_level = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for pressure */\n if ((tmp_p_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for temperature */\n if ((tmp_T_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for temperature in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* read nt (= 1 or 2) time steps */\n for (t = 0; t <= nt - 1; t++) {\n\n if (t == 0)\n itime = itime1;\n if (t == 1)\n itime = itime2;\n\n /* alloc and read pressure */\n /* requires that SP/LNSP, hyai and hybi are in the ECMWF netCDF file */ /* in ancillary.c */\n status =\n alloc_and_read_ECMWF_netCDF_pressure (ncid, &(tmp_p_level[t]), nlev, &(tmp_p_layer[t]), nlay, itime, ilat, ilon, FALSE);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading pressure from netCDF file\\n\", status);\n return status;\n }\n\n if ((tmp_p_layer[t] = realloc (tmp_p_layer[t], ((*nlay) + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'tmp_p_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n#if HAVE_NETCDF4\n /* read surface pressure from ECMWF file */\n status = read_ECMWF_surface_pressure (ncid, itime, ilat, ilon, &(SP), FALSE); /* FALSE == no verbose */\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', while read_ECMWF_surface_pressure in %s (%s)\\n\",\n nc_strerror (status),\n function_name,\n file_name);\n return status;\n }\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use ECMWF input options. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n\n tmp_p_layer[t][(*nlay)] = SP / 100.0; /* Pa -> hPa */\n\n /* allocate and read temperature, defined on layers */\n status = alloc_and_read_netCDF_column_float (ncid, \"T\", &tmp_T_layer[t], (*nlay), itime, ilat, ilon, FALSE);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading temperature 'T' from netCDF file\\n\", status);\n return status;\n }\n\n if ((tmp_T_layer[t] = realloc (tmp_T_layer[t], ((*nlay) + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'T_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n /* extrapolate temperature from last layer midpoint to surface */\n dx = (log (tmp_p_level[0][(*nlev) - 1] / tmp_p_level[0][(*nlev) - 1]) -\n log (tmp_p_layer[0][(*nlay) - 1] / tmp_p_level[0][(*nlev) - 1])) /\n (log (tmp_p_layer[0][(*nlay) - 1] / tmp_p_level[0][(*nlev) - 1]) -\n log (tmp_p_layer[0][(*nlay) - 2] / tmp_p_level[0][(*nlev) - 1]));\n tmp_T_layer[t][(*nlay)] = (1.0 + dx) * tmp_T_layer[0][(*nlay) - 1] - dx * tmp_T_layer[0][(*nlay) - 2];\n }\n\n /* number of final layers == number of layers plus one for surface */\n (*nlay) = (*nlay) + 1;\n\n if (verbose)\n fprintf (stderr, \" found %4zd levels, \\n\", (*nlev));\n\n if (nt == 1) {\n /* no time interpolation needed, just copy data */\n } else {\n /* time interpolation */\n for (lc = 0; lc < (*nlay); lc++) {\n tmp_p_layer[0][lc] = (1.0 - dt) * tmp_p_layer[0][lc] + dt * tmp_p_layer[1][lc];\n tmp_T_layer[0][lc] = (1.0 - dt) * tmp_T_layer[0][lc] + dt * tmp_T_layer[1][lc];\n }\n }\n\n /* calculate z from T and p using hydrostatic equation (in ancillary.c) */\n status = calculate_z_from_p_and_T (tmp_p_layer[0], tmp_T_layer[0], z_layer, (*nlay), altitude, FALSE);\n if (status != 0) {\n fprintf (stderr,\n \"Error %d during calculate_z_from_p_and_T (line %d, function '%s' in '%s') \\n\",\n status,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n /* allocate space for final results */\n if (((*p_layer) = calloc ((*nlay), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n\n /* allocate space for final results */\n if (((*T_layer) = calloc ((*nlay), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n\n for (lc = 0; lc < (*nlay); lc++) {\n (*p_layer)[lc] = tmp_p_layer[0][lc];\n (*T_layer)[lc] = tmp_T_layer[0][lc];\n }\n\n return status;\n}\n\n/****************************************************************/\n/* get_number_from_netCDF_map */\n/* */\n/* Purpose: */\n/* search one entry (float) */\n/* by latitude, longitude, time from one netCDF file */\n/* */\n/* input: */\n/* ------ */\n/* lat latitude */\n/* lon longitude */\n/* UTC universal time correlated */\n/* filename name of the netCDF file including the map */\n/* */\n/* output: */\n/* ------- */\n/* result data read from the map */\n/* February 2007 by Ulrich Hamann */\n/****************************************************************/\n\nint get_number_from_netCDF_map (float lat,\n float lon,\n struct tm UTC,\n int time_interpolate,\n char* filename,\n void* data,\n int external_type,\n char* variable_name,\n int verbose,\n int quiet) {\n int status = 0;\n\n#if HAVE_NETCDF4\n\n int ncid = 0;\n int id_data = 0;\n nc_type netCDF_type;\n\n char lat_name[FILENAME_MAX] = \"\";\n char lon_name[FILENAME_MAX] = \"\";\n\n size_t nlat = 0;\n size_t nlon = 0;\n\n int ilat = NOT_DEFINED_INTEGER;\n int ilon = NOT_DEFINED_INTEGER;\n int dummy = NOT_DEFINED_INTEGER;\n\n double* lat_grid = NULL;\n double* lon_grid = NULL;\n\n int i = 0, j = 0, t = 0;\n int nt = -1;\n int itime1 = NOT_DEFINED_INTEGER, itime2 = NOT_DEFINED_INTEGER;\n float dt = NOT_DEFINED_FLOAT;\n\n int dimensions = NOT_DEFINED_INTEGER;\n\n size_t* index = NULL;\n\n float lon_tmp = NOT_DEFINED_FLOAT;\n float lat_min = NOT_DEFINED_FLOAT, lat_max = NOT_DEFINED_FLOAT;\n float lon_min = NOT_DEFINED_FLOAT, lon_max = NOT_DEFINED_FLOAT;\n\n unsigned char* data_uchar = NULL;\n short* data_short = NULL;\n int* data_int = NULL;\n float* data_float = NULL;\n double* data_double = NULL;\n\n /* int data_unit_len = NOT_DEFINED_INTEGER; */\n /* nc_type unit_type; */\n char data_unit[50] = \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n float missing_value = NOT_DEFINED_FLOAT;\n float unit_factor = 1.0;\n float scale_factor = 1.0;\n float add_offset = 0.0;\n\n if (verbose) {\n fprintf (stderr, \" ... read %s from map: \\n\", variable_name);\n fprintf (stderr, \" %s \\n\", filename);\n }\n\n lon_tmp = lon;\n\n /* open netcdf file */\n status = nc_open (filename, NC_NOWRITE, &ncid);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s' opening netCDF file %s\\n\", nc_strerror (status), filename);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* check format */\n status = nc_inq_varid (ncid, \"lat\", &id_data);\n if (status == NC_NOERR) {\n strcpy (lat_name, \"lat\");\n strcpy (lon_name, \"lon\");\n } else {\n status = nc_inq_varid (ncid, \"latitude\", &id_data);\n if (status == NC_NOERR) {\n strcpy (lat_name, \"latitude\");\n strcpy (lon_name, \"longitude\");\n } else {\n fprintf (stderr, \"Error, neither 'lat' nor 'latitude' in %s while reading '%s'\\n\", filename, variable_name);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n }\n\n /* get id for \"data to read\" (variable_name) */\n status = nc_inq_varid (ncid, variable_name, &id_data);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting ncid for %s from %s\\n\", nc_strerror (status), variable_name, filename);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* get type of the variable */\n status = nc_inq_vartype (ncid, id_data, &(netCDF_type));\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting type for %s from %s\\n\", nc_strerror (status), variable_name, filename);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n if (verbose)\n fprintf (stderr,\n \" data type = %d (NC_BYTE %d, NC_CHAR %d, NC_SHORT %d, NC_INT %d, NC_FLOAT %d, NC_DOUBLE %d)\\n\",\n netCDF_type,\n NC_BYTE,\n NC_CHAR,\n NC_SHORT,\n NC_INT,\n NC_FLOAT,\n NC_DOUBLE);\n\n /* read attribute unit and interprete it as much as possible */\n status = nc_get_att_text (ncid, id_data, \"units\", data_unit);\n\n if (status != NC_NOERR) {\n /* no given units -> default unit_factor = 1.0 */\n unit_factor = 1.0;\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* some information is given about the unit, try to interprete it */\n if (strncasecmp (\"per cent\", data_unit, 8) == 0)\n unit_factor = 100.0; /* % -> 1 */\n if (strcasecmp (\"m\", data_unit) == 0)\n unit_factor = 1000.0; /* m -> km */\n\n if (strncasecmp (\"meter\", data_unit, 5) == 0)\n unit_factor = 1000.0; /* m -> km */\n if (strcasecmp (\"m**2 s**-2\", data_unit) == 0)\n unit_factor = 9.80 * 1000.0; /* gpm -> km */\n if (verbose)\n fprintf (stderr, \" data unit = %s, scale data with %f\\n\", data_unit, unit_factor);\n }\n\n /* read attribute scale_factor */\n status = nc_get_att_float (ncid, id_data, \"scale_factor\", &scale_factor);\n if (status != NC_NOERR) {\n /* no given scale_factor -> default scale_factor = 1.0 */\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" scale_factor = %f \\n\", scale_factor); */\n }\n\n /* read attribute add_offset */\n status = nc_get_att_float (ncid, id_data, \"add_offset\", &add_offset);\n if (status != NC_NOERR) {\n /* no given offset -> default offset = 0.0 */\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" add_offset = %f \\n\", add_offset); */\n }\n\n /* read attribute _FillValue / missing_value */\n status = nc_get_att_float (ncid, id_data, \"missing_value\", &missing_value);\n if (status != NC_NOERR) {\n /* no given missing_value -> try to read _FillValue */\n status = nc_get_att_float (ncid, id_data, \"_FillValue\", &missing_value);\n if (status != NC_NOERR) {\n /* no given attribute, that's OK, we can' make checks, but we continue */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" missing_value = %f \\n\", missing_value); */\n }\n }\n\n /* read latitude array */\n status = alloc_and_read_netCDF_1D_double (ncid, lat_name, &nlat, lat_name, &(lat_grid));\n if (status != 0) {\n fprintf (stderr,\n \"Error %d reading '%s' from %s (line %d, function %s in %s)\\n\",\n status,\n lat_name,\n filename,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n /* read longitude */\n status = alloc_and_read_netCDF_1D_double (ncid, lon_name, &nlon, lon_name, &(lon_grid));\n if (status != 0) {\n fprintf (stderr,\n \"Error %d reading '%s' from %s (line %d, function %s in %s)\\n\",\n status,\n lon_name,\n filename,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n if (verbose)\n fprintf (stderr, \" found %zd (south-north) x %zd (west-east) data points\\n\", nlat, nlon);\n\n /* get range of latitude */\n lat_min = lat_grid[0];\n lat_max = lat_grid[0];\n for (i = 1; i < nlat; i++) {\n if (lat_grid[i] > lat_max)\n lat_max = lat_grid[i];\n if (lat_grid[i] < lat_min)\n lat_min = lat_grid[i];\n }\n\n /* get range of longitude */\n lon_min = lon_grid[0];\n lon_max = lon_grid[0];\n\n for (j = 1; j < nlon; j++) {\n if (lon_grid[j] > lon_max)\n lon_max = lon_grid[j];\n if (lon_grid[j] < lon_min)\n lon_min = lon_grid[j];\n }\n\n /* longitude periodicity */\n /* correct periodicity of latitude so, that longitude is inside the range of the map */\n if (lon_tmp < lon_min)\n lon_tmp += 360.0;\n if (lon_tmp > lon_max)\n lon_tmp -= 360.0;\n\n if (verbose) {\n fprintf (stderr,\n \" map size = [%8.3f (South),%8.3f (North)] x [%8.3f (West),%8.3f (East)]\\n\",\n lat_min,\n lat_max,\n lon_min,\n lon_max);\n }\n\n /* read time in netCDF file (if present) */\n status = nc_inq_dimid (ncid, \"time\", &dummy);\n if (status == NC_NOERR) {\n\n /* get time index */\n status = get_time_index (ncid, UTC, time_interpolate, &(nt), &(itime1), &(itime2), &(dt), verbose, quiet);\n if (status != 0) {\n fprintf (stderr, \"Error '%s', during get_time_index\\n\", nc_strerror (status));\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* data in the netCDF file is assumed to have 3 dimensions: lat/lon/time */\n dimensions = 3;\n } else {\n /* no time variable in the netCDF file */\n status = 0; /* it's OK, even if there is no time information */\n nt = 1; /* take the first entry */\n dimensions = 2; /* lon / lat */\n }\n\n /* netCDF index might have 2 (lat/lon) or 3 (time/lat/lon) elements */\n if ((index = calloc (dimensions, sizeof (size_t))) == NULL) {\n fprintf (stderr, \"Error allocation of memory for 'index'\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* start_2D[0] as type size_t can not be negative, that why first index is used here */\n ilat = get_grid_index (lat, lat_grid, nlat, FALSE);\n if (ilat < 0) {\n fprintf (stderr, \"Error %d, while searching index in lat_grid \\n\", ilat);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return ilat;\n }\n\n /* start_2D[1] as type size_t can not be negative, that why first index is used here */\n ilon = get_grid_index (lon_tmp, lon_grid, nlon, TRUE);\n if (ilon < 0) {\n fprintf (stderr, \"Error %d, while searching index in lon_grid \\n\", ilon);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return ilon;\n }\n\n /* alloc nt timesteps for data */\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n if ((data_uchar = calloc (nt, sizeof (char*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for data_intern\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n break;\n case (NC_SHORT):\n if ((data_short = calloc (nt, sizeof (short*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for data_intern\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n break;\n case (NC_INT):\n if ((data_int = calloc (nt, sizeof (int*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for data_intern\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n break;\n case (NC_FLOAT):\n if ((data_float = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for data_intern\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n break;\n case (NC_DOUBLE):\n if ((data_double = calloc (nt, sizeof (double*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for data_intern\\n\");\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n break;\n default:\n fprintf (stderr, \"Error, unknown type (short, float, double ...) of variable %d\\n\", netCDF_type);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n if (dimensions == 2) {\n\n index[0] = ilat;\n index[1] = ilon;\n\n if (verbose) {\n fprintf (stderr, \" read data at: lat =%7.2f (%7.2f), lon =%7.2f (%7.2f), \", lat_grid[ilat], lat, lon_grid[ilon], lon_tmp);\n fprintf (stderr, \" element: (j=%6d) x (i=%6d) \\n\", ilat, ilon);\n }\n\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n status = nc_get_var1_uchar (ncid, id_data, index, &(data_uchar[0]));\n /* fprintf (stderr, \" read data value is %d (unscaled)\\n\", (data_uchar[0])); */\n if (data_uchar[0] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_SHORT):\n status = nc_get_var1_short (ncid, id_data, index, &(data_short[0]));\n /* fprintf (stderr, \" read data value is %d (unscaled)\\n\", (data_short[0])); */\n if (data_short[0] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_INT):\n status = nc_get_var1_int (ncid, id_data, index, &(data_int[0]));\n /* fprintf (stderr, \" read data value is %d (unscaled)\\n\", (data_int[0])); */\n if (data_int[0] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_FLOAT):\n status = nc_get_var1_float (ncid, id_data, index, &(data_float[0]));\n /* fprintf (stderr, \" read data value is %f (unscaled)\\n\", (data_float[0])); */\n if (data_float[0] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_DOUBLE):\n status = nc_get_var1_double (ncid, id_data, index, &(data_double[0]));\n /* fprintf (stderr, \" read data value is %lf (unscaled)\\n\", (data_double[0])); */\n if (data_double[0] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n default:\n fprintf (stderr,\n \"Error, unknown variable type %d (short, float, ...) in data file %s (line %d, function %s in %s) \\n\",\n netCDF_type,\n filename,\n __LINE__,\n __func__,\n __FILE__);\n return -1;\n }\n\n if (status == ERROR_READ_MISSING_VALUE) {\n fprintf (stderr, \" !!! Error 'Read missing_value' reading %s from %s\\n\", variable_name, filename);\n return status;\n }\n\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s'\\n\", nc_strerror (status));\n fprintf (stderr, \" reading %s from %s\\n\", variable_name, filename);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_SHORT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_INT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_FLOAT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_DOUBLE):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n default:\n fprintf (stderr, \"Error, type of variable %d in get_float_from_netCDF_map (ancillary.c) \\n\", netCDF_type);\n return -1;\n }\n\n switch (external_type) {\n case (TYPE_CHAR):\n if (verbose)\n fprintf (stderr, \" read data value is %d\\n\", (*(char*)data));\n break;\n case (TYPE_SHORT):\n if (verbose)\n fprintf (stderr, \" read data value is %d\\n\", (*(short*)data));\n break;\n case (TYPE_INT):\n if (verbose)\n fprintf (stderr, \" read data value is %d\\n\", (*(int*)data));\n break;\n case (TYPE_FLOAT):\n if (verbose)\n fprintf (stderr, \" read data value is %f\\n\", (*(float*)data));\n break;\n case (TYPE_DOUBLE):\n if (verbose)\n fprintf (stderr, \" read data value is %lf\\n\", (*(double*)data));\n break;\n }\n } else if (dimensions == 3) {\n\n index[1] = ilat;\n index[2] = ilon;\n\n if (verbose) {\n if (UTC.tm_mday > 0) {\n fprintf (stderr,\n \" read data at: lat =%7.2f (%7.2f), lon =%7.2f (%7.2f), time = %s\",\n lat_grid[ilat],\n lat,\n lon_grid[ilon],\n lon_tmp,\n asctime (&UTC));\n if (nt == 1)\n fprintf (stderr, \" element: (j=%6d) x (i=%6d) x (t=%6d)\\n\", ilat, ilon, itime1);\n if (nt == 2)\n fprintf (stderr, \" element: (j=%6d) x (i=%6d) x (t1/t2)=(%4d/%4d)\\n\", ilat, ilon, itime1, itime2);\n } else {\n fprintf (stderr,\n \" read data at: lat =%7.2f (%7.2f), lon =%7.2f (%7.2f)\\n\",\n lat_grid[ilat],\n lat,\n lon_grid[ilon],\n lon_tmp);\n fprintf (stderr, \" element: (j=%6d) x (i=%6d) x (t=%6d)\\n\", ilat, ilon, itime1);\n }\n }\n\n /* read nt (= 1 or 2) time steps */\n for (t = 0; t <= nt - 1; t++) {\n\n if (t == 0)\n index[0] = itime1;\n if (t == 1)\n index[0] = itime2;\n\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n status = nc_get_var1_uchar (ncid, id_data, index, &(data_uchar[t]));\n /* fprintf (stderr, \" read data value is %d (unscaled)\\n\", (data_uchar[t])); */\n if (data_uchar[t] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_SHORT):\n status = nc_get_var1_short (ncid, id_data, index, &(data_short[t]));\n /* fprintf (stderr, \" read data value is %d (unscaled)\\n\", (data_short[t])); */\n if (data_short[t] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_INT):\n status = nc_get_var1_int (ncid, id_data, index, &(data_int[t]));\n /* fprintf (stderr, \" read data value is %d (unscaled)\\n\", (data_int[t])); */\n if (data_int[t] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_FLOAT):\n status = nc_get_var1_float (ncid, id_data, index, &(data_float[t]));\n /* fprintf (stderr, \" read data value is %f (unscaled)\\n\", (data_float[t])); */\n if (data_float[t] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n case (NC_DOUBLE):\n status = nc_get_var1_double (ncid, id_data, index, &(data_double[t]));\n /* fprintf (stderr, \" read data value is %lf (unscaled)\\n\", (data_double[t])); */\n if (data_double[t] == missing_value)\n status = ERROR_READ_MISSING_VALUE;\n break;\n default:\n fprintf (stderr,\n \"Error, unknown variable type %d (short, float, ...) in data file %s (line %d, function %s in %s) \\n\",\n netCDF_type,\n filename,\n __LINE__,\n __func__,\n __FILE__);\n return -1;\n }\n\n if (status == ERROR_READ_MISSING_VALUE) {\n fprintf (stderr, \"Error 'Read missing_value' reading %s from %s\\n\", variable_name, filename);\n return status;\n }\n\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s'\\n\", nc_strerror (status));\n fprintf (stderr, \" reading %s from %s\\n\", variable_name, filename);\n fprintf (stderr, \" (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n }\n\n if (nt == 1) {\n /* no time interpolation nessesary */\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_uchar[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_SHORT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_short[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_INT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_int[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_FLOAT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_float[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_DOUBLE):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(data_double[0] * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n default:\n fprintf (stderr, \"Error, type of variable %d in get_float_from_netCDF_map (ancillary.c) \\n\", netCDF_type);\n return -1;\n }\n if (verbose)\n fprintf (stderr, \" read data value is\");\n } else {\n /* time interpolation */\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(((1.0 - dt) * data_uchar[0] + dt * data_uchar[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(((1.0 - dt) * data_uchar[0] + dt * data_uchar[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(((1.0 - dt) * data_uchar[0] + dt * data_uchar[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(((1.0 - dt) * data_uchar[0] + dt * data_uchar[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(((1.0 - dt) * data_uchar[0] + dt * data_uchar[1]) * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_SHORT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(((1.0 - dt) * data_short[0] + dt * data_short[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(((1.0 - dt) * data_short[0] + dt * data_short[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(((1.0 - dt) * data_short[0] + dt * data_short[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(((1.0 - dt) * data_short[0] + dt * data_short[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(((1.0 - dt) * data_short[0] + dt * data_short[1]) * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_INT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(((1.0 - dt) * data_int[0] + dt * data_int[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(((1.0 - dt) * data_int[0] + dt * data_int[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(((1.0 - dt) * data_int[0] + dt * data_int[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(((1.0 - dt) * data_int[0] + dt * data_int[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(((1.0 - dt) * data_int[0] + dt * data_int[1]) * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_FLOAT):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(((1.0 - dt) * data_float[0] + dt * data_float[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(((1.0 - dt) * data_float[0] + dt * data_float[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(((1.0 - dt) * data_float[0] + dt * data_float[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(((1.0 - dt) * data_float[0] + dt * data_float[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) = (double)(((1.0 - dt) * data_float[0] + dt * data_float[1]) * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n case (NC_DOUBLE):\n switch (external_type) {\n case (TYPE_CHAR):\n (*(char*)data) = (char)(((1.0 - dt) * data_double[0] + dt * data_double[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_SHORT):\n (*(short*)data) = (short)(((1.0 - dt) * data_double[0] + dt * data_double[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_INT):\n (*(int*)data) = (int)(((1.0 - dt) * data_double[0] + dt * data_double[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_FLOAT):\n (*(float*)data) = (float)(((1.0 - dt) * data_double[0] + dt * data_double[1]) * scale_factor + add_offset) / unit_factor;\n break;\n case (TYPE_DOUBLE):\n (*(double*)data) =\n (double)(((1.0 - dt) * data_double[0] + dt * data_double[1]) * scale_factor + add_offset) / unit_factor;\n break;\n }\n break;\n default:\n fprintf (stderr, \"Error, type of variable %d in get_float_from_netCDF_map (ancillary.c) \\n\", netCDF_type);\n return -1;\n }\n\n if (verbose)\n fprintf (stderr, \" interpolated data value is\");\n }\n\n if (verbose) {\n switch (external_type) {\n case (TYPE_CHAR):\n fprintf (stderr, \" %d\\n\", (*(char*)data));\n break;\n case (TYPE_SHORT):\n fprintf (stderr, \" %d\\n\", (*(short*)data));\n break;\n case (TYPE_INT):\n fprintf (stderr, \" %d\\n\", (*(int*)data));\n break;\n case (TYPE_FLOAT):\n fprintf (stderr, \" %f\\n\", (*(float*)data));\n break;\n case (TYPE_DOUBLE):\n fprintf (stderr, \" %lf\\n\", (*(double*)data));\n break;\n }\n }\n }\n\n nc_close (ncid);\n\n free (lat_grid);\n free (lon_grid);\n free (index);\n\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n free (data_uchar);\n break;\n case (NC_SHORT):\n free (data_short);\n break;\n case (NC_INT):\n free (data_int);\n break;\n case (NC_FLOAT):\n free (data_float);\n break;\n case (NC_DOUBLE):\n free (data_double);\n break;\n default:\n fprintf (stderr,\n \"Error, unknown variable type %d (short, float, ...) in data file %s (line %d, function %s in %s) \\n\",\n netCDF_type,\n filename,\n __LINE__,\n __func__,\n __FILE__);\n return -1;\n }\n\n#else\n fprintf (stderr, \" ******************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use the any map option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ******************************************************************\\n\");\n return -1;\n#endif\n\n return status;\n}\n\n/*****************************************************************/\n/* read satellite geometry */\n/* */\n/* Purpose: */\n/* read satellite geometry from netCDF file */\n/* */\n/* input: */\n/* ------ */\n/* sat_pixel_x pixel index in x direction */\n/* sat_pixel_y pixel index in y direction */\n/* UTC simulated time (universal time correlated) */\n/* filename name of netCDF file (contain sat geometry) */\n/* */\n/* output: */\n/* ------- */\n/* latitude latitude */\n/* longitude longitude */\n/* numu number of cos(theta_sat) angles */\n/* maxumu number of cos(theta_sat) angles */\n/* umu cos(theta_sat) angles */\n/* nphi number of azimith_sat angles */\n/* maxphi number of azimith_sat angles */\n/* phi azimith_sat angles in degrees */\n/* */\n/* Mai 2007 by Ulrich Hamann */\n/*****************************************************************/\n\nint read_sat_geometry (int pixel_x,\n int pixel_y,\n struct tm UTC,\n char* filename,\n float* latitude,\n float* longitude,\n int* numu,\n int* maxumu,\n float** umu,\n int* nphi,\n int* maxphi,\n float** phi,\n int solver,\n int verbose,\n int quiet) {\n\n#if HAVE_NETCDF4\n\n int status = 0;\n int ncid = NOT_DEFINED_INTEGER;\n int id_lat = NOT_DEFINED_INTEGER;\n int id_lon = NOT_DEFINED_INTEGER;\n int id_vza = NOT_DEFINED_INTEGER;\n int id_vaa = NOT_DEFINED_INTEGER;\n size_t n_pixel_x = NOT_DEFINED_INTEGER;\n size_t n_pixel_y = NOT_DEFINED_INTEGER;\n double* sat_pixel_x_grid = NULL;\n double* sat_pixel_y_grid = NULL;\n int ix = NOT_DEFINED_INTEGER;\n int iy = NOT_DEFINED_INTEGER;\n int dummy = NOT_DEFINED_INTEGER;\n size_t* index = NULL;\n int nt = -1;\n int itime1 = NOT_DEFINED_INTEGER, itime2 = NOT_DEFINED_INTEGER;\n float dt = NOT_DEFINED_FLOAT;\n int dimensions = NOT_DEFINED_INTEGER;\n\n /* open netcdf file */\n status = nc_open (filename, NC_NOWRITE, &ncid);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s' opening netCDF file %s\\n\", nc_strerror (status), filename);\n return status;\n }\n\n /* get id for latitude */\n status = nc_inq_varid (ncid, \"lat\", &id_lat);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting id for 'latitude' from %s\\n\", nc_strerror (status), filename);\n return status;\n }\n /* get id for longitude */\n status = nc_inq_varid (ncid, \"lon\", &id_lon);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting id for 'longitude' from %s\\n\", nc_strerror (status), filename);\n return status;\n }\n /* get id for viewing zenith angle */\n status = nc_inq_varid (ncid, \"vza\", &id_vza);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting id for 'viewing zenith angle' from %s\\n\", nc_strerror (status), filename);\n return status;\n }\n /* get id for viewing azimuth angle */\n status = nc_inq_varid (ncid, \"vaa\", &id_vaa);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting id for 'viewing azimuth angle' from %s\\n\", nc_strerror (status), filename);\n return status;\n }\n\n /* read pixel_x array (must already be stored in the result file) */\n status = alloc_and_read_netCDF_1D_double (ncid, \"pixel_x\", &n_pixel_x, \"pixel_x\", &(sat_pixel_x_grid));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading sat_pixel_x-grid from %s\\n\", status, filename);\n return status;\n }\n\n /* read pixel_y array (must already be stored in the file) */\n status = alloc_and_read_netCDF_1D_double (ncid, \"pixel_y\", &n_pixel_y, \"pixel_y\", &(sat_pixel_y_grid));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading sat_pixel_y-grid from %s\\n\", status, filename);\n return status;\n }\n\n /* search index */\n ix = get_grid_index (pixel_x, sat_pixel_x_grid, n_pixel_x, FALSE);\n if (ix < 0) {\n fprintf (stderr, \"Error %d, while searching index for pixel %6d in pixel-x_grid \\n\", ix, pixel_x);\n return ix;\n }\n\n iy = get_grid_index (pixel_y, sat_pixel_y_grid, n_pixel_y, FALSE);\n if (iy < 0) {\n fprintf (stderr, \"Error %d, while searching index for pixel %6d in pixel-y_grid \\n\", iy, pixel_y);\n return iy;\n }\n\n /* read time in netCDF file (if present) */\n status = nc_inq_dimid (ncid, \"time\", &dummy);\n if (status == NC_NOERR) {\n\n /* get time index */\n status = get_time_index (ncid, UTC, TIME_NEAREST_DATE, &(nt), &(itime1), &(itime2), &(dt), verbose, quiet);\n if (status != 0) {\n fprintf (stderr, \"Error %d, during get_time_index in get_float_from_netCDF_map (ancillary.c)\\n\", status);\n return status;\n }\n\n /* data in the netCDF file is assumed to have 3 dimensions: lat/lon/time */\n dimensions = 3;\n } else {\n /* no time variable in the netCDF file */\n nt = 1;\n dimensions = 2;\n }\n status = NC_NOERR;\n\n /* netCDF index might have 2 (lat/lon) or 3 (time/lat/lon) elements */\n if ((index = calloc (dimensions, sizeof (size_t))) == NULL) {\n fprintf (stderr, \"Error: Allocation of index in get_float_from_netCDF_map (ancillary.c)\\n\");\n return -1;\n }\n\n (*numu) = 1;\n (*maxumu) = 1;\n (*nphi) = 1;\n\n switch (solver) {\n case SOLVER_SDISORT:\n case SOLVER_SPSDISORT:\n case SOLVER_FDISORT1:\n case SOLVER_FDISORT2:\n (*maxphi) = 3; /* Minimum number required by disort. */\n break;\n case SOLVER_DISORT:\n case SOLVER_FTWOSTR:\n case SOLVER_SOS:\n case SOLVER_MONTECARLO:\n case SOLVER_POLRADTRAN:\n case SOLVER_TZS:\n case SOLVER_SSS:\n case SOLVER_SSSI:\n case SOLVER_NULL:\n case SOLVER_RODENTS:\n case SOLVER_TWOSTREBE:\n case SOLVER_TWOMAXRND:\n case SOLVER_TWOMAXRND3C:\n case SOLVER_DYNAMIC_TWOSTREAM:\n case SOLVER_DYNAMIC_TENSTREAM:\n case SOLVER_TWOSTR:\n case SOLVER_SSLIDAR:\n (*maxphi) = 1;\n break;\n default:\n fprintf (stderr, \"Error, unknown rte_solver %d in read_sat_geometry\\n\", solver);\n return -1;\n }\n\n if (((*umu) = calloc ((*numu), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for umu in read_sat_geometry (ancillary.c)\\n\");\n return -10;\n }\n\n if (((*phi) = calloc ((*nphi), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for phi in read_sat_geometry (ancillary.c)\\n\");\n return -10;\n }\n\n if (dimensions == 2) {\n index[0] = iy;\n index[1] = ix;\n\n if (verbose) {\n fprintf (stderr,\n \"*** read satellite geometry for pixel_x =%5.0f (%5d), pixel_y =%7.2f (%5d), \",\n sat_pixel_x_grid[ix],\n pixel_x,\n sat_pixel_y_grid[iy],\n pixel_y);\n fprintf (stderr, \" element: %6d x %6d \\n\", ix + 1, iy + 1);\n }\n\n } else if (dimensions == 3) {\n\n index[0] = itime1;\n index[1] = iy;\n index[2] = ix;\n\n if (verbose) {\n if (UTC.tm_mday > 0) {\n fprintf (stderr,\n \" ... read satellite geometry for pixel_x =%6.0f (%5d), lon =%6.0f (%5d), time = %s\",\n sat_pixel_x_grid[ix],\n pixel_x,\n sat_pixel_y_grid[iy],\n pixel_y,\n asctime (&UTC));\n if (nt == 1)\n fprintf (stderr, \" element: %6d x %6d x %6d\\n\", ix + 1, iy + 1, itime1 + 1);\n if (nt == 2)\n fprintf (stderr, \" element: %6d x %6d x (%4d/%4d)\\n\", ix + 1, iy + 1, itime1 + 1, itime2 + 1);\n } else {\n fprintf (stderr,\n \" ... read satellite geometry for pixel_x =%6.0f (%5d), lon =%6.0f (%5d)\\n\",\n sat_pixel_x_grid[ix],\n pixel_x,\n sat_pixel_y_grid[iy],\n pixel_y);\n fprintf (stderr, \" element: %6d x %6d x %6d\\n\", ix + 1, iy + 1, itime1 + 1);\n }\n }\n\n } else {\n fprintf (stderr, \"Error, wrong number for dimensions %d in read_sat_geometry (ancillary.c)\\n\", dimensions);\n return -1;\n }\n\n /* fprintf (stderr,\"index= [%d, %d], status = %d/%d \\n\", index[0], index[1], status, NC_NOERR ); */\n\n status = nc_get_var1_float (ncid, id_lat, index, latitude);\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading 'lat' (latitude) from %s in read_sat_geometry (ancillary.c)\\n\",\n nc_strerror (status),\n filename);\n return -1;\n }\n status = nc_get_var1_float (ncid, id_lon, index, longitude);\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading 'lon' (longitude) from %s in read_sat_geometry (ancillary.c)\\n\",\n nc_strerror (status),\n filename);\n return -1;\n }\n status = nc_get_var1_float (ncid, id_vza, index, &((*umu)[0]));\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading 'vza' (viewing zenith angle) from %s in read_sat_geometry (ancillary.c)\\n\",\n nc_strerror (status),\n filename);\n return -1;\n }\n status = nc_get_var1_float (ncid, id_vaa, index, &((*phi)[0]));\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading 'vaa' (viewing azimuth angle) from %s in read_sat_geometry (ancillary.c)\\n\",\n nc_strerror (status),\n filename);\n return -1;\n }\n\n if (verbose)\n fprintf (stderr,\n \" latitude: %9.5f, longitude: %9.5f, theta_sat=%8.3f, phi_sat=%8.3f \\n\",\n (*latitude),\n (*longitude),\n (*umu)[0],\n (*phi)[0]);\n\n (*umu)[0] = cos (PI / 180 * (*umu)[0]);\n\n return status;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use the satellite_geometry option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/****************************************************************/\n/* read_u10_from_map */\n/* */\n/* Purpose: */\n/* read wind in 10m height from an ECMWF file */\n/* */\n/* input: */\n/* ------ */\n/* lat latitude */\n/* lon longitude */\n/* UTC universal time correlated */\n/* filename name of the netCDF file including the wind map */\n/* */\n/* output: */\n/* ------- */\n/* u10 wind velocity (vector norm) in m/s */\n/* */\n/* September 2007 by Ulrich Hamann */\n/****************************************************************/\n\nint read_u10_from_map (float lat,\n float lon,\n struct tm UTC,\n int time_interpolate,\n char* filename,\n float* u10,\n int verbose,\n int quiet) {\n\n#if HAVE_NETCDF4\n\n int status = 0;\n\n float u_10 = 0.0;\n float v_10 = 0.0;\n\n float* u = NULL;\n float* v = NULL;\n float* w = NULL;\n float* z_wind = NULL;\n size_t nlev = 0;\n\n char function_name[] = \"read_u10_from_ECMWF_file\";\n char file_name[] = \"ancillary.c\";\n\n /* read u in 10m height */\n status = get_number_from_netCDF_map (lat, lon, UTC, time_interpolate, filename, &(u_10), TYPE_FLOAT, \"U10\", verbose, quiet);\n if (status != 0) {\n fprintf (stderr,\n \" Error '%s' reading '%s' from %s in %s (%s) \\n\",\n nc_strerror (status),\n \"10U\",\n filename,\n function_name,\n file_name);\n }\n\n /* read v in 10m height */\n status = get_number_from_netCDF_map (lat, lon, UTC, time_interpolate, filename, &(v_10), TYPE_FLOAT, \"V10\", verbose, quiet);\n if (status != 0) {\n fprintf (stderr,\n \" Error '%s' reading '%s' from %s in %s (%s) \\n\",\n nc_strerror (status),\n \"10V\",\n filename,\n function_name,\n file_name);\n }\n\n if (status == 0) {\n\n /* everything OK, calculate norm of the vector */\n (*u10) = sqrt (u_10 * u_10 + v_10 * v_10);\n return status;\n\n } else {\n\n if (verbose) {\n fprintf (stderr, \" ... didn't find u10 and v10 in netCDF file %s \\n\", filename);\n fprintf (stderr, \" try to read profiles u(z) and v(z) \\n\");\n }\n\n status = read_wind_from_ECMWF_file (lat,\n lon,\n UTC,\n time_interpolate,\n filename,\n 0.0,\n &(u),\n &(v),\n &(w),\n &(z_wind),\n &(nlev),\n verbose,\n quiet);\n\n if (status != 0) {\n fprintf (stderr,\n \"Error '%s' reading '%s' from %s in %s (%s) \\n\",\n nc_strerror (status),\n \"u(z) and v(z)\",\n filename,\n function_name,\n file_name);\n return status;\n }\n\n if (verbose)\n fprintf (stderr,\n \" take data from lowest level, lc=%3zd, z=%7.3f km, u=%7.2f m/s, v=%7.2f m/s \\n\",\n (nlev - 2),\n z_wind[nlev - 2],\n u[nlev - 2],\n v[nlev - 2]);\n\n /* (nlev-1) = surface, where u=0, v=0; (nlev-2)=last layer before surface, in ECMWF data approx 20m */\n (*u10) = sqrt (u[nlev - 2] * u[nlev - 2] + v[nlev - 2] * v[nlev - 2]);\n\n free (u);\n free (v);\n free (z_wind);\n }\n\n return status;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use the cox_and_munk_u10_map option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/****************************************************************/\n/* read_wind_from_ECMWF_file */\n/* */\n/* Purpose: */\n/* read wind components u and v from an ECMWF file */\n/* */\n/* input: */\n/* ------ */\n/* lat latitude */\n/* lon longitude */\n/* UTC universal time correlated */\n/* filename name of the netCDF file including the wind map */\n/* */\n/* output: */\n/* ------- */\n/* u-profil wind (west-east component) */\n/* v-profil wind (south north component) */\n/* z_wind height scale for u and v */\n/* nlev_wind number of levels for u, v, and z */\n/* */\n/* September 2007 by Ulrich Hamann */\n/****************************************************************/\n\nint read_wind_from_ECMWF_file (float lat,\n float lon,\n struct tm UTC,\n int time_interpolate,\n char* filename,\n float altitude,\n float** u,\n float** v,\n float** w,\n float** z_wind,\n size_t* nlev,\n int verbose,\n int quiet) {\n\n int status = 0;\n\n#if HAVE_NETCDF4\n\n int ncid = NOT_DEFINED_INTEGER;\n\n int lc = NOT_DEFINED_INTEGER;\n int t = NOT_DEFINED_INTEGER;\n int nt = -1;\n long ilat = NOT_DEFINED_INTEGER, ilon = NOT_DEFINED_INTEGER,\n itime = NOT_DEFINED_INTEGER; /* index for lat, lon, time in netCDF file */\n\n size_t nlat = 0;\n size_t nlon = 0;\n\n double* ECMWF_lat = NULL;\n double* ECMWF_lon = NULL;\n\n int itime1 = -1, itime2 = -1;\n float dt = NOT_DEFINED_FLOAT;\n\n size_t tmp_nlev = 0;\n size_t nlay = 0;\n\n float** p_level = NULL;\n float** p_layer = NULL;\n\n float** T_layer = NULL;\n float** u_layer = NULL;\n float** v_layer = NULL;\n float** w_layer = NULL;\n\n int id_var_test = 0;\n char T_name[2] = \"\";\n char U_name[2] = \"\";\n char V_name[2] = \"\";\n char W_name[2] = \"\";\n\n float dx = NOT_DEFINED_FLOAT;\n\n float SP = -999.0;\n\n char function_name[] = \"read_u10_from_ECMWF_file\";\n char file_name[] = \"ancillary.c\";\n\n if (verbose)\n fprintf (stderr, \" ... read wind profiles from netCDF file %s \\n\", filename);\n\n /* open netcdf file */\n status = nc_open (filename, NC_NOWRITE, &ncid);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error %d opening netCDF file %s in %s (%s)\\n\", status, filename, function_name, file_name);\n return status;\n }\n\n /* read latitude array */\n status = alloc_and_read_netCDF_1D_double (ncid, \"lat\", &nlat, \"lat\", &(ECMWF_lat));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading latitude in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n /* search correct latitude index */\n ilat = get_grid_index (lat, ECMWF_lat, nlat, FALSE);\n if (ilat < 0) {\n fprintf (stderr, \"Error -1 finding index for lat=%5.2f in %s, %s (%s)\\n\", lat, filename, function_name, file_name);\n return -1;\n }\n\n /* read longitude */\n status = alloc_and_read_netCDF_1D_double (ncid, \"lon\", &nlon, \"lon\", &(ECMWF_lon));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading longitude in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n /* search correct longitude index */\n ilon = get_grid_index (lon, ECMWF_lon, nlon, TRUE);\n if (ilon < 0) {\n fprintf (stderr, \"Error -2 finding index for lon=%5.2f in %s, %s (%s)\\n\", lon, filename, function_name, file_name);\n return -2;\n }\n\n /* get time index */\n status = get_time_index (ncid, UTC, time_interpolate, &(nt), &(itime1), &(itime2), &(dt), verbose, quiet);\n if (status != 0) {\n fprintf (stderr, \"Error %d, during get_time_index in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n /* alloc nt timesteps for pressure */\n if ((p_level = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for pressure */\n if ((p_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for temperature */\n if ((T_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for temperature in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for west-east wind component u */\n if ((u_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for water vapour in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for south north wind component v */\n if ((v_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for water vapour in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc nt timesteps for vertical wind component w */\n if ((w_layer = calloc (nt, sizeof (float*))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for water vapour in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* read nt (= 1 or 2) time steps */\n for (t = 0; t <= nt - 1; t++) {\n\n if (t == 0)\n itime = itime1;\n if (t == 1)\n itime = itime2;\n\n /* alloc and read pressure */\n /* requires that SP/LNSP, hyai and hybi are in the ECMWF netCDF file */ /* in ancillary.c */\n status =\n alloc_and_read_ECMWF_netCDF_pressure (ncid, &(p_level[t]), &(tmp_nlev), &(p_layer[t]), &(nlay), itime, ilat, ilon, verbose);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading pressure from netCDF file %s\\n\", status, filename);\n return status;\n }\n\n if ((p_layer[t] = realloc (p_layer[t], (nlay + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'p_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n /* read surface pressure from ECMWF file */\n status = read_ECMWF_surface_pressure (ncid, itime, ilat, ilon, &(SP), verbose);\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', while read_ECMWF_surface_pressure in %s (%s)\\n\",\n nc_strerror (status),\n function_name,\n file_name);\n return status;\n }\n\n p_layer[t][nlay] = SP / 100.0;\n\n status = nc_inq_varid (ncid, \"t\", &id_var_test);\n if (status == NC_NOERR) {\n strcpy (T_name, \"t\");\n strcpy (U_name, \"u\");\n strcpy (V_name, \"v\");\n strcpy (W_name, \"w\");\n } else {\n status = nc_inq_varid (ncid, \"T\", &id_var_test);\n if (status == NC_NOERR) {\n strcpy (T_name, \"T\");\n strcpy (U_name, \"U\");\n strcpy (V_name, \"V\");\n strcpy (W_name, \"W\");\n } else {\n fprintf (stderr, \"Error, unknown format of the ECMWF wind file %s\\n\", filename);\n return status;\n }\n }\n\n /* allocate and read temperature, defined on layers */\n status = alloc_and_read_netCDF_column_float (ncid, T_name, &T_layer[t], nlay, itime, ilat, ilon, verbose);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading temperature '%s' from netCDF file %s\\n\", status, T_name, filename);\n return status;\n }\n\n if ((T_layer[t] = realloc (T_layer[t], (nlay + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'T_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n /* extrapolate temperature from last layer midpoint to surface */\n dx = (log (p_level[0][tmp_nlev - 1] / p_level[0][tmp_nlev - 1]) - log (p_layer[0][nlay - 1] / p_level[0][tmp_nlev - 1])) /\n (log (p_layer[0][nlay - 1] / p_level[0][tmp_nlev - 1]) - log (p_layer[0][nlay - 2] / p_level[0][tmp_nlev - 1]));\n T_layer[t][nlay] = (1.0 + dx) * T_layer[0][nlay - 1] - dx * T_layer[0][nlay - 2];\n\n /* allocate and read wind component u, defined on layers */\n status = alloc_and_read_netCDF_column_float (ncid, U_name, &u_layer[t], nlay, itime, ilat, ilon, verbose);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading wind component '%s' from netCDF file %s\\n\", status, U_name, filename);\n return status;\n }\n\n if ((u_layer[t] = realloc (u_layer[t], (nlay + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'u_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n u_layer[t][nlay] = 0.0;\n\n /* allocate and read wind component v, defined on layers */\n status = alloc_and_read_netCDF_column_float (ncid, V_name, &v_layer[t], nlay, itime, ilat, ilon, verbose);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading wind component '%s' from netCDF file %s\\n\", status, V_name, filename);\n return status;\n }\n\n if ((v_layer[t] = realloc (v_layer[t], (nlay + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'v_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n v_layer[t][nlay] = 0.0;\n\n /* allocate and read wind component w, defined on layers */\n status = alloc_and_read_netCDF_column_float (ncid, W_name, &w_layer[t], nlay, itime, ilat, ilon, verbose);\n if (status != 0) {\n fprintf (stderr, \"Error %d reading wind component '%s' from netCDF file %s\\n\", status, W_name, filename);\n return status;\n }\n\n if ((w_layer[t] = realloc (w_layer[t], (nlay + 1) * sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, reallocating memory for 'w_layer' in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n w_layer[t][nlay] = 0.0;\n }\n\n if (verbose) {\n fprintf (stderr, \" found %zd x %zd x %zd (lat x lon x lev) data points\\n\", nlat, nlon, (*nlev));\n fprintf (stderr, \" reading pixel lat = %5.2f (%4ld), lon = %5.2f (%4ld)\\n\", lat, ilat, lon, ilon);\n }\n\n /* number of final levels == number of layers plus one, which was additional realloced above */\n (*nlev) = nlay + 1;\n\n if (nt == 1) {\n /* no time interpolation needed, do nothing */\n } else {\n /* write time interpolated data into the zero'th entry */\n for (lc = 0; lc < (*nlev); lc++) {\n p_layer[0][lc] = (1.0 - dt) * p_layer[0][lc] + dt * p_layer[1][lc];\n T_layer[0][lc] = (1.0 - dt) * T_layer[0][lc] + dt * T_layer[1][lc];\n u_layer[0][lc] = (1.0 - dt) * u_layer[0][lc] + dt * u_layer[1][lc];\n v_layer[0][lc] = (1.0 - dt) * v_layer[0][lc] + dt * v_layer[1][lc];\n w_layer[0][lc] = (1.0 - dt) * w_layer[0][lc] + dt * w_layer[1][lc];\n }\n }\n\n /* calculate z from T and p using hydrostatic equation (in ancillary.c) */\n status = calculate_z_from_p_and_T (p_layer[0], T_layer[0], z_wind, (*nlev), altitude, verbose);\n if (status != 0) {\n fprintf (stderr,\n \"Error %d during calculate_z_from_p_and_T (line %d, function '%s' in '%s') \\n\",\n status,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n /* allocate space for final results */\n if (((*u) = calloc ((*nlev), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n /* allocate space for final results */\n if (((*v) = calloc ((*nlev), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n /* allocate space for final results */\n if (((*w) = calloc ((*nlev), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for pressure (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n\n /* copy data */\n for (lc = 0; lc < (*nlev); lc++) {\n (*u)[lc] = u_layer[0][lc];\n (*v)[lc] = v_layer[0][lc];\n (*w)[lc] = w_layer[0][lc];\n /* /\\* additional verbose output at layer mid-points *\\/ */\n /* fprintf (stderr, \" lc =%3d, z=%7.3f, u=%7.3f, v=%7.3f, w=%7.3f ( p_layer=%9.3f, T_layer=%7.3f ) \\n\", */\n /* lc, (*z_wind)[lc], (*u)[lc], (*v)[lc], (*w)[lc], p_layer[0][lc], T_layer[0][lc]); */\n }\n\n ASCII_free_float (p_layer, nt);\n ASCII_free_float (T_layer, nt);\n ASCII_free_float (u_layer, nt);\n ASCII_free_float (v_layer, nt);\n ASCII_free_float (w_layer, nt);\n\n#else\n fprintf (stderr, \" ******************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use the ECMWF data file option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ******************************************************************\\n\");\n return -1;\n#endif\n\n return status;\n}\n\n/*****************************************************************/\n/* get_time_index */\n/* */\n/* Purpose: */\n/* read time grid from netCDF file and search */\n/* the suitable time index to input.UTC */\n/* if only one time is specified in the netCDF file, */\n/* take that field */\n/* */\n/* input: */\n/* ------ */\n/* ncid id number of the netCDF file */\n/* UTC universal time correlated */\n/* */\n/* output: */\n/* ------- */\n/* nt number of time points for futher calculations */\n/* t1 time index 1 */\n/* t2 time index 2 */\n/* dt normalized fraction between time1 and time2 */\n/* */\n/* February 2007 by Ulrich Hamann */\n/* */\n/* changes: */\n/* - July 2007 by Ulrich Hamann */\n/* interpretation of the attribute time:units */\n/*****************************************************************/\n\nint get_time_index (int ncid, struct tm UTC, int time_interpolate, int* nt, int* t1, int* t2, float* dt, int verbose, int quiet) {\n\n#if HAVE_NETCDF4\n\n#define FORMAT_UNKNOWN 0\n#define YYYYMMDD_FF 1 /* day as %Y%m%d.%f */\n#define MONTH_OF_YEAR 2\n#define HOURS_SINCE 3 /* hours since 1900-01-01 00:00:0.0 */\n#define SECONDS_SINCE 4\n\n int status = 0;\n\n time_t time_in_s = NOT_DEFINED_INTEGER;\n time_t min_delta_t = 999999999;\n\n int id_time = NOT_DEFINED_INTEGER;\n int time_format = NOT_DEFINED_INTEGER;\n double* time_grid = NULL;\n time_t* time_grid_in_s = NULL;\n struct tm* date_grid = NULL;\n\n char tmp_string[FILENAME_MAX] = \"\";\n int i = 0;\n int year = 0, month = 0, day = 0, hour = 0, min = 0;\n\n size_t ntime = NOT_DEFINED_INTEGER;\n int t = NOT_DEFINED_INTEGER;\n int t_min = NOT_DEFINED_INTEGER;\n\n double tmp_time = NOT_DEFINED_FLOAT;\n char* timestr = NULL;\n\n char data_unit[50] = \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n if (UTC.tm_mday < 0) {\n if (!quiet) {\n fprintf (stderr, \" ******* WARNING >>>>>> no time specified\\n\");\n fprintf (stderr, \" take first entry in the netCDF file\\n\");\n }\n (*t1) = 0; /* read first entry in the netCDF file */\n (*t2) = 0;\n (*dt) = 0.0;\n (*nt) = 1; /* read one entry in the netCDF file */\n return status;\n }\n\n /* read time in ECMWF file */\n status = alloc_and_read_netCDF_1D_double (ncid, \"time\", &(ntime), \"time\", &(time_grid));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading time in get_time_index (ancillary.c)\\n\", status);\n return status;\n }\n\n /* alloc ECMWF time in s - array */\n if ((time_grid_in_s = calloc (ntime, sizeof (time_t))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for time_grid_in_s (line %d, function %s in %s) \\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* get id for time */\n status = nc_inq_varid (ncid, \"time\", &id_time);\n\n if (status == NC_NOERR) { /* time is specified in the netCDF file */\n\n /* try to read attribute 'unit' and interprete it as much as possible */\n status = nc_get_att_text (ncid, id_time, \"units\", data_unit);\n\n if (status != NC_NOERR) {\n /* no given units -> take first entry in netCDF file */\n\n /*assume that it is day as %Y%m%d.%f */\n if (!quiet)\n fprintf (stderr,\n \"*** Warning, no time unit specified in the netCDF file, assume that it is \\'day as \\%%Y\\%%m\\%%d.\\%%f\\'\\n\");\n\n time_format = YYYYMMDD_FF;\n\n /* we hope this is OK, so set status to OK again */\n status = 0;\n } else {\n\n /* some information is given about the unit, try to interprete it */\n if (strncasecmp (\"day as %Y%m%d.%f\", data_unit, 15) == 0)\n time_format = YYYYMMDD_FF;\n else if (strncasecmp (\"hours since\", data_unit, 10) == 0)\n time_format = HOURS_SINCE;\n else if (strncasecmp (\"seconds since\", data_unit, 12) == 0)\n time_format = SECONDS_SINCE;\n else if (strncasecmp (\"month of year\", data_unit, 12) == 0)\n time_format = MONTH_OF_YEAR;\n else {\n fprintf (stderr,\n \" ... Error, unknown time format %s (line %d, function %s in %s)\\n\",\n data_unit,\n __LINE__,\n __func__,\n __FILE__);\n return -1;\n }\n }\n } else {\n /* no time specified in netCDF file -> take first entry in netCDF file */\n status = 0;\n time_format = FORMAT_UNKNOWN;\n }\n\n /* alloc date_grid ( structure - ) array */\n if ((date_grid = calloc (ntime, sizeof (struct tm))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for date_grid (line %d, function %s in %s)\\n\", __LINE__, __func__, __FILE__);\n return -10;\n }\n\n switch (time_format) {\n case FORMAT_UNKNOWN:\n /* do nothing, than automatically the first entry is specified (index=0) */\n break;\n\n case YYYYMMDD_FF:\n case MONTH_OF_YEAR:\n\n /* if 'month of year', then shift the month by 2 digits to the left, and add 15 for the middle of the month */\n if (time_format == MONTH_OF_YEAR)\n for (t = 0; t < ntime; t++)\n time_grid[t] = time_grid[t] * 100.0 + 15.;\n\n if (ntime > 1) {\n\n /* for year 0 AD we assume climatologic data, add current year for time selection */\n if (0101.0 <= time_grid[0] && time_grid[ntime - 1] < 1232.0)\n for (t = 0; t < ntime; t++)\n time_grid[t] += (UTC.tm_year + 1900) * 10000.0;\n\n /* time range check */\n /* dates after the year 1600 AD and before 3000 AD */\n if (time_grid[0] < 16000101.00 || 30000101.00 < time_grid[0]) {\n fprintf (stderr,\n \"Error, time [%f,%f] in netCDF file outside assumed range [1600AD, 3000AD] \\n\",\n time_grid[0],\n time_grid[ntime - 1]);\n return -1;\n }\n\n /* convert format \"YYYYMMDD.FF\" into \"C-standard format\" */\n for (t = 0; t < ntime; t++) {\n date_grid[t].tm_year = floor (time_grid[t]) / 10000 - 1900;\n tmp_time = time_grid[t] - (date_grid[t].tm_year + 1900.0) * 10000.0;\n date_grid[t].tm_mon = floor (tmp_time) / 100 - 1;\n tmp_time = tmp_time - (date_grid[t].tm_mon + 1.0) * 100.0;\n date_grid[t].tm_mday = floor (tmp_time);\n tmp_time = tmp_time - date_grid[t].tm_mday;\n date_grid[t].tm_hour = floor (tmp_time * 24.0);\n tmp_time = tmp_time - date_grid[t].tm_hour / 24.0;\n date_grid[t].tm_min = floor (tmp_time * 24.0 * 60.0);\n tmp_time = tmp_time - date_grid[t].tm_min / (24.0 * 60.0);\n date_grid[t].tm_sec = floor (tmp_time * (24.0 * 60.0 * 60.0));\n\n date_grid[t].tm_wday = weekday (date_grid[t].tm_year + 1900, date_grid[t].tm_mon + 1, date_grid[t].tm_mday);\n\n time_grid_in_s[t] = my_timegm (&(date_grid[t]));\n\n /* timestr = asctime( &(date_grid[t]) ); */\n /* fprintf (stderr,\"time_grid[%d] = %10.5f, %ld , %s\", t, time_grid[t], time_grid_in_s[t], timestr); */\n }\n }\n /* else, do nothing, than automatically the first entry is specified (index=0) */\n\n break;\n\n case HOURS_SINCE:\n case SECONDS_SINCE:\n\n if (time_format == HOURS_SINCE)\n i = 0;\n if (time_format == SECONDS_SINCE)\n i = 2;\n\n year = atoi (substr (tmp_string, data_unit, 12 + i, 4));\n month = atoi (substr (tmp_string, data_unit, 17 + i, 2));\n day = atoi (substr (tmp_string, data_unit, 20 + i, 2));\n hour = atoi (substr (tmp_string, data_unit, 23 + i, 2));\n min = atoi (substr (tmp_string, data_unit, 26 + i, 2));\n /* there are not always seconds in the format */\n\n /* fprintf (stderr, \" time scince: %d %d %d %d %d \\n\", year, month, day, hour, min ); */\n\n /* /\\* boundary check *\\/ */\n /* if ( time_grid[0] < 0.0 || 500.0 < time_grid[0] ) { /\\* assuming more than 0 and less than 500 forecast hours *\\/ */\n /* fprintf (stderr, \"Error -1, wrong format for time %f in the netCDF file \\n\", time_grid[0] ); */\n /* return -1; */\n /* } */\n\n /* convert format \"hours since 1900-01-01 00:00:0.0\" into \"C-standard format\" */\n for (t = 0; t < ntime; t++) {\n date_grid[t].tm_year = year - 1900;\n date_grid[t].tm_mon = month - 1;\n date_grid[t].tm_mday = day;\n if (time_format == HOURS_SINCE)\n date_grid[t].tm_hour = hour + time_grid[t];\n else\n date_grid[t].tm_hour = hour;\n date_grid[t].tm_min = min;\n if (time_format == SECONDS_SINCE)\n date_grid[t].tm_sec = 0.0 + time_grid[t];\n else\n date_grid[t].tm_sec = 0.0;\n\n date_grid[t].tm_wday = weekday (date_grid[t].tm_year + 1900, date_grid[t].tm_mon + 1, date_grid[t].tm_mday);\n\n time_grid_in_s[t] = my_timegm (&(date_grid[t]));\n\n timestr = asctime (&(date_grid[t]));\n /* fprintf (stderr,\"time_grid[%d] = %10.5f, %ld , %s\", t, time_grid[t], time_grid_in_s[t], timestr); */\n }\n break;\n\n default:\n fprintf (stderr, \"Error, unknown time_format = %d (line %d, function %s in %s)\\n\", time_format, __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* convert time to search for into seconds scince 01.01.1970 00:00:00 UTC */\n time_in_s = my_timegm (&(UTC));\n\n /* search time index */\n switch (time_interpolate) {\n case TIME_NEAREST_DATE:\n min_delta_t = labs (time_grid_in_s[0] - time_in_s); /* first guess for time difference */\n t_min = 0; /* first guess for index */\n for (t = 1; t < ntime; t++)\n if (labs (time_grid_in_s[t] - time_in_s) < min_delta_t) {\n min_delta_t = labs (time_grid_in_s[t] - time_in_s);\n t_min = t;\n }\n (*t1) = t_min;\n (*t2) = NOT_DEFINED_INTEGER;\n (*dt) = (float)t_min;\n (*nt) = 1; /* read first and only time step from file */\n\n if (verbose) {\n timestr = asctime (&(UTC));\n fprintf (stderr, \" specified time: %s\", timestr);\n timestr = asctime (&(date_grid[(*t1)]));\n fprintf (stderr, \" nearest time in netCDF file: %s\", timestr);\n }\n\n break;\n case TIME_INTERPOLATION:\n if (ntime == 1) {\n if ((time_grid_in_s[0] != time_in_s) && !quiet) {\n timestr = asctime (&(UTC));\n fprintf (stderr, \"\\n ******* WARNING >>>>>> specified time %s\", timestr);\n timestr = asctime (&(date_grid[0]));\n fprintf (stderr, \" ******* WARNING >>>>>> is NOT the time found in the ECMWF atmosphere data file %s\\n\", timestr);\n }\n (*t1) = 0;\n (*t2) = NOT_DEFINED_INTEGER;\n (*dt) = 0.0;\n (*nt) = 1; /* read first and only time step from file */\n } else {\n for (t = 1; t < ntime; t++) {\n if (time_grid_in_s[t - 1] <= time_in_s && time_in_s <= time_grid_in_s[t]) {\n /* fprintf (stderr,\"E[t-1] = %ld, t_s = %ld, E[t] = %ld\\n\", time_grid_in_s[t-1], time_in_s, time_grid_in_s[t]); */\n (*t1) = t - 1;\n (*t2) = t;\n (*dt) = (float)(time_in_s - time_grid_in_s[t - 1]) / (float)(time_grid_in_s[t] - time_grid_in_s[t - 1]);\n (*nt) = 2; /* read two time steps from file */\n /* fprintf (stderr,\"t1 = %3d, t2 = %3d , dt = %10.5f\\n\", t1, t2, dt); */\n break;\n }\n }\n if (t1 < 0) {\n fprintf (stderr, \"Error -1 finding index for time = %s in get_time_index (ancillary.c)\\n\", asctime (&(UTC)));\n return -1;\n }\n\n if (verbose) {\n fprintf (stderr, \" time interpolation of data between \\n\");\n timestr = asctime (&(date_grid[(*t1)]));\n fprintf (stderr, \" %s\", timestr);\n timestr = asctime (&(date_grid[(*t2)]));\n fprintf (stderr, \" %s\", timestr);\n }\n }\n break;\n default:\n fprintf (stderr, \"Error, unknown time_interpolate = %d in get_time_index (in ancillary.c)\\n\", time_interpolate);\n return -1;\n }\n\n free (date_grid);\n free (time_grid);\n free (time_grid_in_s);\n return status;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any netCDF option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/*****************************************************************/\n/* get_local_apparent_time_index */\n/* (almost the same as get_time_index) */\n/* */\n/* Purpose: */\n/* read time grid from netCDF file and search */\n/* the suitable time index to input.LAT */\n/* if only one time is specified in the netCDF file, */\n/* take that field */\n/* */\n/* input: */\n/* ------ */\n/* ncid id number of the netCDF file */\n/* LAT local apparent time */\n/* */\n/* output: */\n/* ------- */\n/* nt number of time points for futher calculations */\n/* t1 time index 1 */\n/* t2 time index 2 */\n/* dt normalized fraction between time1 and time2 */\n/* */\n/* April 2007 by Ulrich Hamann */\n/*****************************************************************/\n\nint get_local_apparent_time_index (int ncid,\n struct tm LAT,\n int time_interpolate,\n int* nt,\n int* t1,\n int* t2,\n float* dt,\n int verbose,\n int quiet) {\n int status = 0;\n\n time_t time_in_s = NOT_DEFINED_INTEGER;\n time_t min_delta_t = 999999999;\n\n double* time_grid = NULL;\n time_t* time_grid_in_s = NULL;\n struct tm* date_grid = NULL;\n\n size_t ntime = NOT_DEFINED_INTEGER;\n int t = NOT_DEFINED_INTEGER;\n int t_min = NOT_DEFINED_INTEGER;\n\n double tmp_time = NOT_DEFINED_FLOAT;\n char* timestr = NULL;\n\n char function_name[] = \"get_local_apparent_time_index\";\n char file_name[] = \"ancillary.c\";\n\n if (LAT.tm_mday < 0) {\n fprintf (stderr, \" ******* WARNING >>>>>> no time specified\\n\");\n fprintf (stderr, \" take first entry in the netCDF file\\n\");\n (*t1) = 0; /* read first entry in the netCDF file */\n (*t2) = 0;\n (*dt) = 0.0;\n (*nt) = 1; /* read one entry in the netCDF file */\n return status;\n }\n\n /* time in seconds scince 01.01.1970 00:00:00 LAT */\n time_in_s = my_timegm (&(LAT));\n\n /* read time in netCDF file */\n status = alloc_and_read_netCDF_1D_double (ncid, \"local_apparent_time\", &(ntime), \"local_apparent_time\", &(time_grid));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading time in %s (%s)\\n\", status, function_name, file_name);\n return status;\n }\n\n /* alloc netCDF date structure */\n if ((date_grid = calloc (ntime, sizeof (struct tm))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for date_grid in %s (%s)\\n\", function_name, file_name);\n return -10;\n }\n\n /* alloc netCDF time in s - array */\n if ((time_grid_in_s = calloc (ntime, sizeof (time_t))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for date_grid time_grid_in_s in get_local_apparent_time_index (ancillary.c) \\n\");\n return -1;\n }\n\n /* convert format \"YYYYMMDD.day_fraction\" into \"C-standard format\" */\n for (t = 0; t < ntime; t++) {\n date_grid[t].tm_year = floor (time_grid[t]) / 10000 - 1900;\n tmp_time = time_grid[t] - (date_grid[t].tm_year + 1900.0) * 10000.0;\n date_grid[t].tm_mon = floor (tmp_time) / 100 - 1;\n tmp_time = tmp_time - (date_grid[t].tm_mon + 1.0) * 100.0;\n date_grid[t].tm_mday = floor (tmp_time);\n tmp_time = tmp_time - date_grid[t].tm_mday;\n date_grid[t].tm_hour = floor (tmp_time * 24.0);\n tmp_time = tmp_time - date_grid[t].tm_hour / 24.0;\n date_grid[t].tm_min = floor (tmp_time * 24.0 * 60.0);\n tmp_time = tmp_time - date_grid[t].tm_min / (24.0 * 60.0);\n date_grid[t].tm_min = floor (tmp_time * (24.0 * 60.0 * 60.0));\n\n date_grid[t].tm_wday = weekday (date_grid[t].tm_year + 1900, date_grid[t].tm_mon + 1, date_grid[t].tm_mday);\n\n time_grid_in_s[t] = my_timegm (&(date_grid[t]));\n\n timestr = asctime (&(date_grid[t]));\n /* fprintf (stderr,\"time_grid[%d] = %10.5f, %ld , %s\", t, time_grid[t], time_grid_in_s[t], timestr); */\n }\n\n /* search time index */\n\n switch (time_interpolate) {\n case TIME_NEAREST_DATE:\n min_delta_t = labs (time_grid_in_s[0] - time_in_s); /* first guess for time difference */\n t_min = 0; /* first guess for index */\n for (t = 1; t < ntime; t++)\n if (labs (time_grid_in_s[t] - time_in_s) < min_delta_t) {\n min_delta_t = labs (time_grid_in_s[t] - time_in_s);\n t_min = t;\n }\n (*t1) = t_min;\n (*t2) = NOT_DEFINED_INTEGER;\n (*dt) = (float)t_min;\n (*nt) = 1; /* read first and only time step from file */\n\n if (verbose) {\n timestr = asctime (&(LAT));\n fprintf (stderr, \" specified time: %s\", timestr);\n timestr = asctime (&(date_grid[(*t1)]));\n fprintf (stderr, \" nearest time in netCDF file: %s\", timestr);\n }\n\n break;\n case TIME_INTERPOLATION:\n if (ntime == 1) {\n if ((time_grid_in_s[0] != time_in_s) && !quiet) {\n timestr = asctime (&(LAT));\n fprintf (stderr, \"\\n ******* WARNING >>>>>> specified time %s\", timestr);\n timestr = asctime (&(date_grid[0]));\n fprintf (stderr, \" ******* WARNING >>>>>> is NOT the time found in the netCDF atmosphere data file %s\\n\", timestr);\n }\n (*t1) = 0;\n (*t2) = NOT_DEFINED_INTEGER;\n (*dt) = 0.0;\n (*nt) = 1; /* read first and only time step from file */\n } else {\n for (t = 1; t < ntime; t++) {\n if (time_grid_in_s[t - 1] <= time_in_s && time_in_s <= time_grid_in_s[t]) {\n /* fprintf (stderr,\"E[t-1] = %ld, t_s = %ld, E[t] = %ld\\n\", time_grid_in_s[t-1], time_in_s, time_grid_in_s[t]); */\n (*t1) = t - 1;\n (*t2) = t;\n (*dt) = (float)(time_in_s - time_grid_in_s[t - 1]) / (float)(time_grid_in_s[t] - time_grid_in_s[t - 1]);\n (*nt) = 2; /* read two time steps from file */\n /* fprintf (stderr,\"t1 = %3d, t2 = %3d , dt = %10.5f\\n\", t1, t2, dt); */\n break;\n }\n }\n if (t1 < 0) {\n fprintf (stderr, \"Error -1 finding index for time = %s in %s (%s)\\n\", asctime (&(LAT)), function_name, file_name);\n return -1;\n }\n\n if (verbose) {\n fprintf (stderr, \" time interpolation of data between \\n\");\n timestr = asctime (&(date_grid[(*t1)]));\n fprintf (stderr, \" %s\", timestr);\n timestr = asctime (&(date_grid[(*t2)]));\n fprintf (stderr, \" %s\", timestr);\n }\n }\n break;\n default:\n fprintf (stderr, \"Error, unknown time_interpolate = %d in %s (%s)\\n\", time_interpolate, function_name, file_name);\n return -1;\n }\n\n return status;\n}\n\n/******************************************************************************/\n/* alloc_and_read_ECMWF_netCDF_pressure */\n/* small function to read hybrid coefficients hyai, hybi and surface pressure */\n/* from ECMWF netCDF file and convert those to a pressure array */\n/* requires that SP, hyai and hybi are in the ECMWF netCDF file */\n/******************************************************************************/\n\nint alloc_and_read_ECMWF_netCDF_pressure (int ncid,\n float** p_level,\n size_t* nlev,\n float** p_layer,\n size_t* nlay,\n size_t itime,\n size_t ilat,\n size_t ilon,\n int verbose) {\n\n#if HAVE_NETCDF4\n\n int status = 0;\n\n float SP = -999.0;\n\n double* hyai = NULL;\n double* hybi = NULL;\n double* hyam = NULL;\n double* hybm = NULL;\n int lc = 0;\n\n /* read surface pressure from ECMWF file */\n status = read_ECMWF_surface_pressure (ncid, itime, ilat, ilon, &(SP), verbose);\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s' returned by read_ECMWF_surface_pressure (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n /* read hybrid pressure coefficients on levels (layer boundaries) */\n status = alloc_and_read_netCDF_1D_double (ncid, \"ilev\", nlev, \"hyai\", &(hyai));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading hyai (line %d, function '%s' in '%s') \\n\", status, __LINE__, __func__, __FILE__);\n return status;\n }\n status = alloc_and_read_netCDF_1D_double (ncid, \"ilev\", nlev, \"hybi\", &(hybi));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading hybi (line %d, function '%s' in '%s')\\n\", status, __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* read hybrid pressure coefficients at layers (layer midpoints) */\n status = alloc_and_read_netCDF_1D_double (ncid, \"mlev\", nlay, \"hyam\", &(hyam));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading hyam (line %d, function '%s' in '%s')\\n\", status, __LINE__, __func__, __FILE__);\n return status;\n }\n status = alloc_and_read_netCDF_1D_double (ncid, \"mlev\", nlay, \"hybm\", &(hybm));\n if (status != 0) {\n fprintf (stderr, \"Error %d reading hybm (line %d, function '%s' in '%s')\\n\", status, __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* allocate pressure */\n if (((*p_level) = calloc ((*nlev), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error allocating memory for 'p_level' (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* /\\***************************************************************\\/ */\n /* /\\* calculate level pressure (layer boundaries) *\\/ */\n /* /\\* starting from 1, because we DO NOT like the uppermost p=0.0 *\\/ */\n /* /\\* it is bad for merging with background atmosphere *\\/ */\n /* /\\***************************************************************\\/ */\n\n /* /\\* allocate pressure *\\/ */\n /* if (((*p_level) = calloc((*nlev)-1, sizeof(float)))==NULL) { */\n /* fprintf (stderr, \"Error allocating memory for 'p_level' (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__); */\n /* return -1; */\n /* } */\n\n /* /\\* fprintf (stderr,\"level pressures\\n\"); *\\/ */\n /* for (lc=1; lc<(*nlev); lc++) { */\n /* (*p_level)[lc-1]= 0.01*(hyai[lc]+hybi[lc]*SP); /\\* 0.01 == Pa -> hPa *\\/ */\n /* /\\* fprintf (stderr,\"lc=%3d a=%10.2f, b=%10.6f, p=%10.4f, SP=%10.4f, SP-p=%10.4f\\n\", *\\/ */\n /* /\\* lc-1,hyai[lc],hybi[lc],(*p_level)[lc-1],SP/100.,SP/100.-(*p_level)[lc-1]); *\\/ */\n /* } */\n\n /* (*nlev)=(*nlev)-1; */\n\n /* fprintf (stderr,\"level pressures\\n\"); */\n for (lc = 0; lc < (*nlev); lc++) {\n (*p_level)[lc] = 0.01 * (hyai[lc] + hybi[lc] * SP); /* 0.01 == Pa -> hPa */\n /* fprintf (stderr,\"lc=%3d a=%10.2f, b=%10.6f, p=%10.4f, SP=%10.4f, SP-p=%10.4f\\n\", */\n /* lc-1,hyai[lc],hybi[lc],(*p_level)[lc],SP/100.,SP/100.-(*p_level)[lc]); */\n }\n\n /* allocate pressure */\n if (((*p_layer) = calloc ((*nlay), sizeof (float))) == NULL) {\n fprintf (stderr, \"Error allocating memory for 'p_layer' (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* calculate layer pressure (layer midpoints) */\n /* fprintf (stderr,\"layer pressures\\n\"); */\n for (lc = 0; lc < (*nlay); lc++) {\n (*p_layer)[lc] = 0.01 * (hyam[lc] + hybm[lc] * SP); /* 0.01 == Pa -> hPa */\n /* fprintf (stderr,\"lc=%3d a=%10.2f, b=%10.6f, p=%10.4f, SP=%10.4f, SP-p=%10.4f\\n\", */\n /* lc,hyam[lc],hybm[lc],(*p_layer)[lc],SP/100.,SP/100.-(*p_layer)[lc]); */\n }\n\n return status;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any ECMWF input option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\nint read_ECMWF_surface_pressure (int ncid, size_t itime, size_t ilat, size_t ilon, float* SP, int verbose) {\n\n#if HAVE_NETCDF4\n\n int status = 0;\n\n int id_data = 0;\n int log_SP = FALSE;\n\n nc_type netCDF_type;\n float scale_factor = 1.0;\n float add_offset = 0.0;\n char variable_name[FILENAME_MAX] = \"\";\n\n size_t* index = NULL;\n\n /* get variable id for \"SP\" (surface pressure) */\n if ((status = nc_inq_varid (ncid, \"SP\", &id_data)) == NC_NOERR)\n strcpy (variable_name, \"SP\");\n else if ((status = nc_inq_varid (ncid, \"sp\", &id_data)) == NC_NOERR)\n strcpy (variable_name, \"sp\");\n else if ((status = nc_inq_varid (ncid, \"LNSP\", &id_data)) == NC_NOERR) {\n strcpy (variable_name, \"LNSP\");\n log_SP = TRUE;\n } else if ((status = nc_inq_varid (ncid, \"lnsp\", &id_data)) == NC_NOERR) {\n strcpy (variable_name, \"lnsp\");\n log_SP = TRUE;\n } else {\n fprintf (stderr, \"Error '%s', while getting id for surface pressure\\n\", nc_strerror (status));\n fprintf (stderr, \" (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* get type of the variable */\n status = nc_inq_vartype (ncid, id_data, &(netCDF_type));\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while getting type (float, double ...) of '%s'\\n\", nc_strerror (status), variable_name);\n fprintf (stderr, \" (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n /* read attribute scale_factor */\n status = nc_get_att_float (ncid, id_data, \"scale_factor\", &scale_factor);\n if (status != NC_NOERR) {\n /* no given scale_factor -> default scale_factor = 1.0 */\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" scale_factor = %f \\n\", scale_factor); */\n }\n\n /* read attribute add_offset */\n status = nc_get_att_float (ncid, id_data, \"add_offset\", &add_offset);\n if (status != NC_NOERR) {\n /* no given offset -> default offset = 0.0 */\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" add_offset = %f \\n\", add_offset); */\n }\n\n if (log_SP == FALSE) {\n\n if (((index) = calloc (3, sizeof (size_t))) == NULL) {\n fprintf (stderr, \"Error, allocting memory for index\\n\");\n fprintf (stderr, \" (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* index for surface pressure */\n index[0] = itime;\n index[1] = ilat;\n index[2] = ilon;\n\n } else { /* that means -> if (log_SP == TRUE) */\n\n if (((index) = calloc (4, sizeof (size_t))) == NULL) {\n fprintf (stderr, \"Error, allocting memory for index\\n\");\n fprintf (stderr, \" (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* index for log surface pressure */\n index[0] = itime;\n index[1] = 0; /* level == 0, there is only one level! */\n index[2] = ilat;\n index[3] = ilon;\n }\n\n /* read surface pressure */\n status = nc_get_var1_float (ncid, id_data, index, SP);\n if (status != NC_NOERR) {\n fprintf (stderr, \"Error '%s', while reading surface pressure\\n\", nc_strerror (status));\n fprintf (stderr, \" (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return status;\n }\n\n (*SP) = (*SP) * scale_factor + add_offset;\n\n /* if (verbose) */\n /* fprintf (stderr,\" %s = %f \\n\", variable_name, (*SP)); */\n\n if (log_SP == TRUE)\n (*SP) = exp ((*SP));\n\n free (index);\n\n return status;\n\n#else\n fprintf (stderr, \" ***********************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any ECMWF input option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ***********************************************************************\\n\");\n return -1;\n#endif\n}\n\n/**********************************************************************/\n/* alloc_and_read_netCDF_column_float */\n/* function extracts a column of size nlev of data from a netCDF file */\n/* at the indeces itime, ilat, ilon */\n/* variable is the name (string), which is stored in the netCDF file */\n/**********************************************************************/\n\nint alloc_and_read_netCDF_column_float (int ncid,\n char* variable_name,\n float** data,\n size_t nlev,\n size_t itime,\n size_t ilat,\n size_t ilon,\n int verbose) {\n\n#if HAVE_NETCDF4\n\n int status = 0;\n int id_data = 0;\n nc_type netCDF_type;\n double scale_factor = 1.0;\n double add_offset = 0.0;\n\n unsigned char data_uchar = 0;\n short data_short = -999;\n int data_int = -999;\n float data_float = -999.0;\n double data_double = -999.0;\n\n size_t index4D[4] = {0, 0, 0, 0}; /* time, lev, lat, lon */\n int lc = 0;\n\n /* get variable id for data */\n status = nc_inq_varid (ncid, variable_name, &id_data);\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', while getting id for '%s' (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n /* get type of the variable */\n status = nc_inq_vartype (ncid, id_data, &(netCDF_type));\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', while getting type for %s (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n\n if (verbose)\n fprintf (stderr,\n \" reading '%s' type %d (NC_BYTE %d, NC_CHAR %d, NC_SHORT %d, NC_INT %d, NC_FLOAT %d, NC_DOUBLE %d)\\n\",\n variable_name,\n netCDF_type,\n NC_BYTE,\n NC_CHAR,\n NC_SHORT,\n NC_INT,\n NC_FLOAT,\n NC_DOUBLE);\n\n /* read attribute scale_factor */\n status = nc_get_att_double (ncid, id_data, \"scale_factor\", &scale_factor);\n if (status != NC_NOERR) {\n /* no given scale_factor -> default scale_factor = 1.0 */\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" scale_factor = %f \\n\", scale_factor); */\n }\n\n /* read attribute add_offset */\n status = nc_get_att_double (ncid, id_data, \"add_offset\", &add_offset);\n if (status != NC_NOERR) {\n /* no given offset -> default offset = 0.0 */\n /* that's OK, put status to 0 */\n status = 0;\n } else {\n /* if (verbose) */\n /* fprintf (stderr,\" add_offset = %f \\n\", add_offset); */\n }\n\n /* allocate temporary data array */\n if (((*data) = calloc (nlev, sizeof (float))) == NULL) {\n fprintf (stderr, \"Error allocating memory for 'data' \\n (line %d, function '%s' in '%s') \\n\", __LINE__, __func__, __FILE__);\n return -1;\n }\n\n /* read temperature (in netCDF = float *T(time, mlev, lat, lon);)*/\n index4D[0] = itime;\n /* index4D[1] see loops */\n index4D[2] = ilat;\n index4D[3] = ilon;\n\n switch (netCDF_type) {\n case (NC_BYTE):\n case (NC_CHAR):\n for (lc = 0; lc < nlev; lc++) {\n index4D[1] = lc;\n status = nc_get_var1_uchar (ncid, id_data, index4D, &(data_uchar));\n (*data)[lc] = (float)(((double)data_uchar) * scale_factor + add_offset);\n /* fprintf (stderr,\" lc = %3d, %s = %e \\n\", lc, variable_name, (*data)[lc]); */\n }\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading %s (uchar) \\n (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n break;\n case (NC_SHORT):\n for (lc = 0; lc < nlev; lc++) {\n index4D[1] = lc;\n status = nc_get_var1_short (ncid, id_data, index4D, &(data_short));\n (*data)[lc] = (float)(((double)data_short) * scale_factor + add_offset);\n if (fabs ((*data)[lc]) < scale_factor * 10E-6 && scale_factor != 1.0) /* THIS IS REALLY NOT NICE !!!! */\n (*data)[lc] = 0.0; /* THIS IS REALLY NOT NICE !!!! */\n /* fprintf (stderr,\" lc = %3d, %s = %e \\n\", lc, variable_name, (*data)[lc]); */\n }\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading %s (short) \\n (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n break;\n case (NC_INT):\n for (lc = 0; lc < nlev; lc++) {\n index4D[1] = lc;\n status = nc_get_var1_int (ncid, id_data, index4D, &(data_int));\n (*data)[lc] = (float)(((double)data_int) * scale_factor + add_offset);\n /* fprintf (stderr,\" lc = %3d, %s = %e \\n\", lc, variable_name, (*data)[lc]); */\n }\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading %s (integer) \\n (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n break;\n case (NC_FLOAT):\n for (lc = 0; lc < nlev; lc++) {\n index4D[1] = lc;\n status = nc_get_var1_float (ncid, id_data, index4D, &(data_float));\n (*data)[lc] = (float)(((double)data_float) * scale_factor + add_offset);\n /* if (status != NC_NOERR) fprintf (stderr,\"Error '%s' reading '%s', index lc = %3d \\n\", \n nc_strerror(status), variable_name, lc); */\n }\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading %s (float) \\n (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n break;\n case (NC_DOUBLE):\n for (lc = 0; lc < nlev; lc++) {\n index4D[1] = lc;\n status = nc_get_var1_double (ncid, id_data, index4D, &(data_double));\n (*data)[lc] = (float)((data_double)*scale_factor + add_offset);\n /* fprintf (stderr,\" lc = %3d, %s = %e \\n\", lc, variable_name, (*data)[lc]); */\n }\n if (status != NC_NOERR) {\n fprintf (stderr,\n \"Error '%s', reading %s (double)\\n (line %d, function '%s' in '%s')\\n\",\n nc_strerror (status),\n variable_name,\n __LINE__,\n __func__,\n __FILE__);\n return status;\n }\n break;\n default:\n fprintf (stderr,\n \"Error, unknown type of variable %d \\n (line %d, function '%s' in '%s') \\n\",\n netCDF_type,\n __LINE__,\n __func__,\n __FILE__);\n return -1;\n }\n\n return status;\n\n#else\n fprintf (stderr, \" ******************************************************************\\n\");\n fprintf (stderr, \" * You have built uvspec without libnetcdf and hence cannot *\\n\");\n fprintf (stderr, \" * use any netCDF option. Please get netcdf and rebuild. *\\n\");\n fprintf (stderr, \" ******************************************************************\\n\");\n return -1;\n#endif\n}\n\n/***********************************************************************************/\n/* Function: calculate_z_from_p_and_T */\n/* Description: */\n/* calculates a z-grid using the hydrostatic equation */\n/* 2 possible equation: */\n/* first: z_{i-1} - z_{i} = R / g *0.5* bar{T} * log(p_{i}/p_{i-1} */\n/* second: (longer derivation takes */\n/* */\n/* Parameters: */\n/* p pressure in hPa (input) */\n/* T temperature in K (input) */\n/* z height above sea level in km (output) */\n/* n number of height levels */\n/* altitude altitude of the ground in km (input) */\n/* */\n/* Return value: */\n/* int status == 0, if everthing is OK */\n/* < 0, if there was an error */\n/* Example: */\n/* Files: ancillary.c */\n/* Known bugs: - */\n/* Author: */\n/* xx 200? U. Hamann Created */\n/* */\n/***********************************************************************************/\n\nint calculate_z_from_p_and_T (float* p, float* T, float** z, int n, float altitude, int verbose) {\n int status = 0;\n int lc = NOT_DEFINED_INTEGER;\n //20120816ak g is not used, commented\n // float g = NOT_DEFINED_FLOAT;\n\n /* Allocate z */\n if (((*z) = (float*)calloc (n, sizeof (float))) == NULL) {\n fprintf (stderr, \"Error, allocating memory for z\\n\");\n fprintf (stderr, \" (line %d, function '%s' in '%s')\\n\", __LINE__, __func__, __FILE__);\n return -2;\n }\n\n if (verbose) {\n fprintf (stderr, \" ... converting p and T to a z-grid\\n\");\n fprintf (stderr, \" assuming: R = %12.6f, g(z=0km) = %12.6f\\n\", R_AIR, G_SURFACE);\n }\n\n /* initialise lowest level */\n if (altitude == 0.0) {\n (*z)[n - 1] = 0.0;\n //20120816ak g is not used, commented\n // g = G_SURFACE;\n } else {\n (*z)[n - 1] = altitude;\n //20120816ak g is not used, commented\n // g = G_SURFACE * (R_EARTH * R_EARTH) / ((R_EARTH+(*z)[n-1]*1000.)*(R_EARTH+(*z)[n-1]*1000.));\n }\n\n /* calculate radiosonde z-grid (hydrostatic equation) */\n for (lc = n - 1; lc >= 1; lc--) {\n\n /* equation (1) for no variation of g inside one layer */\n /* (*z)[lc-1]=(*z)[lc] + 0.001 * R/g*0.5*(T[lc]+T[lc-1])*log(p[lc]/p[lc-1]); */\n /* /\\* 0.001 <==> m -> km *\\/ */\n /* g = G_SURFACE * (R_EARTH * R_EARTH) / ((R_EARTH+1000.0*(*z)[lc-1])*(R_EARTH+1000.0*(*z)[lc-1])); */\n\n /* equation (2) taking care of variation of g inside one layer */\n (*z)[lc - 1] = -R_EARTH + 1 / (1 / (R_EARTH + 1000.0 * (*z)[lc]) -\n R_AIR / (G_SURFACE * R_EARTH * R_EARTH) * 0.5 * (T[lc] + T[lc - 1]) * log (p[lc] / p[lc - 1]));\n (*z)[lc - 1] *= 0.001; /* m -> km */\n\n /* /\\* addiotional verbose output *\\/ */\n /* fprintf (stderr,\" lc-1=%3d, dz(g=const)[km]=%7.4f, dz(g=g(z))[km]=%7.4f, z_sur[km]=%8.4f, T=%5.2f, p=%10.4f \\n\", */\n /* lc-1, 0.001 * R_AIR/g*0.5*(T[lc]+T[lc-1])*log(p[lc]/p[lc-1]), */\n /* (*z)[lc-1]-(*z)[lc],(*z)[lc-1],T[lc-1], p[lc-1]); */\n }\n\n return status;\n}\n\n/* given month, day, year, returns day of week, eg. Monday = 0 etc. */\n/* tested for 1901 to 2099 (seems to work from 1800 on too) */\n\nint weekday (int year, int month, int day) {\n int ix = NOT_DEFINED_INTEGER, tx = NOT_DEFINED_INTEGER, vx = NOT_DEFINED_INTEGER;\n\n switch (month) {\n case 2:\n case 6:\n vx = 0;\n break;\n case 8:\n vx = 4;\n break;\n case 10:\n vx = 8;\n break;\n case 9:\n case 12:\n vx = 12;\n break;\n case 3:\n case 11:\n vx = 16;\n break;\n case 1:\n case 5:\n vx = 20;\n break;\n case 4:\n case 7:\n vx = 24;\n break;\n default:\n fprintf (stderr, \"Error, determening day of week in function weekday (in ancillary.c) (month = %d)\\n\", month);\n return -1000;\n break;\n }\n\n if (year > 1900) /* 1900 was not a leap year */\n year -= 1900;\n ix = ((year - 21) % 28) + vx + (month > 2); /* take care of February */\n tx = (ix + (ix / 4)) % 7 + day; /* take care of leap year */\n return ((tx + 1) % 7);\n}\n\nchar* strtrim (char* str, const char* trim) {\n return strltrim (strrtrim (str, trim), trim);\n}\n\nchar* strrtrim (char* str, const char* trim) {\n char* end;\n\n if (!str)\n return NULL;\n\n if (!trim)\n trim = \" \\t\\n\\r\";\n\n end = str + strlen (str);\n\n while (end-- > str) {\n if (!strchr (trim, *end))\n return str;\n *end = 0;\n }\n return str;\n}\n\nchar* strltrim (char* str, const char* trim) {\n if (!str)\n return NULL;\n\n if (!trim)\n trim = \" \\t\\r\\n\";\n\n while (*str) {\n if (!strchr (trim, *str))\n return str;\n ++str;\n }\n return str;\n}\n\n/***********************************************************************************/\n/* Function: specific_heat_capacity_moist_air */\n/* Description: */\n/* calculated the specific heat capacity of dry air and water vapour and */\n/* returns a mass weighted average according to the specific humidity */\n/* */\n/* Parameters: */\n/* float T_in_K temperature in Kelvin */\n/* float dens_air number density of air moleculs in cm-3 */\n/* float dens_wv number density of water vapour moleculs in cm-3 */\n/* float mol_mass_air weight of one 'air' molecul in u */\n/* float mol_mass_wv weight of one 'water vapour' molecul in u */\n/* float *c_p returned result */\n/* specific heat capacity in J/(kg K) */\n/* Return value: */\n/* int status == 0, if everthing is OK */\n/* < 0, if there was an error */\n/* Example: */\n/* Files: ancillary.c */\n/* Known bugs: - */\n/* Author: */\n/* Feb 2008 U. Hamann Created */\n/* */\n/***********************************************************************************/\n\nint specific_heat_capacity_moist_air (float T_in_K, float dens_air, float dens_wv, float* c_p, int quiet) {\n\n int status = 0;\n\n float mmr_h2o = NOT_DEFINED_FLOAT;\n float c_p_dry_air = NOT_DEFINED_FLOAT;\n float c_p_wv = NOT_DEFINED_FLOAT;\n\n char function_name[] = \"specific_heat_capacity_moist_air\";\n char file_name[] = \"ancillary.c\";\n\n mmr_h2o = (dens_wv * MOL_MASS_WV) / (dens_air * MOL_MASS_AIR);\n\n /* temperature dependent heat capacity of dry air */\n c_p_dry_air = specific_heat_capacity_dry_air (T_in_K, quiet);\n if (c_p_dry_air < 0.0) {\n fprintf (stderr, \"Error during specific_heat_capacity_dry_air in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n /* temperature dependent heat capacity of water vapour */\n c_p_wv = specific_heat_capacity_water_vapour (T_in_K, quiet);\n if (c_p_wv < 0.0) {\n fprintf (stderr, \"Error during specific_heat_capacity_water_vapour in %s (%s)\\n\", function_name, file_name);\n return -1;\n }\n\n /* mass weighted mean of specific heat capacity (moist air), e.g. Etling page 34 */\n *c_p = (1 - mmr_h2o) * c_p_dry_air + mmr_h2o * c_p_wv;\n\n return status;\n}\n\n/***********************************************************************************************/\n/* function: specific_heat_capacity_dry_air */\n/* interpolate a table to get the temperature dependent specific heat capacity of dry air */\n/* input float T in K */\n/* output float specific heat capacity of dry air in J/(kg K) */\n/* ulrich hamann 2007-03-31 */\n/***********************************************************************************************/\n\nfloat specific_heat_capacity_dry_air (float T_in_K, int quiet) {\n\n const int n = 14;\n int i = NOT_DEFINED_INTEGER;\n float c_p_dry_air = NOT_DEFINED_FLOAT;\n\n float c_p_grid[14] =\n {1002.3, 1002.5, 1002.7, 1003.1, 1003.8, 1004.9, 1006.3, 1008.2, 1010.6, 1013.5, 1020.6, 1029.5, 1039.8, 1051.1};\n float T_grid[14] = {175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0, 375.0, 400.0, 450.0, 500.0, 550.0, 600.0};\n\n if (T_in_K < T_grid[0]) {\n if (!quiet) {\n fprintf (stderr, \" *** Warning, getting specific heat capacity of dry air,\\n\");\n fprintf (stderr, \" temperature %7.2f is below of the tabled temperature region.\\n\", T_in_K);\n }\n return c_p_grid[0];\n } else if (T_in_K > T_grid[n - 1]) {\n if (!quiet) {\n fprintf (stderr, \" *** Warning, getting specific heat capacity of dry air,\\n\");\n fprintf (stderr, \" temperature %7.2f is above of the tabled temperature region.\\n\", T_in_K);\n }\n return c_p_grid[n - 1];\n } else {\n\n for (i = 1; i < n; i++) {\n if (T_grid[i - 1] <= T_in_K && T_in_K <= T_grid[i]) {\n c_p_dry_air = c_p_grid[i - 1] + (c_p_grid[i] - c_p_grid[i - 1]) / (T_grid[i] - T_grid[i - 1]) * (T_in_K - T_grid[i - 1]);\n /* fprintf (stderr,\"T_(i-1)=%5.2f, T=%5.2f, T_(i)=%5.2f, c_(i-1)=%6.2f, c=%6.2f, c_(i)=%6.2f (dry air) \\n\", */\n /* T_grid[i-1],T_in_K,T_grid[i],c_p_grid[i-1],c_p_dry_air,c_p_grid[i]); */\n break;\n }\n }\n\n if (c_p_dry_air < 0.0) {\n fprintf (stderr, \"Error, determening specific heat of dry air, T = %6.2f K (in ancillary.c)\\n\", T_in_K);\n return -1.0;\n }\n\n return c_p_dry_air;\n }\n}\n\n/***********************************************************************************************/\n/* function: specific_heat_capacity_water_vapour */\n/* interpolate a table to get the temperature dependent specific heat capacity of water vapour */\n/* input float T in K */\n/* output float specific heat capacity of water vapour in J/(kg K) */\n/* ulrich hamann: 2007-03-31 */\n/***********************************************************************************************/\n\nfloat specific_heat_capacity_water_vapour (float T_in_K, int quiet) {\n\n const int n = 14;\n int i = NOT_DEFINED_INTEGER;\n float c_p_wv = NOT_DEFINED_FLOAT;\n float c_p_wv_grid[14] =\n {1850.0, 1851.0, 1852.0, 1855.0, 1859.0, 1864.0, 1871.0, 1880.0, 1890.0, 1901.0, 1926.0, 1954.0, 1984.0, 2015.0};\n float T_grid[14] = {175.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0, 375.0, 400.0, 450.0, 500.0, 550.0, 600.0};\n\n if (T_in_K < T_grid[0]) {\n if (!quiet) {\n fprintf (stderr, \" *** Warning, getting specific heat capacity of water vapour,\\n\");\n fprintf (stderr, \" temperature %7.2f is below of the tabled temperature region.\\n\", T_in_K);\n }\n return c_p_wv_grid[0];\n } else if (T_in_K > T_grid[n - 1]) {\n if (!quiet) {\n fprintf (stderr, \" *** Warning, getting specific heat capacity of water vapour,\\n\");\n fprintf (stderr, \" temperature %7.2f is above of the tabled temperature region.\\n\", T_in_K);\n }\n return c_p_wv_grid[n - 1];\n } else {\n\n for (i = 1; i < n; i++) {\n if (T_grid[i - 1] <= T_in_K && T_in_K <= T_grid[i]) {\n c_p_wv =\n c_p_wv_grid[i - 1] + (c_p_wv_grid[i] - c_p_wv_grid[i - 1]) / (T_grid[i] - T_grid[i - 1]) * (T_in_K - T_grid[i - 1]);\n /* fprintf (stderr,\"T_(i-1)=%5.2f, T=%5.2f, T_(i)=%5.2f, c_(i-1)=%6.2f, c=%6.2f, c_(i)=%6.2f (water vapour) \\n\", */\n /* T_grid[i-1],T_in_K,T_grid[i],c_p_wv_grid[i-1],c_p_wv,c_p_wv_grid[i]); */\n break;\n }\n }\n\n if (c_p_wv < 0.0) {\n fprintf (stderr, \"Error, determening specific heat of water vapour, T = %6.2f K (in ancillary.c)\\n\", T_in_K);\n return -1.0;\n }\n\n return c_p_wv;\n }\n}\n\n/***********************************************************************************/\n/* Function: my_timegm */\n/* Description: */\n/* converts a tm-struct (date as year, month, day, hour, min, ...) */\n/* into time in s since 1.1.1970 */\n/* (reverse function to gmtime) */\n/* (essentially the same as timegm, which is part of many GNU C libraries, */\n/* but not all, and therefor not portable) */\n/* */\n/* Parameters: */\n/* struct tm *tm input date */\n/* */\n/* Return value: */\n/* time_t time */\n/* == -1 if there was some error */\n/* */\n/* Example: */\n/* Files: ancillary.c */\n/* Known bugs: - */\n/* Author: */\n/* Oct 2003 Roger Dingledine */\n/* Delivered-to the SEUL-project under the Gnu Public Licence */\n/* http://archives.seul.org/or/cvs/Oct-2003/msg00123.html */\n/* Jan 2007 Ulrich Hamann */\n/* implemented into libRadtran */\n/* */\n/***********************************************************************************/\n\ntime_t my_timegm (struct tm* tm) {\n time_t ret;\n char* tz;\n\n tz = getenv (\"TZ\");\n setenv (\"TZ\", \"\", 1);\n tzset();\n ret = mktime (tm);\n if (tz)\n setenv (\"TZ\", tz, 1);\n else\n unsetenv (\"TZ\");\n tzset();\n return ret;\n}\n\n/* check if two floats are equal - still not optimal, but how to improve? */\n/* THIS CODE IS IDENTICALLY IN CLOUD3D.C */\n\nstatic inline int float_equal (float a, float b) {\n\n if (a == 0 || b == 0) {\n if (fabs (a - b) < MC_EPSILON)\n return 1;\n } else { /* relative difference smaller than MC_EPSILON */\n if (fabs (a - b) < MC_EPSILON * fabs (a))\n return 1;\n }\n\n return 0;\n}\n\ndouble nm_to_inv_cm (double wavelength_nm) {\n double wavenumber_inv_cm;\n\n wavenumber_inv_cm = 1 / (wavelength_nm * 1E-07);\n\n return wavenumber_inv_cm;\n}\n\ndouble inv_cm_to_nm (double wavenumber_inv_cm) {\n double wavelength_nm;\n\n wavelength_nm = 1E+07 / wavenumber_inv_cm;\n\n return wavelength_nm;\n}\n\ndouble polarizability_anisotropy_N2 (double nu) {\n\n double gam = 0;\n\n gam = -6.01466e-25 + 2.38557e-14 / (1.86099e+10 - nu * nu);\n\n return gam;\n}\n\ndouble polarizability_anisotropy_O2 (double nu) {\n double gam;\n\n gam = 7.149e-26 + 4.59364e-15 / (4.82716e+9 - nu * nu);\n\n return gam;\n}\n\nstruct E_rot_N2 {\n\n int gJ;\n int J;\n double E;\n};\n\nstruct E_rot_O2 {\n\n int N;\n int J;\n double E;\n};\n\nstruct E_rot_trans_N2 {\n\n int J;\n int Jp; /* J prime */\n int gJ; /* Statistical weight */\n double E;\n double delta_E;\n double cpt; /* Plazcek-Teller coefficient */\n};\n\nstruct E_rot_trans_O2 {\n\n int N;\n int J;\n int Np; /* N prime */\n int Jp; /* J prime */\n double E;\n double delta_E;\n double cpt; /* Plazcek-Teller coefficient */\n};\n\nint crs_raman_N2 (double lambda, int n_transitions, float temper, double*** crs, int* iv, int verbose) {\n\n /* Calculate Raman shifted wavelengths for input wavelength lambda in nm and */\n /* temperature temper. n_transitions are considered. Wavelength are returned */\n /* in first column of crs and cross section in the second column. Cross */\n /* section is weighted by the volume mixing ratio. */\n\n double c = 299792458; /* Speed of light, m/s, from wikipedia */\n double h = 6.62606896e-34; /* Planck constant, Js, from wikipedia */\n double hc = h * c * 100; /* Converted to J*cm */\n\n double nm_to_cm = 1e-07; /* Convert from nm to cm */\n\n double raman_const = 256 * pow (M_PI, 5) / 27;\n\n /* All the numbers below for the Rotational energy states of O2 are */\n /* from the report: Accounting for Raman Scattering in DOAS, */\n /* J.F. de Haan, SN-OMIE-KNMI-409, Version 1.0, May 18, 2003 */\n\n /* \n N: Nuclear rotational angular momentum quantum number \n gJ: statistical weight factor\n E: Rotational energy of state in cm-1\n From Table A-1\n */\n int N_E = 31;\n struct E_rot_N2 E_rot[N_E];\n E_rot[0].J = 0;\n E_rot[0].gJ = 6;\n E_rot[0].E = 0.0000;\n E_rot[1].J = 1;\n E_rot[1].gJ = 3;\n E_rot[1].E = 3.9791;\n E_rot[2].J = 2;\n E_rot[2].gJ = 6;\n E_rot[2].E = 11.9373;\n E_rot[3].J = 3;\n E_rot[3].gJ = 3;\n E_rot[3].E = 23.8741;\n E_rot[4].J = 4;\n E_rot[4].gJ = 6;\n E_rot[4].E = 39.7892;\n E_rot[5].J = 5;\n E_rot[5].gJ = 3;\n E_rot[5].E = 59.6821;\n E_rot[6].J = 6;\n E_rot[6].gJ = 6;\n E_rot[6].E = 83.5521;\n E_rot[7].J = 7;\n E_rot[7].gJ = 3;\n E_rot[7].E = 111.3983;\n E_rot[8].J = 8;\n E_rot[8].gJ = 6;\n E_rot[8].E = 143.2197;\n E_rot[9].J = 9;\n E_rot[9].gJ = 3;\n E_rot[9].E = 179.0154;\n E_rot[10].J = 10;\n E_rot[10].gJ = 6;\n E_rot[10].E = 218.7839;\n E_rot[11].J = 11;\n E_rot[11].gJ = 3;\n E_rot[11].E = 262.5240;\n E_rot[12].J = 12;\n E_rot[12].gJ = 6;\n E_rot[12].E = 310.2341;\n E_rot[13].J = 13;\n E_rot[13].gJ = 3;\n E_rot[13].E = 361.9126;\n E_rot[14].J = 14;\n E_rot[14].gJ = 6;\n E_rot[14].E = 417.5576;\n E_rot[15].J = 15;\n E_rot[15].gJ = 3;\n E_rot[15].E = 477.1673;\n E_rot[16].J = 16;\n E_rot[16].gJ = 6;\n E_rot[16].E = 540.7395;\n E_rot[17].J = 17;\n E_rot[17].gJ = 3;\n E_rot[17].E = 608.2722;\n E_rot[18].J = 18;\n E_rot[18].gJ = 6;\n E_rot[18].E = 679.7628;\n E_rot[19].J = 19;\n E_rot[19].gJ = 3;\n E_rot[19].E = 755.2090;\n E_rot[20].J = 20;\n E_rot[20].gJ = 6;\n E_rot[20].E = 834.6081;\n E_rot[21].J = 21;\n E_rot[21].gJ = 3;\n E_rot[21].E = 917.9574;\n E_rot[22].J = 22;\n E_rot[22].gJ = 6;\n E_rot[22].E = 1005.2540;\n E_rot[23].J = 23;\n E_rot[23].gJ = 3;\n E_rot[23].E = 1096.4948;\n E_rot[24].J = 24;\n E_rot[24].gJ = 6;\n E_rot[24].E = 1191.6766;\n E_rot[25].J = 25;\n E_rot[25].gJ = 3;\n E_rot[25].E = 1290.7963;\n E_rot[26].J = 26;\n E_rot[26].gJ = 6;\n E_rot[26].E = 1393.8503;\n E_rot[27].J = 27;\n E_rot[27].gJ = 3;\n E_rot[27].E = 1500.8350;\n E_rot[28].J = 28;\n E_rot[28].gJ = 6;\n E_rot[28].E = 1611.7467;\n E_rot[29].J = 29;\n E_rot[29].gJ = 3;\n E_rot[29].E = 1726.5816;\n E_rot[30].J = 30;\n E_rot[30].gJ = 6;\n E_rot[30].E = 1845.3358;\n\n /* \n N: Nuclear rotational angular momentum quantum number \n J: Total angular momentum quantum number\n E: Rotational energy of state in cm-1\n From Table A-2\n */\n int N_E_trans = 48;\n struct E_rot_trans_N2 Etr[N_E_trans];\n Etr[0].J = 25;\n Etr[0].Jp = 23;\n Etr[0].gJ = 3;\n Etr[0].E = 1290.7963;\n Etr[0].delta_E = -194.3015;\n Etr[0].cpt = 0.3601;\n Etr[1].J = 24;\n Etr[1].Jp = 22;\n Etr[1].gJ = 6;\n Etr[1].E = 1191.6766;\n Etr[1].delta_E = -186.4226;\n Etr[1].cpt = 0.3595;\n Etr[2].J = 23;\n Etr[2].Jp = 21;\n Etr[2].gJ = 3;\n Etr[2].E = 1096.4948;\n Etr[2].delta_E = -178.5374;\n Etr[2].cpt = 0.3589;\n Etr[3].J = 22;\n Etr[3].Jp = 20;\n Etr[3].gJ = 6;\n Etr[3].E = 1005.2540;\n Etr[3].delta_E = -170.6459;\n Etr[3].cpt = 0.3581;\n Etr[4].J = 21;\n Etr[4].Jp = 19;\n Etr[4].gJ = 3;\n Etr[4].E = 917.9574;\n Etr[4].delta_E = -162.7484;\n Etr[4].cpt = 0.3573;\n Etr[5].J = 20;\n Etr[5].Jp = 18;\n Etr[5].gJ = 6;\n Etr[5].E = 834.6081;\n Etr[5].delta_E = -154.8453;\n Etr[5].cpt = 0.3565;\n Etr[6].J = 19;\n Etr[6].Jp = 17;\n Etr[6].gJ = 3;\n Etr[6].E = 755.2090;\n Etr[6].delta_E = -146.9368;\n Etr[6].cpt = 0.3555;\n Etr[7].J = 18;\n Etr[7].Jp = 16;\n Etr[7].gJ = 6;\n Etr[7].E = 679.7628;\n Etr[7].delta_E = -139.0233;\n Etr[7].cpt = 0.3544;\n Etr[8].J = 17;\n Etr[8].Jp = 15;\n Etr[8].gJ = 3;\n Etr[8].E = 608.2722;\n Etr[8].delta_E = -131.1049;\n Etr[8].cpt = 0.3532;\n Etr[9].J = 16;\n Etr[9].Jp = 14;\n Etr[9].gJ = 6;\n Etr[9].E = 540.7395;\n Etr[9].delta_E = -123.1819;\n Etr[9].cpt = 0.3519;\n Etr[10].J = 15;\n Etr[10].Jp = 13;\n Etr[10].gJ = 3;\n Etr[10].E = 477.1673;\n Etr[10].delta_E = -115.2547;\n Etr[10].cpt = 0.3504;\n Etr[11].J = 14;\n Etr[11].Jp = 12;\n Etr[11].gJ = 6;\n Etr[11].E = 417.5576;\n Etr[11].delta_E = -107.3235;\n Etr[11].cpt = 0.3487;\n Etr[12].J = 13;\n Etr[12].Jp = 11;\n Etr[12].gJ = 3;\n Etr[12].E = 361.9126;\n Etr[12].delta_E = -99.3886;\n Etr[12].cpt = 0.3467;\n Etr[13].J = 12;\n Etr[13].Jp = 10;\n Etr[13].gJ = 6;\n Etr[13].E = 310.2341;\n Etr[13].delta_E = -91.4502;\n Etr[13].cpt = 0.3443;\n Etr[14].J = 11;\n Etr[14].Jp = 9;\n Etr[14].gJ = 3;\n Etr[14].E = 262.5240;\n Etr[14].delta_E = -83.5086;\n Etr[14].cpt = 0.3416;\n Etr[15].J = 10;\n Etr[15].Jp = 8;\n Etr[15].gJ = 6;\n Etr[15].E = 218.7839;\n Etr[15].delta_E = -75.5642;\n Etr[15].cpt = 0.3383;\n Etr[16].J = 9;\n Etr[16].Jp = 7;\n Etr[16].gJ = 3;\n Etr[16].E = 179.0154;\n Etr[16].delta_E = -67.6171;\n Etr[16].cpt = 0.3344;\n Etr[17].J = 8;\n Etr[17].Jp = 6;\n Etr[17].gJ = 6;\n Etr[17].E = 143.2197;\n Etr[17].delta_E = -59.6676;\n Etr[17].cpt = 0.3294;\n Etr[18].J = 7;\n Etr[18].Jp = 5;\n Etr[18].gJ = 3;\n Etr[18].E = 111.3983;\n Etr[18].delta_E = -51.7162;\n Etr[18].cpt = 0.3231;\n Etr[19].J = 6;\n Etr[19].Jp = 4;\n Etr[19].gJ = 6;\n Etr[19].E = 83.5521;\n Etr[19].delta_E = -43.7629;\n Etr[19].cpt = 0.3147;\n Etr[20].J = 5;\n Etr[20].Jp = 3;\n Etr[20].gJ = 3;\n Etr[20].E = 59.6821;\n Etr[20].delta_E = -35.8080;\n Etr[20].cpt = 0.3030;\n Etr[21].J = 4;\n Etr[21].Jp = 2;\n Etr[21].gJ = 6;\n Etr[21].E = 39.7892;\n Etr[21].delta_E = -27.8519;\n Etr[21].cpt = 0.2857;\n Etr[22].J = 3;\n Etr[22].Jp = 1;\n Etr[22].gJ = 3;\n Etr[22].E = 23.8741;\n Etr[22].delta_E = -19.8950;\n Etr[22].cpt = 0.2571;\n Etr[23].J = 2;\n Etr[23].Jp = 0;\n Etr[23].gJ = 6;\n Etr[23].E = 11.9373;\n Etr[23].delta_E = -11.9373;\n Etr[23].cpt = 0.2000;\n Etr[24].J = 0;\n Etr[24].Jp = 2;\n Etr[24].gJ = 6;\n Etr[24].E = 0.0000;\n Etr[24].delta_E = 11.9373;\n Etr[24].cpt = 1.0000;\n Etr[25].J = 1;\n Etr[25].Jp = 3;\n Etr[25].gJ = 3;\n Etr[25].E = 3.9791;\n Etr[25].delta_E = 19.8950;\n Etr[25].cpt = 0.6000;\n Etr[26].J = 2;\n Etr[26].Jp = 4;\n Etr[26].gJ = 6;\n Etr[26].E = 11.9373;\n Etr[26].delta_E = 27.8519;\n Etr[26].cpt = 0.5143;\n Etr[27].J = 3;\n Etr[27].Jp = 5;\n Etr[27].gJ = 3;\n Etr[27].E = 23.8741;\n Etr[27].delta_E = 35.8080;\n Etr[27].cpt = 0.4762;\n Etr[28].J = 4;\n Etr[28].Jp = 6;\n Etr[28].gJ = 6;\n Etr[28].E = 39.7892;\n Etr[28].delta_E = 43.7629;\n Etr[28].cpt = 0.4545;\n Etr[29].J = 5;\n Etr[29].Jp = 7;\n Etr[29].gJ = 3;\n Etr[29].E = 59.6821;\n Etr[29].delta_E = 51.7162;\n Etr[29].cpt = 0.4406;\n Etr[30].J = 6;\n Etr[30].Jp = 8;\n Etr[30].gJ = 6;\n Etr[30].E = 83.5521;\n Etr[30].delta_E = 59.6676;\n Etr[30].cpt = 0.4308;\n Etr[31].J = 7;\n Etr[31].Jp = 9;\n Etr[31].gJ = 3;\n Etr[31].E = 111.3983;\n Etr[31].delta_E = 67.6171;\n Etr[31].cpt = 0.4235;\n Etr[32].J = 8;\n Etr[32].Jp = 10;\n Etr[32].gJ = 6;\n Etr[32].E = 143.2197;\n Etr[32].delta_E = 75.5642;\n Etr[32].cpt = 0.4180;\n Etr[33].J = 9;\n Etr[33].Jp = 11;\n Etr[33].gJ = 3;\n Etr[33].E = 179.0154;\n Etr[33].delta_E = 83.5086;\n Etr[33].cpt = 0.4135;\n Etr[34].J = 10;\n Etr[34].Jp = 12;\n Etr[34].gJ = 6;\n Etr[34].E = 218.7839;\n Etr[34].delta_E = 91.4502;\n Etr[34].cpt = 0.4099;\n Etr[35].J = 11;\n Etr[35].Jp = 13;\n Etr[35].gJ = 3;\n Etr[35].E = 262.5240;\n Etr[35].delta_E = 99.3886;\n Etr[35].cpt = 0.4070;\n Etr[36].J = 12;\n Etr[36].Jp = 14;\n Etr[36].gJ = 6;\n Etr[36].E = 310.2341;\n Etr[36].delta_E = 107.3235;\n Etr[36].cpt = 0.4044;\n Etr[37].J = 13;\n Etr[37].Jp = 15;\n Etr[37].gJ = 3;\n Etr[37].E = 361.9126;\n Etr[37].delta_E = 115.2547;\n Etr[37].cpt = 0.4023;\n Etr[38].J = 14;\n Etr[38].Jp = 16;\n Etr[38].gJ = 6;\n Etr[38].E = 417.5576;\n Etr[38].delta_E = 123.1819;\n Etr[38].cpt = 0.4004;\n Etr[39].J = 15;\n Etr[39].Jp = 17;\n Etr[39].gJ = 3;\n Etr[39].E = 477.1673;\n Etr[39].delta_E = 131.1049;\n Etr[39].cpt = 0.3988;\n Etr[40].J = 16;\n Etr[40].Jp = 18;\n Etr[40].gJ = 6;\n Etr[40].E = 540.7395;\n Etr[40].delta_E = 139.0233;\n Etr[40].cpt = 0.3974;\n Etr[41].J = 17;\n Etr[41].Jp = 19;\n Etr[41].gJ = 3;\n Etr[41].E = 608.2722;\n Etr[41].delta_E = 146.9368;\n Etr[41].cpt = 0.3961;\n Etr[42].J = 18;\n Etr[42].Jp = 20;\n Etr[42].gJ = 6;\n Etr[42].E = 679.7628;\n Etr[42].delta_E = 154.8453;\n Etr[42].cpt = 0.3950;\n Etr[43].J = 19;\n Etr[43].Jp = 21;\n Etr[43].gJ = 3;\n Etr[43].E = 755.2090;\n Etr[43].delta_E = 162.7484;\n Etr[43].cpt = 0.3940;\n Etr[44].J = 20;\n Etr[44].Jp = 22;\n Etr[44].gJ = 6;\n Etr[44].E = 834.6081;\n Etr[44].delta_E = 170.6459;\n Etr[44].cpt = 0.3931;\n Etr[45].J = 21;\n Etr[45].Jp = 23;\n Etr[45].gJ = 3;\n Etr[45].E = 917.9574;\n Etr[45].delta_E = 178.5374;\n Etr[45].cpt = 0.3922;\n Etr[46].J = 22;\n Etr[46].Jp = 24;\n Etr[46].gJ = 6;\n Etr[46].E = 1005.2540;\n Etr[46].delta_E = 186.4226;\n Etr[46].cpt = 0.3915;\n Etr[47].J = 23;\n Etr[47].Jp = 25;\n Etr[47].gJ = 3;\n Etr[47].E = 1096.4948;\n Etr[47].delta_E = 194.3015;\n Etr[47].cpt = 0.3908;\n\n double E_J = 0; /* Rotational energy of state J */\n double W_J = 0; /* Fraction of molecules in the rotational state J at temperature T */\n double b_J = 0; /* Placzek-Teller coefficient */\n double lambda_inv_cm = 0, lambda_cm = 0, lambda_shifted_inv_cm = 0, lambda_shifted_nm = 0, lambda_shifted_cm = 0;\n double delta_nu = 0;\n double crs_i = 0, crs_j = 0;\n double fNJ = 0, Z = 0; /* Eq 5 and 10 */\n double gam_i = 0, gam_j = 0;\n double volume_mixing_ratio = 0.7905;\n double sum = 0;\n\n int J = 0; /* Rotational state J */\n int g_J = 0;\n\n int status = 0;\n int ivi = 0, is = 0;\n\n if (verbose) {\n fprintf (stderr, \"Calculating Raman scattering wavelength shifts and cross sections \");\n fprintf (stderr, \"for N2, wavelength %5.1f nm, number of transitions %d, T=%6.2f.\\n\", lambda, n_transitions, temper);\n fprintf (stderr,\n \" %3s %1s %7s %8s %7s %9s %10s %9s %17s %9s %12s %7s %12s %12s %11s %14s %12s\\n\",\n \"ivi\",\n \"J\",\n \"E_J\",\n \"g_J\",\n \"W_J\",\n \"b_J\",\n \"W_J*b_J\",\n \"wvl\",\n \"wvl_shift_cm-1\",\n \"delta_nu\",\n \"wvl_shift_nm\",\n \"gam_i\",\n \"gam_j\",\n \"crs_i\",\n \"crs_j\",\n \"crs_i*vmr\",\n \"crs_j*vmr\");\n }\n\n ivi = *iv;\n\n sum = 0;\n for (is = 0; is < N_E; is++) {\n g_J = E_rot[is].gJ;\n J = E_rot[is].J;\n E_J = E_rot[is].E * hc;\n sum += g_J * (2 * J + 1) * exp (-E_J / (BOLTZMANN * temper));\n }\n Z = sum;\n\n for (is = 0; is < n_transitions; is++) {\n\n g_J = Etr[is].gJ;\n J = Etr[is].J;\n E_J = Etr[is].E * hc;\n b_J = Etr[is].cpt;\n delta_nu = -Etr[is].delta_E; /* Negative delta_E corresponds to a photon with a larger */\n /* energy, shorter wavelength than the incident photon */\n /* delta_E is the change in rotational energy of the */\n /* molecule. The minus puts the photon in the right */\n /* wavelength. */\n\n W_J = g_J * (2 * J + 1) * exp (-E_J / (BOLTZMANN * temper));\n fNJ = W_J / Z;\n lambda_inv_cm = nm_to_inv_cm (lambda);\n lambda_shifted_inv_cm = lambda_inv_cm + delta_nu;\n lambda_shifted_nm = inv_cm_to_nm (lambda_shifted_inv_cm);\n lambda_shifted_cm = lambda_shifted_nm * nm_to_cm;\n lambda_cm = lambda * nm_to_cm;\n gam_i = polarizability_anisotropy_N2 (lambda_shifted_inv_cm);\n gam_j = polarizability_anisotropy_N2 (lambda_inv_cm);\n crs_i = fNJ * gam_i * gam_i * raman_const * b_J / pow (lambda_shifted_cm, 4);\n crs_j = fNJ * gam_j * gam_j * raman_const * b_J / pow (lambda_cm, 4);\n (*crs)[ivi][0] = lambda_shifted_nm;\n (*crs)[ivi][1] = crs_i * volume_mixing_ratio;\n (*crs)[ivi][2] = crs_j * volume_mixing_ratio;\n if (verbose)\n fprintf (stderr,\n \"Raman_crs_N2 %2d %2d %12.6e %2d %12.6e %6.3f %12.6e %10.6f %10.6f %10.4f %10.6f %12.6e %12.6e %12.6e %12.6e %12.6e \"\n \"%12.6e\\n\",\n ivi,\n J,\n E_J,\n g_J,\n W_J,\n b_J,\n W_J * b_J,\n lambda,\n lambda_shifted_inv_cm,\n delta_nu,\n lambda_shifted_nm,\n gam_i,\n gam_j,\n crs_i,\n crs_j,\n crs_i * volume_mixing_ratio,\n crs_j * volume_mixing_ratio);\n ivi++;\n }\n\n *iv = ivi;\n\n return status;\n}\n\nint crs_raman_O2 (double lambda, int n_transitions, float temper, double*** crs, int* iv, int verbose) {\n\n /* Calculate Raman shifted wavelengths for input wavelength lambda in nm and */\n /* temperature temper. n_transitions are considered. Wavelength are returned */\n /* in first column of crs and cross section in the second column. Cross */\n /* section is weighted by the volume mixing ratio. */\n\n double c = 299792458; /* Speed of light, m/s, from wikipedia */\n double h = 6.62606896e-34; /* Planck constant, Js, from wikipedia */\n double hc = h * c * 100; /* Converted to J*cm */\n\n double nm_to_cm = 1e-07; /* Convert from nm to cm */\n\n double raman_const = 256 * pow (M_PI, 5) / 27;\n\n /* All the numbers below for the Rotational energy states of O2 are */\n /* from the report: Accounting for Raman Scattering in DOAS, */\n /* J.F. de Haan, SN-OMIE-KNMI-409, Version 1.0, May 18, 2003 */\n\n /* \n N: Nuclear rotational angular momentum quantum number \n J: Total angular momentum quantum number\n E: Rotational energy of state in cm-1\n From Table A-1\n */\n int N_E = 54;\n struct E_rot_O2 E_rot[N_E];\n E_rot[0].N = 1;\n E_rot[0].J = 0;\n E_rot[0].E = 0.0000;\n E_rot[1].N = 1;\n E_rot[1].J = 2;\n E_rot[1].E = 2.0843;\n E_rot[2].N = 1;\n E_rot[2].J = 1;\n E_rot[2].E = 3.9611;\n E_rot[3].N = 3;\n E_rot[3].J = 2;\n E_rot[3].E = 16.2529;\n E_rot[4].N = 3;\n E_rot[4].J = 4;\n E_rot[4].E = 16.3876;\n E_rot[5].N = 3;\n E_rot[5].J = 3;\n E_rot[5].E = 18.3372;\n E_rot[6].N = 5;\n E_rot[6].J = 4;\n E_rot[6].E = 42.2001;\n E_rot[7].N = 5;\n E_rot[7].J = 6;\n E_rot[7].E = 42.2240;\n E_rot[8].N = 5;\n E_rot[8].J = 5;\n E_rot[8].E = 44.2117;\n E_rot[9].N = 7;\n E_rot[9].J = 8;\n E_rot[9].E = 79.5646;\n E_rot[10].N = 7;\n E_rot[10].J = 6;\n E_rot[10].E = 79.6070;\n E_rot[11].N = 7;\n E_rot[11].J = 7;\n E_rot[11].E = 81.5805;\n E_rot[12].N = 9;\n E_rot[12].J = 10;\n E_rot[12].E = 128.3978;\n E_rot[13].N = 9;\n E_rot[13].J = 8;\n E_rot[13].E = 128.4921;\n E_rot[14].N = 9;\n E_rot[14].J = 9;\n E_rot[14].E = 130.4376;\n E_rot[15].N = 11;\n E_rot[15].J = 12;\n E_rot[15].E = 188.7135;\n E_rot[16].N = 11;\n E_rot[16].J = 10;\n E_rot[16].E = 188.8532;\n E_rot[17].N = 11;\n E_rot[17].J = 11;\n E_rot[17].E = 190.7749;\n E_rot[18].N = 13;\n E_rot[18].J = 14;\n E_rot[18].E = 260.5011;\n E_rot[19].N = 13;\n E_rot[19].J = 12;\n E_rot[19].E = 260.6826;\n E_rot[20].N = 13;\n E_rot[20].J = 13;\n E_rot[20].E = 262.5829;\n E_rot[21].N = 15;\n E_rot[21].J = 16;\n E_rot[21].E = 343.7484;\n E_rot[22].N = 15;\n E_rot[22].J = 14;\n E_rot[22].E = 343.9697;\n E_rot[23].N = 15;\n E_rot[23].J = 15;\n E_rot[23].E = 345.8500;\n E_rot[24].N = 17;\n E_rot[24].J = 18;\n E_rot[24].E = 438.4418;\n E_rot[25].N = 17;\n E_rot[25].J = 16;\n E_rot[25].E = 438.7015;\n E_rot[26].N = 17;\n E_rot[26].J = 17;\n E_rot[26].E = 440.5620;\n E_rot[27].N = 19;\n E_rot[27].J = 20;\n E_rot[27].E = 544.5658;\n E_rot[28].N = 19;\n E_rot[28].J = 18;\n E_rot[28].E = 544.8628;\n E_rot[29].N = 19;\n E_rot[29].J = 19;\n E_rot[29].E = 546.7050;\n E_rot[30].N = 21;\n E_rot[30].J = 22;\n E_rot[30].E = 662.1030;\n E_rot[31].N = 21;\n E_rot[31].J = 20;\n E_rot[31].E = 662.4368;\n E_rot[32].N = 21;\n E_rot[32].J = 21;\n E_rot[32].E = 664.2610;\n E_rot[33].N = 23;\n E_rot[33].J = 24;\n E_rot[33].E = 791.0344;\n E_rot[34].N = 23;\n E_rot[34].J = 22;\n E_rot[34].E = 791.4045;\n E_rot[35].N = 23;\n E_rot[35].J = 23;\n E_rot[35].E = 793.2100;\n E_rot[36].N = 25;\n E_rot[36].J = 26;\n E_rot[36].E = 931.3390;\n E_rot[37].N = 25;\n E_rot[37].J = 24;\n E_rot[37].E = 931.7450;\n E_rot[38].N = 25;\n E_rot[38].J = 25;\n E_rot[38].E = 933.5330;\n E_rot[39].N = 27;\n E_rot[39].J = 28;\n E_rot[39].E = 1082.9941;\n E_rot[40].N = 27;\n E_rot[40].J = 26;\n E_rot[40].E = 1083.4356;\n E_rot[41].N = 27;\n E_rot[41].J = 27;\n E_rot[41].E = 1085.2060;\n E_rot[42].N = 29;\n E_rot[42].J = 30;\n E_rot[42].E = 1245.9750;\n E_rot[43].N = 29;\n E_rot[43].J = 28;\n E_rot[43].E = 1246.4518;\n E_rot[44].N = 29;\n E_rot[44].J = 29;\n E_rot[44].E = 1248.2040;\n E_rot[45].N = 31;\n E_rot[45].J = 32;\n E_rot[45].E = 1420.2552;\n E_rot[46].N = 31;\n E_rot[46].J = 30;\n E_rot[46].E = 1420.7672;\n E_rot[47].N = 31;\n E_rot[47].J = 31;\n E_rot[47].E = 1422.5020;\n E_rot[48].N = 33;\n E_rot[48].J = 34;\n E_rot[48].E = 1605.8064;\n E_rot[49].N = 33;\n E_rot[49].J = 32;\n E_rot[49].E = 1606.3533;\n E_rot[50].N = 33;\n E_rot[50].J = 33;\n E_rot[50].E = 1608.0710;\n E_rot[51].N = 35;\n E_rot[51].J = 36;\n E_rot[51].E = 1802.5983;\n E_rot[52].N = 35;\n E_rot[52].J = 34;\n E_rot[52].E = 1803.1802;\n E_rot[53].N = 35;\n E_rot[53].J = 35;\n E_rot[53].E = 1804.8810;\n\n /* \n N: Nuclear rotational angular momentum quantum number \n J: Total angular momentum quantum number\n E: Rotational energy of state in cm-1\n From Table A-3\n */\n int N_E_trans = 185;\n struct E_rot_trans_O2 Etr[N_E_trans];\n Etr[0].N = 33;\n Etr[0].J = 32;\n Etr[0].Np = 31;\n Etr[0].Jp = 30;\n Etr[0].E = 1606.3533;\n Etr[0].delta_E = -185.5861;\n Etr[0].cpt = 0.3630;\n Etr[1].N = 33;\n Etr[1].J = 33;\n Etr[1].Np = 31;\n Etr[1].Jp = 31;\n Etr[1].E = 1608.0710;\n Etr[1].delta_E = -185.5690;\n Etr[1].cpt = 0.3630;\n Etr[2].N = 33;\n Etr[2].J = 34;\n Etr[2].Np = 31;\n Etr[2].Jp = 32;\n Etr[2].E = 1605.8064;\n Etr[2].delta_E = -185.5512;\n Etr[2].cpt = 0.3637;\n Etr[3].N = 31;\n Etr[3].J = 30;\n Etr[3].Np = 29;\n Etr[3].Jp = 28;\n Etr[3].E = 1420.7672;\n Etr[3].delta_E = -174.3154;\n Etr[3].cpt = 0.3622;\n Etr[4].N = 31;\n Etr[4].J = 31;\n Etr[4].Np = 29;\n Etr[4].Jp = 29;\n Etr[4].E = 1422.5020;\n Etr[4].delta_E = -174.2980;\n Etr[4].cpt = 0.3622;\n Etr[5].N = 31;\n Etr[5].J = 32;\n Etr[5].Np = 29;\n Etr[5].Jp = 30;\n Etr[5].E = 1420.2552;\n Etr[5].delta_E = -174.2802;\n Etr[5].cpt = 0.3630;\n Etr[6].N = 29;\n Etr[6].J = 28;\n Etr[6].Np = 27;\n Etr[6].Jp = 26;\n Etr[6].E = 1246.4518;\n Etr[6].delta_E = -163.0162;\n Etr[6].cpt = 0.3613;\n Etr[7].N = 29;\n Etr[7].J = 29;\n Etr[7].Np = 27;\n Etr[7].Jp = 27;\n Etr[7].E = 1248.2040;\n Etr[7].delta_E = -162.9980;\n Etr[7].cpt = 0.3613;\n Etr[8].N = 29;\n Etr[8].J = 30;\n Etr[8].Np = 27;\n Etr[8].Jp = 28;\n Etr[8].E = 1245.9750;\n Etr[8].delta_E = -162.9809;\n Etr[8].cpt = 0.3622;\n Etr[9].N = 27;\n Etr[9].J = 26;\n Etr[9].Np = 25;\n Etr[9].Jp = 24;\n Etr[9].E = 1083.4355;\n Etr[9].delta_E = -151.6906;\n Etr[9].cpt = 0.3602;\n Etr[10].N = 27;\n Etr[10].J = 27;\n Etr[10].Np = 25;\n Etr[10].Jp = 25;\n Etr[10].E = 1085.2061;\n Etr[10].delta_E = -151.6730;\n Etr[10].cpt = 0.3602;\n Etr[11].N = 27;\n Etr[11].J = 28;\n Etr[11].Np = 25;\n Etr[11].Jp = 26;\n Etr[11].E = 1082.9941;\n Etr[11].delta_E = -151.6551;\n Etr[11].cpt = 0.3612;\n Etr[12].N = 25;\n Etr[12].J = 24;\n Etr[12].Np = 23;\n Etr[12].Jp = 22;\n Etr[12].E = 931.7450;\n Etr[12].delta_E = -140.3405;\n Etr[12].cpt = 0.3589;\n Etr[13].N = 25;\n Etr[13].J = 25;\n Etr[13].Np = 23;\n Etr[13].Jp = 23;\n Etr[13].E = 933.5330;\n Etr[13].delta_E = -140.3230;\n Etr[13].cpt = 0.3589;\n Etr[14].N = 25;\n Etr[14].J = 26;\n Etr[14].Np = 23;\n Etr[14].Jp = 24;\n Etr[14].E = 931.3390;\n Etr[14].delta_E = -140.3046;\n Etr[14].cpt = 0.3601;\n Etr[15].N = 23;\n Etr[15].J = 22;\n Etr[15].Np = 21;\n Etr[15].Jp = 20;\n Etr[15].E = 791.4045;\n Etr[15].delta_E = -128.9677;\n Etr[15].cpt = 0.3574;\n Etr[16].N = 23;\n Etr[16].J = 23;\n Etr[16].Np = 21;\n Etr[16].Jp = 21;\n Etr[16].E = 793.2100;\n Etr[16].delta_E = -128.9490;\n Etr[16].cpt = 0.3574;\n Etr[17].N = 23;\n Etr[17].J = 24;\n Etr[17].Np = 21;\n Etr[17].Jp = 22;\n Etr[17].E = 791.0344;\n Etr[17].delta_E = -128.9314;\n Etr[17].cpt = 0.3589;\n Etr[18].N = 21;\n Etr[18].J = 20;\n Etr[18].Np = 19;\n Etr[18].Jp = 18;\n Etr[18].E = 662.4368;\n Etr[18].delta_E = -117.5740;\n Etr[18].cpt = 0.3556;\n Etr[19].N = 21;\n Etr[19].J = 21;\n Etr[19].Np = 19;\n Etr[19].Jp = 19;\n Etr[19].E = 664.2610;\n Etr[19].delta_E = -117.5560;\n Etr[19].cpt = 0.3556;\n Etr[20].N = 21;\n Etr[20].J = 22;\n Etr[20].Np = 19;\n Etr[20].Jp = 20;\n Etr[20].E = 662.1030;\n Etr[20].delta_E = -117.5372;\n Etr[20].cpt = 0.3573;\n Etr[21].N = 19;\n Etr[21].J = 19;\n Etr[21].Np = 17;\n Etr[21].Jp = 18;\n Etr[21].E = 546.7050;\n Etr[21].delta_E = -108.2632;\n Etr[21].cpt = 0.0021;\n Etr[22].N = 19;\n Etr[22].J = 18;\n Etr[22].Np = 17;\n Etr[22].Jp = 16;\n Etr[22].E = 544.8628;\n Etr[22].delta_E = -106.1613;\n Etr[22].cpt = 0.3533;\n Etr[23].N = 19;\n Etr[23].J = 19;\n Etr[23].Np = 17;\n Etr[23].Jp = 17;\n Etr[23].E = 546.7050;\n Etr[23].delta_E = -106.1430;\n Etr[23].cpt = 0.3534;\n Etr[24].N = 19;\n Etr[24].J = 20;\n Etr[24].Np = 17;\n Etr[24].Jp = 18;\n Etr[24].E = 544.5658;\n Etr[24].delta_E = -106.1240;\n Etr[24].cpt = 0.3555;\n Etr[25].N = 19;\n Etr[25].J = 18;\n Etr[25].Np = 17;\n Etr[25].Jp = 17;\n Etr[25].E = 544.8628;\n Etr[25].delta_E = -104.3008;\n Etr[25].cpt = 0.0022;\n Etr[26].N = 17;\n Etr[26].J = 17;\n Etr[26].Np = 15;\n Etr[26].Jp = 16;\n Etr[26].E = 440.5620;\n Etr[26].delta_E = -96.8136;\n Etr[26].cpt = 0.0026;\n Etr[27].N = 17;\n Etr[27].J = 16;\n Etr[27].Np = 15;\n Etr[27].Jp = 14;\n Etr[27].E = 438.7015;\n Etr[27].delta_E = -94.7318;\n Etr[27].cpt = 0.3505;\n Etr[28].N = 17;\n Etr[28].J = 17;\n Etr[28].Np = 15;\n Etr[28].Jp = 15;\n Etr[28].E = 440.5620;\n Etr[28].delta_E = -94.7120;\n Etr[28].cpt = 0.3506;\n Etr[29].N = 17;\n Etr[29].J = 18;\n Etr[29].Np = 15;\n Etr[29].Jp = 16;\n Etr[29].E = 438.4418;\n Etr[29].delta_E = -94.6934;\n Etr[29].cpt = 0.3532;\n Etr[30].N = 17;\n Etr[30].J = 16;\n Etr[30].Np = 15;\n Etr[30].Jp = 15;\n Etr[30].E = 438.7015;\n Etr[30].delta_E = -92.8515;\n Etr[30].cpt = 0.0028;\n Etr[31].N = 15;\n Etr[31].J = 15;\n Etr[31].Np = 13;\n Etr[31].Jp = 14;\n Etr[31].E = 345.8500;\n Etr[31].delta_E = -85.3489;\n Etr[31].cpt = 0.0033;\n Etr[32].N = 15;\n Etr[32].J = 14;\n Etr[32].Np = 13;\n Etr[32].Jp = 12;\n Etr[32].E = 343.9697;\n Etr[32].delta_E = -83.2871;\n Etr[32].cpt = 0.3468;\n Etr[33].N = 15;\n Etr[33].J = 15;\n Etr[33].Np = 13;\n Etr[33].Jp = 13;\n Etr[33].E = 345.8500;\n Etr[33].delta_E = -83.2671;\n Etr[33].cpt = 0.3471;\n Etr[34].N = 15;\n Etr[34].J = 16;\n Etr[34].Np = 13;\n Etr[34].Jp = 14;\n Etr[34].E = 343.7484;\n Etr[34].delta_E = -83.2473;\n Etr[34].cpt = 0.3504;\n Etr[35].N = 15;\n Etr[35].J = 14;\n Etr[35].Np = 13;\n Etr[35].Jp = 13;\n Etr[35].E = 343.9697;\n Etr[35].delta_E = -81.3868;\n Etr[35].cpt = 0.0036;\n Etr[36].N = 13;\n Etr[36].J = 13;\n Etr[36].Np = 11;\n Etr[36].Jp = 12;\n Etr[36].E = 262.5829;\n Etr[36].delta_E = -73.8694;\n Etr[36].cpt = 0.0044;\n Etr[37].N = 13;\n Etr[37].J = 12;\n Etr[37].Np = 11;\n Etr[37].Jp = 10;\n Etr[37].E = 260.6826;\n Etr[37].delta_E = -71.8294;\n Etr[37].cpt = 0.3418;\n Etr[38].N = 13;\n Etr[38].J = 13;\n Etr[38].Np = 11;\n Etr[38].Jp = 11;\n Etr[38].E = 262.5829;\n Etr[38].delta_E = -71.8080;\n Etr[38].cpt = 0.3422;\n Etr[39].N = 13;\n Etr[39].J = 14;\n Etr[39].Np = 11;\n Etr[39].Jp = 12;\n Etr[39].E = 260.5011;\n Etr[39].delta_E = -71.7876;\n Etr[39].cpt = 0.3467;\n Etr[40].N = 13;\n Etr[40].J = 12;\n Etr[40].Np = 11;\n Etr[40].Jp = 11;\n Etr[40].E = 260.6826;\n Etr[40].delta_E = -69.9077;\n Etr[40].cpt = 0.0048;\n Etr[41].N = 11;\n Etr[41].J = 11;\n Etr[41].Np = 9;\n Etr[41].Jp = 10;\n Etr[41].E = 190.7749;\n Etr[41].delta_E = -62.3771;\n Etr[41].cpt = 0.0062;\n Etr[42].N = 11;\n Etr[42].J = 10;\n Etr[42].Np = 9;\n Etr[42].Jp = 9;\n Etr[42].E = 188.8532;\n Etr[42].delta_E = -60.3611;\n Etr[42].cpt = 0.3348;\n Etr[43].N = 11;\n Etr[43].J = 11;\n Etr[43].Np = 9;\n Etr[43].Jp = 9;\n Etr[43].E = 190.7749;\n Etr[43].delta_E = -60.3373;\n Etr[43].cpt = 0.3354;\n Etr[44].N = 11;\n Etr[44].J = 12;\n Etr[44].Np = 9;\n Etr[44].Jp = 10;\n Etr[44].E = 188.7135;\n Etr[44].delta_E = -60.3157;\n Etr[44].cpt = 0.3416;\n Etr[45].N = 11;\n Etr[45].J = 10;\n Etr[45].Np = 9;\n Etr[45].Jp = 9;\n Etr[45].E = 188.8532;\n Etr[45].delta_E = -58.4156;\n Etr[45].cpt = 0.0068;\n Etr[46].N = 9;\n Etr[46].J = 9;\n Etr[46].Np = 7;\n Etr[46].Jp = 8;\n Etr[46].E = 130.4376;\n Etr[46].delta_E = -50.8730;\n Etr[46].cpt = 0.0093;\n Etr[47].N = 9;\n Etr[47].J = 8;\n Etr[47].Np = 7;\n Etr[47].Jp = 6;\n Etr[47].E = 128.4921;\n Etr[47].delta_E = -48.8851;\n Etr[47].cpt = 0.3220;\n Etr[48].N = 9;\n Etr[48].J = 9;\n Etr[48].Np = 7;\n Etr[48].Jp = 7;\n Etr[48].E = 130.4376;\n Etr[48].delta_E = -48.8571;\n Etr[48].cpt = 0.3251;\n Etr[49].N = 9;\n Etr[49].J = 10;\n Etr[49].Np = 7;\n Etr[49].Jp = 8;\n Etr[49].E = 128.3978;\n Etr[49].delta_E = -48.8332;\n Etr[49].cpt = 0.3344;\n Etr[50].N = 9;\n Etr[50].J = 8;\n Etr[50].Np = 7;\n Etr[50].Jp = 7;\n Etr[50].E = 128.4921;\n Etr[50].delta_E = -46.9116;\n Etr[50].cpt = 0.0113;\n Etr[51].N = 5;\n Etr[51].J = 4;\n Etr[51].Np = 1;\n Etr[51].Jp = 2;\n Etr[51].E = 42.2001;\n Etr[51].delta_E = -40.1158;\n Etr[51].cpt = 0.0011;\n Etr[52].N = 7;\n Etr[52].J = 7;\n Etr[52].Np = 5;\n Etr[52].Jp = 6;\n Etr[52].E = 81.5805;\n Etr[52].delta_E = -39.3565;\n Etr[52].cpt = 0.0139;\n Etr[53].N = 7;\n Etr[53].J = 6;\n Etr[53].Np = 5;\n Etr[53].Jp = 4;\n Etr[53].E = 79.6070;\n Etr[53].delta_E = -37.4069;\n Etr[53].cpt = 0.3013;\n Etr[54].N = 7;\n Etr[54].J = 7;\n Etr[54].Np = 5;\n Etr[54].Jp = 5;\n Etr[54].E = 81.5805;\n Etr[54].delta_E = -37.3688;\n Etr[54].cpt = 0.3077;\n Etr[55].N = 7;\n Etr[55].J = 8;\n Etr[55].Np = 5;\n Etr[55].Jp = 6;\n Etr[55].E = 79.5646;\n Etr[55].delta_E = -37.3406;\n Etr[55].cpt = 0.3223;\n Etr[56].N = 7;\n Etr[56].J = 6;\n Etr[56].Np = 5;\n Etr[56].Jp = 5;\n Etr[56].E = 79.6070;\n Etr[56].delta_E = -35.3953;\n Etr[56].cpt = 0.0198;\n Etr[57].N = 5;\n Etr[57].J = 5;\n Etr[57].Np = 3;\n Etr[57].Jp = 4;\n Etr[57].E = 44.2117;\n Etr[57].delta_E = -27.8241;\n Etr[57].cpt = 0.0261;\n Etr[58].N = 5;\n Etr[58].J = 4;\n Etr[58].Np = 3;\n Etr[58].Jp = 2;\n Etr[58].E = 42.2001;\n Etr[58].delta_E = -25.9472;\n Etr[58].cpt = 0.2544;\n Etr[59].N = 5;\n Etr[59].J = 5;\n Etr[59].Np = 3;\n Etr[59].Jp = 3;\n Etr[59].E = 44.2117;\n Etr[59].delta_E = -25.8745;\n Etr[59].cpt = 0.2727;\n Etr[60].N = 5;\n Etr[60].J = 6;\n Etr[60].Np = 3;\n Etr[60].Jp = 4;\n Etr[60].E = 42.2240;\n Etr[60].delta_E = -25.8364;\n Etr[60].cpt = 0.3020;\n Etr[61].N = 5;\n Etr[61].J = 4;\n Etr[61].Np = 3;\n Etr[61].Jp = 4;\n Etr[61].E = 42.2001;\n Etr[61].delta_E = -25.8125;\n Etr[61].cpt = 0.0015;\n Etr[62].N = 5;\n Etr[62].J = 4;\n Etr[62].Np = 3;\n Etr[62].Jp = 3;\n Etr[62].E = 42.2001;\n Etr[62].delta_E = -23.8629;\n Etr[62].cpt = 0.0434;\n Etr[63].N = 3;\n Etr[63].J = 2;\n Etr[63].Np = 1;\n Etr[63].Jp = 0;\n Etr[63].E = 16.2529;\n Etr[63].delta_E = -16.2529;\n Etr[63].cpt = 0.0923;\n Etr[64].N = 3;\n Etr[64].J = 3;\n Etr[64].Np = 1;\n Etr[64].Jp = 2;\n Etr[64].E = 18.3372;\n Etr[64].delta_E = -16.2529;\n Etr[64].cpt = 0.0660;\n Etr[65].N = 3;\n Etr[65].J = 3;\n Etr[65].Np = 1;\n Etr[65].Jp = 1;\n Etr[65].E = 18.3372;\n Etr[65].delta_E = -14.3761;\n Etr[65].cpt = 0.1714;\n Etr[66].N = 3;\n Etr[66].J = 4;\n Etr[66].Np = 1;\n Etr[66].Jp = 2;\n Etr[66].E = 16.3876;\n Etr[66].delta_E = -14.3033;\n Etr[66].cpt = 0.2571;\n Etr[67].N = 3;\n Etr[67].J = 2;\n Etr[67].Np = 1;\n Etr[67].Jp = 2;\n Etr[67].E = 16.2529;\n Etr[67].delta_E = -14.1686;\n Etr[67].cpt = 0.0184;\n Etr[68].N = 3;\n Etr[68].J = 2;\n Etr[68].Np = 1;\n Etr[68].Jp = 1;\n Etr[68].E = 16.2529;\n Etr[68].delta_E = -12.2918;\n Etr[68].cpt = 0.1615;\n Etr[69].N = 19;\n Etr[69].J = 19;\n Etr[69].Np = 19;\n Etr[69].Jp = 20;\n Etr[69].E = 546.7050;\n Etr[69].delta_E = -2.1392;\n Etr[69].cpt = 0.0020;\n Etr[70].N = 17;\n Etr[70].J = 17;\n Etr[70].Np = 17;\n Etr[70].Jp = 18;\n Etr[70].E = 440.5620;\n Etr[70].delta_E = -2.1202;\n Etr[70].cpt = 0.0024;\n Etr[71].N = 15;\n Etr[71].J = 15;\n Etr[71].Np = 15;\n Etr[71].Jp = 16;\n Etr[71].E = 345.8500;\n Etr[71].delta_E = -2.1016;\n Etr[71].cpt = 0.0031;\n Etr[72].N = 1;\n Etr[72].J = 2;\n Etr[72].Np = 1;\n Etr[72].Jp = 0;\n Etr[72].E = 2.0843;\n Etr[72].delta_E = -2.0843;\n Etr[72].cpt = 0.1077;\n Etr[73].N = 3;\n Etr[73].J = 3;\n Etr[73].Np = 3;\n Etr[73].Jp = 2;\n Etr[73].E = 18.3372;\n Etr[73].delta_E = -2.0843;\n Etr[73].cpt = 0.0769;\n Etr[74].N = 13;\n Etr[74].J = 13;\n Etr[74].Np = 13;\n Etr[74].Jp = 14;\n Etr[74].E = 262.5829;\n Etr[74].delta_E = -2.0818;\n Etr[74].cpt = 0.0041;\n Etr[75].N = 11;\n Etr[75].J = 11;\n Etr[75].Np = 11;\n Etr[75].Jp = 12;\n Etr[75].E = 190.7749;\n Etr[75].delta_E = -2.0614;\n Etr[75].cpt = 0.0057;\n Etr[76].N = 9;\n Etr[76].J = 9;\n Etr[76].Np = 9;\n Etr[76].Jp = 10;\n Etr[76].E = 130.4376;\n Etr[76].delta_E = -2.0398;\n Etr[76].cpt = 0.0083;\n Etr[77].N = 7;\n Etr[77].J = 7;\n Etr[77].Np = 7;\n Etr[77].Jp = 8;\n Etr[77].E = 81.5805;\n Etr[77].delta_E = -2.0159;\n Etr[77].cpt = 0.0122;\n Etr[78].N = 5;\n Etr[78].J = 5;\n Etr[78].Np = 5;\n Etr[78].Jp = 4;\n Etr[78].E = 44.2117;\n Etr[78].delta_E = -2.0116;\n Etr[78].cpt = 0.0284;\n Etr[79].N = 5;\n Etr[79].J = 5;\n Etr[79].Np = 5;\n Etr[79].Jp = 6;\n Etr[79].E = 44.2117;\n Etr[79].delta_E = -1.9877;\n Etr[79].cpt = 0.0221;\n Etr[80].N = 7;\n Etr[80].J = 7;\n Etr[80].Np = 7;\n Etr[80].Jp = 6;\n Etr[80].E = 81.5805;\n Etr[80].delta_E = -1.9735;\n Etr[80].cpt = 0.0147;\n Etr[81].N = 3;\n Etr[81].J = 3;\n Etr[81].Np = 3;\n Etr[81].Jp = 4;\n Etr[81].E = 18.3372;\n Etr[81].delta_E = -1.9496;\n Etr[81].cpt = 0.0513;\n Etr[82].N = 9;\n Etr[82].J = 9;\n Etr[82].Np = 9;\n Etr[82].Jp = 8;\n Etr[82].E = 130.4376;\n Etr[82].delta_E = -1.9455;\n Etr[82].cpt = 0.0083;\n Etr[83].N = 11;\n Etr[83].J = 11;\n Etr[83].Np = 11;\n Etr[83].Jp = 10;\n Etr[83].E = 190.7749;\n Etr[83].delta_E = -1.9217;\n Etr[83].cpt = 0.0056;\n Etr[84].N = 13;\n Etr[84].J = 13;\n Etr[84].Np = 13;\n Etr[84].Jp = 12;\n Etr[84].E = 262.5829;\n Etr[84].delta_E = -1.9003;\n Etr[84].cpt = 0.0041;\n Etr[85].N = 15;\n Etr[85].J = 15;\n Etr[85].Np = 15;\n Etr[85].Jp = 14;\n Etr[85].E = 345.8500;\n Etr[85].delta_E = -1.8803;\n Etr[85].cpt = 0.0031;\n Etr[86].N = 1;\n Etr[86].J = 1;\n Etr[86].Np = 1;\n Etr[86].Jp = 2;\n Etr[86].E = 3.9611;\n Etr[86].delta_E = -1.8768;\n Etr[86].cpt = 0.2308;\n Etr[87].N = 17;\n Etr[87].J = 17;\n Etr[87].Np = 17;\n Etr[87].Jp = 16;\n Etr[87].E = 440.5620;\n Etr[87].delta_E = -1.8605;\n Etr[87].cpt = 0.0024;\n Etr[88].N = 19;\n Etr[88].J = 19;\n Etr[88].Np = 19;\n Etr[88].Jp = 18;\n Etr[88].E = 546.7050;\n Etr[88].delta_E = -1.8422;\n Etr[88].cpt = 0.0020;\n Etr[89].N = 3;\n Etr[89].J = 4;\n Etr[89].Np = 3;\n Etr[89].Jp = 2;\n Etr[89].E = 16.3876;\n Etr[89].delta_E = -0.1347;\n Etr[89].cpt = 0.0021;\n Etr[90].N = 3;\n Etr[90].J = 2;\n Etr[90].Np = 3;\n Etr[90].Jp = 4;\n Etr[90].E = 16.2529;\n Etr[90].delta_E = 0.1347;\n Etr[90].cpt = 0.0038;\n Etr[91].N = 19;\n Etr[91].J = 18;\n Etr[91].Np = 19;\n Etr[91].Jp = 19;\n Etr[91].E = 544.8628;\n Etr[91].delta_E = 1.8422;\n Etr[91].cpt = 0.0021;\n Etr[92].N = 17;\n Etr[92].J = 16;\n Etr[92].Np = 17;\n Etr[92].Jp = 17;\n Etr[92].E = 438.7015;\n Etr[92].delta_E = 1.8605;\n Etr[92].cpt = 0.0026;\n Etr[93].N = 1;\n Etr[93].J = 2;\n Etr[93].Np = 1;\n Etr[93].Jp = 1;\n Etr[93].E = 2.0843;\n Etr[93].delta_E = 1.8768;\n Etr[93].cpt = 0.1385;\n Etr[94].N = 15;\n Etr[94].J = 14;\n Etr[94].Np = 15;\n Etr[94].Jp = 15;\n Etr[94].E = 343.9697;\n Etr[94].delta_E = 1.8803;\n Etr[94].cpt = 0.0033;\n Etr[95].N = 13;\n Etr[95].J = 12;\n Etr[95].Np = 13;\n Etr[95].Jp = 13;\n Etr[95].E = 260.6826;\n Etr[95].delta_E = 1.9003;\n Etr[95].cpt = 0.0044;\n Etr[96].N = 11;\n Etr[96].J = 10;\n Etr[96].Np = 11;\n Etr[96].Jp = 11;\n Etr[96].E = 188.8532;\n Etr[96].delta_E = 1.9217;\n Etr[96].cpt = 0.0062;\n Etr[97].N = 9;\n Etr[97].J = 8;\n Etr[97].Np = 9;\n Etr[97].Jp = 9;\n Etr[97].E = 128.4921;\n Etr[97].delta_E = 1.9455;\n Etr[97].cpt = 0.0092;\n Etr[98].N = 3;\n Etr[98].J = 4;\n Etr[98].Np = 3;\n Etr[98].Jp = 3;\n Etr[98].E = 16.3876;\n Etr[98].delta_E = 1.9496;\n Etr[98].cpt = 0.0399;\n Etr[99].N = 7;\n Etr[99].J = 6;\n Etr[99].Np = 7;\n Etr[99].Jp = 7;\n Etr[99].E = 79.6070;\n Etr[99].delta_E = 1.9735;\n Etr[99].cpt = 0.0170;\n Etr[100].N = 5;\n Etr[100].J = 6;\n Etr[100].Np = 5;\n Etr[100].Jp = 5;\n Etr[100].E = 42.2240;\n Etr[100].delta_E = 1.9877;\n Etr[100].cpt = 0.0187;\n Etr[101].N = 5;\n Etr[101].J = 4;\n Etr[101].Np = 5;\n Etr[101].Jp = 5;\n Etr[101].E = 42.2001;\n Etr[101].delta_E = 2.0116;\n Etr[101].cpt = 0.0347;\n Etr[102].N = 7;\n Etr[102].J = 8;\n Etr[102].Np = 7;\n Etr[102].Jp = 7;\n Etr[102].E = 79.5646;\n Etr[102].delta_E = 2.0159;\n Etr[102].cpt = 0.0108;\n Etr[103].N = 9;\n Etr[103].J = 10;\n Etr[103].Np = 9;\n Etr[103].Jp = 9;\n Etr[103].E = 128.3978;\n Etr[103].delta_E = 2.0398;\n Etr[103].cpt = 0.0075;\n Etr[104].N = 11;\n Etr[104].J = 12;\n Etr[104].Np = 11;\n Etr[104].Jp = 11;\n Etr[104].E = 188.7135;\n Etr[104].delta_E = 2.0614;\n Etr[104].cpt = 0.0052;\n Etr[105].N = 13;\n Etr[105].J = 14;\n Etr[105].Np = 13;\n Etr[105].Jp = 13;\n Etr[105].E = 260.5011;\n Etr[105].delta_E = 2.0818;\n Etr[105].cpt = 0.0038;\n Etr[106].N = 1;\n Etr[106].J = 0;\n Etr[106].Np = 1;\n Etr[106].Jp = 2;\n Etr[106].E = 0.0000;\n Etr[106].delta_E = 2.0843;\n Etr[106].cpt = 0.5383;\n Etr[107].N = 3;\n Etr[107].J = 2;\n Etr[107].Np = 3;\n Etr[107].Jp = 3;\n Etr[107].E = 16.2529;\n Etr[107].delta_E = 2.0843;\n Etr[107].cpt = 0.1077;\n Etr[108].N = 15;\n Etr[108].J = 16;\n Etr[108].Np = 15;\n Etr[108].Jp = 15;\n Etr[108].E = 343.7484;\n Etr[108].delta_E = 2.1016;\n Etr[108].cpt = 0.0029;\n Etr[109].N = 17;\n Etr[109].J = 18;\n Etr[109].Np = 17;\n Etr[109].Jp = 17;\n Etr[109].E = 438.4418;\n Etr[109].delta_E = 2.1202;\n Etr[109].cpt = 0.0023;\n Etr[110].N = 19;\n Etr[110].J = 20;\n Etr[110].Np = 19;\n Etr[110].Jp = 19;\n Etr[110].E = 544.5658;\n Etr[110].delta_E = 2.1392;\n Etr[110].cpt = 0.0019;\n Etr[111].N = 1;\n Etr[111].J = 1;\n Etr[111].Np = 3;\n Etr[111].Jp = 2;\n Etr[111].E = 3.9611;\n Etr[111].delta_E = 12.2918;\n Etr[111].cpt = 0.2692;\n Etr[112].N = 1;\n Etr[112].J = 2;\n Etr[112].Np = 3;\n Etr[112].Jp = 2;\n Etr[112].E = 2.0843;\n Etr[112].delta_E = 14.1686;\n Etr[112].cpt = 0.0184;\n Etr[113].N = 1;\n Etr[113].J = 2;\n Etr[113].Np = 3;\n Etr[113].Jp = 4;\n Etr[113].E = 2.0843;\n Etr[113].delta_E = 14.3033;\n Etr[113].cpt = 0.4628;\n Etr[114].N = 1;\n Etr[114].J = 1;\n Etr[114].Np = 3;\n Etr[114].Jp = 3;\n Etr[114].E = 3.9611;\n Etr[114].delta_E = 14.3761;\n Etr[114].cpt = 0.4000;\n Etr[115].N = 1;\n Etr[115].J = 0;\n Etr[115].Np = 3;\n Etr[115].Jp = 2;\n Etr[115].E = 0.0000;\n Etr[115].delta_E = 16.2529;\n Etr[115].cpt = 0.4617;\n Etr[116].N = 1;\n Etr[116].J = 2;\n Etr[116].Np = 3;\n Etr[116].Jp = 3;\n Etr[116].E = 2.0843;\n Etr[116].delta_E = 16.2529;\n Etr[116].cpt = 0.0923;\n Etr[117].N = 3;\n Etr[117].J = 3;\n Etr[117].Np = 5;\n Etr[117].Jp = 4;\n Etr[117].E = 18.3372;\n Etr[117].delta_E = 23.8629;\n Etr[117].cpt = 0.0558;\n Etr[118].N = 3;\n Etr[118].J = 4;\n Etr[118].Np = 5;\n Etr[118].Jp = 4;\n Etr[118].E = 16.3876;\n Etr[118].delta_E = 25.8125;\n Etr[118].cpt = 0.0015;\n Etr[119].N = 3;\n Etr[119].J = 4;\n Etr[119].Np = 5;\n Etr[119].Jp = 6;\n Etr[119].E = 16.3876;\n Etr[119].delta_E = 25.8364;\n Etr[119].cpt = 0.4362;\n Etr[120].N = 3;\n Etr[120].J = 3;\n Etr[120].Np = 5;\n Etr[120].Jp = 5;\n Etr[120].E = 18.3372;\n Etr[120].delta_E = 25.8745;\n Etr[120].cpt = 0.4286;\n Etr[121].N = 3;\n Etr[121].J = 2;\n Etr[121].Np = 5;\n Etr[121].Jp = 4;\n Etr[121].E = 16.2529;\n Etr[121].delta_E = 25.9472;\n Etr[121].cpt = 0.4579;\n Etr[122].N = 3;\n Etr[122].J = 4;\n Etr[122].Np = 5;\n Etr[122].Jp = 5;\n Etr[122].E = 16.3876;\n Etr[122].delta_E = 27.8241;\n Etr[122].cpt = 0.0319;\n Etr[123].N = 5;\n Etr[123].J = 5;\n Etr[123].Np = 7;\n Etr[123].Jp = 6;\n Etr[123].E = 44.2117;\n Etr[123].delta_E = 35.3953;\n Etr[123].cpt = 0.0234;\n Etr[124].N = 5;\n Etr[124].J = 6;\n Etr[124].Np = 7;\n Etr[124].Jp = 8;\n Etr[124].E = 42.2240;\n Etr[124].delta_E = 37.3406;\n Etr[124].cpt = 0.4214;\n Etr[125].N = 5;\n Etr[125].J = 5;\n Etr[125].Np = 7;\n Etr[125].Jp = 7;\n Etr[125].E = 44.2117;\n Etr[125].delta_E = 37.3688;\n Etr[125].cpt = 0.4196;\n Etr[126].N = 5;\n Etr[126].J = 4;\n Etr[126].Np = 7;\n Etr[126].Jp = 6;\n Etr[126].E = 42.2001;\n Etr[126].delta_E = 37.4069;\n Etr[126].cpt = 0.4352;\n Etr[127].N = 5;\n Etr[127].J = 6;\n Etr[127].Np = 7;\n Etr[127].Jp = 7;\n Etr[127].E = 42.2240;\n Etr[127].delta_E = 39.3565;\n Etr[127].cpt = 0.0160;\n Etr[128].N = 1;\n Etr[128].J = 2;\n Etr[128].Np = 5;\n Etr[128].Jp = 4;\n Etr[128].E = 2.0843;\n Etr[128].delta_E = 40.1158;\n Etr[128].cpt = 0.0019;\n Etr[129].N = 7;\n Etr[129].J = 7;\n Etr[129].Np = 9;\n Etr[129].Jp = 8;\n Etr[129].E = 81.5805;\n Etr[129].delta_E = 46.9116;\n Etr[129].cpt = 0.0128;\n Etr[130].N = 7;\n Etr[130].J = 8;\n Etr[130].Np = 9;\n Etr[130].Jp = 10;\n Etr[130].E = 79.5646;\n Etr[130].delta_E = 48.8332;\n Etr[130].cpt = 0.4130;\n Etr[131].N = 7;\n Etr[131].J = 7;\n Etr[131].Np = 9;\n Etr[131].Jp = 9;\n Etr[131].E = 81.5805;\n Etr[131].delta_E = 48.8571;\n Etr[131].cpt = 0.4118;\n Etr[132].N = 7;\n Etr[132].J = 6;\n Etr[132].Np = 9;\n Etr[132].Jp = 8;\n Etr[132].E = 79.6070;\n Etr[132].delta_E = 48.8851;\n Etr[132].cpt = 0.4210;\n Etr[133].N = 7;\n Etr[133].J = 8;\n Etr[133].Np = 9;\n Etr[133].Jp = 9;\n Etr[133].E = 79.5646;\n Etr[133].delta_E = 50.8730;\n Etr[133].cpt = 0.0104;\n Etr[134].N = 9;\n Etr[134].J = 9;\n Etr[134].Np = 11;\n Etr[134].Jp = 10;\n Etr[134].E = 130.4376;\n Etr[134].delta_E = 58.4156;\n Etr[134].cpt = 0.0075;\n Etr[135].N = 9;\n Etr[135].J = 10;\n Etr[135].Np = 11;\n Etr[135].Jp = 12;\n Etr[135].E = 128.3978;\n Etr[135].delta_E = 60.3157;\n Etr[135].cpt = 0.4067;\n Etr[136].N = 9;\n Etr[136].J = 9;\n Etr[136].Np = 11;\n Etr[136].Jp = 11;\n Etr[136].E = 130.4376;\n Etr[136].delta_E = 60.3373;\n Etr[136].cpt = 0.4060;\n Etr[137].N = 9;\n Etr[137].J = 8;\n Etr[137].Np = 11;\n Etr[137].Jp = 10;\n Etr[137].E = 128.4921;\n Etr[137].delta_E = 60.3611;\n Etr[137].cpt = 0.4135;\n Etr[138].N = 9;\n Etr[138].J = 10;\n Etr[138].Np = 11;\n Etr[138].Jp = 11;\n Etr[138].E = 128.3978;\n Etr[138].delta_E = 62.3771;\n Etr[138].cpt = 0.0068;\n Etr[139].N = 11;\n Etr[139].J = 11;\n Etr[139].Np = 13;\n Etr[139].Jp = 12;\n Etr[139].E = 190.7749;\n Etr[139].delta_E = 69.9077;\n Etr[139].cpt = 0.0052;\n Etr[140].N = 11;\n Etr[140].J = 12;\n Etr[140].Np = 13;\n Etr[140].Jp = 14;\n Etr[140].E = 188.7135;\n Etr[140].delta_E = 71.7876;\n Etr[140].cpt = 0.4021;\n Etr[141].N = 11;\n Etr[141].J = 11;\n Etr[141].Np = 13;\n Etr[141].Jp = 13;\n Etr[141].E = 190.7749;\n Etr[141].delta_E = 71.8080;\n Etr[141].cpt = 0.4017;\n Etr[142].N = 11;\n Etr[142].J = 10;\n Etr[142].Np = 13;\n Etr[142].Jp = 12;\n Etr[142].E = 188.8532;\n Etr[142].delta_E = 71.8294;\n Etr[142].cpt = 0.4070;\n Etr[143].N = 11;\n Etr[143].J = 12;\n Etr[143].Np = 13;\n Etr[143].Jp = 13;\n Etr[143].E = 188.7135;\n Etr[143].delta_E = 73.8694;\n Etr[143].cpt = 0.0048;\n Etr[144].N = 13;\n Etr[144].J = 13;\n Etr[144].Np = 15;\n Etr[144].Jp = 14;\n Etr[144].E = 262.5829;\n Etr[144].delta_E = 81.3868;\n Etr[144].cpt = 0.0038;\n Etr[145].N = 13;\n Etr[145].J = 14;\n Etr[145].Np = 15;\n Etr[145].Jp = 16;\n Etr[145].E = 260.5011;\n Etr[145].delta_E = 83.2473;\n Etr[145].cpt = 0.3987;\n Etr[146].N = 13;\n Etr[146].J = 13;\n Etr[146].Np = 15;\n Etr[146].Jp = 15;\n Etr[146].E = 262.5829;\n Etr[146].delta_E = 83.2671;\n Etr[146].cpt = 0.3985;\n Etr[147].N = 13;\n Etr[147].J = 12;\n Etr[147].Np = 15;\n Etr[147].Jp = 14;\n Etr[147].E = 260.6826;\n Etr[147].delta_E = 83.2871;\n Etr[147].cpt = 0.4023;\n Etr[148].N = 13;\n Etr[148].J = 14;\n Etr[148].Np = 15;\n Etr[148].Jp = 15;\n Etr[148].E = 260.5011;\n Etr[148].delta_E = 85.3489;\n Etr[148].cpt = 0.0036;\n Etr[149].N = 15;\n Etr[149].J = 15;\n Etr[149].Np = 17;\n Etr[149].Jp = 16;\n Etr[149].E = 345.8500;\n Etr[149].delta_E = 92.8515;\n Etr[149].cpt = 0.0029;\n Etr[150].N = 15;\n Etr[150].J = 16;\n Etr[150].Np = 17;\n Etr[150].Jp = 18;\n Etr[150].E = 343.7484;\n Etr[150].delta_E = 94.6934;\n Etr[150].cpt = 0.3961;\n Etr[151].N = 15;\n Etr[151].J = 15;\n Etr[151].Np = 17;\n Etr[151].Jp = 17;\n Etr[151].E = 345.8500;\n Etr[151].delta_E = 94.7120;\n Etr[151].cpt = 0.3959;\n Etr[152].N = 15;\n Etr[152].J = 14;\n Etr[152].Np = 17;\n Etr[152].Jp = 16;\n Etr[152].E = 343.9697;\n Etr[152].delta_E = 94.7318;\n Etr[152].cpt = 0.3988;\n Etr[153].N = 15;\n Etr[153].J = 16;\n Etr[153].Np = 17;\n Etr[153].Jp = 17;\n Etr[153].E = 343.7484;\n Etr[153].delta_E = 96.8136;\n Etr[153].cpt = 0.0028;\n Etr[154].N = 17;\n Etr[154].J = 17;\n Etr[154].Np = 19;\n Etr[154].Jp = 18;\n Etr[154].E = 440.5620;\n Etr[154].delta_E = 104.3008;\n Etr[154].cpt = 0.0023;\n Etr[155].N = 17;\n Etr[155].J = 18;\n Etr[155].Np = 19;\n Etr[155].Jp = 20;\n Etr[155].E = 438.4418;\n Etr[155].delta_E = 106.1240;\n Etr[155].cpt = 0.3939;\n Etr[156].N = 17;\n Etr[156].J = 17;\n Etr[156].Np = 19;\n Etr[156].Jp = 19;\n Etr[156].E = 440.5620;\n Etr[156].delta_E = 106.1430;\n Etr[156].cpt = 0.3938;\n Etr[157].N = 17;\n Etr[157].J = 16;\n Etr[157].Np = 19;\n Etr[157].Jp = 18;\n Etr[157].E = 438.7015;\n Etr[157].delta_E = 106.1613;\n Etr[157].cpt = 0.3961;\n Etr[158].N = 17;\n Etr[158].J = 18;\n Etr[158].Np = 19;\n Etr[158].Jp = 19;\n Etr[158].E = 438.4418;\n Etr[158].delta_E = 108.2632;\n Etr[158].cpt = 0.0022;\n Etr[159].N = 19;\n Etr[159].J = 19;\n Etr[159].Np = 21;\n Etr[159].Jp = 20;\n Etr[159].E = 546.7050;\n Etr[159].delta_E = 115.7318;\n Etr[159].cpt = 0.0019;\n Etr[160].N = 19;\n Etr[160].J = 20;\n Etr[160].Np = 21;\n Etr[160].Jp = 22;\n Etr[160].E = 544.5658;\n Etr[160].delta_E = 117.5372;\n Etr[160].cpt = 0.3922;\n Etr[161].N = 19;\n Etr[161].J = 19;\n Etr[161].Np = 21;\n Etr[161].Jp = 21;\n Etr[161].E = 546.7050;\n Etr[161].delta_E = 117.5560;\n Etr[161].cpt = 0.3921;\n Etr[162].N = 19;\n Etr[162].J = 18;\n Etr[162].Np = 21;\n Etr[162].Jp = 20;\n Etr[162].E = 544.8628;\n Etr[162].delta_E = 117.5740;\n Etr[162].cpt = 0.3940;\n Etr[163].N = 19;\n Etr[163].J = 20;\n Etr[163].Np = 21;\n Etr[163].Jp = 21;\n Etr[163].E = 544.5658;\n Etr[163].delta_E = 119.6952;\n Etr[163].cpt = 0.0018;\n Etr[164].N = 21;\n Etr[164].J = 22;\n Etr[164].Np = 23;\n Etr[164].Jp = 24;\n Etr[164].E = 662.1030;\n Etr[164].delta_E = 128.9314;\n Etr[164].cpt = 0.3908;\n Etr[165].N = 21;\n Etr[165].J = 21;\n Etr[165].Np = 23;\n Etr[165].Jp = 23;\n Etr[165].E = 664.2610;\n Etr[165].delta_E = 128.9490;\n Etr[165].cpt = 0.3907;\n Etr[166].N = 21;\n Etr[166].J = 20;\n Etr[166].Np = 23;\n Etr[166].Jp = 22;\n Etr[166].E = 662.4368;\n Etr[166].delta_E = 128.9677;\n Etr[166].cpt = 0.3922;\n Etr[167].N = 23;\n Etr[167].J = 24;\n Etr[167].Np = 25;\n Etr[167].Jp = 26;\n Etr[167].E = 791.0344;\n Etr[167].delta_E = 140.3046;\n Etr[167].cpt = 0.3895;\n Etr[168].N = 23;\n Etr[168].J = 23;\n Etr[168].Np = 25;\n Etr[168].Jp = 25;\n Etr[168].E = 793.2100;\n Etr[168].delta_E = 140.3230;\n Etr[168].cpt = 0.3895;\n Etr[169].N = 23;\n Etr[169].J = 22;\n Etr[169].Np = 25;\n Etr[169].Jp = 24;\n Etr[169].E = 791.4045;\n Etr[169].delta_E = 140.3405;\n Etr[169].cpt = 0.3908;\n Etr[170].N = 25;\n Etr[170].J = 26;\n Etr[170].Np = 27;\n Etr[170].Jp = 28;\n Etr[170].E = 931.3390;\n Etr[170].delta_E = 151.6551;\n Etr[170].cpt = 0.3885;\n Etr[171].N = 25;\n Etr[171].J = 25;\n Etr[171].Np = 27;\n Etr[171].Jp = 27;\n Etr[171].E = 933.5330;\n Etr[171].delta_E = 151.6730;\n Etr[171].cpt = 0.3885;\n Etr[172].N = 25;\n Etr[172].J = 24;\n Etr[172].Np = 27;\n Etr[172].Jp = 26;\n Etr[172].E = 931.7450;\n Etr[172].delta_E = 151.6906;\n Etr[172].cpt = 0.3896;\n Etr[173].N = 27;\n Etr[173].J = 28;\n Etr[173].Np = 29;\n Etr[173].Jp = 30;\n Etr[173].E = 1082.9941;\n Etr[173].delta_E = 162.9809;\n Etr[173].cpt = 0.3876;\n Etr[174].N = 27;\n Etr[174].J = 27;\n Etr[174].Np = 29;\n Etr[174].Jp = 29;\n Etr[174].E = 1085.2061;\n Etr[174].delta_E = 162.9980;\n Etr[174].cpt = 0.3876;\n Etr[175].N = 27;\n Etr[175].J = 26;\n Etr[175].Np = 29;\n Etr[175].Jp = 28;\n Etr[175].E = 1083.4355;\n Etr[175].delta_E = 163.0162;\n Etr[175].cpt = 0.3885;\n Etr[176].N = 29;\n Etr[176].J = 30;\n Etr[176].Np = 31;\n Etr[176].Jp = 32;\n Etr[176].E = 1245.9750;\n Etr[176].delta_E = 174.2802;\n Etr[176].cpt = 0.3868;\n Etr[177].N = 29;\n Etr[177].J = 29;\n Etr[177].Np = 31;\n Etr[177].Jp = 31;\n Etr[177].E = 1248.2040;\n Etr[177].delta_E = 174.2980;\n Etr[177].cpt = 0.3868;\n Etr[178].N = 29;\n Etr[178].J = 28;\n Etr[178].Np = 31;\n Etr[178].Jp = 30;\n Etr[178].E = 1246.4518;\n Etr[178].delta_E = 174.3154;\n Etr[178].cpt = 0.3876;\n Etr[179].N = 31;\n Etr[179].J = 32;\n Etr[179].Np = 33;\n Etr[179].Jp = 34;\n Etr[179].E = 1420.2552;\n Etr[179].delta_E = 185.5512;\n Etr[179].cpt = 0.3861;\n Etr[180].N = 31;\n Etr[180].J = 31;\n Etr[180].Np = 33;\n Etr[180].Jp = 33;\n Etr[180].E = 1422.5020;\n Etr[180].delta_E = 185.5690;\n Etr[180].cpt = 0.3861;\n Etr[181].N = 31;\n Etr[181].J = 30;\n Etr[181].Np = 33;\n Etr[181].Jp = 32;\n Etr[181].E = 1420.7672;\n Etr[181].delta_E = 185.5861;\n Etr[181].cpt = 0.3868;\n Etr[182].N = 33;\n Etr[182].J = 34;\n Etr[182].Np = 35;\n Etr[182].Jp = 36;\n Etr[182].E = 1605.8064;\n Etr[182].delta_E = 196.7919;\n Etr[182].cpt = 0.3855;\n Etr[183].N = 33;\n Etr[183].J = 33;\n Etr[183].Np = 35;\n Etr[183].Jp = 35;\n Etr[183].E = 1608.0710;\n Etr[183].delta_E = 196.8100;\n Etr[183].cpt = 0.3855;\n Etr[184].N = 33;\n Etr[184].J = 32;\n Etr[184].Np = 35;\n Etr[184].Jp = 34;\n Etr[184].E = 1606.3533;\n Etr[184].delta_E = 196.8269;\n Etr[184].cpt = 0.3861;\n\n double E_J = 0; /* Rotational energy of state J */\n double W_J = 0; /* Fraction of molecules in the rotational state J at temperature T */\n double b_J = 0; /* Placzek-Teller coefficient */\n double lambda_inv_cm = 0, lambda_cm = 0, lambda_shifted_inv_cm = 0, lambda_shifted_nm = 0, lambda_shifted_cm = 0;\n double delta_nu = 0;\n double crs_i = 0, crs_j = 0;\n double fNJ = 0, Z = 0; /* Eq 5 and 10 */\n double gam_i = 0, gam_j = 0;\n double volume_mixing_ratio = 0.2095;\n double sum = 0;\n\n int J = 0; /* Rotational state J */\n int g_J = 0;\n int is = 0;\n\n int status = 0;\n int ivi = 0;\n\n if (verbose) {\n fprintf (stderr, \"Calculating Raman scattering wavelength shifts and cross sections \");\n fprintf (stderr,\n \"for O2, wavelength %5.1f nm, number of transitions %d, T=%6.2f, iv=%d.\\n\",\n lambda,\n n_transitions,\n temper,\n *iv);\n fprintf (stderr,\n \" %3s %1s %7s %8s %7s %9s %10s %9s %17s %9s %12s %7s %12s %12s %11s %14s %12s\\n\",\n \"ivi\",\n \"J\",\n \"E_J\",\n \"g_J\",\n \"W_J\",\n \"b_J\",\n \"W_J*b_J\",\n \"wvl\",\n \"wvl_shift_cm-1\",\n \"delta_nu\",\n \"wvl_shift_nm\",\n \"gam_i\",\n \"gam_j\",\n \"crs_i\",\n \"crs_j\",\n \"crs_i*vmr\",\n \"crs_j*vmr\");\n }\n\n ivi = *iv;\n\n sum = 0;\n for (is = 0; is < N_E; is++) {\n g_J = 1; /* Only states for odd J are included in the summation */\n J = E_rot[is].J;\n E_J = E_rot[is].E * hc;\n sum += g_J * (2 * J + 1) * exp (-E_J / (BOLTZMANN * temper));\n }\n Z = sum;\n /* fprintf(stderr,\" %13.6e\", Z); */\n\n for (is = 0; is < n_transitions; is++) {\n g_J = 1; /* Only states for odd J are included in the summation */\n J = Etr[is].J;\n E_J = Etr[is].E * hc;\n W_J = g_J * (2 * J + 1) * exp (-E_J / (BOLTZMANN * temper));\n fNJ = W_J / Z;\n b_J = Etr[is].cpt;\n\n delta_nu = -Etr[is].delta_E; /* Negative delta_E corresponds to a photon with a larger */\n /* energy, shorter wavelength than the incident photon */\n /* delta_E is the change in rotational energy of the */\n /* molecule. The minus puts the photon in the right */\n /* wavelength. */\n\n lambda_inv_cm = nm_to_inv_cm (lambda);\n lambda_shifted_inv_cm = lambda_inv_cm + delta_nu;\n lambda_shifted_nm = inv_cm_to_nm (lambda_shifted_inv_cm);\n lambda_shifted_cm = lambda_shifted_nm * nm_to_cm;\n lambda_cm = lambda * nm_to_cm;\n gam_i = polarizability_anisotropy_O2 (lambda_shifted_inv_cm);\n gam_j = polarizability_anisotropy_O2 (lambda_inv_cm);\n crs_i = fNJ * gam_i * gam_i * raman_const * b_J / pow (lambda_shifted_cm, 4);\n crs_j = fNJ * gam_j * gam_j * raman_const * b_J / pow (lambda_cm, 4);\n (*crs)[ivi][0] = lambda_shifted_nm;\n (*crs)[ivi][1] = crs_i * volume_mixing_ratio;\n (*crs)[ivi][2] = crs_j * volume_mixing_ratio;\n if (verbose)\n fprintf (stderr,\n \"Raman_crs_O2 %2d %2d %12.6e %2d %12.6e %6.3f %12.6e %10.6f %10.6f %10.4f %10.6f %12.6e %12.6e %12.6e %12.6e %12.6e \"\n \"%12.6e\\n\",\n ivi,\n J,\n E_J,\n g_J,\n W_J,\n b_J,\n W_J * b_J,\n lambda,\n lambda_shifted_inv_cm,\n delta_nu,\n lambda_shifted_nm,\n gam_i,\n gam_j,\n crs_i,\n crs_j,\n crs_i * volume_mixing_ratio,\n crs_j * volume_mixing_ratio);\n ivi++;\n }\n\n *iv = ivi;\n\n return status;\n}\n\n/***********************************************************************************/\n/* Function: dewpoint */\n/* Description: */\n/* Calculates the dewpoint temperature in K */\n/* */\n/* Parameters: */\n/* float press_h2o partial pressure of water vapour in hPa */\n/* Return value: */\n/* float dewpoint dewpoint temperature in K */\n/* */\n/* Example: */\n/* Files: ancillary.c */\n/* Known bugs: - */\n/* Author: */\n/* Jan 2009 U. Hamann converted from Fortran to C (see wvapour.f) */\n/* */\n/***********************************************************************************/\n\nfloat dewpoint (float press_h2o) {\n float dewpoint = NOT_DEFINED_FLOAT;\n\n if (press_h2o != 0.0) {\n\n press_h2o = log (press_h2o);\n dewpoint = 273.15 + (243.5 * press_h2o - 440.8) / (19.48 - press_h2o);\n } else {\n dewpoint = 0.0; /* 0 Kelvin */\n }\n return dewpoint;\n}\n\n/***********************************************************************************/\n/* Function: Tcon */\n/* Description: */\n/* THIS FUNCTION RETURNS THE TEMPERATURE TCON (CELSIUS) AT */\n/* THE LIFTING CONDENSATION LEVEL, GIVEN THE TEMPERATURE T (CELSIUS) */\n/* AND THE DEW POINT D (CELSIUS). */\n/* */\n/* Parameters: */\n/* T - REAL TEMPERATURE (K) */\n/* TD - REAL DEWPOINT TEMPERATURE (K) */\n/* Return value: */\n/* float Tcon temperature at the lifting condensation level (CELSIUS) */\n/* */\n/* Example: */\n/* Files: ancillary.c */\n/* Known bugs: - */\n/* Author: */\n/* May 1982 D. Baker, T. Schlatter original version */\n/* Jan 2009 U. Hamann converted from Fortran to C (see wvapour.f) */\n/* change Celsius to Kelvin */\n/* */\n/***********************************************************************************/\n\nfloat Tcon (float T, float TD) {\n float S = NOT_DEFINED_FLOAT;\n float dT = NOT_DEFINED_FLOAT;\n float Tcon = NOT_DEFINED_FLOAT;\n\n /* compute the dew point depression S. */\n S = T - TD;\n /* the approximation below, a third order polynomial in S and T, */\n /* is due to herman wobus. the source of data for fitting the */\n /* polynomial is unknown. */\n\n dT = S * (1.2185 + 1.278e-3 * (T - 273.15) + S * (-2.19e-3 + 1.173e-5 * S - 5.2e-6 * (T - 273.15)));\n Tcon = T - dT;\n return Tcon;\n}\n\n/***********************************************************************************/\n/* Function: EPT */\n/* Description: */\n/* This function returns the equivalent potential temperature EPT */\n/* (Celsius) for a parcel of air initially at temperature t (celsius), */\n/* dew point Td (celsius) and pressure p (millibars). The formula used */\n/* is eq.(43) in Bolton, David, 1980: \"the computation of equivalent */\n/* potential temperature,\" Monthly Weather Review, vol. 108, no. 7 */\n/* (july), pp. 1046-1053. the maximum error in ept in 0.3c. in most */\n/* cases the error is less than 0.1c. */\n/* */\n/* Parameters: */\n/* T - REAL TEMPERATURE (K) */\n/* TD - REAL DEWPOINT TEMPERATURE (K) */\n/* p - REAL PRESSURE (hPa) */\n/* Return value: */\n/* float EPT equivalent potential temperature (CELSIUS) */\n/* */\n/* Example: */\n/* Files: ancillary.c */\n/* Known bugs: - */\n/* Author: */\n/* May 1982 T. Schlatter original version */\n/* Jan 2009 U. Hamann converted from Fortran to C (see wvapour.f) */\n/* replaced function WMR by real calculaton */\n/* change Celsius to Kelvin */\n/* */\n/***********************************************************************************/\n\nfloat EPT (float T, float TD, float p, float N_AIR, float N_H2O) {\n\n float kappa = (C_P_DRY_STD - C_V_DRY_STD) / C_P_DRY_STD;\n float W = NOT_DEFINED_FLOAT;\n float TL = NOT_DEFINED_FLOAT;\n float PT = NOT_DEFINED_FLOAT;\n float EPT = NOT_DEFINED_FLOAT;\n\n /* replaced the wmr (compute the water mixing ratio) function as */\n /* it is not valid for all wanted temperatures and pressures !!! */\n /* 1000 == kg(water)/kg(dry air) -> g(water)/kg(dry air) */\n W = N_H2O * MOL_MASS_WV / (N_AIR * MOL_MASS_AIR) * 1000.;\n\n /* compute the temperature (celsius) at the lifting condensation level. */\n TL = Tcon (T, TD);\n PT = T * pow (1000. / p, kappa * (1. - 0.00028 * W));\n EPT = PT * exp ((3.376 / TL - 0.00254) * W * (1. + 0.00081 * W));\n\n return EPT;\n}\n", "meta": {"hexsha": "c128ed21b5192897ba52c0c7c4c9738fd2781e5e", "size": 598888, "ext": "c", "lang": "C", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/ancillary.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/ancillary.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/ancillary.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": 38.287175553, "max_line_length": 180, "alphanum_fraction": 0.4928968355, "num_tokens": 175964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.2628418489200747, "lm_q1q2_score": 0.15478470793995264}} {"text": "/*\n# Program to run a Monte Carlo radiation transfer through the 2D\n# simulations of GRB jets.\n#\n# Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State \n# ver 0.1 July 8, 2015\n# ver 1.1 July 20, 2015: added record of number of scatterings, included\n# \tall terms in weight. Should now give correct light curves.\n# ver 1.2 July 21, 2015: added parameter file to keep track of input\n# \tparams of each simulation\n\n# ver 2.0 July 22, 2015: corrected the problem that arises when there is\n# \tno scattering in the time span of one frame. Fixed output arrays dimension.\n\n# ver 2.1 July 25, 2015: fixed bug that did not make the number of\n# \tscattering grow with the number of photons.\n\n# ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to\n# \tspeed things up. Gained about factor 2\n\n# ver 3.1 July 29, 2015: added radial spread of photon injection points\n# ver 3.2 July 31, 2015: added Gamma to the weight of photons!!!\n\n# ver 4.0 Aug 5, 2015: try to speed up by inverting cycle\n# ver 4.1 Aug 8, 2015: add spherical test as an option\n# ver 4.2 Aug 9, 2015: saving files appending rather than re-writing\n# ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature\n# ver 4.4 Aug 13, 2015: added cylindrical test\n# ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test\n# ver 4.6 Aug 21, 2015: corrected mean free path for large radii\n\n# ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings\n# ver 5.1 Aug 25, 2015: cleaned-up coding\n# ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections\n * \n * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path\n so you just need to supply the sub directory of MC_XXX as a command line argument\n* version 7.0 used OpenMP to parallelize the code by angle and the function findminmfp()\n \n version 8.0 added 3D capabilities for RIKEN hydro data and 2D capablities for RIKEN 2D hydro data and made it more efficient with grid selection to speed it up\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mclib_3d.h\"\n#include \n#include \"mpi.h\"\n\n/*\n#define THISRUN \"Science\"\n#define FILEPATH \"/home/physics/parsotat/16OI/\"\n#define FILEROOT \"rhd_jet_big_16OI_hdf5_plt_cnt_\"\n#define MC_PATH \"MPI_CMC_16OI_SPHERICAL/\"\n \n#define THISRUN \"Science\"\n#define FILEPATH \"/Users/Tylerparsotan/Documents/Box Sync/1spike/\"\n#define FILEROOT \"m0_rhop0.1big_hdf5_plt_cnt_\"\n#define MC_PATH \"CMC_1spike/\"\n//#define MC_PATH \"MC_16OI/Single_Photon_Cy_mc_total/\"\n * */\n /*\n #define THISRUN \"Science\"\n#define FILEPATH \"/home/physics/parsotat/16OM/\"\n#define FILEROOT \"rhd_jet_big_16OM_hdf5_plt_cnt_\"\n#define MC_PATH \"DIR_TEST/\"\n\n #define THISRUN \"Science\"\n#define FILEPATH \"/Volumes/DATA6TB/Collapsars/2D/HUGE_BOXES/VARY/40spikes/\"\n#define FILEROOT \"m0_rhop0.1big_hdf5_plt_cnt_\"\n#define MC_PATH \"CMC_40spikes_TEST/\"\n * */\n \n #define THISRUN \"Spherical\"\n#define FILEPATH \"/Volumes/DATA6TB/Collapsars/2D/HUGE_BOXES/CONSTANT/16OI/\"\n//#define FILEPATH \"/Users/Tylerparsotan//Documents/16OI_TEST/\"\n#define FILEROOT \"rhd_jet_big_16OI_hdf5_plt_cnt_\"\n#define MC_PATH \"TEST/\"\n\n#define MCPAR \"mc.par\"\n#define RIKEN_SWITCH 0\n\nint main(int argc, char **argv)\n{\n //compile each time a macro is changed, have to supply the subfolder within the MC_PATH directory as a command line argument to the C program eg. MCRAT 1/\n \n\t// Define variables\n\tchar flash_prefix[200]=\"\";\n\tchar mc_file[200]=\"\" ;\n char this_run[200]=THISRUN;\n char *cyl=\"Cylindrical\";\n char *sph=\"Spherical\";\n char spect;//type of spectrum\n char restrt;//restart or not\n double fps, fps_modified, theta_jmin, theta_jmax, hydro_domain_y,hydro_domain_x ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians, max y value of fluid simulation domain\n double inj_radius_small, inj_radius_large, ph_weight_suggest, ph_weight_small, ph_weight_large ;//radius at chich photons are injected into sim\n int frm0,last_frm, frm2_small, frm2_large, j=0, min_photons, max_photons, frm0_small, frm0_large ;//frame starting from, last frame of sim, frame of last injection\n int dim_switch=0;\n int find_nearest_grid_switch=0;\n int increment_inj=1, increment_scatt=1; //increments for injection loop and scattering loop, outer and inner loops respectively, the increment can change for RIKEN 3D hydro files\n \n double inj_radius;\n int frm2;\n char mc_filename[200]=\"\";\n char mc_filename_2[200]=\"\";\n char mc_operation[200]=\"\";\n char mc_dir[200]=\"\" ;\n int file_count = 0;\n DIR * dirp;\n struct dirent * entry;\n struct stat st = {0};\n double theta_jmin_thread=0, theta_jmax_thread=0;\n \n char flash_file[200]=\"\";\n char log_file[200]=\"\";\n FILE *fPtr=NULL; //pointer to log file for each thread\n double *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL;\n double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files\n double *phiPtr=NULL, *velzPtr=NULL, *zPtr=NULL;\n int num_ph=0, array_num=0, ph_scatt_index=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter\n double dt_max=0, thescatt=0, accum_time=0; \n double gamma_infinity=0, time_now=0, time_step=0, avg_scatt=0, avg_r=0; //gamma_infinity not used?\n double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0, ph_vzPtr=0;;// *ph_cosanglePtr=NULL ;\n double min_r=0, max_r=0, min_theta=0, max_theta=0;\n int frame=0, scatt_frame=0, frame_scatt_cnt=0, scatt_framestart=0, framestart=0;\n struct photon *phPtr=NULL; //pointer to array of photons \n \n int num_thread=0, angle_count=0;\n int num_angles=0, old_num_angle_procs=0; //old_num_angle_procs is to hold the old number of procs in each angle when cont sims, if restarting sims this gets set to angle_procs\n int *frame_array=NULL, *proc_frame_array=NULL, *element_num=NULL, proc_frame_size=0;\n double *thread_theta=NULL; //saves ranges of thetas for each thread to go through\n double delta_theta=1;\n \n int myid, numprocs, angle_procs, angle_id, procs_per_angle;\n \n \n //new OpenMPI stuff\n MPI_Init(NULL,NULL);\n MPI_Comm_size(MPI_COMM_WORLD, &numprocs);\n MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n \n \n //new muliple threads injecting and propagating photons\n const gsl_rng_type *rng_t;\n gsl_rng *rng;\n gsl_rng_env_setup();\n rng_t = gsl_rng_ranlxs0;\n rng = gsl_rng_alloc (rng_t); //initalize random number generator to seed the others with random numbers\n\n \n //want to break up simulation by angle and injection frame & have each thread save data in its own folder \n //have each thread check if its directory is made and if its restarting (delete evrything) or if its continuing with a previous simulation\n //the angle and the injection frames will be the names of mc_dir, therefore read mc.par first in MC_XXX directory\n \n //make strings of proper directories etc.\n\tsnprintf(flash_prefix,sizeof(flash_prefix),\"%s%s\",FILEPATH,FILEROOT );\n snprintf(mc_file,sizeof(flash_prefix),\"%s%s%s\",FILEPATH, MC_PATH,MCPAR);\n\n \n printf(\">> mc.py: Reading mc.par: %s\\n\", mc_file);\n \n readMcPar(mc_file, &hydro_domain_x, &hydro_domain_y, &fps, &theta_jmin, &theta_jmax, &delta_theta, &inj_radius_small,&inj_radius_large, &frm0_small,&frm0_large, &last_frm ,&frm2_small, &frm2_large, &ph_weight_small, &ph_weight_large, &min_photons, &max_photons, &spect, &restrt, &num_thread,&dim_switch); //thetas that comes out is in degrees\n //printf(\"%c\\n\", restrt);\n \n //divide up angles and frame injections among threads DONT WANT NUMBER OF THREADS TO BE ODD\n //assign ranges to array that hold them\n \n //leave angles in degrees here\n num_angles=(int) (((theta_jmax-theta_jmin)/delta_theta)) ;//*(180/M_PI));\n thread_theta=malloc( num_angles *sizeof(double) );\n *(thread_theta+0)=theta_jmin;//*(180/M_PI);\n //printf(\"%e\\n\", *(thread_theta+0));\n \n for (j=1;j<(num_angles); j++)\n {\n *(thread_theta+j)=*(thread_theta+(j-1))+delta_theta;\n //printf(\"%e\\n\", *(thread_theta+j));\n }\n\n \n\n //make comm without the procs that deal with angle\n //comm for angles\n \n procs_per_angle= numprocs/num_angles;\n //printf(\"%d\\n\", procs_per_angle);\n \n MPI_Comm angle_comm;\n if (restrt=='r') //uncomment this when I run MCRAT for sims that didnt originally save angle_procs \n {\n \n MPI_Comm_split(MPI_COMM_WORLD, myid/procs_per_angle , myid, &angle_comm);\n MPI_Comm_rank(angle_comm, &angle_id);\n MPI_Comm_size(angle_comm, &angle_procs);\n \n //printf(\"WORLD RANK/SIZE: %d/%d \\t ROW RANK/SIZE: %d/%d\\n\", myid, numprocs, angle_id, angle_procs); \n \n theta_jmin_thread= (*(thread_theta+ (myid/procs_per_angle))) *(M_PI/180);\n theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180));\n \n snprintf(mc_dir,sizeof(flash_prefix),\"%s%s%0.1lf-%0.1lf/\",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this\n \n old_num_angle_procs=angle_procs;\n }\n else\n {\n MPI_Group sub_world_group;\n MPI_Comm sub_world_comm;\n int incl_procs[procs_per_angle*num_angles], count, sub_world_id;\n int total_num_to_restart=0;\n int color=1;\n int *all_cont_process_idPtr=NULL, *each_num_to_restart_per_anglePtr=NULL, *tmp=NULL;\n //for restart='c' case if the number of processes isnt a multiple of procs_per_angle*num_angles make a comm out of those that are in order to analyze files and count number of processes for each angle range need to con't\n count=0;\n for (j=0;j0)\n {\n if (myid != 0 )\n {\n //allocate data of appropriate size for all processes to hold the data from MPI_Bcast\n tmp=realloc(all_cont_process_idPtr,total_num_to_restart *sizeof(int));\n if (tmp!=NULL)\n {\n all_cont_process_idPtr=tmp;\n }\n else\n {\n printf(\"Error with reserving space to hold data about restarting process ID's\\n\");\n }\n //free(tmp);\n tmp=realloc(each_num_to_restart_per_anglePtr, num_angles*sizeof(int));\n if (tmp!=NULL)\n {\n each_num_to_restart_per_anglePtr=tmp;\n }\n else\n {\n printf(\"Error with reserving space to hold data about restarting process numbers for each angle range\\n\");\n }\n //free(tmp);\n }\n \n MPI_Bcast( all_cont_process_idPtr, total_num_to_restart, MPI_INT, 0, MPI_COMM_WORLD );\n MPI_Bcast( each_num_to_restart_per_anglePtr, num_angles, MPI_INT, 0, MPI_COMM_WORLD );\n MPI_Bcast( &old_num_angle_procs, 1, MPI_INT, 0, MPI_COMM_WORLD );\n \n MPI_Barrier(MPI_COMM_WORLD);\n if (myid==numprocs-1)\n {\n printf(\"Number of processes: %d\\n\", old_num_angle_procs);\n printf(\"restarting process numbers for each angle range: %d, %d, %d\\n\", *(each_num_to_restart_per_anglePtr), *(each_num_to_restart_per_anglePtr+1), *(each_num_to_restart_per_anglePtr+2));\n }\n \n //assign proper number of processes to each angle range to con't sims and then reset angle_id to original value from when simulation was first started\n color=0; //by default all processes have this value\n \n count=0;\n for (j=0;j=count && myid= 0) && (theta_jmax_thread <= (2*M_PI/180) )) //if within small angle (0-2 degrees) use _small inj_radius and frm2 have to think about this for larger domains\n {\n inj_radius=inj_radius_small;\n frm2=frm2_small;\n frm0=frm0_small;\n ph_weight_suggest=ph_weight_small;\n }\n else\n {\n inj_radius=inj_radius_large;\n frm2=frm2_large;\n frm0=frm0_large;\n ph_weight_suggest=ph_weight_large;\n }\n \n //make vector to hold the frames we are injecting in, vector should have (frm2-frm0)/angle_procs slots, if fps is const\n proc_frame_size=ceil((frm2-frm0)/ (float) angle_procs);\n frame_array=malloc(((frm2-frm0)+1)*sizeof(int));\n \n for (j=0;j<((frm2-frm0)+1); j++)\n {\n *(frame_array+j)=frm0+j ;\n \t//printf(\"proc: %d frame: %d\\n\", angle_id, *(frame_array+j));\n }\n \n \n {\n //set this now incase there is no checkpoint file, then this wont be overwritten and the corretc values will be passed even if the user decides to restart\n framestart=(*(frame_array +(angle_id*proc_frame_size)));\n scatt_framestart=framestart;\n \n if (angle_id != (angle_procs-1)) \n {\n frm2=(*(frame_array +((angle_id*proc_frame_size) + proc_frame_size-1) )); //section off blocks of the frame_array to give to each angle_id\n }\n else\n {\n frm2=(*(frame_array + (frm2-frm0) )); //if angle_id is last give it the last set, even if its uneven\n }\n \n \n if (restrt=='c')\n {\n printf(\">> mc.py: Reading checkpoint\\n\");\n //#pragma omp critical\n \n readCheckpoint(mc_dir, &phPtr, &frm2, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now, angle_id, &angle_procs, dim_switch, RIKEN_SWITCH);\n \n /*\n for (i=0;ip0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt );\n }\n */\n if (restrt=='c')\n {\n printf(\">> Rank %d: Starting from photons injected at frame: %d out of %d\\n\", angle_id,framestart, frm2);\n printf(\">> Rank %d with angles %0.1lf-%0.1lf: Continuing scattering %d photons from frame: %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,num_ph, scatt_framestart);\n printf(\">> Rank %d with angles %0.1lf-%0.1lf: The time now is: %e\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,time_now);\n }\n else\n {\n printf(\">> Rank %d with angles %0.1lf-%0.1lf: Continuing simulation by injecting photons at frame: %d out of %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,framestart, frm2); //starting with new photon injection is same as restarting sim\n }\n \n }\n else if ((stat(mc_dir, &st) == -1) && (restrt=='r'))\n {\n mkdir(mc_dir, 0777); //make the directory with full permissions\n \n \n }\n else \n {\n if (angle_id==0)\n {\n printf(\">> proc %d with angles %0.1lf-%0.1lf: Cleaning directory \\n\",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI);\n dirp = opendir(mc_dir);\n while ((entry = readdir(dirp)) != NULL) \n {\n if (entry->d_type == DT_REG) { /* If the entry is a regular file */\n file_count++; //count how many files are in dorectory\n }\n }\n printf(\"File count %d\\n\", file_count);\n \n if (file_count>0)\n {\n for (i=0;i<=last_frm;i++)\n {\n \n snprintf(mc_filename,sizeof(mc_filename),\"%s%s%d%s\", mc_dir,\"mcdata_\",i,\"_P0.dat\");\n //snprintf(mc_filename_2,sizeof(mc_filename),\"%s%s%d%s\", mc_dir,\"mcdata_\",i,\"_P0_0.dat\");\n for (j=0;j=3000))\n {\n increment_inj=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n fps_modified=1;\n }\n else\n {\n increment_inj=1;\n fps_modified=fps;\n }\n \n dt_max=1.0/fps_modified;\n \n MPI_Barrier(angle_comm); \n snprintf(log_file,sizeof(log_file),\"%s%s%d%s\",mc_dir,\"mc_output_\", angle_id,\".log\" );\n printf(\"%s\\n\",log_file);\n fPtr=fopen(log_file, \"a\");\n \n printf( \"Im Proc %d with angles %0.1lf-%0.1lf proc_frame_size is %d Starting on Frame: %d Injecting until %d scatt_framestart: %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, proc_frame_size, framestart, frm2, scatt_framestart);\n \n fprintf(fPtr, \"Im Proc %d with angles %0.1lf-%0.1lf Starting on Frame: %d scatt_framestart: %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, framestart, scatt_framestart);\n fflush(fPtr);\n \n free(frame_array);\n \n //for a checkpoint implementation, start from the last saved \"frame\" value and go to the saved \"frm2\" value\n \n //#pragma omp for \n \n for (frame=framestart;frame<=frm2;frame=frame+increment_inj)\n {\n \n if ((RIKEN_SWITCH==1) && (dim_switch==1) && (frame>=3000))\n {\n increment_inj=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n fps_modified=1;\n }\n else\n {\n increment_inj=1;\n fps_modified=fps;\n }\n \n if (restrt=='r')\n {\n time_now=frame/fps; //for a checkpoint implmentation, load the saved \"time_now\" value when reading the ckeckpoint file otherwise calculate it normally\n }\n \n //printf(\">> mc.py: Working on Frame %d\\n\", frame);\n fprintf(fPtr,\"Im Proc: %d with angles %0.1lf - %0.1lf Working on Frame: %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frame);\n fflush(fPtr);\n \n if (restrt=='r')\n {\n \n \n if (dim_switch==0)\n {\n if (RIKEN_SWITCH==0)\n {\n //if using FLASH data for 2D\n //put proper number at the end of the flash file\n modifyFlashName(flash_file, flash_prefix, frame, dim_switch);\n \n fprintf(fPtr,\">> Im Proc: %d with angles %0.1lf-%0.1lf: Opening FLASH file %s\\n\",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, flash_file);\n fflush(fPtr);\n \n readAndDecimate(flash_file, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, min_theta, max_theta, fPtr);\n }\n else\n {\n //if using RIKEN hydro data for 2D szx becomes delta r szy becomes delta theta\n readHydro2D(FILEPATH, frame, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fPtr);\n //fprintf(fPtr, \"%d\\n\\n\", array_num);\n }\n }\n else\n {\n fprintf(fPtr,\">> Im Proc: %d with angles %0.1lf-%0.1lf\\n\",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI);\n fflush(fPtr);\n \n read_hydro(FILEPATH, frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fps_modified, fPtr);\n }\n \n //check for run type\n if(strcmp(cyl, this_run)==0)\n {\n //printf(\"In cylindrical prep\\n\");\n cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num);\n }\n else if (strcmp(sph, this_run)==0)\n {\n printf(\"In Spherical\\n\");\n sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num , fPtr);\n }\n \n //determine where to place photons and how many should go in a given place\n //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data \n fprintf(fPtr,\">> Proc: %d with angles %0.1lf-%0.1lf: Injecting photons\\n\",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI);\n fflush(fPtr);\n \n if (dim_switch==0)\n {\n photonInjection(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps_modified, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, szxPtr, szyPtr,rPtr,thetaPtr, tempPtr, velxPtr, velyPtr,rng, RIKEN_SWITCH, fPtr );\n }\n else\n {\n photonInjection3D(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps_modified, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, zPtr, szxPtr, szyPtr,rPtr,thetaPtr, phiPtr, tempPtr, velxPtr, velyPtr, velzPtr, rng, fPtr);\n\n }\n \n \n \n //printf(\"This many Photons: %d\\n\",num_ph); //num_ph is one more photon than i actually have\n \n //for (i=0;ir0, (phPtr+i)->r1, (phPtr+i)->r2 );\n \n }\n \n //scatter photons all the way thoughout the jet\n //for a checkpoint implmentation, start from the last saved \"scatt_frame\" value eh start_frame=frame or start_frame=cont_frame\n if (restrt=='r')\n {\n scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incrememnted by one the inner loop starts at that new value and not the one read by readCheckpoint()\n }\n \n for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame=scatt_frame+increment_scatt)\n {\n if ((RIKEN_SWITCH==1) && (dim_switch==1) && (scatt_frame>=3000))\n {\n increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n fps_modified=1; //therefore dt between files become 1 second\n \n }\n else\n {\n increment_scatt=1;\n fps_modified=fps;\n }\n \n dt_max=1.0/fps_modified; //if working with RIKEN files and scatt_frame>=3000 dt is 1 second between each subsequent frame\n \n fprintf(fPtr,\">>\\n\");\n fprintf(fPtr,\">> Proc %d with angles %0.1lf-%0.1lf: Working on photons injected at frame: %d out of %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,frame, frm2);\n fprintf(fPtr,\">> Proc %d with angles %0.1lf-%0.1lf: %s - Working on frame %d\\n\",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, THISRUN, scatt_frame);\n fprintf(fPtr,\">> Proc %d with angles %0.1lf-%0.1lf: Opening file...\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI);\n fflush(fPtr);\n \n //set new seed to increase randomness?\n gsl_rng_set(rng, gsl_rng_get(rng));\n \n \n if (dim_switch==0)\n {\n if (RIKEN_SWITCH==0)\n {\n //put proper number at the end of the flash file\n modifyFlashName(flash_file, flash_prefix, scatt_frame, dim_switch);\n phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr);\n readAndDecimate(flash_file, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, min_theta, max_theta, fPtr);\n }\n else\n {\n phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr);\n //if using RIKEN hydro data for 2D szx becomes delta r szy becomes delta theta\n readHydro2D(FILEPATH, scatt_frame, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fPtr);\n \n }\n }\n else\n {\n phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr);\n read_hydro(FILEPATH, scatt_frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fps_modified, fPtr);\n }\n fprintf(fPtr, \"Number of Flash Elements %d\\n\", array_num);\n \n \n //check for run type\n if(strcmp(cyl, this_run)==0)\n {\n //printf(\"In cylindrical prep\\n\");\n cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num);\n }\n else if (strcmp(sph, this_run)==0)\n {\n sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num, fPtr );\n }\n //printf(\"The result of read and decimate are arrays with %d elements\\n\", array_num);\n \n fprintf(fPtr,\">> Proc %d with angles %0.1lf-%0.1lf: propagating and scattering %d photons\\n\",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,num_ph);\n fflush(fPtr);\n \n frame_scatt_cnt=0;\n find_nearest_grid_switch=1; // set to true so the function findNearestPropertiesAndMinMFP by default finds the index of the grid block closest to each photon since we just read in a file and the prior index is invalid\n\n while (time_now<((scatt_frame+increment_scatt)/fps))\n {\n //if simulation time is less than the simulation time of the next frame, keep scattering in this frame\n //for RIKEN hydro data, theres still 10 fps but after frame 3000, file increment is 10 not 1, therefore modify dt_max not fps\n \n //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path\n //and choose the photon with the smallest mfp and calculate the timestep\n \n\n ph_scatt_index=findNearestPropertiesAndMinMFP(phPtr, num_ph, array_num, hydro_domain_x, hydro_domain_y, &time_step, xPtr, yPtr, zPtr, szxPtr, szyPtr, velxPtr, velyPtr, velzPtr, dens_labPtr, tempPtr,\\\n &ph_dens_labPtr, &ph_vxPtr, &ph_vyPtr, &ph_vzPtr, &ph_tempPtr, rng, dim_switch, find_nearest_grid_switch, RIKEN_SWITCH, fPtr);\n \n find_nearest_grid_switch=0; //set to zero (false) since we do not absolutely need to refind the index, this makes the function findNearestPropertiesAndMinMFP just check if the photon is w/in the given grid box still\n\n \n //fprintf(fPtr, \"In main: %e, %d, %e, %e\\n\",((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now);\n //fflush(fPtr);\n \n \n if (time_stepnum_scatt)+=1;\n frame_scatt_cnt+=1;\n time_now+=time_step;\n \n updatePhotonPosition(phPtr, num_ph, time_step, fPtr);\n \n //scatter the photon\n //fprintf(fPtr, \"Passed Parameters: %e, %e, %e\\n\", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr));\n\n photonScatter( (phPtr+ph_scatt_index), (ph_vxPtr), (ph_vyPtr),ph_vzPtr, (ph_tempPtr), rng, dim_switch, fPtr );\n \n \n if (frame_scatt_cnt%1000 == 0)\n {\n fprintf(fPtr,\"Scattering Number: %d\\n\", frame_scatt_cnt);\n fprintf(fPtr,\"The local temp is: %e\\n\", (ph_tempPtr));\n fprintf(fPtr,\"Average photon energy is: %e\\n\", averagePhotonEnergy(phPtr, num_ph)); //write function to average over the photons p0 and then do (*3e10/1.6e-9)\n fprintf(fPtr,\"The last time step was: %e.\\nThe time now is: %e\\n\", time_step,time_now);\n fflush(fPtr);\n }\n \n }\n else\n {\n time_now+=dt_max;\n \n //for each photon update its position based on its momentum\n \n updatePhotonPosition(phPtr, num_ph, dt_max, fPtr);\n }\n \n //printf(\"In main 2: %e, %d, %e, %e\\n\", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now);\n\n }\n \n //get scattering statistics\n phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt, &avg_r);\n \n fprintf(fPtr,\"The number of scatterings in this frame is: %d\\n\", frame_scatt_cnt);\n fprintf(fPtr,\"The last time step was: %e.\\nThe time now is: %e\\n\", time_step,time_now);\n fprintf(fPtr,\"The maximum number of scatterings for a photon is: %d\\nThe minimum number of scattering for a photon is: %d\\n\", max_scatt, min_scatt);\n fprintf(fPtr,\"The average number of scatterings thus far is: %lf\\nThe average position of photons is %e\\n\", avg_scatt, avg_r);\n fflush(fPtr);\n \n printPhotons(phPtr, num_ph, scatt_frame , frame, mc_dir, angle_id);\n //exit(0);\n fprintf(fPtr, \">> Proc %d with angles %0.1lf-%0.1lf: Making checkpoint file\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI);\n fflush(fPtr);\n \n fprintf(fPtr, \" mc_dir: %s\\nframe %d\\nfrm2: %d\\nscatt_frame: %d\\n num_photon: %d\\ntime_now: %e\\nlast_frame: %d\\n\", mc_dir, frame, frm2, scatt_frame, num_ph, time_now, last_frm );\n fflush(fPtr);\n\n saveCheckpoint(mc_dir, frame, frm2, scatt_frame, num_ph, time_now, phPtr, last_frm, angle_id, old_num_angle_procs);\n \n if (dim_switch==1)\n {\n if (RIKEN_SWITCH==1)\n {\n free(zPtr);free(phiPtr);free(velzPtr);\n zPtr=NULL; phiPtr=NULL; velzPtr=NULL;\n }\n }\n \n free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr);\n free(gammaPtr);free(dens_labPtr);free(tempPtr);\n xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL;\n szxPtr=NULL; szyPtr=NULL; tempPtr=NULL;\n }\n \n restrt='r';//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file\n free(phPtr); \n phPtr=NULL;\n \n } \n saveCheckpoint(mc_dir, frame, frm2, scatt_frame, 0, time_now, phPtr, last_frm, angle_id, old_num_angle_procs); //this is for processes using the old code that didnt restart efficiently\n fprintf(fPtr, \"Process %d has completed the MC calculation.\\n\", angle_id);\n fflush(fPtr);\n \n }//end omp parallel inner section\n \n MPI_Barrier(angle_comm);\n \n //merge files from each worker thread within a directory\n {\n \n increment_scatt=1;\n file_count=0;\n \n //count number of files\n for (i=frm0;i<=last_frm;i=i+increment_scatt)\n {\n if ((RIKEN_SWITCH==1) && (dim_switch==1) && (i>=3000))\n {\n increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n }\n file_count++;\n }\n \n //holds number of files for each process to merge\n MPI_Comm_size(angle_comm, &angle_procs); //to get the proper number of processes within the group\n MPI_Comm_rank(angle_comm, &angle_id); //reset the value of angle_id to what it should actualy be to properly distribute files to merge\n \n proc_frame_size=floor(file_count/ (float) angle_procs);\n frame_array=malloc(file_count*sizeof(int));\n proc_frame_array=malloc(angle_procs*sizeof(int)); //sets index of each proceesed acquired value\n element_num=malloc(angle_procs*sizeof(int));\n \n for (i=0;i=3000))\n {\n increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n }\n \n *(frame_array+file_count)=i ;\n file_count++;\n //printf(\"file_count: %d frame: %d\\n\", file_count-1, *(frame_array+file_count-1));\n }\n //pass first frame number that each rpocess should start to merge, can calulate the file it should merge until\n MPI_Scatterv(frame_array, element_num, proc_frame_array, MPI_INT, &frm0, 1, MPI_INT, 0, angle_comm);\n \n //fprintf(fPtr, \"Value: last_frm: ,%d\\n\", file_count);\n //fflush(fPtr);\n \n //make sure all files get merged by giving the rest to the last process\n if (angle_id==angle_procs-1)\n {\n proc_frame_size=file_count-proc_frame_size*(angle_procs-1); //for last process take over the remaining number of files\n }\n //calculate what the last file the preocess should merge up to\n i=0;\n last_frm=frm0;\n while(i=3000))\n {\n increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1\n }\n else\n {\n increment_scatt=1;\n }\n \n last_frm+=increment_scatt;\n i++;\n }\n \n \n //if (angle_id==0)\n {\n //fprintf(fPtr, \">> Proc %d with angles %0.1lf-%0.1lf: Merging Files from %d to %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm0, last_frm);\n fprintf(fPtr, \">> Proc %d with angles %0.1lf-%0.1lf: Merging Files from %d to %d\\n\", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm0, last_frm);\n fflush(fPtr);\n \n dirFileMerge(mc_dir, frm0, last_frm, old_num_angle_procs, angle_id, dim_switch, RIKEN_SWITCH, fPtr); \n }\n }\n \n fprintf(fPtr, \"Process %d has completed merging files.\\n\", angle_id);\n fflush(fPtr);\n \n fclose(fPtr);\n gsl_rng_free (rng);\n \t \n MPI_Finalize();\n //free(rng);\n //free(thread_theta);\n \n\treturn 0; \n}\n", "meta": {"hexsha": "2effc30f3abbb7470d0829cc440344c8c3d154e5", "size": 52297, "ext": "c", "lang": "C", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mcrat.c", "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mcrat.c", "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "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": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mcrat.c", "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "avg_line_length": 51.8819444444, "max_line_length": 346, "alphanum_fraction": 0.5533395797, "num_tokens": 12458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.15428517300404462}}