source
stringlengths
3
92
c
stringlengths
26
2.25M
exercice3.c
#include <stdio.h> int main(void){ int total = 0; #pragma omp parallel for reduction(+:total) for (int i = 0; i < 100; i++){ total += i; } printf("total : %d", total); }
mixed_tentusscher_myo_epi_2004_S2_13.c
// Scenario 2 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S2_13.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5539038753567,0.00129412448996796,0.779360292837132,0.779249119724812,0.000175123544000358,0.484940918252471,0.00294329963917416,0.999998343965409,1.93809582696782e-08,1.89468693200808e-05,0.999768982807075,1.00735744125472,0.999998089726980,3.89830144793233e-05,1.72829326331064,9.02393126594947,140.110171882154}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.6562217355457,0.000322374069155616,0.000173047827857537,0.000696326655746097,0.278632619847976,0.150655618402204,0.199964802834043,3.69236346658384,0.0186563054578193,2.52084572386843,1094.23899275256,0.000612998466562635,0.523532987188625,0.0168738706166519,0.00354670636620307,9.88277000414890e-06}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
integrateLinearOrbit.c
/* Wrappers around the C integration code for linear Orbits */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <bovy_symplecticode.h> #include <bovy_rk.h> #include <leung_dop853.h> #include <integrateFullOrbit.h> //Potentials #include <galpy_potentials.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef ORBITS_CHUNKSIZE #define ORBITS_CHUNKSIZE 1 #endif //Macros to export functions in DLL on different OS #if defined(_WIN32) #define EXPORT __declspec(dllexport) #elif defined(__GNUC__) #define EXPORT __attribute__((visibility("default"))) #else // Just do nothing? #define EXPORT #endif /* Function Declarations */ void evalLinearForce(double, double *, double *, int, struct potentialArg *); void evalLinearDeriv(double, double *, double *, int, struct potentialArg *); /* Actual functions */ void parse_leapFuncArgs_Linear(int npot,struct potentialArg * potentialArgs, int ** pot_type, double ** pot_args){ int ii,jj; init_potentialArgs(npot,potentialArgs); for (ii=0; ii < npot; ii++){ switch ( *(*pot_type)++ ) { default: //verticalPotential potentialArgs->linearForce= &verticalPotentialLinearForce; break; case 31: // KGPotential potentialArgs->linearForce= &KGPotentialLinearForce; potentialArgs->nargs= 4; break; case 32: // IsothermalDiskPotential potentialArgs->linearForce= &IsothermalDiskPotentialLinearForce; potentialArgs->nargs= 2; break; //////////////////////////////// WRAPPERS ///////////////////////////////////// // NOT CURRENTLY SUPPORTED /* case -1: //DehnenSmoothWrapperPotential potentialArgs->linearForce= &DehnenSmoothWrapperPotentialPlanarRforce; potentialArgs->nargs= (int) 3; break; case -2: //SolidBodyRotationWrapperPotential potentialArgs->linearForce= &SolidBodyRotationWrapperPotentialPlanarRforce; potentialArgs->nargs= (int) 3; break; case -4: //CorotatingRotationWrapperPotential potentialArgs->linearForce= &CorotatingRotationWrapperPotentialPlanarRforce; potentialArgs->nargs= (int) 5; break; case -5: //GaussianAmplitudeWrapperPotential potentialArgs->linearForce= &GaussianAmplitudeWrapperPotentialPlanarRforce; potentialArgs->nargs= (int) 3; break; */ } /* if ( *(*pot_type-1) < 0) { // Parse wrapped potential for wrappers potentialArgs->nwrapped= (int) *(*pot_args)++; potentialArgs->wrappedPotentialArg= \ (struct potentialArg *) malloc ( potentialArgs->nwrapped \ * sizeof (struct potentialArg) ); parse_leapFuncArgs_Linear(potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg, pot_type,pot_args); } */ // linear from 3D: assign R location parameter as the only one, rest // of potential as wrapped if ( potentialArgs->linearForce == &verticalPotentialLinearForce ) { potentialArgs->nwrapped= (int) 1; potentialArgs->wrappedPotentialArg= \ (struct potentialArg *) malloc ( potentialArgs->nwrapped \ * sizeof (struct potentialArg) ); *(pot_type)-= 1; // Do FullOrbit processing for same potential parse_leapFuncArgs_Full(potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg, pot_type,pot_args); potentialArgs->nargs= 2; // R, phi } potentialArgs->args= (double *) malloc( potentialArgs->nargs * sizeof(double)); for (jj=0; jj < potentialArgs->nargs; jj++){ *(potentialArgs->args)= *(*pot_args)++; potentialArgs->args++; } potentialArgs->args-= potentialArgs->nargs; potentialArgs++; } potentialArgs-= npot; } EXPORT void integrateLinearOrbit(int nobj, double *yo, int nt, double *t, int npot, int * pot_type, double * pot_args, double dt, double rtol, double atol, double *result, int * err, int odeint_type){ //Set up the forces, first count int dim; int ii; int max_threads; int * thread_pot_type; double * thread_pot_args; max_threads= ( nobj < omp_get_max_threads() ) ? nobj : omp_get_max_threads(); // Because potentialArgs may cache, safest to have one / thread struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( max_threads * npot * sizeof (struct potentialArg) ); #pragma omp parallel for schedule(static,1) private(ii,thread_pot_type,thread_pot_args) num_threads(max_threads) for (ii=0; ii < max_threads; ii++) { thread_pot_type= pot_type; // need to make thread-private pointers, bc thread_pot_args= pot_args; // these pointers are changed in parse_... parse_leapFuncArgs_Linear(npot,potentialArgs+ii*npot, &thread_pot_type,&thread_pot_args); } //Integrate void (*odeint_func)(void (*func)(double, double *, double *, int, struct potentialArg *), int, double *, int, double, double *, int, struct potentialArg *, double, double, double *,int *); void (*odeint_deriv_func)(double, double *, double *, int,struct potentialArg *); switch ( odeint_type ) { case 0: //leapfrog odeint_func= &leapfrog; odeint_deriv_func= &evalLinearForce; dim= 1; break; case 1: //RK4 odeint_func= &bovy_rk4; odeint_deriv_func= &evalLinearDeriv; dim= 2; break; case 2: //RK6 odeint_func= &bovy_rk6; odeint_deriv_func= &evalLinearDeriv; dim= 2; break; case 3: //symplec4 odeint_func= &symplec4; odeint_deriv_func= &evalLinearForce; dim= 1; break; case 4: //symplec6 odeint_func= &symplec6; odeint_deriv_func= &evalLinearForce; dim= 1; break; case 5: //DOPR54 odeint_func= &bovy_dopr54; odeint_deriv_func= &evalLinearDeriv; dim= 2; break; case 6: //DOP853 odeint_func= &dop853; odeint_deriv_func= &evalLinearDeriv; dim= 2; break; } #pragma omp parallel for schedule(dynamic,ORBITS_CHUNKSIZE) private(ii) num_threads(max_threads) for (ii=0; ii < nobj; ii++) odeint_func(odeint_deriv_func,dim,yo+2*ii,nt,dt,t, npot,potentialArgs+omp_get_thread_num()*npot,rtol,atol, result+2*nt*ii,err+ii); //Free allocated memory #pragma omp parallel for schedule(static,1) private(ii) num_threads(max_threads) for (ii=0; ii < max_threads; ii++) free_potentialArgs(npot,potentialArgs+ii*npot); free(potentialArgs); //Done! } void evalLinearForce(double t, double *q, double *a, int nargs, struct potentialArg * potentialArgs){ *a= calcLinearForce(*q,t,nargs,potentialArgs); } void evalLinearDeriv(double t, double *q, double *a, int nargs, struct potentialArg * potentialArgs){ *a++= *(q+1); *a= calcLinearForce(*q,t,nargs,potentialArgs); }
tpi_openmp.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2002-2019 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SCIP is distributed under the terms of the ZIB Academic License. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SCIP; see the file COPYING. If not visit scip.zib.de. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file tpi_openmp.c * @ingroup TASKINTERFACE * @brief the interface functions for openmp * @author Stephen J. Maher * @author Robert Lion Gottwald */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #include "tpi/tpi.h" #include "blockmemshell/memory.h" /** A job added to the queue */ struct SCIP_Job { int jobid; /**< id to identify jobs from a common process */ struct SCIP_Job* nextjob; /**< pointer to the next job in the queue */ SCIP_RETCODE (*jobfunc)(void* args);/**< pointer to the job function */ void* args; /**< pointer to the function arguements */ SCIP_RETCODE retcode; /**< return code of the job */ }; /** the thread pool job queue */ struct SCIP_JobQueue { SCIP_JOB* firstjob; /**< pointer to the first job in the queue */ SCIP_JOB* lastjob; /**< pointer to the last job in the queue */ int njobs; /**< number of jobs in the queue */ }; typedef struct SCIP_JobQueue SCIP_JOBQUEUE; struct SCIP_JobQueues { SCIP_JOBQUEUE jobqueue; /**< queue of unprocessed jobs */ SCIP_JOB** currentjobs; /**< array with slot for each thread to store the currently running job */ int ncurrentjobs; /**< number of currently running jobs */ int nthreads; /**< number of threads */ SCIP_JOBQUEUE finishedjobs; /**< jobqueue containing the finished jobs */ SCIP_LOCK lock; /**< lock to protect this stucture from concurrent access */ SCIP_CONDITION jobfinished; /**< condition to signal if a job was finished */ }; typedef struct SCIP_JobQueues SCIP_JOBQUEUES; static SCIP_JOBQUEUES* _jobqueues = NULL; static SCIP_RETCODE createJobQueue( int nthreads, /**< the number of threads */ int qsize, /**< the queue size */ SCIP_Bool blockwhenfull /**< should the queue be blocked from new jobs when full */ ) { int i; assert(nthreads >= 0); assert(qsize >= 0); SCIP_UNUSED( blockwhenfull ); /* allocting memory for the job queue */ SCIP_ALLOC( BMSallocMemory(&_jobqueues) ); _jobqueues->jobqueue.firstjob = NULL; _jobqueues->jobqueue.lastjob = NULL; _jobqueues->jobqueue.njobs = 0; _jobqueues->finishedjobs.firstjob = NULL; _jobqueues->finishedjobs.lastjob = NULL; _jobqueues->finishedjobs.njobs = 0; _jobqueues->ncurrentjobs = 0; _jobqueues->nthreads = nthreads; SCIP_ALLOC( BMSallocMemoryArray(&_jobqueues->currentjobs, nthreads) ); for( i = 0; i < nthreads; ++i ) _jobqueues->currentjobs[i] = NULL; SCIP_CALL( SCIPtpiInitLock(&_jobqueues->lock) ); SCIP_CALL( SCIPtpiInitCondition(&_jobqueues->jobfinished) ); return SCIP_OKAY; } static SCIP_RETCODE freeJobQueue( void ) { assert(_jobqueues != NULL); SCIPtpiDestroyLock(&_jobqueues->lock); SCIPtpiDestroyCondition(&_jobqueues->jobfinished); BMSfreeMemoryArray(&_jobqueues->currentjobs); BMSfreeMemory(&_jobqueues); return SCIP_OKAY; } static void executeJob( SCIP_JOB* job /**< the job to be executed in parallel */ ) { int threadnum; threadnum = SCIPtpiGetThreadNum(); SCIP_CALL_ABORT( SCIPtpiAcquireLock(&_jobqueues->lock) ); _jobqueues->currentjobs[threadnum] = job; SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) ); job->retcode = (*(job->jobfunc))(job->args); SCIP_CALL_ABORT( SCIPtpiAcquireLock(&_jobqueues->lock) ); _jobqueues->ncurrentjobs--; _jobqueues->currentjobs[threadnum] = NULL; /* insert job into finished jobs */ if( _jobqueues->finishedjobs.njobs == 0 ) { _jobqueues->finishedjobs.firstjob = job; _jobqueues->finishedjobs.lastjob = job; } else { _jobqueues->finishedjobs.lastjob->nextjob = job; _jobqueues->finishedjobs.lastjob = job; } ++_jobqueues->finishedjobs.njobs; SCIP_CALL_ABORT( SCIPtpiBroadcastCondition(&_jobqueues->jobfinished) ); SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) ); } /** this is a job that will be executed on to process the job queue * * The job will only be added when the number of active jobs is equal to the number of threads. * As such, there will always be number of threads + 1 tasks available for the scheduler to run. */ static void jobQueueProcessJob( void ) { SCIP_JOB* job; SCIP_CALL_ABORT( SCIPtpiAcquireLock(&_jobqueues->lock) ); while( _jobqueues->ncurrentjobs == SCIPtpiGetNumThreads() ) { SCIP_CALL_ABORT( SCIPtpiWaitCondition(&_jobqueues->jobfinished, &_jobqueues->lock) ); } if( _jobqueues->jobqueue.njobs == 1 ) { job = _jobqueues->jobqueue.firstjob; _jobqueues->jobqueue.firstjob = NULL; _jobqueues->jobqueue.lastjob = NULL; --_jobqueues->jobqueue.njobs; } else if( _jobqueues->jobqueue.njobs > 1 ) { job = _jobqueues->jobqueue.firstjob; _jobqueues->jobqueue.firstjob = job->nextjob; --_jobqueues->jobqueue.njobs; } else { job = NULL; } ++_jobqueues->ncurrentjobs; SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) ); if( job ) { executeJob(job); } } /** adding a job to the job queue. * * This gives some more flexibility in the handling of new jobs. * IMPORTANT: This function MUST be called from within a mutex. */ static SCIP_RETCODE jobQueueAddJob( SCIP_JOB* newjob ) { /* @todo we want to work out what to do with a full job queue. Is there a problem if the limit is hit? */ /* @note it is important to have a queuesize. This will stop the code submitting infinitely many jobs. */ assert(newjob != NULL); newjob->nextjob = NULL; /* this function queries the current job list. This could change by other threads writing to the list. So a lock is * required to ensure that the current joblist remains static. */ SCIP_CALL( SCIPtpiAcquireLock(&_jobqueues->lock) ); /* checking the status of the job queue */ if( _jobqueues->ncurrentjobs == SCIPtpiGetNumThreads() ) { if( _jobqueues->jobqueue.njobs == 0 ) { _jobqueues->jobqueue.firstjob = newjob; _jobqueues->jobqueue.lastjob = newjob; } else /* it is assumed that the jobqueue is not full */ { _jobqueues->jobqueue.lastjob->nextjob = newjob; _jobqueues->jobqueue.lastjob = newjob; } _jobqueues->jobqueue.njobs++; SCIP_CALL( SCIPtpiReleaseLock(&_jobqueues->lock) ); #pragma omp task jobQueueProcessJob(); } else { assert(_jobqueues->ncurrentjobs < SCIPtpiGetNumThreads()); _jobqueues->ncurrentjobs++; SCIP_CALL( SCIPtpiReleaseLock(&_jobqueues->lock) ); /* running the new job */ #pragma omp task firstprivate(newjob) executeJob(newjob); } return SCIP_OKAY; } SCIP_RETCODE SCIPtpiSignalCondition( SCIP_CONDITION* condition ) { SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) ); if( condition->_waitnum > condition->_signals ) ++condition->_signals; SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) ); return SCIP_OKAY; } SCIP_RETCODE SCIPtpiBroadcastCondition( SCIP_CONDITION* condition ) { SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) ); condition->_signals = condition->_waitnum; SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) ); return SCIP_OKAY; } SCIP_RETCODE SCIPtpiWaitCondition( SCIP_CONDITION* condition, SCIP_LOCK* lock ) { int waitnum; SCIP_CALL( SCIPtpiReleaseLock(lock) ); SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) ); waitnum = ++condition->_waitnum; ++condition->_waiters; do { SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) ); #pragma omp taskyield SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) ); } while( condition->_signals < waitnum ); --condition->_waiters; if( condition->_waiters == 0 ) { condition->_signals = 0; condition->_waitnum = 0; } SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) ); SCIP_CALL( SCIPtpiAcquireLock(lock) ); return SCIP_OKAY; } /** Returns the number of threads */ int SCIPtpiGetNumThreads( ) { return omp_get_num_threads(); } /** Returns the thread number */ int SCIPtpiGetThreadNum( ) { return omp_get_thread_num(); } /** creates a job for parallel processing*/ SCIP_RETCODE SCIPtpiCreateJob( SCIP_JOB** job, /**< pointer to the job that will be created */ int jobid, /**< the id for the current job */ SCIP_RETCODE (*jobfunc)(void* args),/**< pointer to the job function */ void* jobarg /**< the job's argument */ ) { SCIP_ALLOC( BMSallocMemory(job) ); (*job)->jobid = jobid; (*job)->jobfunc = jobfunc; (*job)->args = jobarg; (*job)->nextjob = NULL; return SCIP_OKAY; } /** get a new job id for the new set of submitted jobs */ int SCIPtpiGetNewJobID( void ) { static int currentjobid = 0; int jobid; #pragma omp atomic capture jobid = ++currentjobid; return jobid; } /** submit a job for parallel processing * * the return is a globally defined status */ SCIP_RETCODE SCIPtpiSumbitJob( SCIP_JOB* job, /**< pointer to the job to be submitted */ SCIP_SUBMITSTATUS* status /**< pointer to store the submit status */ ) { assert(_jobqueues != NULL); *status = SCIP_SUBMIT_SUCCESS; SCIP_CALL( jobQueueAddJob(job) ); return SCIP_OKAY; } static SCIP_Bool isJobRunning( int jobid ) { int i; if( _jobqueues->ncurrentjobs > 0 ) { for( i = 0; i < _jobqueues->nthreads; ++i ) { if( _jobqueues->currentjobs[i] != NULL && _jobqueues->currentjobs[i]->jobid == jobid ) return TRUE; } } return FALSE; } static SCIP_Bool isJobWaiting( int jobid ) { if( _jobqueues->jobqueue.njobs > 0 ) { SCIP_JOB* currjob; currjob = _jobqueues->jobqueue.firstjob; do { if( currjob->jobid == jobid ) return TRUE; if( currjob == _jobqueues->jobqueue.lastjob ) break; currjob = currjob->nextjob; } while( TRUE ); /*lint !e506*/ } return FALSE; } /** Blocks until all jobs of the given jobid have finished * and then returns the smallest SCIP_RETCODE of all the jobs */ SCIP_RETCODE SCIPtpiCollectJobs( int jobid ) { SCIP_RETCODE retcode; retcode = SCIP_OKAY; SCIP_CALL( SCIPtpiAcquireLock(&_jobqueues->lock) ); while( isJobRunning(jobid) || isJobWaiting(jobid) ) { SCIP_CALL( SCIPtpiWaitCondition(&_jobqueues->jobfinished, &_jobqueues->lock) ); } if( _jobqueues->finishedjobs.njobs > 0 ) { SCIP_JOB* currjob = _jobqueues->finishedjobs.firstjob; SCIP_JOB* prevjob = NULL; /* finding the location of the processed job in the currentjobs queue */ do { if( currjob->jobid == jobid ) { SCIP_JOB* nextjob; /* if the job has the right jobid collect its retcode, remove it from the finished job list, and free it */ retcode = MIN(retcode, currjob->retcode); /* removing the finished job from finished jobs list */ if( currjob == _jobqueues->finishedjobs.firstjob ) _jobqueues->finishedjobs.firstjob = currjob->nextjob; else prevjob->nextjob = currjob->nextjob; /*lint !e613*/ if( currjob == _jobqueues->finishedjobs.lastjob ) _jobqueues->finishedjobs.lastjob = prevjob; _jobqueues->finishedjobs.njobs--; /* update currjob and free finished job; prevjob stays the same */ nextjob = currjob->nextjob; BMSfreeMemory(&currjob); currjob = nextjob; } else { prevjob = currjob; currjob = prevjob->nextjob; } } while( prevjob != _jobqueues->finishedjobs.lastjob ); } else { /* given jobid was not submitted */ printf("err1"); retcode = SCIP_ERROR; } SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) ); return retcode; } /** initializes tpi */ SCIP_RETCODE SCIPtpiInit( int nthreads, int queuesize, SCIP_Bool blockwhenfull ) { omp_set_num_threads(nthreads); assert(_jobqueues == NULL); SCIP_CALL( createJobQueue(nthreads, queuesize, blockwhenfull) ); return SCIP_OKAY; } /** deinitializes tpi */ SCIP_RETCODE SCIPtpiExit( void ) { assert(_jobqueues != NULL); assert(_jobqueues->finishedjobs.njobs == 0); assert(_jobqueues->jobqueue.njobs == 0); assert(_jobqueues->ncurrentjobs == 0); SCIP_CALL( freeJobQueue() ); return SCIP_OKAY; }
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 4; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
explicit_solver_strategy.h
// // Authors: // Miguel Angel Celigueta maceli@cimne.upc.edu // Miquel Santasusana msantasusana@cimne.upc.edu // #if !defined(KRATOS_EXPLICIT_SOLVER_STRATEGY) #define KRATOS_EXPLICIT_SOLVER_STRATEGY // Project includes #include "utilities/timer.h" #include "custom_elements/Particle_Contact_Element.h" #include "includes/variables.h" #include "includes/deprecated_variables.h" /* System includes */ #include <limits> #include <iostream> #include <iomanip> #include <time.h> /* External includes */ #ifdef _OPENMP #include <omp.h> #endif #define CUSTOMTIMER 0 // ACTIVATES AND DISABLES ::TIMER::::: #include "includes/define.h" #include "utilities/openmp_utils.h" #include "includes/model_part.h" #include "solving_strategies/strategies/solving_strategy.h" #include "solving_strategies/schemes/scheme.h" #include "custom_strategies/schemes/dem_integration_scheme.h" #include "custom_utilities/create_and_destroy.h" #include "custom_utilities/dem_fem_utilities.h" #include "custom_utilities/GeometryFunctions.h" #include "custom_utilities/inlet.h" #include "custom_elements/cluster3D.h" #include "custom_elements/rigid_body_element.h" ////Cfeng #include "custom_utilities/dem_fem_search.h" #include "custom_utilities/discrete_particle_configure.h" #include "custom_utilities/rigid_face_geometrical_object_configure.h" #ifdef USING_CGAL #include <CGAL/spatial_sort.h> #endif /* Timer defines */ #ifdef CUSTOMTIMER #define KRATOS_TIMER_START(t) Timer::Start(t); #define KRATOS_TIMER_STOP(t) Timer::Stop(t); #else #define KRATOS_TIMER_START(t) #define KRATOS_TIMER_STOP(t) #endif namespace Kratos { class ExplicitSolverSettings { public: KRATOS_CLASS_POINTER_DEFINITION(ExplicitSolverSettings); ExplicitSolverSettings() { } ~ExplicitSolverSettings() { } ModelPart* r_model_part; ModelPart* contact_model_part; ModelPart* fem_model_part; ModelPart* cluster_model_part; ModelPart* inlet_model_part; }; class KRATOS_API(DEM_APPLICATION) ExplicitSolverStrategy { public: typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ElementsArrayType::iterator ElementsIterator; typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef ModelPart::NodesContainerType::ContainerType NodesContainerType; typedef ModelPart::ElementsContainerType::ContainerType ElementsContainerType; typedef ModelPart::ConditionsContainerType::ContainerType ConditionsContainerType; typedef SpatialSearch::ResultElementsContainerType ResultElementsContainerType; typedef SpatialSearch::VectorResultElementsContainerType VectorResultElementsContainerType; typedef SpatialSearch::RadiusArrayType RadiusArrayType; typedef SpatialSearch::DistanceType DistanceType; typedef SpatialSearch::VectorDistanceType VectorDistanceType; typedef SpatialSearch::ResultConditionsContainerType ResultConditionsContainerType; typedef SpatialSearch::VectorResultConditionsContainerType VectorResultConditionsContainerType; typedef PointerVectorSet<Properties, IndexedObject> PropertiesContainerType; typedef PropertiesContainerType::iterator PropertiesIterator; typedef DiscreteParticleConfigure<3> ElementConfigureType; typedef RigidFaceGeometricalObjectConfigure<3> RigidFaceGeometricalConfigureType; typedef Variable<double> ComponentOf3ComponentsVariableType; /// Pointer definition of ExplicitSolverStrategy KRATOS_CLASS_POINTER_DEFINITION(ExplicitSolverStrategy); ExplicitSolverStrategy() { } ExplicitSolverStrategy(ExplicitSolverSettings& settings, const double max_delta_time, const int n_step_search, const double safety_factor, const int delta_option, ParticleCreatorDestructor::Pointer p_creator_destructor, DEM_FEM_Search::Pointer p_dem_fem_search, SpatialSearch::Pointer pSpSearch, Parameters strategy_parameters) { mParameters = strategy_parameters; mDeltaOption = delta_option; mpParticleCreatorDestructor = p_creator_destructor; mpDemFemSearch = p_dem_fem_search; mpSpSearch = pSpSearch; if(mParameters["do_search_neighbours"].GetBool()) mDoSearchNeighbourElements = true; else mDoSearchNeighbourElements = false; p_creator_destructor->SetDoSearchNeighbourElements(mDoSearchNeighbourElements); mMaxTimeStep = max_delta_time; mNStepSearch = n_step_search; mSafetyFactor = safety_factor; mpDem_model_part = &(*(settings.r_model_part)); KRATOS_ERROR_IF(mpDem_model_part == NULL) << "Undefined settings.r_model_part in ExplicitSolverStrategy constructor" << std::endl; mpContact_model_part = &(*(settings.contact_model_part)); KRATOS_ERROR_IF(mpContact_model_part == NULL) << "Undefined settings.contact_model_part in ExplicitSolverStrategy constructor" << std::endl; mpFem_model_part = &(*(settings.fem_model_part)); KRATOS_ERROR_IF(mpFem_model_part == NULL) << "Undefined settings.fem_model_part in ExplicitSolverStrategy constructor" << std::endl; mpCluster_model_part = &(*(settings.cluster_model_part)); KRATOS_ERROR_IF(mpCluster_model_part == NULL) << "Undefined settings.cluster_model_part in ExplicitSolverStrategy constructor" << std::endl; mpInlet_model_part = &(*(settings.inlet_model_part)); KRATOS_ERROR_IF(mpInlet_model_part == NULL) << "Undefined settings.inlet_model_part in ExplicitSolverStrategy constructor" << std::endl; if(mParameters["RemoveBallsInitiallyTouchingWalls"].GetBool()) mRemoveBallsInitiallyTouchingWallsOption = true; else mRemoveBallsInitiallyTouchingWallsOption = false; } /// Destructor. virtual ~ExplicitSolverStrategy() { //Timer::SetOuputFile("TimesPartialRelease"); //Timer::PrintTimingInformation(); } struct LessX { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[0] < q->GetGeometry()[0].Coordinates()[0];} }; struct LessY { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[1] < q->GetGeometry()[0].Coordinates()[1];} }; struct LessZ { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[2] < q->GetGeometry()[0].Coordinates()[2];} }; struct SpatialSortingTraits { typedef SphericParticle* Point_2; typedef LessX Less_x_2; typedef LessY Less_y_2; typedef LessZ Less_z_2; Less_x_2 less_x_2_object() const {return Less_x_2();} Less_y_2 less_y_2_object() const {return Less_y_2();} Less_z_2 less_z_2_object() const { return Less_z_2();} }; #ifdef USING_CGAL void ReorderParticles() { SpatialSortingTraits sst; CGAL::spatial_sort(mListOfSphericParticles.begin(), mListOfSphericParticles.end(), sst); } #endif template <class T> void RebuildListOfSphericParticles(ElementsArrayType& pElements, std::vector<T*>& rCustomListOfParticles){ KRATOS_TRY rCustomListOfParticles.resize(pElements.size()); #pragma omp parallel for for (int k = 0; k < (int)pElements.size(); k++){ ElementsArrayType::iterator particle_pointer_it = pElements.ptr_begin() + k; T* spheric_particle = dynamic_cast<T*>(&(*particle_pointer_it)); rCustomListOfParticles[k] = spheric_particle; } return; KRATOS_CATCH("") } void RebuildListOfDiscontinuumSphericParticles() { RebuildListOfSphericParticles<SphericParticle>(GetModelPart().GetCommunicator().LocalMesh().Elements(), mListOfSphericParticles); } void RebuildPropertiesProxyPointers(std::vector<SphericParticle*>& rCustomListOfSphericParticles); void SendProcessInfoToClustersModelPart(); void UpdateMaxIdOfCreatorDestructor(); void RepairPointersToNormalProperties(std::vector<SphericParticle*>& rCustomListOfSphericParticles); virtual void Initialize(); virtual void AttachSpheresToStickyWalls(); virtual void DisplayThreadInfo(); virtual void CalculateMaxTimeStep(); double CalculateMaxInletTimeStep(); virtual void InitializeClusters(); virtual void GetClustersForce(); virtual void GetRigidBodyElementsForce(); virtual double SolveSolutionStep(); void SearchDEMOperations(ModelPart& r_model_part, bool has_mpi = true); void SearchFEMOperations(ModelPart& r_model_part, bool has_mpi = true) ; virtual void ForceOperations(ModelPart& r_model_part); void InitialTimeStepCalculation(); //TODO: remove this one void GetForce(); void FastGetForce(); virtual void PerformTimeIntegrationOfMotion(int StepFlag = 0); void InitializeSolutionStep(); virtual void BoundingBoxUtility(bool is_time_to_mark_and_remove = true); virtual void FinalizeSolutionStep(); void InitializeElements(); void InitializeDEMElements(); void InitializeFEMElements(); //void InitializeRigidBodyElements(); void InitializeFEMWallsAsRigidBodyElements(ModelPart::SubModelPartsContainerType::iterator& sub_model_part); void MarkToDeleteAllSpheresInitiallyIndentedWithFEM(ModelPart& rSpheresModelPart); void ComputeNodalArea(); void ComputeNormalPressureVectorField(); virtual void CalculateConditionsRHSAndAdd(); void ClearFEMForces(); void CalculateNodalPressuresAndStressesOnWalls(); void SetFlagAndVariableToNodes(const Kratos::Flags& r_flag_name, ComponentOf3ComponentsVariableType& r_variable_to_set, const double value, NodesArrayType& r_nodes_array); void SetVariableToNodes(ComponentOf3ComponentsVariableType& r_variable_to_set, const double value, NodesArrayType& r_nodes_array); void ResetPrescribedMotionFlagsRespectingImposedDofs(); void ApplyPrescribedBoundaryConditions(); void ApplyInitialConditions(); void SetSearchRadiiOnAllParticles(ModelPart& r_model_part, const double added_search_distance = 0.0, const double amplification = 1.0); void SetNormalRadiiOnAllParticles(ModelPart& r_model_part); void SetSearchRadiiWithFemOnAllParticles(ModelPart& r_model_part, const double added_search_distance = 0.0, const double amplification = 1.0); virtual void SearchNeighbours(); virtual void ComputeNewNeighboursHistoricalData(); virtual void CreateContactElements(); void InitializeContactElements(); // void ContactInitializeSolutionStep(); void PrepareContactElementsForPrinting(); virtual void ComputeNewRigidFaceNeighboursHistoricalData(); virtual void SearchRigidFaceNeighbours(); void CheckHierarchyWithCurrentNeighbours(); /* This should work only with one iteration, but it with mpi does not */ void CalculateInitialMaxIndentations(const ProcessInfo& r_process_info); void PrepareContactModelPart(ModelPart& r_model_part, ModelPart& mcontacts_model_part); void PrepareElementsForPrinting(); void SynchronizeHistoricalVariables(ModelPart& r_model_part); void SynchronizeRHS(ModelPart& r_model_part); void CleanEnergies(); ModelPart& GetModelPart() { return (*mpDem_model_part);} ModelPart& GetFemModelPart() { return (*mpFem_model_part);} ModelPart& GetContactModelPart() { return (*mpContact_model_part);} ModelPart& GetClusterModelPart() { return (*mpCluster_model_part);} ModelPart& GetInletModelPart() { return (*mpInlet_model_part);} ModelPart& GetRigidBodyModelPart() { return (*mpRigidBody_model_part);} VectorResultElementsContainerType& GetResults() { return (mResults);} VectorDistanceType& GetResultsDistances() { return (mResultsDistances);} RadiusArrayType& GetArrayOfAmplifiedRadii() { return (mArrayOfAmplifiedRadii);} int& GetNStepSearch() { return (mNStepSearch);} int& GetSearchControl() { return mSearchControl;} int& GetNumberOfThreads() { return (mNumberOfThreads);} double& GetMaxTimeStep() { return (mMaxTimeStep);} double& GetSafetyFactor() { return (mSafetyFactor);} int& GetDeltaOption() { return (mDeltaOption);} std::vector<unsigned int>& GetElementPartition() { return (mElementPartition);} ParticleCreatorDestructor::Pointer& GetParticleCreatorDestructor() { return (mpParticleCreatorDestructor);} SpatialSearch::Pointer& GetSpSearch() { return (mpSpSearch);} VectorResultConditionsContainerType& GetRigidFaceResults() { return (mRigidFaceResults);} VectorDistanceType& GetRigidFaceResultsDistances() { return (mRigidFaceResultsDistances);} std::vector<unsigned int>& GetConditionPartition() { return (mConditionPartition);} DEM_FEM_Search::Pointer& GetDemFemSearch() { return (mpDemFemSearch);} virtual ElementsArrayType& GetElements(ModelPart& r_model_part) { return r_model_part.GetCommunicator().LocalMesh().Elements();} virtual ElementsArrayType& GetAllElements(ModelPart& r_model_part) { return r_model_part.Elements(); } protected: Parameters mParameters; bool mRemoveBallsInitiallyTouchingWallsOption; VectorResultElementsContainerType mResults; VectorDistanceType mResultsDistances; RadiusArrayType mArrayOfAmplifiedRadii; int mNStepSearch; int mSearchControl; int mNumberOfThreads; double mMaxTimeStep; double mSafetyFactor; int mDeltaOption; std::vector<unsigned int> mElementPartition; ParticleCreatorDestructor::Pointer mpParticleCreatorDestructor; DEM_FEM_Search::Pointer mpDemFemSearch; SpatialSearch::Pointer mpSpSearch; bool mDoSearchNeighbourElements; VectorResultConditionsContainerType mRigidFaceResults; VectorDistanceType mRigidFaceResultsDistances; std::vector<unsigned int> mConditionPartition; ModelPart *mpFem_model_part; ModelPart *mpDem_model_part; ModelPart *mpInlet_model_part; ModelPart *mpContact_model_part; ModelPart *mpCluster_model_part; ModelPart *mpRigidBody_model_part; std::vector<SphericParticle*> mListOfSphericParticles; std::vector<SphericParticle*> mListOfGhostSphericParticles; }; // Class ExplicitSolverStrategy } // namespace Kratos. #endif // KRATOS_EXPLICIT_SOLVER_STRATEGY defined
GB_binop__gt_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__gt_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__gt_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__gt_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__gt_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__gt_uint16) // A*D function (colscale): GB (_AxD__gt_uint16) // D*A function (rowscale): GB (_DxB__gt_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__gt_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__gt_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__gt_uint16) // C=scalar+B GB (_bind1st__gt_uint16) // C=scalar+B' GB (_bind1st_tran__gt_uint16) // C=A+scalar GB (_bind2nd__gt_uint16) // C=A'+scalar GB (_bind2nd_tran__gt_uint16) // C type: bool // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 0 // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint16_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x > y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GT || GxB_NO_UINT16 || GxB_NO_GT_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__gt_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__gt_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__gt_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__gt_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__gt_uint16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__gt_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint16_t alpha_scalar ; uint16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ; beta_scalar = (*((uint16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__gt_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__gt_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__gt_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__gt_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__gt_uint16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = (x > bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__gt_uint16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = (aij > y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB (_bind1st_tran__gt_uint16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB (_bind2nd_tran__gt_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Example_simple_lock.1.c
/* * @@name: simple_lock.1c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: success */ #include <stdio.h> #include <omp.h> void skip(int i) {} void work(int i) {} int main() { omp_lock_t lck; int id; omp_init_lock(&lck); #pragma omp parallel shared(lck) private(id) { id = omp_get_thread_num(); omp_set_lock(&lck); /* only one thread at a time can execute this printf */ printf("My thread id is %d.\n", id); omp_unset_lock(&lck); while (! omp_test_lock(&lck)) { skip(id); /* we do not yet have the lock, so we must do something else */ } work(id); /* we now have the lock and can do the work */ omp_unset_lock(&lck); } omp_destroy_lock(&lck); return 0; }
GB_binop__iseq_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_08__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_02__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_04__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_int64) // A*D function (colscale): GB (_AxD__iseq_int64) // D*A function (rowscale): GB (_DxB__iseq_int64) // C+=B function (dense accum): GB (_Cdense_accumB__iseq_int64) // C+=b function (dense accum): GB (_Cdense_accumb__iseq_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_int64) // C=scalar+B GB (_bind1st__iseq_int64) // C=scalar+B' GB (_bind1st_tran__iseq_int64) // C=A+scalar GB (_bind2nd__iseq_int64) // C=A'+scalar GB (_bind2nd_tran__iseq_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISEQ || GxB_NO_INT64 || GxB_NO_ISEQ_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__iseq_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__iseq_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__iseq_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__iseq_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__iseq_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__iseq_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__iseq_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__iseq_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__iseq_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__iseq_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__iseq_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__iseq_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__iseq_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__iseq_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
rawSHA256_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2010 by Solar Designer * based on rawMD4_fmt.c code, with trivial changes by groszek. * * Understands hex hashes as well as Cisco "type 4" base64. * * Rewritten Spring 2013, JimF. SSE code added and released with the following terms: * No copyright is claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is Copyright (c) 2011 JimF * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rawSHA256; #elif FMT_REGISTERS_H john_register_one(&fmt_rawSHA256); #else #include <stdint.h> #include "arch.h" #include "sha2.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "formats.h" //#undef SIMD_COEF_32 //#undef SIMD_PARA_SHA256 /* * Only effective for SIMD. * Undef to disable reversing steps for benchmarking. */ #define REVERSE_STEPS #ifdef _OPENMP #ifdef SIMD_COEF_32 #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include <omp.h> #endif #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "Raw-SHA256" #define FORMAT_NAME "" #ifdef SIMD_COEF_32 #define ALGORITHM_NAME SHA256_ALGORITHM_NAME #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR " " SHA2_LIB #endif /* Note: Cisco hashes are truncated at length 25. We currently ignore this. */ #ifdef SIMD_COEF_32 #define PLAINTEXT_LENGTH 55 #else #define PLAINTEXT_LENGTH 125 #endif #define _RAWSHA256_H #include "rawSHA256_common.h" #undef _RAWSHA256_H #define BINARY_SIZE 4 #define SALT_SIZE 0 #define SALT_ALIGN 1 #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_32*SIMD_PARA_SHA256) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_32*SIMD_PARA_SHA256) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #ifdef SIMD_COEF_32 #define FMT_IS_BE #include "common-simd-getpos.h" static uint32_t (*saved_key); static uint32_t (*crypt_out); #else static int (*saved_len); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out) [(DIGEST_SIZE + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifndef SIMD_COEF_32 saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); #else saved_key = mem_calloc_align(self->params.max_keys_per_crypt * SHA_BUF_SIZ, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_out = mem_calloc_align(self->params.max_keys_per_crypt * 8, sizeof(*crypt_out), MEM_ALIGN_SIMD); #endif } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); #ifndef SIMD_COEF_32 MEM_FREE(saved_len); #endif } static void *get_binary(char *ciphertext) { static unsigned int *outw; unsigned char *out; char *p; int i; if (!outw) outw = mem_calloc_tiny(DIGEST_SIZE, MEM_ALIGN_WORD); out = (unsigned char*)outw; p = ciphertext + HEX_TAG_LEN; for (i = 0; i < DIGEST_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef SIMD_COEF_32 #if ARCH_LITTLE_ENDIAN alter_endianity (out, DIGEST_SIZE); #endif #ifdef REVERSE_STEPS sha256_reverse(outw); #endif #endif return out; } #define COMMON_GET_HASH_SIMD32 8 #define COMMON_GET_HASH_VAR crypt_out #include "common-get-hash.h" #define HASH_IDX ((((unsigned int)index)&(SIMD_COEF_32-1))+(((unsigned int)index)/SIMD_COEF_32)*SIMD_COEF_32*8) #define NON_SIMD_SET_SAVED_LEN #include "common-simd-setkey32.h" #ifndef REVERSE_STEPS #undef SSEi_REVERSE_STEPS #define SSEi_REVERSE_STEPS 0 #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_32 SIMDSHA256body(&saved_key[(unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32], &crypt_out[(unsigned int)index/SIMD_COEF_32*8*SIMD_COEF_32], NULL, SSEi_REVERSE_STEPS | SSEi_MIXED_IN); #else SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, saved_key[index], saved_len[index]); SHA256_Final((unsigned char *)crypt_out[index], &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { unsigned int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_32 if (((uint32_t*) binary)[0] == crypt_out[HASH_IDX]) #else if ( ((uint32_t*)binary)[0] == crypt_out[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 return ((uint32_t*)binary)[0] == crypt_out[HASH_IDX]; #else return *(uint32_t*)binary == crypt_out[index][0]; #endif } static int cmp_exact(char *source, int index) { uint32_t *binary = get_binary(source); char *key = get_key(index); SHA256_CTX ctx; uint32_t crypt_out[DIGEST_SIZE / sizeof(uint32_t)]; SHA256_Init(&ctx); SHA256_Update(&ctx, key, strlen(key)); SHA256_Final((unsigned char*)crypt_out, &ctx); #ifdef SIMD_COEF_32 #if ARCH_LITTLE_ENDIAN alter_endianity(crypt_out, DIGEST_SIZE); #endif #ifdef REVERSE_STEPS sha256_reverse(crypt_out); #endif #endif return !memcmp(binary, crypt_out, DIGEST_SIZE); } struct fmt_main fmt_rawSHA256 = { { FORMAT_LABEL, FORMAT_NAME, "SHA256 " ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD | FMT_SPLIT_UNIFIES_CASE, { NULL }, { HEX_TAG, CISCO_TAG }, sha256_common_tests }, { init, done, fmt_default_reset, sha256_common_prepare, sha256_common_valid, sha256_common_split, get_binary, fmt_default_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 8; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1,2),ceild(8*t2-Nz+5,8));t3<=min(floord(4*Nt+Ny-9,8),floord(4*t1+Ny-1,8));t3++) { for (t4=max(max(ceild(t1-6,8),ceild(8*t2-Nz-19,32)),ceild(8*t3-Ny-19,32));t4<=min(min(floord(4*Nt+Nx-9,32),floord(4*t1+Nx-1,32)),floord(8*t3+Nx-5,32));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(32*t4-Nx+5,4)),t1);t5<=min(min(min(2*t3,Nt-1),t1+1),8*t4+6);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(32*t4,4*t5+4); ubv=min(32*t4+31,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 24; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(24*t2-Nz-11,24));t3<=min(min(min(floord(4*Nt+Ny-9,24),floord(12*t1+Ny+15,24)),floord(24*t2+Ny+11,24)),floord(24*t1-24*t2+Nz+Ny+13,24));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-14,16)),ceild(3*t1-30,32)),ceild(24*t2-Nz-115,128)),ceild(24*t3-Ny-115,128));t4<=min(min(min(min(floord(4*Nt+Nx-9,128),floord(12*t1+Nx+15,128)),floord(24*t2+Nx+11,128)),floord(24*t3+Nx+11,128)),floord(24*t1-24*t2+Nz+Nx+13,128));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(24*t3-Ny+5,4)),ceild(128*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),6*t3+4),32*t4+30);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(24*t3,4*t5+4);t7<=min(24*t3+23,4*t5+Ny-5);t7++) { lbv=max(128*t4,4*t5+4); ubv=min(128*t4+127,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
nco_rgr.c
/* $Header$ */ /* Purpose: NCO regridding utilities */ /* Copyright (C) 2015--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License with exceptions described in the LICENSE file */ #include "nco_rgr.h" /* Regridding */ extern double min_dbl(double a, double b); extern double max_dbl(double a, double b); inline double min_dbl(double a, double b){return (a < b) ? a : b;} inline double max_dbl(double a, double b){return (a > b) ? a : b;} int /* O [enm] Return code */ nco_rgr_ctl /* [fnc] Control regridding logic */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Control regridding logic */ int rcd=NCO_NOERR; const char fnc_nm[]="nco_rgr_ctl()"; nco_bool flg_grd=False; /* [flg] Create SCRIP-format grid file */ nco_bool flg_map=False; /* [flg] Create ESMF-format mapfile */ nco_bool flg_nfr=False; /* [flg] Infer SCRIP-format grid file */ nco_bool flg_smf=False; /* [flg] ESMF regridding (unused) */ nco_bool flg_s1d=False; /* [flg] Unpack sparse-1D CLM/ELM variables */ nco_bool flg_tps=False; /* [flg] Tempest regridding (unused) */ nco_bool flg_vrt=False; /* [flg] Interpolate to new vertical grid */ nco_bool flg_wgt=False; /* [flg] Regrid with external weights */ /* Main control branching occurs here Branching complexity and utility will increase as regridding features are added */ if(rgr->flg_grd) flg_grd=True; if(rgr->flg_grd_src && rgr->flg_grd_dst && rgr->flg_wgt) flg_map=True; if(rgr->flg_nfr) flg_nfr=True; if(rgr->flg_wgt && !(rgr->flg_grd_src && rgr->flg_grd_dst)) flg_wgt=True; if(rgr->flg_s1d) flg_s1d=True; if(rgr->fl_vrt) flg_vrt=True; assert(!flg_smf); assert(!flg_tps); /* Create SCRIP-format grid file */ if(flg_grd) rcd=nco_grd_mk(rgr); /* Create ESMF-format map file */ if(flg_map) rcd=nco_map_mk(rgr); /* Infer SCRIP-format grid file from data file */ if(flg_nfr) rcd=nco_grd_nfr(rgr); /* Interpolate data file to new vertical grid */ if(flg_vrt) rcd=nco_ntp_vrt(rgr,trv_tbl); /* Unpack sparse-1D CLM/ELM variables into full file */ if(flg_s1d) rcd=nco_s1d_unpack(rgr,trv_tbl); /* Regrid data horizontally using weights from mapping file */ if(flg_wgt) rcd=nco_rgr_wgt(rgr,trv_tbl); /* Regrid using ESMF library 20150701: On-line weight generation with ESMF never worked well and was abandoned */ if(flg_smf){ #ifdef ENABLE_ESMF (void)fprintf(stderr,"%s: %s calling nco_rgr_esmf() to generate and apply regridding map\n",nco_prg_nm_get(),fnc_nm); rcd=nco_rgr_esmf(rgr); /* Close output and free dynamic memory */ (void)nco_fl_out_cls(rgr->fl_out,rgr->fl_out_tmp,rgr->out_id); #else /* !ENABLE_ESMF */ (void)fprintf(stderr,"%s: ERROR %s reports attempt to use ESMF regridding without built-in support. Re-configure with --enable_esmf.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); #endif /* !ENABLE_ESMF */ } /* !flg_smf */ /* Regrid using TempestRemap regridding 20180314: Weight generation with Tempest is implemented off-line via ncremap, not internally on-line However, do not deprecate this since TempestRemap2 has a library that could be accessed on-line */ if(flg_tps) rcd=nco_rgr_tps(rgr); return rcd; } /* end nco_rgr_ctl() */ rgr_sct * /* O [sct] Pointer to free'd regridding structure */ nco_rgr_free /* [fnc] Deallocate regridding structure */ (rgr_sct *rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Free all dynamic memory in regridding structure */ /* free() standalone command-line arguments */ if(rgr->cmd_ln) rgr->cmd_ln=(char *)nco_free(rgr->cmd_ln); if(rgr->grd_ttl) rgr->grd_ttl=(char *)nco_free(rgr->grd_ttl); if(rgr->fl_grd_src) rgr->fl_grd_src=(char *)nco_free(rgr->fl_grd_src); if(rgr->fl_grd_dst) rgr->fl_grd_dst=(char *)nco_free(rgr->fl_grd_dst); if(rgr->fl_hrz) rgr->fl_hrz=(char *)nco_free(rgr->fl_hrz); if(rgr->fl_in) rgr->fl_in=(char *)nco_free(rgr->fl_in); if(rgr->fl_map) rgr->fl_map=(char *)nco_free(rgr->fl_map); if(rgr->fl_msh) rgr->fl_msh=(char *)nco_free(rgr->fl_msh); if(rgr->fl_out) rgr->fl_out=(char *)nco_free(rgr->fl_out); if(rgr->fl_out_tmp) rgr->fl_out_tmp=(char *)nco_free(rgr->fl_out_tmp); if(rgr->fl_vrt) rgr->fl_vrt=(char *)nco_free(rgr->fl_vrt); if(rgr->var_nm) rgr->var_nm=(char *)nco_free(rgr->var_nm); if(rgr->xtn_var) rgr->xtn_var=(char **)nco_sng_lst_free(rgr->xtn_var,rgr->xtn_nbr); /* free() strings associated with grid properties */ if(rgr->fl_grd) rgr->fl_grd=(char *)nco_free(rgr->fl_grd); if(rgr->fl_hnt_dst) rgr->fl_hnt_dst=(char *)nco_free(rgr->fl_hnt_dst); if(rgr->fl_hnt_src) rgr->fl_hnt_src=(char *)nco_free(rgr->fl_hnt_src); if(rgr->fl_skl) rgr->fl_skl=(char *)nco_free(rgr->fl_skl); if(rgr->fl_ugrid) rgr->fl_ugrid=(char *)nco_free(rgr->fl_ugrid); /* Tempest */ if(rgr->drc_tps) rgr->drc_tps=(char *)nco_free(rgr->drc_tps); /* free() memory used to construct KVMs */ if(rgr->rgr_nbr > 0) rgr->rgr_arg=nco_sng_lst_free(rgr->rgr_arg,rgr->rgr_nbr); /* free() memory copied from KVMs */ if(rgr->area_nm) rgr->area_nm=(char *)nco_free(rgr->area_nm); if(rgr->bnd_nm) rgr->bnd_nm=(char *)nco_free(rgr->bnd_nm); if(rgr->bnd_tm_nm) rgr->bnd_tm_nm=(char *)nco_free(rgr->bnd_tm_nm); if(rgr->col_nm_in) rgr->col_nm_in=(char *)nco_free(rgr->col_nm_in); if(rgr->col_nm_out) rgr->col_nm_out=(char *)nco_free(rgr->col_nm_out); if(rgr->frc_nm) rgr->frc_nm=(char *)nco_free(rgr->frc_nm); if(rgr->ilev_nm_in) rgr->ilev_nm_in=(char *)nco_free(rgr->ilev_nm_in); if(rgr->ilev_nm_out) rgr->ilev_nm_out=(char *)nco_free(rgr->ilev_nm_out); if(rgr->lat_bnd_nm) rgr->lat_bnd_nm=(char *)nco_free(rgr->lat_bnd_nm); if(rgr->lat_nm_in) rgr->lat_nm_in=(char *)nco_free(rgr->lat_nm_in); if(rgr->lat_nm_out) rgr->lat_nm_out=(char *)nco_free(rgr->lat_nm_out); if(rgr->lat_vrt_nm) rgr->lat_vrt_nm=(char *)nco_free(rgr->lat_vrt_nm); if(rgr->lat_wgt_nm) rgr->lat_wgt_nm=(char *)nco_free(rgr->lat_wgt_nm); if(rgr->lev_nm_in) rgr->lev_nm_in=(char *)nco_free(rgr->lev_nm_in); if(rgr->lev_nm_out) rgr->lev_nm_out=(char *)nco_free(rgr->lev_nm_out); if(rgr->lon_bnd_nm) rgr->lon_bnd_nm=(char *)nco_free(rgr->lon_bnd_nm); if(rgr->lon_nm_in) rgr->lon_nm_in=(char *)nco_free(rgr->lon_nm_in); if(rgr->lon_nm_out) rgr->lon_nm_out=(char *)nco_free(rgr->lon_nm_out); if(rgr->lon_vrt_nm) rgr->lon_vrt_nm=(char *)nco_free(rgr->lon_vrt_nm); if(rgr->msk_nm) rgr->msk_nm=(char *)nco_free(rgr->msk_nm); if(rgr->plev_nm_in) rgr->plev_nm_in=(char *)nco_free(rgr->plev_nm_in); if(rgr->vrt_nm) rgr->vrt_nm=(char *)nco_free(rgr->vrt_nm); /* Lastly, free() regrid structure itself */ if(rgr) rgr=(rgr_sct *)nco_free(rgr); return rgr; } /* end nco_rgr_free() */ rgr_sct * /* O [sct] Regridding structure */ nco_rgr_ini /* [fnc] Initialize regridding structure */ (const char * const cmd_ln, /* I [sng] Command-line */ const int in_id, /* I [id] Input netCDF file ID */ char **rgr_arg, /* [sng] Regridding arguments */ const int rgr_arg_nbr, /* [nbr] Number of regridding arguments */ char * const rgr_in, /* I [sng] File containing fields to be regridded */ char * const rgr_out, /* I [sng] File containing regridded fields */ char * const rgr_grd_src, /* I [sng] File containing input grid */ char * const rgr_grd_dst, /* I [sng] File containing destination grid */ char * const rgr_hrz, /* I [sng] File containing horizontal coordinate grid */ char * const rgr_map, /* I [sng] File containing mapping weights from source to destination grid */ char * const rgr_var, /* I [sng] Variable for special regridding treatment */ char * const rgr_vrt, /* I [sng] File containing vertical coordinate grid */ const double wgt_vld_thr, /* I [frc] Weight threshold for valid destination value */ char **xtn_var, /* [sng] I Extensive variables */ const int xtn_nbr) /* [nbr] I Number of extensive variables */ { /* Purpose: Initialize regridding structure */ const char fnc_nm[]="nco_rgr_ini()"; rgr_sct *rgr; /* Allocate */ rgr=(rgr_sct *)nco_malloc(sizeof(rgr_sct)); /* Initialize variables directly or indirectly set via command-line (except for key-value arguments) */ rgr->cmd_ln=strdup(cmd_ln); /* [sng] Command-line */ rgr->flg_usr_rqs=False; /* [flg] User requested regridding */ rgr->out_id=int_CEWI; /* [id] Output netCDF file ID */ rgr->in_id=in_id; /* [id] Input netCDF file ID */ rgr->rgr_arg=rgr_arg; /* [sng] Regridding arguments */ rgr->rgr_nbr=rgr_arg_nbr; /* [nbr] Number of regridding arguments */ rgr->drc_tps=NULL; /* [sng] Directory where Tempest grids, meshes, and weights are stored */ rgr->flg_grd_src= rgr_grd_src ? True : False; /* [flg] User-specified input grid */ rgr->fl_grd_src=rgr_grd_src; /* [sng] File containing input grid */ rgr->flg_grd_dst= rgr_grd_dst ? True : False; /* [flg] User-specified destination grid */ rgr->fl_grd_dst=rgr_grd_dst; /* [sng] File containing destination grid */ rgr->fl_in=rgr_in; /* [sng] File containing fields to be regridded */ rgr->fl_out=rgr_out; /* [sng] File containing regridded fields */ rgr->fl_out_tmp=NULL_CEWI; /* [sng] Temporary file containing regridded fields */ rgr->flg_wgt= rgr_map ? True : False; /* [flg] User-specified mapping weights */ rgr->fl_map=rgr_map; /* [sng] File containing mapping weights from source to destination grid */ rgr->fl_hrz=rgr_hrz; /* [sng] [sng] File containing horizontal coordinate grid (for S1D) */ rgr->fl_vrt=rgr_vrt; /* [sng] [sng] File containing vertical coordinate grid */ rgr->var_nm=rgr_var; /* [sng] Variable for special regridding treatment */ rgr->xtn_var=xtn_var; /* [sng] Extensive variables */ rgr->xtn_nbr=xtn_nbr; /* [nbr] Number of extensive variables */ /* Did user explicitly request regridding? */ if(rgr_arg_nbr > 0 || rgr_grd_src != NULL || rgr_grd_dst != NULL || rgr_map != NULL || rgr_vrt != NULL) rgr->flg_usr_rqs=True; /* Initialize arguments after copying */ if(!rgr->fl_out) rgr->fl_out=(char *)strdup("/data/zender/rgr/rgr_out.nc"); if(!rgr->fl_grd_dst) rgr->fl_grd_dst=(char *)strdup("/data/zender/scrip/grids/remap_grid_T42.nc"); // if(!rgr->var_nm) rgr->var_nm=(char *)strdup("ORO"); if(nco_dbg_lvl_get() >= nco_dbg_crr){ (void)fprintf(stderr,"%s: INFO %s reports ",nco_prg_nm_get(),fnc_nm); (void)fprintf(stderr,"flg_usr_rqs = %d, ",rgr->flg_usr_rqs); (void)fprintf(stderr,"rgr_nbr = %d, ",rgr->rgr_nbr); (void)fprintf(stderr,"fl_grd_src = %s, ",rgr->fl_grd_src ? rgr->fl_grd_src : "NULL"); (void)fprintf(stderr,"fl_grd_dst = %s, ",rgr->fl_grd_dst ? rgr->fl_grd_dst : "NULL"); (void)fprintf(stderr,"fl_hrz = %s, ",rgr->fl_hrz ? rgr->fl_hrz : "NULL"); (void)fprintf(stderr,"fl_in = %s, ",rgr->fl_in ? rgr->fl_in : "NULL"); (void)fprintf(stderr,"fl_out = %s, ",rgr->fl_out ? rgr->fl_out : "NULL"); (void)fprintf(stderr,"fl_out_tmp = %s, ",rgr->fl_out_tmp ? rgr->fl_out_tmp : "NULL"); (void)fprintf(stderr,"fl_map = %s, ",rgr->fl_map ? rgr->fl_map : "NULL"); (void)fprintf(stderr,"fl_vrt = %s, ",rgr->fl_vrt ? rgr->fl_vrt : "NULL"); (void)fprintf(stderr,"\n"); } /* endif dbg */ /* Flags */ if(wgt_vld_thr == NC_MIN_DOUBLE){ rgr->flg_rnr=False; }else if(wgt_vld_thr >= 0.0 && wgt_vld_thr <= 1.0){ /* NB: Weight thresholds of 0.0 or nearly zero can lead to underflow or divide-by-zero errors */ // const double wgt_vld_thr_min=1.0e-10; /* [frc] Minimum weight threshold for valid destination value */ rgr->flg_rnr=True; rgr->wgt_vld_thr=wgt_vld_thr; }else{ (void)fprintf(stderr,"%s: ERROR weight threshold must be in [0.0,1.0] and user supplied wgt_vld_thr = %g\n",nco_prg_nm_get(),wgt_vld_thr); nco_exit(EXIT_FAILURE); } /* endif */ /* Parse extended kvm options */ char *sng_fnl=NULL; int cnv_nbr; /* [nbr] Number of elements converted by sscanf() */ int rgr_var_idx; /* [idx] Index over rgr_lst (i.e., all names explicitly specified in all "--rgr var1[,var2]=val" options) */ int rgr_var_nbr=0; kvm_sct *rgr_lst=NULL; /* [sct] List of all regrid specifications */ if(rgr_arg_nbr > 0){ /* Join arguments together */ sng_fnl=nco_join_sng(rgr_arg,rgr_arg_nbr); rgr_lst=nco_arg_mlt_prs(sng_fnl); if(sng_fnl) sng_fnl=(char *)nco_free(sng_fnl); /* Count number of keys */ for(rgr_var_idx=0;(rgr_lst+rgr_var_idx)->key;rgr_var_idx++,rgr_var_nbr++);/* !rgr_var_idx */ } /* !rgr_arg_nbr */ /* NULL-initialize key-value properties required for string variables */ rgr->area_nm=NULL; /* [sng] Name of variable containing gridcell area */ rgr->bnd_nm=NULL; /* [sng] Name of dimension to employ for spatial bounds */ rgr->bnd_tm_nm=NULL; /* [sng] Name of dimension to employ for temporal bounds */ rgr->col_nm_in=NULL; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ rgr->col_nm_out=NULL; /* [sng] Name of horizontal spatial output dimension on unstructured grid */ rgr->frc_nm=NULL; /* [sng] Name of variable containing gridcell fraction */ rgr->ilev_nm_in=NULL; /* [sng] Name of input dimension to recognize as vertical dimension at layer interfaces */ rgr->ilev_nm_out=NULL; /* [sng] Name of output vertical dimension at layer interfaces */ rgr->lat_bnd_nm=NULL; /* [sng] Name of rectangular boundary variable for latitude */ rgr->lat_dmn_nm=NULL; /* [sng] Name of latitude dimension in inferred grid */ rgr->lat_nm_in=NULL; /* [sng] Name of input dimension to recognize as latitude */ rgr->lat_nm_out=NULL; /* [sng] Name of output dimension for latitude */ rgr->lat_vrt_nm=NULL; /* [sng] Name of non-rectangular boundary variable for latitude */ rgr->lat_wgt_nm=NULL; /* [sng] Name of variable containing latitude weights */ rgr->lev_nm_in=NULL; /* [sng] Name of input dimension to recognize as vertical dimension at layer midpoints */ rgr->lev_nm_out=NULL; /* [sng] Name of output vertical dimension at layer midpoints */ rgr->lon_bnd_nm=NULL; /* [sng] Name of rectangular boundary variable for longitude */ rgr->lon_dmn_nm=NULL; /* [sng] Name of longitude dimension in inferred grid */ rgr->lon_nm_in=NULL; /* [sng] Name of dimension to recognize as longitude */ rgr->lon_nm_out=NULL; /* [sng] Name of output dimension for longitude */ rgr->lon_vrt_nm=NULL; /* [sng] Name of non-rectangular boundary variable for longitude */ rgr->msk_nm=NULL; /* [sng] Name of variable containing destination mask */ rgr->plev_nm_in=NULL; /* [sng] Name of input variable recognize as pure-pressure coordinate */ rgr->sgs_frc_nm=NULL; /* [sng] Name of variable sub-gridscale fraction */ rgr->sgs_msk_nm=NULL; /* [sng] Name of variable sub-gridscale mask */ rgr->vrt_nm=NULL; /* [sng] Name of dimension to employ for vertices */ /* Initialize key-value properties used in grid and weight generation */ rgr->area_mth=1; /* [enm] Method to compute grid cell area */ rgr->edg_typ=nco_edg_nil; /* [enm] Edge/Arc-type for triangle edges */ rgr->fl_grd=NULL; /* [sng] Name of SCRIP grid file to create */ rgr->fl_hnt_dst=NULL; /* [sng] ERWG hint destination */ rgr->fl_hnt_src=NULL; /* [sng] ERWG hint source */ rgr->fl_msh=NULL; /* [sng] Name of SCRIP intersection mesh file to create */ rgr->fl_skl=NULL; /* [sng] Name of skeleton data file to create */ rgr->fl_ugrid=NULL; /* [sng] Name of UGRID grid file to create */ rgr->flg_area_out=True; /* [flg] Add area to output */ rgr->flg_cf_units=False; /* [flg] Generate CF-compliant (breaks ERWG 7.1.0r-) units fields in SCRIP-format grid files */ rgr->flg_cll_msr=True; /* [flg] Add cell_measures attribute */ rgr->flg_crv=False; /* [flg] Use curvilinear coordinates */ rgr->flg_dgn_area=False; /* [flg] Diagnose rather than copy inferred area */ rgr->flg_dgn_bnd=False; /* [flg] Diagnose rather than copy inferred bounds */ rgr->flg_erwg_units=True; /* [flg] Generate ERWG 7.1.0r-compliant SCRIP-format grid files */ rgr->flg_grd=False; /* [flg] Create SCRIP-format grid file */ rgr->flg_msk_out=False; /* [flg] Add mask to output */ rgr->flg_nfr=False; /* [flg] Infer SCRIP-format grid file */ rgr->flg_s1d=False; /* [flg] Unpack sparse-1D CLM/ELM variables */ rgr->flg_stg=True; /* [flg] Write staggered grid with FV output */ rgr->grd_ttl=strdup("None given (supply with --rgr grd_ttl=\"Grid Title\")"); /* [enm] Grid title */ rgr->grd_typ=nco_grd_2D_eqa; /* [enm] Grid type */ rgr->idx_dbg=0; /* [idx] Index of gridcell for debugging */ rgr->lat_drc=nco_grd_lat_drc_s2n; /* [enm] Latitude grid direction */ rgr->lat_typ=nco_grd_lat_eqa; /* [enm] Latitude grid type */ rgr->lon_typ=nco_grd_lon_Grn_ctr; /* [enm] Longitude grid type */ rgr->lat_nbr=180; /* [nbr] Number of latitudes in destination grid */ rgr->lon_nbr=360; /* [nbr] Number of longitudes in destination grid */ rgr->lat_crv=0.0; /* [dgr] Latitudinal curvilinearity */ rgr->lon_crv=0.0; /* [dgr] Longitudinal curvilinearity */ rgr->lat_sth=NC_MAX_DOUBLE; /* [dgr] Latitude of southern edge of grid */ rgr->lon_wst=NC_MAX_DOUBLE; /* [dgr] Longitude of western edge of grid */ rgr->lat_nrt=NC_MAX_DOUBLE; /* [dgr] Latitude of northern edge of grid */ rgr->lon_est=NC_MAX_DOUBLE; /* [dgr] Longitude of eastern edge of grid */ rgr->msk_var=NULL; /* [sng] Mask-template variable */ rgr->ply_tri_mth=nco_ply_tri_mth_csz; /* [enm] Polygon-to-triangle decomposition method */ rgr->sgs_nrm=1.0; /* [sng] Sub-gridscale normalization */ rgr->tst=0L; /* [enm] Generic key for testing (undocumented) */ rgr->ntp_mth=nco_ntp_log; /* [enm] Interpolation method */ rgr->xtr_mth=nco_xtr_fll_ngh; /* [enm] Extrapolation method */ rgr->xtr_nsp=8; /* [sng] Extrapolation number of source points */ rgr->xtr_xpn=2.0; /* [sng] Exponent of distance in extrapolation (absolute value) */ rgr->wgt_typ=nco_wgt_con; /* [enm] Weight generation method */ /* Parse key-value properties */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ for(rgr_var_idx=0;rgr_var_idx<rgr_var_nbr;rgr_var_idx++){ if(!strcmp(rgr_lst[rgr_var_idx].key,"grid") || !strcasecmp(rgr_lst[rgr_var_idx].key,"scrip")){ rgr->fl_grd=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_grd=True; continue; } /* !grid */ if(!strcmp(rgr_lst[rgr_var_idx].key,"hnt_dst") || !strcmp(rgr_lst[rgr_var_idx].key,"fl_hnt_dst")){ rgr->fl_hnt_dst=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !hnt_dst */ if(!strcmp(rgr_lst[rgr_var_idx].key,"hnt_src") || !strcmp(rgr_lst[rgr_var_idx].key,"fl_hnt_src")){ rgr->fl_hnt_src=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !hnt_src */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_var") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_var") || !strcmp(rgr_lst[rgr_var_idx].key,"mask") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_variable")){ rgr->msk_var=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_msk_out=True; continue; } /* !msk_var */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msh") || !strcmp(rgr_lst[rgr_var_idx].key,"mesh")){ rgr->fl_msh=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !msh */ if(!strcmp(rgr_lst[rgr_var_idx].key,"skl")){ rgr->fl_skl=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_grd=True; continue; } /* !skl */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"ugrid")){ rgr->fl_ugrid=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_nfr=True; continue; } /* !ugrid */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"fl_hrz") || !strcasecmp(rgr_lst[rgr_var_idx].key,"hrz")){ rgr->fl_hrz=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !hrz */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"fl_vrt") || !strcasecmp(rgr_lst[rgr_var_idx].key,"vrt")){ rgr->fl_vrt=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !vrt */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_area") || !strcmp(rgr_lst[rgr_var_idx].key,"no_area_out")){ rgr->flg_area_out=False; continue; } /* !area */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_msk") || !strcmp(rgr_lst[rgr_var_idx].key,"no_msk_out") || !strcmp(rgr_lst[rgr_var_idx].key,"no_mask") || !strcmp(rgr_lst[rgr_var_idx].key,"no_mask_out")){ rgr->flg_msk_out=False; continue; } /* !msk */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_out") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_out")){ rgr->flg_msk_out=True; continue; } /* !mask */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cell_measures") || !strcmp(rgr_lst[rgr_var_idx].key,"cll_msr")){ rgr->flg_cll_msr=True; continue; } /* !cell_measures */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_cell_measures") || !strcmp(rgr_lst[rgr_var_idx].key,"no_cll_msr")){ rgr->flg_cll_msr=False; continue; } /* !cell_measures */ if(!strcmp(rgr_lst[rgr_var_idx].key,"curvilinear") || !strcmp(rgr_lst[rgr_var_idx].key,"crv")){ rgr->flg_crv=True; continue; } /* !curvilinear */ if(!strcmp(rgr_lst[rgr_var_idx].key,"diagnose_area") || !strcmp(rgr_lst[rgr_var_idx].key,"dgn_area")){ rgr->flg_dgn_area=True; continue; } /* !diagnose_area */ if(!strcmp(rgr_lst[rgr_var_idx].key,"diagnose_bounds") || !strcmp(rgr_lst[rgr_var_idx].key,"dgn_bnd")){ rgr->flg_dgn_bnd=True; continue; } /* !diagnose_bounds */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cf_units") || !strcmp(rgr_lst[rgr_var_idx].key,"CF_units")){ rgr->flg_cf_units=True; rgr->flg_erwg_units=False; continue; } /* !erwg_units */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cell_area_quad")){ rgr->area_mth=2; continue; } /* !area_nco */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cell_area_nco")){ rgr->area_mth=1; continue; } /* !area_nco */ if(!strcmp(rgr_lst[rgr_var_idx].key,"edg_typ") || !strcmp(rgr_lst[rgr_var_idx].key,"tri_arc") || !strcmp(rgr_lst[rgr_var_idx].key,"vrt_cnc")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"grt_crc") || !strcasecmp(rgr_lst[rgr_var_idx].val,"gtc") || !strcasecmp(rgr_lst[rgr_var_idx].val,"great_circle") || !strcasecmp(rgr_lst[rgr_var_idx].val,"geodesic") || !strcasecmp(rgr_lst[rgr_var_idx].val,"orthodrome")){ rgr->edg_typ=nco_edg_gtc; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"sml_crc") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ltr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"small_circle") || !strcasecmp(rgr_lst[rgr_var_idx].val,"latitude_triangle") || !strcasecmp(rgr_lst[rgr_var_idx].val,"true")){ rgr->edg_typ=nco_edg_smc; (void)fprintf(stderr,"%s: WARNING Requested to run with small-circle edges. This option has not yet been tested and validated. Use only at your own risk.\n",nco_prg_nm_get()); }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"crt") || !strcasecmp(rgr_lst[rgr_var_idx].val,"cartesian") || !strcasecmp(rgr_lst[rgr_var_idx].val,"planar") || !strcasecmp(rgr_lst[rgr_var_idx].val,"flat")){ rgr->edg_typ=nco_edg_crt; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !edg_typ */ if(!strcmp(rgr_lst[rgr_var_idx].key,"erwg_units") || !strcmp(rgr_lst[rgr_var_idx].key,"esmf_units") || !strcmp(rgr_lst[rgr_var_idx].key,"degrees")){ rgr->flg_cf_units=False; rgr->flg_erwg_units=True; continue; } /* !erwg_units */ if(!strcmp(rgr_lst[rgr_var_idx].key,"infer") || !strcmp(rgr_lst[rgr_var_idx].key,"nfr")){ rgr->flg_nfr=True; continue; } /* !infer */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_stagger") || !strcmp(rgr_lst[rgr_var_idx].key,"no_stg")){ rgr->flg_stg=False; continue; } /* !stagger */ if(!strcmp(rgr_lst[rgr_var_idx].key,"grd_ttl") || !strcmp(rgr_lst[rgr_var_idx].key,"ttl")){ if(rgr->grd_ttl) rgr->grd_ttl=(char *)nco_free(rgr->grd_ttl); rgr->grd_ttl=(char *)strdup(rgr_lst[rgr_var_idx].val); /* 20180828 Replace unquoted tildes with spaces (like LaTeX, NCL) so ncremap users can put tildes in place of spaces in ttl 20180905 Reverted this since quoting command in ncremap is superior solution */ if(False){ size_t ttl_lng=strlen(rgr->grd_ttl); for(size_t ttl_idx=0L;ttl_idx<ttl_lng;ttl_idx++) if(rgr->grd_ttl[ttl_idx] == '~'){ if(ttl_idx == 0L) rgr->grd_ttl[ttl_idx]=' '; // Always convert tilde to space if first character else if(rgr->grd_ttl[ttl_idx-1L] != '\\') rgr->grd_ttl[ttl_idx]=' '; // Convert tilde in other locations unless backslash-quoted } /* !tilde */ } /* !0 */ continue; } /* !grd_ttl */ if(!strcmp(rgr_lst[rgr_var_idx].key,"idx_dbg")){ rgr->idx_dbg=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !idx_dbg */ if(!strcmp(rgr_lst[rgr_var_idx].key,"latlon")){ cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%ld,%ld",&rgr->lat_nbr,&rgr->lon_nbr); assert(cnv_nbr == 2); continue; } /* !latlon */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lonlat")){ cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%ld,%ld",&rgr->lon_nbr,&rgr->lat_nbr); assert(cnv_nbr == 2); continue; } /* !lonlat */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nbr")){ rgr->lat_nbr=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !lat_nbr */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_nbr")){ rgr->lon_nbr=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !lon_nbr */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"snwe")){ cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%lf,%lf,%lf,%lf",&rgr->lat_sth,&rgr->lat_nrt,&rgr->lon_wst,&rgr->lon_est); if(cnv_nbr != 4) (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); assert(cnv_nbr == 4); if(cnv_nbr != 4) abort(); /* CEWI Use cnv_nbr at least once outside of assert() to avoid gcc 4.8.2 set-but-not-used warning */ continue; } /* !snwe */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"wesn")){ if(cnv_nbr != 4) cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%lf,%lf,%lf,%lf",&rgr->lon_wst,&rgr->lon_est,&rgr->lat_sth,&rgr->lat_nrt); assert(cnv_nbr == 4); continue; } /* !wesn */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_crv")){ rgr->lat_crv=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !lat_crv */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_crv")){ rgr->lon_crv=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !lon_crv */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_sth")){ rgr->lat_sth=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); // rgr->lat_typ=nco_grd_lat_bb; continue; } /* !lat_sth */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_wst")){ rgr->lon_wst=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); rgr->lon_typ=nco_grd_lon_bb; continue; } /* !lon_wst */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nrt")){ rgr->lat_nrt=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); //rgr->lat_typ=nco_grd_lat_bb; continue; } /* !lat_nrt */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_est")){ rgr->lon_est=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); rgr->lon_typ=nco_grd_lon_bb; continue; } /* !lon_est */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_drc")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"s2n") || !strcasecmp(rgr_lst[rgr_var_idx].val,"south2north") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ston") || !strcasecmp(rgr_lst[rgr_var_idx].val,"southnorth")){ rgr->lat_drc=nco_grd_lat_drc_s2n; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"n2s") || !strcasecmp(rgr_lst[rgr_var_idx].val,"north2south") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ntos") || !strcasecmp(rgr_lst[rgr_var_idx].val,"northsouth")){ rgr->lat_drc=nco_grd_lat_drc_n2s; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !lat_drc */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_typ")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"cap") || !strcasecmp(rgr_lst[rgr_var_idx].val,"fv") || !strcasecmp(rgr_lst[rgr_var_idx].val,"fix") || !strcasecmp(rgr_lst[rgr_var_idx].val,"yarmulke")){ rgr->lat_typ=nco_grd_lat_fv; rgr->grd_typ=nco_grd_2D_fv; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"eqa") || !strcasecmp(rgr_lst[rgr_var_idx].val,"rgl") || !strcasecmp(rgr_lst[rgr_var_idx].val,"unf") || !strcasecmp(rgr_lst[rgr_var_idx].val,"uni")){ rgr->lat_typ=nco_grd_lat_eqa; rgr->grd_typ=nco_grd_2D_eqa; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"gss")){ rgr->lat_typ=nco_grd_lat_gss; rgr->grd_typ=nco_grd_2D_gss; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !lat_typ */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_typ")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"180_wst") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wst_180")) rgr->lon_typ=nco_grd_lon_180_wst; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"180_ctr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ctr_180")) rgr->lon_typ=nco_grd_lon_180_ctr; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"Grn_wst") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wst_Grn")) rgr->lon_typ=nco_grd_lon_Grn_wst; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"Grn_ctr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ctr_Grn")) rgr->lon_typ=nco_grd_lon_Grn_ctr; else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !lon_typ */ if(!strcmp(rgr_lst[rgr_var_idx].key,"area_nm")){ rgr->area_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !area_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"bnd_nm")){ rgr->bnd_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !bnd_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"bnd_tm_nm")){ rgr->bnd_tm_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !bnd_tm_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"col_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"col_nm")){ rgr->col_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !col_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"col_nm_out")){ rgr->col_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !col_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"frc_nm")){ rgr->frc_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !frc_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"ilev_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"ilev_nm")){ rgr->ilev_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !ilev_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"ilev_nm_out")){ rgr->ilev_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !ilev_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_bnd_nm")){ rgr->lat_bnd_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_bnd_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_dmn_nm") || !strcmp(rgr_lst[rgr_var_idx].key,"lat_dmn")){ rgr->lat_dmn_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_dmn_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"lat_nm")){ rgr->lat_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nm_out")){ rgr->lat_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_vrt_nm")){ rgr->lat_vrt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_vrt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_wgt_nm")){ rgr->lat_wgt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_wgt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lev_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"lev_nm")){ rgr->lev_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lev_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lev_nm_out")){ rgr->lev_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lev_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_bnd_nm")){ rgr->lon_bnd_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_bnd_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_dmn_nm") || !strcmp(rgr_lst[rgr_var_idx].key,"lon_dmn")){ rgr->lon_dmn_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_dmn_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"lon_nm")){ rgr->lon_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_nm_out")){ rgr->lon_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_vrt_nm")){ rgr->lon_vrt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_vrt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"plev_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"plev_nm")){ rgr->plev_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !plev_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"ply_tri")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"csz")){ rgr->ply_tri_mth=nco_ply_tri_mth_csz; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"ctr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"centroid") || !strcasecmp(rgr_lst[rgr_var_idx].val,"snl") || !strcasecmp(rgr_lst[rgr_var_idx].val,"mat")){ rgr->ply_tri_mth=nco_ply_tri_mth_ctr; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !ply_tri */ if(!strcmp(rgr_lst[rgr_var_idx].key,"sgs_frc_nm")){ rgr->sgs_frc_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !sgs_frc */ if(!strcmp(rgr_lst[rgr_var_idx].key,"sgs_msk_nm")){ rgr->sgs_msk_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !sgs_msk */ if(!strcmp(rgr_lst[rgr_var_idx].key,"sgs_nrm")){ rgr->sgs_nrm=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !sgs_nrm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"tst")){ rgr->tst=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !tst */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_nm") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_nm")){ rgr->msk_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_msk_out=True; continue; } /* !msk_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"vrt_nm")){ rgr->vrt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !vrt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"vrt_ntp") || !strcmp(rgr_lst[rgr_var_idx].key,"ntp_mth")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"lin") || !strcasecmp(rgr_lst[rgr_var_idx].val,"linear") || !strcasecmp(rgr_lst[rgr_var_idx].val,"lnr")){ rgr->ntp_mth=nco_ntp_lnr; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"log") || !strcasecmp(rgr_lst[rgr_var_idx].val,"logarithmic") || !strcasecmp(rgr_lst[rgr_var_idx].val,"lgr")){ rgr->ntp_mth=nco_ntp_log; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !ntp_mth */ if(!strcmp(rgr_lst[rgr_var_idx].key,"xtr_mth")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"nrs_ngh") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ngh") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nearest_neighbor") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nn")){ rgr->xtr_mth=nco_xtr_fll_ngh; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"mss_val") || !strcasecmp(rgr_lst[rgr_var_idx].val,"msv") || !strcasecmp(rgr_lst[rgr_var_idx].val,"fll_val") || !strcasecmp(rgr_lst[rgr_var_idx].val,"missing_value")){ rgr->xtr_mth=nco_xtr_fll_msv; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !xtr_mth */ if(!strcmp(rgr_lst[rgr_var_idx].key,"xtr_nsp") || !strcmp(rgr_lst[rgr_var_idx].key,"xtr_nbr_src_pnt") || !strcmp(rgr_lst[rgr_var_idx].key,"number_source_points") || !strcmp(rgr_lst[rgr_var_idx].key,"extrapolation_number_source_points")){ rgr->xtr_nsp=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !xtr_nsp */ if(!strcmp(rgr_lst[rgr_var_idx].key,"xtr_xpn") || !strcmp(rgr_lst[rgr_var_idx].key,"extrapolation_exponent") || !strcmp(rgr_lst[rgr_var_idx].key,"exponent_of_distance_in_extrapolation")){ rgr->xtr_xpn=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !xtr_xpn */ if(!strcmp(rgr_lst[rgr_var_idx].key,"wgt_typ") || !strcmp(rgr_lst[rgr_var_idx].key,"weight_type")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"con") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nco_con") || !strcasecmp(rgr_lst[rgr_var_idx].val,"conservative") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wgt_con")) rgr->wgt_typ=nco_wgt_con; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"dwe") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nco_dwe") || !strcasecmp(rgr_lst[rgr_var_idx].val,"distance_weighted") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wgt_dwe")) rgr->wgt_typ=nco_wgt_dwe; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"bln") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nco_bln") || !strcasecmp(rgr_lst[rgr_var_idx].val,"bilinear") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wgt_bln")) rgr->wgt_typ=nco_wgt_bln; else { (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !wgt_typ */ (void)fprintf(stderr,"%s: ERROR %s reports unrecognized key-value option to --rgr switch: %s\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key); nco_exit(EXIT_FAILURE); } /* end for */ /* Eliminate sticky wickets: Give nfr precedence over grd */ if(rgr->flg_nfr && rgr->flg_grd) rgr->flg_grd=False; /* Revert to defaults for any names not specified on command-line */ if(!rgr->area_nm) rgr->area_nm=(char *)strdup("area"); /* [sng] Name of variable containing gridcell area */ if(!rgr->bnd_nm) rgr->bnd_nm=(char *)strdup("nvertices"); /* [sng] Name of dimension to employ for spatial bounds */ /* NB: CESM uses nbnd and ilev for temporal and vertical bounds, respectively (CESM outputs no horizontal spatial bounds). NCO defaults to nbnd for all bounds with two endpoints. */ if(!rgr->bnd_tm_nm) rgr->bnd_tm_nm=(char *)strdup("nbnd"); /* [sng] Name of dimension to employ for temporal bounds */ if(!rgr->col_nm_in) rgr->col_nm_in=(char *)strdup("ncol"); /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ if(!rgr->frc_nm) rgr->frc_nm=(char *)strdup("frac_b"); /* [sng] Name of variable containing gridcell fraction */ if(!rgr->ilev_nm_in) rgr->ilev_nm_in=(char *)strdup("ilev"); /* [sng] Name of input dimension to recognize as vertical dimension at layer interfaces */ if(!rgr->lat_bnd_nm) rgr->lat_bnd_nm=(char *)strdup("lat_bnds"); /* [sng] Name of rectangular boundary variable for latitude */ if(!rgr->lat_nm_in) rgr->lat_nm_in=(char *)strdup("lat"); /* [sng] Name of input dimension to recognize as latitude */ if(!rgr->lev_nm_in) rgr->lev_nm_in=(char *)strdup("lev"); /* [sng] Name of input dimension to recognize as vertical dimension at layer midpoints */ if(!rgr->lat_vrt_nm) rgr->lat_vrt_nm=(char *)strdup("lat_vertices"); /* [sng] Name of non-rectangular boundary variable for latitude */ if(!rgr->lat_wgt_nm) rgr->lat_wgt_nm=(char *)strdup("gw"); /* [sng] Name of variable containing latitude weights */ if(!rgr->lon_bnd_nm) rgr->lon_bnd_nm=(char *)strdup("lon_bnds"); /* [sng] Name of rectangular boundary variable for longitude */ if(!rgr->lon_nm_in) rgr->lon_nm_in=(char *)strdup("lon"); /* [sng] Name of dimension to recognize as longitude */ if(!rgr->lon_vrt_nm) rgr->lon_vrt_nm=(char *)strdup("lon_vertices"); /* [sng] Name of non-rectangular boundary variable for longitude */ if(!rgr->msk_nm) rgr->msk_nm=(char *)strdup("mask"); /* [sng] Name of variable containing destination mask */ if(!rgr->vrt_nm) rgr->vrt_nm=(char *)strdup("nv"); /* [sng] Name of dimension to employ for vertices */ if(!rgr->plev_nm_in) rgr->plev_nm_in=(char *)strdup("plev"); /* [sng] Name of variable to recognize as pure pressure coordinate */ /* Derived from defaults and command-line arguments */ // On second thought, do not strdup() these here. This way, NULL means user never specified lon/lat-out names // if(!rgr->col_nm_out) rgr->col_nm_out=(char *)strdup("ncol"); /* [sng] Name of dimension to output as horizontal spatial dimension on unstructured grid */ // if(!rgr->lat_nm_out) rgr->lat_nm_out=(char *)strdup("lat"); /* [sng] Name of dimension to output as latitude */ // if(!rgr->lon_nm_out) rgr->lon_nm_out=(char *)strdup("lon"); /* [sng] Name of dimension to output as longitude */ // if(!rgr->lat_nm_out) rgr->lat_nm_out=(char *)strdup(rgr_lat_nm_in); /* [sng] Name of output dimension for latitude */ // if(!rgr->lon_nm_out) rgr->lon_nm_out=(char *)strdup(rgr_lon_nm_in); /* [sng] Name of output dimension for longitude */ /* Free kvms */ if(rgr_lst) rgr_lst=nco_kvm_lst_free(rgr_lst,rgr_var_nbr); return rgr; } /* end nco_rgr_ini() */ int /* O [enm] Return code */ nco_ntp_vrt /* [fnc] Interpolate vertically */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Interpolate fields to new vertical grid specified in a vertical file */ const char fnc_nm[]="nco_ntp_vrt()"; /* [sng] Function name */ char *fl_tpl; /* [sng] Template file (vertical grid file) */ char *fl_pth_lcl=NULL; int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int in_id; /* I [id] Input netCDF file ID */ int tpl_id; /* [id] Input netCDF file ID (for vertical grid template) */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int dmn_idx; /* [idx] Dimension index */ int rec_idx; /* [idx] Record dimension index */ nco_bool FL_RTR_RMT_LCN; nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stderr,"%s: INFO %s obtaining vertical grid from %s\n",nco_prg_nm_get(),fnc_nm,rgr->fl_vrt); /* Duplicate (because nco_fl_mk_lcl() free()'s its fl_in) */ fl_tpl=(char *)strdup(rgr->fl_vrt); /* Make sure file is on local system and is readable or die trying */ fl_tpl=nco_fl_mk_lcl(fl_tpl,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_tpl,md_open,&bfr_sz_hnt,&tpl_id); /* Formula-terms for hybrid pressure vertical grid on unstructured CAM/EAM horizontal grid: prs_mdp[time,lev,col]=P0*hyam[lev] +PS[time,col]*hybm[lev] prs_ntf[time,lev,col]=P0*hyai[ilev]+PS[time,col]*hybi[ilev] */ /* Formula-terms for hybrid pressure vertical grid on ECMWF RLL horizontal grid: prs_mdp[time,lev,lat,lon]=hyam[lev] +exp(lnsp[time,lat,lon])*hybm[lev] prs_ntf[time,lev,lat,lon]=hyai[ilev]+exp(lnsp[time,lat,lon])*hybi[ilev] */ /* For simplicity and code re-use, all single-variable (not hybrid-variable) coordinate systems adopt "lev" semantics This includes pure pressure coordinates and eventually will include sigma, depth, and height coordinates Only hybrid coordinates will refer to the "ilev" levels and indices All single coordinate systems will refer to "lev" levels and indices */ int dpt_id; /* [id] Ocean depth ID */ int hyai_id=NC_MIN_INT; /* [id] Hybrid A coefficient at layer interfaces ID */ int hyam_id=NC_MIN_INT; /* [id] Hybrid A coefficient at layer midpoints ID */ int hybi_id=NC_MIN_INT; /* [id] Hybrid B coefficient at layer interfaces ID */ int hybm_id=NC_MIN_INT; /* [id] Hybrid B coefficient at layer midpoints ID */ int ilev_id=NC_MIN_INT; /* [id] Interface pressure ID */ int lev_id=NC_MIN_INT; /* [id] Midpoint pressure ID */ int p0_id=NC_MIN_INT; /* [id] Reference pressure ID */ int ps_id=NC_MIN_INT; /* [id] Surface pressure ID */ int plev_id; /* [id] Air pressure ID */ nco_bool flg_grd_hyb_cameam=False; /* [flg] Hybrid coordinate vertical grid uses CAM/EAM conventions */ nco_bool flg_grd_hyb_ecmwf=False; /* [flg] Hybrid coordinate vertical grid uses ECMWF conventions */ nco_bool flg_grd_in_dpt=False; /* [flg] Input depth coordinate vertical grid */ nco_bool flg_grd_in_hyb=False; /* [flg] Input hybrid coordinate vertical grid */ nco_bool flg_grd_in_prs=False; /* [flg] Input pressure coordinate vertical grid */ nco_bool flg_grd_out_dpt=False; /* [flg] Output depth coordinate vertical grid */ nco_bool flg_grd_out_hyb=False; /* [flg] Output hybrid coordinate vertical grid */ nco_bool flg_grd_out_prs=False; /* [flg] Output pressure coordinate vertical grid */ nco_bool flg_vrt_tm=False; /* [flg] Output depends on time-varying vertical grid */ nco_grd_vrt_typ_enm nco_vrt_grd_in=nco_vrt_grd_nil; /* [enm] Vertical grid type for input grid */ nco_grd_vrt_typ_enm nco_vrt_grd_out=nco_vrt_grd_nil; /* [enm] Vertical grid type for output grid */ nco_ntp_typ_enm ntp_mth=rgr->ntp_mth; /* [enm] Interpolation method */ nco_xtr_typ_enm xtr_mth=rgr->xtr_mth; /* [enm] Extrapolation method */ /* Determine output grid type */ if((rcd=nco_inq_varid_flg(tpl_id,"hyai",&hyai_id)) == NC_NOERR){ nco_vrt_grd_out=nco_vrt_grd_hyb; /* EAM */ flg_grd_out_hyb=True; }else if((rcd=nco_inq_varid_flg(tpl_id,"plev",&plev_id)) == NC_NOERR){ nco_vrt_grd_out=nco_vrt_grd_prs; /* NCEP */ flg_grd_out_prs=True; }else if((rcd=nco_inq_varid_flg(tpl_id,"depth",&dpt_id)) == NC_NOERR){ nco_vrt_grd_out=nco_vrt_grd_dpt; /* MPAS */ flg_grd_out_dpt=True; }else{ /* !hyai */ (void)fprintf(stdout,"%s: ERROR %s Unable to locate hybrid-sigma/pressure or pure-pressure vertical grid coordinate information in vertical grid file\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT ensure vertical grid coordinate file contains a valid vertical grid coordinate\n",nco_prg_nm_get()); return NCO_ERR; } /* !hyai */ if(flg_grd_out_hyb){ rcd=nco_inq_varid(tpl_id,"hyai",&hyai_id); rcd=nco_inq_varid(tpl_id,"hyam",&hyam_id); rcd=nco_inq_varid(tpl_id,"hybi",&hybi_id); rcd=nco_inq_varid(tpl_id,"hybm",&hybm_id); rcd=nco_inq_varid(tpl_id,"P0",&p0_id); rcd=nco_inq_varid_flg(tpl_id,"ilev",&ilev_id); rcd=nco_inq_varid_flg(tpl_id,"lev",&lev_id); rcd=nco_inq_varid_flg(tpl_id,"PS",&ps_id); } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ rcd=nco_inq_varid(tpl_id,"plev",&lev_id); } /* !flg_grd_out_prs */ if(flg_grd_out_dpt){ rcd=nco_inq_varid(tpl_id,"depth",&lev_id); } /* !flg_grd_out_dpt */ const int hyai_id_tpl=hyai_id; /* [id] Hybrid A coefficient at layer interfaces ID */ const int hyam_id_tpl=hyam_id; /* [id] Hybrid A coefficient at layer midpoints ID */ const int hybi_id_tpl=hybi_id; /* [id] Hybrid B coefficient at layer interfaces ID */ const int hybm_id_tpl=hybm_id; /* [id] Hybrid B coefficient at layer midpoints ID */ const int p0_id_tpl=p0_id; /* [id] Reference pressure ID */ const int ilev_id_tpl=ilev_id; /* [id] Interface pressure ID */ const int lev_id_tpl=lev_id; /* [id] Midpoint pressure ID */ const int ps_id_tpl=ps_id; /* [id] Surface pressure ID */ char *ilev_nm_in=NULL; /* [sng] Interface level name */ char *lev_nm_in; char *ilev_nm_out; char *lev_nm_out; char *plev_nm_in; /* [sng] Pure-pressure coordnate name */ char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ int *dmn_ids_in=NULL; /* [nbr] Input file dimension IDs */ int *dmn_ids_out=NULL; /* [nbr] Output file dimension IDs */ int *dmn_ids_rec=NULL; /* [id] Unlimited dimension IDs */ int dmn_nbr_ps; /* [nbr] Number of dimensions in PS variable */ int dmn_nbr_in; /* [nbr] Number of dimensions in input file */ int dmn_nbr_out; /* [nbr] Number of dimensions in output file */ int dmn_id_ilev_out=NC_MIN_INT; /* [id] Dimension ID for interface level in output file */ int dmn_id_lev_out=NC_MIN_INT; /* [id] Dimension ID for midpoint level in output file */ int dmn_id_ilev_in=NC_MIN_INT; /* [id] Dimension ID for interface level in file to be interpolated */ int dmn_id_lev_in=NC_MIN_INT; /* [id] Dimension ID for midpoint level in file to be interpolated */ int dmn_id_tm_in=NC_MIN_INT; /* [id] Dimension ID for time in file to be interpolated */ int dmn_nbr_rec; /* [nbr] Number of unlimited dimensions */ int dmn_idx_tm_in=NC_MIN_INT; /* [idx] Index of record coordinate in input hybrid coordinate PS field */ long *dmn_cnt_in=NULL; long *dmn_cnt_out=NULL; long *dmn_srt=NULL; long ilev_nbr_in; long lev_nbr_in; long ilev_nbr_out; long lev_nbr_out; long tm_idx=0L; /* [idx] Current timestep */ long tm_nbr=1L; /* [idx] Number of timesteps in vertical grid */ long tm_nbr_in=1L; /* [nbr] Number of timesteps in input vertical grid definition */ long tm_nbr_out=1L; /* [nbr] Number of timesetps in output vertical grid definition */ size_t grd_idx; /* [idx] Gridcell index */ size_t grd_sz_in=1L; /* [nbr] Number of elements in single layer of input grid */ size_t grd_sz_out=1L; /* [nbr] Number of elements in single layer of output grid */ size_t idx_fst; /* [idx] Index-offset to current surface pressure timeslice */ if(flg_grd_out_hyb){ /* Interrogate hyai/hyam to obtain ilev/lev dimensions */ rcd=nco_inq_vardimid(tpl_id,hyai_id,&dmn_id_ilev_out); rcd=nco_inq_vardimid(tpl_id,hyam_id,&dmn_id_lev_out); rcd=nco_inq_dimlen(tpl_id,dmn_id_ilev_out,&ilev_nbr_out); rcd=nco_inq_dimlen(tpl_id,dmn_id_lev_out,&lev_nbr_out); rcd=nco_inq_dimname(tpl_id,dmn_id_ilev_out,dmn_nm); ilev_nm_out=strdup(dmn_nm); rcd=nco_inq_dimname(tpl_id,dmn_id_lev_out,dmn_nm); lev_nm_out=strdup(dmn_nm); /* Interrogate PS, if any, for horizontal dimensions */ if(ps_id_tpl != NC_MIN_INT){ rcd=nco_inq_varndims(tpl_id,ps_id,&dmn_nbr_ps); dmn_nbr_out=dmn_nbr_ps; dmn_ids_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_cnt_out=(long *)nco_malloc((dmn_nbr_out+1)*sizeof(long)); dmn_srt=(long *)nco_malloc((dmn_nbr_out+1)*sizeof(long)); rcd=nco_inq_vardimid(tpl_id,ps_id,dmn_ids_out); rcd=nco_inq_unlimdims(tpl_id,&dmn_nbr_rec,(int *)NULL); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd=nco_inq_unlimdims(tpl_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ rcd=nco_inq_dimlen(tpl_id,dmn_ids_out[dmn_idx],dmn_cnt_out+dmn_idx); /* 20190330: Allow possibility that PS has time dimension > 1 We want horizontal not temporal dimensions to contribute to grd_sz Temporal dimension is usually unlimited Only multiply grd_sz by fixed (non-unlimited) dimension sizes Corner-case exception when PS spatial dimension on unstructured grid is unlimited */ for(rec_idx=0;rec_idx<dmn_nbr_rec;rec_idx++) if(dmn_ids_out[dmn_idx] == dmn_ids_rec[rec_idx]) break; if(rec_idx == dmn_nbr_rec || dmn_nbr_out == 1) grd_sz_out*=dmn_cnt_out[dmn_idx]; if(rec_idx != dmn_nbr_rec && dmn_nbr_out > 1 && dmn_cnt_out[dmn_idx] > 1L){ tm_nbr_out=dmn_cnt_out[dmn_idx]; if(tm_nbr_out > 1L) flg_vrt_tm=True; } /* tm_nbr_out > 1 */ dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); } /* !ps_id_tpl */ } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ /* Interrogate plev to obtain plev dimensions */ rcd=nco_inq_vardimid(tpl_id,lev_id,&dmn_id_lev_out); rcd=nco_inq_dimlen(tpl_id,dmn_id_lev_out,&lev_nbr_out); rcd=nco_inq_dimname(tpl_id,dmn_id_lev_out,dmn_nm); ilev_nbr_out=lev_nbr_out; } /* !flg_grd_out_prs */ double *hyai_out=NULL; /* [frc] Hybrid A coefficient at layer interfaces on output grid */ double *hyam_out=NULL; /* [frc] Hybrid A coefficient at layer midpoints on output grid */ double *hybi_out=NULL; /* [frc] Hybrid B coefficient at layer interfaces on output grid */ double *hybm_out=NULL; /* [frc] Hybrid B coefficient at layer midpoints on output grid */ double *ilev_out=NULL; /* [hPa] Interface pressure on output grid */ double *lev_out=NULL; /* [hPa] Midpoint pressure on output grid */ double *ps_out=NULL; /* [Pa] Surface pressure on output grid */ double *prs_mdp_out=NULL; /* [Pa] Midpoint pressure on output grid */ double *prs_ntf_out=NULL; /* [Pa] Interface pressure on output grid */ double p0_out; /* [Pa] Reference pressure on output grid */ long ilev_idx; /* [idx] Interface level index */ long lev_idx; /* [idx] Level index */ const nc_type crd_typ_out=NC_DOUBLE; nc_type var_typ_rgr; /* [enm] Variable type used during regridding */ var_typ_rgr=NC_DOUBLE; /* NB: Perform interpolation in double precision */ if(flg_grd_out_hyb){ hyai_out=(double *)nco_malloc(ilev_nbr_out*nco_typ_lng(var_typ_rgr)); hyam_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); hybi_out=(double *)nco_malloc(ilev_nbr_out*nco_typ_lng(var_typ_rgr)); hybm_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); ilev_out=(double *)nco_malloc(ilev_nbr_out*nco_typ_lng(var_typ_rgr)); lev_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(tpl_id,hyai_id,hyai_out,crd_typ_out); rcd=nco_get_var(tpl_id,hyam_id,hyam_out,crd_typ_out); rcd=nco_get_var(tpl_id,hybi_id,hybi_out,crd_typ_out); rcd=nco_get_var(tpl_id,hybm_id,hybm_out,crd_typ_out); rcd=nco_get_var(tpl_id,p0_id,&p0_out,crd_typ_out); if(ilev_id_tpl != NC_MIN_INT){ rcd=nco_get_var(tpl_id,ilev_id,ilev_out,crd_typ_out); }else{ /* p0 is in Pa but ilev traditionally given in hPa */ for(ilev_idx=0;ilev_idx<ilev_nbr_out;ilev_idx++) ilev_out[ilev_idx]=p0_out*(hyai_out[ilev_idx]+hybi_out[ilev_idx])/100.0; } /* !ilev_id_tpl */ if(lev_id_tpl != NC_MIN_INT){ rcd=nco_get_var(tpl_id,lev_id,lev_out,crd_typ_out); }else{ /* p0 is in Pa but lev traditionally given in hPa */ for(lev_idx=0;lev_idx<lev_nbr_out;lev_idx++) lev_out[lev_idx]=p0_out*(hyam_out[lev_idx]+hybm_out[lev_idx])/100.0; } /* !ilev_id_tpl */ } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ lev_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(tpl_id,lev_id,lev_out,crd_typ_out); } /* !flg_grd_out_prs */ /* For vertical interpolation (unlike horizontal regridding), the destination grid is known a priori Straightforward copy all variables and attributes that define grid from fl_tpl to output would work in theory, but would not allow dynamic identification and relabeling of names */ /* if(flg_grd_out_hyb){ const int vrt_grd_lst_nbr=8; const char *vrt_grd_lst[]={"/hyai","/hyam","/hybi","/hybm","/ilev","/lev","/P0","/PS"}; } if(flg_grd_out_prs){ const int vrt_grd_lst_nbr=1; const char *vrt_grd_lst[]={"/plev"}; } */ /* Above this line, fl_tpl and tpl_id refer to vertical coordinate file (i.e., template file) Below this line, fl_in and in_id refer to input file to be vertically regridded Do not close template file until all grid variables have been copied For maximum efficiency, do this after defining all interpolated variables in output That way no file needs to exit define mode or enter data mode more than once However this requires keeping template file, input data file, and output file simulataneously open */ in_id=rgr->in_id; out_id=rgr->out_id; /* Determine input grid type */ if(rgr->plev_nm_in) plev_nm_in=rgr->plev_nm_in; if((rcd=nco_inq_varid_flg(in_id,"hyai",&hyai_id)) == NC_NOERR){ nco_vrt_grd_in=nco_vrt_grd_hyb; /* EAM */ flg_grd_in_hyb=True; }else if((rcd=nco_inq_varid_flg(in_id,plev_nm_in,&plev_id)) == NC_NOERR){ nco_vrt_grd_in=nco_vrt_grd_prs; /* NCEP */ flg_grd_in_prs=True; }else if((rcd=nco_inq_varid_flg(in_id,"depth",&dpt_id)) == NC_NOERR){ nco_vrt_grd_in=nco_vrt_grd_dpt; /* NCEP */ flg_grd_in_dpt=True; }else{ /* !hyai */ (void)fprintf(stdout,"%s: ERROR %s Unable to locate hybrid-sigma/pressure or pure-pressure vertical grid coordinate information in input file\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT only invoke vertical interpolation on files that contain variables with vertical dimensions, and with known vertical coordinate variable names. These default to \"hyai\" for hybrid, \"plev\" for pressure, \"depth\" for depth. See http://nco.sf.net/nco.html#lev_nm for options to change these names at run-time, e.g., \"--rgr plev_nm=vrt_nm\"\n",nco_prg_nm_get()); return NCO_ERR; } /* !hyai */ /* Sanity checks: One type of input and one type of output grid detected */ assert(!(flg_grd_in_hyb && flg_grd_in_prs)); assert(!(flg_grd_in_hyb && flg_grd_in_dpt)); assert(!(flg_grd_in_prs && flg_grd_in_dpt)); assert(flg_grd_in_hyb || flg_grd_in_prs || flg_grd_in_dpt); assert(!(flg_grd_out_hyb && flg_grd_out_prs)); assert(!(flg_grd_out_hyb && flg_grd_out_dpt)); assert(!(flg_grd_out_prs && flg_grd_out_dpt)); assert(flg_grd_out_hyb || flg_grd_out_prs || flg_grd_out_dpt); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: DEBUG Input grid flags : flg_grd_in_hyb = %d, flg_grd_in_prs = %d, flg_grd_in_dpt = %d\n",nco_prg_nm_get(),flg_grd_in_hyb,flg_grd_in_prs,flg_grd_in_dpt); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: DEBUG Output grid flags: flg_grd_out_hyb = %d, flg_grd_out_prs = %d, flg_grd_out_dpt = %d\n",nco_prg_nm_get(),flg_grd_out_hyb,flg_grd_out_prs,flg_grd_out_dpt); /* 20191219: This block is not used, deprecate it? Or use once new coordinates like altitude, depth supported? */ nco_vrt_ntp_typ_enm nco_vrt_ntp_typ=nco_ntp_nil; /* Vertical interpolation type */ if(nco_vrt_grd_in == nco_vrt_grd_hyb && nco_vrt_grd_out == nco_vrt_grd_hyb) nco_vrt_ntp_typ=nco_ntp_hyb_to_hyb; if(nco_vrt_grd_in == nco_vrt_grd_hyb && nco_vrt_grd_out == nco_vrt_grd_prs) nco_vrt_ntp_typ=nco_ntp_hyb_to_prs; if(nco_vrt_grd_in == nco_vrt_grd_prs && nco_vrt_grd_out == nco_vrt_grd_hyb) nco_vrt_ntp_typ=nco_ntp_prs_to_hyb; if(nco_vrt_grd_in == nco_vrt_grd_prs && nco_vrt_grd_out == nco_vrt_grd_prs) nco_vrt_ntp_typ=nco_ntp_prs_to_prs; assert(nco_vrt_ntp_typ != nco_ntp_nil); /* Variables on input grid, i.e., on grid in data file to be interpolated */ if(flg_grd_in_hyb){ rcd=nco_inq_varid(in_id,"hyai",&hyai_id); rcd=nco_inq_varid(in_id,"hyam",&hyam_id); rcd=nco_inq_varid(in_id,"hybi",&hybi_id); rcd=nco_inq_varid(in_id,"hybm",&hybm_id); /* 20190602: ECMWF hybrid vertical grid parameters and dimensions differ from CAM/EAM: ECMWF defines vertical dimensions "nhym" and "nhyi" specifically for hy[ab][im] and uses "lev" and "lev_2" for all other variables, whereas CAM/EAM uses same dimensions "lev" and "ilev" for all vertical variables including hybrid coefficients ECMWF provides "hya?" as a constant in Pa and "hyb?" as a dimensionless coefficient of PS, whereas CAM/EAM provides "hya?" and "hyb?" both as dimensionless coefficients of P0 and PS ECMWF provides "lev" and "lev_2" with midpoint and surface pressure indices (not values), respectively, whereas CAM/EAM provides "lev" and "ilev" coordinate values in hPa ECMWF provides dimensionless "lnsp" for log(surface pressure) whereas CAM/EAM provides "PS" for surface pressure in Pa ECMWF "lnsp" has degenerate level dimension "lev_2" whereas CAM/EAM "PS" has no "ilev" dimension ECMWF uses hya? instead of reference pressure whereas CAM/EAM provides "P0" in hPa */ if((rcd=nco_inq_varid_flg(in_id,"lnsp",&ps_id)) == NC_NOERR) flg_grd_hyb_ecmwf=True; else if((rcd=nco_inq_varid_flg(in_id,"PS",&ps_id)) == NC_NOERR) flg_grd_hyb_cameam=True; else{ (void)fprintf(stderr,"%s: ERROR %s Unable to find surface pressure variable required for hybrid grid in input file\n",nco_prg_nm_get(),fnc_nm); abort(); } /* !rcd */ if(flg_grd_hyb_cameam){ rcd=nco_inq_varid(in_id,"P0",&p0_id); ilev_id=NC_MIN_INT; lev_id=NC_MIN_INT; if(ilev_id_tpl == NC_MIN_INT) rcd=nco_inq_varid_flg(in_id,"ilev",&ilev_id); if(lev_id_tpl == NC_MIN_INT) rcd=nco_inq_varid_flg(in_id,"lev",&lev_id); } /* !flg_grd_hyb_cameam */ /* 20190603: We require ECMWF IFS input to have a "lev" coordinate so we can use "lev" dimension not "nhyb" */ if(flg_grd_hyb_ecmwf) rcd=nco_inq_varid(in_id,"lev",&lev_id); } /* !flg_grd_in_hyb */ if(flg_grd_in_prs){ rcd=nco_inq_varid(in_id,plev_nm_in,&lev_id); if((rcd=nco_inq_varid_flg(in_id,"PS",&ps_id)) == NC_NOERR){ /* Output file creation procedure discriminates between input surface pressure dimensioned as CAM/EAM vs. ECMWF */ flg_grd_hyb_cameam=True; if(flg_grd_out_hyb && (ps_id_tpl == NC_MIN_INT)) (void)fprintf(stderr,"%s: INFO %s detects variable PS (canonical name for spatially varying surface pressure field in hybrid grids) in pure-pressure input data file. PS will be copied directly from pure-pressure grid input dataset to, and used to construct the pressures of, the output hybrid-coordinate data file.\n",nco_prg_nm_get(),fnc_nm); if(flg_grd_out_hyb && (ps_id_tpl != NC_MIN_INT)) (void)fprintf(stderr,"%s: INFO %s detects variable PS (canonical name for spatially varying surface pressure field in hybrid grids) in both vertical-grid file and pure-pressure input data file. The vertical grid-file takes precedence. PS will be copied directly from vertical-grid file to, and used to construct the pressures of, the output hybrid-coordinate data file. PS in input pure-pressure file will be ignored.\n",nco_prg_nm_get(),fnc_nm); }else{ if(flg_grd_out_hyb && (ps_id_tpl == NC_MIN_INT)){ (void)fprintf(stderr,"%s: ERROR %s does not find variable PS (canonical name for spatially varying surface pressure field in hybrid grids) in pure-pressure input data file or in vertical grid-file for hybrid-pressure output. PS must be present in at least one of these files in order to construct the output hybrid-coordinate pressures.\nHINT: Append a valid PS to the inpud data file or vertical grid-file.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !ps_id_tpl */ } /* !ps_id */ } /* !flg_grd_in_prs */ if(flg_grd_in_dpt){ rcd=nco_inq_varid(in_id,"depth",&lev_id); } /* !flg_grd_in_dpt */ const int ilev_id_in=ilev_id; /* [id] Interface pressure ID */ const int lev_id_in=lev_id; /* [id] Midpoint pressure ID */ const int ps_id_in=ps_id; /* [id] Surface pressure ID */ /* Identify all record-dimensions in input file */ rcd=nco_inq_unlimdims(in_id,&dmn_nbr_rec,(int *)NULL); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ if(flg_grd_in_hyb){ /* Get hybrid vertical information first */ rcd=nco_inq_varndims(in_id,ps_id,&dmn_nbr_in); rcd=nco_inq_vardimid(in_id,hyai_id,&dmn_id_ilev_in); if(flg_grd_hyb_cameam) rcd=nco_inq_vardimid(in_id,hyam_id,&dmn_id_lev_in); if(flg_grd_hyb_ecmwf) rcd=nco_inq_vardimid(in_id,lev_id,&dmn_id_lev_in); rcd=nco_inq_dimlen(in_id,dmn_id_ilev_in,&ilev_nbr_in); rcd=nco_inq_dimlen(in_id,dmn_id_lev_in,&lev_nbr_in); rcd=nco_inq_dimname(in_id,dmn_id_ilev_in,dmn_nm); ilev_nm_in=strdup(dmn_nm); rcd=nco_inq_dimname(in_id,dmn_id_lev_in,dmn_nm); lev_nm_in=strdup(dmn_nm); } /* !flg_grd_in_hyb */ if(flg_grd_in_prs){ /* Interrogate plev to obtain plev dimensions */ rcd=nco_inq_vardimid(in_id,lev_id,&dmn_id_lev_in); rcd=nco_inq_dimlen(in_id,dmn_id_lev_in,&lev_nbr_in); rcd=nco_inq_dimname(in_id,dmn_id_lev_in,dmn_nm); lev_nm_in=strdup(dmn_nm); /* Define horizontal grid if no PS is provided (i.e., pure-pressure to pure-pressure interpolation) */ if(!flg_grd_out_hyb){ /* Problem: What is horizontal grid size of pressure grid file? Algorithm: Examine first multi-dimensional variable that includes plev dimension Assume horizontal dimensions vary more rapidly than (i.e., follow) plev Compute horizontal grid size accordingly Set output horizontal size to input horizontal size */ int var_nbr; /* [nbr] Number of variables in file */ int var_idx; /* [idx] Index over variables in file */ rcd=nco_inq(in_id,&dmn_nbr_in,&var_nbr,(int *)NULL,(int *)NULL); dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_cnt_in=(long *)nco_malloc(dmn_nbr_in*sizeof(long)); for(var_idx=0;var_idx<var_nbr;var_idx++){ rcd=nco_inq_varndims(in_id,var_idx,&dmn_nbr_in); rcd=nco_inq_vardimid(in_id,var_idx,dmn_ids_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++) if(dmn_ids_in[dmn_idx] == dmn_id_lev_in) break; /* Does current variable have lev dimension? */ if(dmn_idx < dmn_nbr_in){ /* Yes. Do any dimensions vary more rapidly than lev? */ if(dmn_idx < dmn_nbr_in-1){ /* Yes. Assume remaining dimension are horizontal spatial dimensions */ char var_nm[NC_MAX_NAME+1L]; (void)nc_inq_varname(in_id,var_idx,var_nm); for(int dmn_idx_hrz=dmn_idx+1;dmn_idx_hrz<dmn_nbr_in;dmn_idx_hrz++){ rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx_hrz],dmn_cnt_in+dmn_idx_hrz); grd_sz_in*=dmn_cnt_in[dmn_idx_hrz]; } /* !dmn_idx_hrz */ break; } /* !dmn_idx */ } /* !dmn_idx */ } /* !var_idx */ assert(var_idx != var_nbr); grd_sz_out=grd_sz_in; } /* !flg_grd_out_hyb */ } /* !flg_grd_in_prs */ double *hyai_in=NULL; /* [frc] Hybrid A coefficient at layer interfaces on input grid */ double *hyam_in=NULL; /* [frc] Hybrid A coefficient at layer midpoints on input grid */ double *hybi_in=NULL; /* [frc] Hybrid B coefficient at layer interfaces on input grid */ double *hybm_in=NULL; /* [frc] Hybrid B coefficient at layer midpoints on input grid */ double *lev_in=NULL; /* [Pa] Air pressure on input grid */ double *prs_mdp_in=NULL; /* [Pa] Midpoint pressure on input grid */ double *prs_ntf_in=NULL; /* [Pa] Interface pressure on input grid */ double *ps_in=NULL; /* [Pa] Surface pressure on input grid */ double p0_in; /* [Pa] Reference pressure on input grid */ if(flg_grd_in_hyb){ hyai_in=(double *)nco_malloc(ilev_nbr_in*nco_typ_lng(var_typ_rgr)); hyam_in=(double *)nco_malloc(lev_nbr_in*nco_typ_lng(var_typ_rgr)); hybi_in=(double *)nco_malloc(ilev_nbr_in*nco_typ_lng(var_typ_rgr)); hybm_in=(double *)nco_malloc(lev_nbr_in*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(in_id,hyai_id,hyai_in,crd_typ_out); rcd=nco_get_var(in_id,hyam_id,hyam_in,crd_typ_out); rcd=nco_get_var(in_id,hybi_id,hybi_in,crd_typ_out); rcd=nco_get_var(in_id,hybm_id,hybm_in,crd_typ_out); if(flg_grd_hyb_cameam) rcd=nco_get_var(in_id,p0_id,&p0_in,crd_typ_out); /* ECMWF distributes IFS forecasts with lnsp = log(surface pressure) */ if(flg_grd_hyb_ecmwf){ /* Decompose ECMWF hya? convention into CAM/EAM-like product of P0 and hya? */ p0_in=100000.0; for(size_t idx=0;idx<lev_nbr_in;idx++){ hyai_in[idx]/=p0_in; hyam_in[idx]/=p0_in; } /* !idx */ } /* flg_grd_hyb_ecmwf */ } /* !flg_grd_in_hyb */ if(flg_grd_in_prs){ lev_in=(double *)nco_malloc(lev_nbr_in*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(in_id,lev_id,lev_in,crd_typ_out); } /* !flg_grd_in_prs */ /* Always obtain surface pressure if input or output grid is hybrid */ if(flg_grd_in_hyb || flg_grd_out_hyb){ /* Copy horizontal grid information from input file LHS variables were set above if PS is in template file */ if(ps_id_tpl == NC_MIN_INT){ /* NB: dmn_nbr_in/out in this block refer only to horizontal dimensions necessary to define PS */ rcd=nco_inq_varndims(in_id,ps_id,&dmn_nbr_in); /* This is harmlessly repeated for hybrid input files */ dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_cnt_in=(long *)nco_malloc((dmn_nbr_in+1)*sizeof(long)); if(!dmn_srt) dmn_srt=(long *)nco_malloc((dmn_nbr_in+1)*sizeof(long)); /* NB: Only allocate dmn_srt once */ rcd=nco_inq_vardimid(in_id,ps_id,dmn_ids_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_in+dmn_idx); /* 20190330: Allow possibility that PS has time dimension > 1 We want horizontal not temporal dimensions to contribute to grd_sz Temporal dimension is usually unlimited Only multiply grd_sz by fixed (non-unlimited) dimension sizes Corner-case exception when PS spatial dimension on unstructured grid is unlimited */ for(rec_idx=0;rec_idx<dmn_nbr_rec;rec_idx++) if(dmn_ids_in[dmn_idx] == dmn_ids_rec[rec_idx]) break; if(rec_idx == dmn_nbr_rec || dmn_nbr_in == 1) grd_sz_in*=dmn_cnt_in[dmn_idx]; if(rec_idx != dmn_nbr_rec && dmn_nbr_in > 1 && dmn_cnt_in[dmn_idx] > 1L){ dmn_id_tm_in=dmn_ids_in[dmn_idx]; dmn_idx_tm_in=dmn_idx; tm_nbr_in=dmn_cnt_in[dmn_idx_tm_in]; if(tm_nbr_in > 1L) flg_vrt_tm=True; } /* tm_nbr_in > 1 */ dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ /* Given all input PS information, define output PS information */ dmn_nbr_ps=dmn_nbr_out=dmn_nbr_in; dmn_ids_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_cnt_out=(long *)nco_malloc((dmn_nbr_out+1)*sizeof(long)); /* fxm: next line works for hyb_in and is buggy for prs_in */ memcpy(dmn_ids_out,dmn_ids_in,dmn_nbr_in*sizeof(int)); memcpy(dmn_cnt_out,dmn_cnt_in,dmn_nbr_in*sizeof(long)); grd_sz_out=grd_sz_in; tm_nbr_out=tm_nbr_in; }else{ /* !ps_id_tpl */ /* 20200825: We have already defined grd_sz_out if PS is in template file We have already defined grd_sz_in and grd_sz_out := grd_sz_in when PS not in template file We have already defined grd_sz_in if input file is pure-pressure However, we have not yet defined grd_sz_in if input file is hybrid Expectation is that grd_sz_in (from input file) = grd_sz_out (from template file) An independent check on this would examine dimension sizes in input file Such a check would immediately flag horizontal mismatches between vertical file and input file The check could not rely on PS being present in input file The check could/should examine the first horizontal variable in input file This would require a lot of code, so we just assume it is true */ grd_sz_in=grd_sz_out; } /* !ps_id_tpl */ /* Timestep sequencing NB: tm_nbr_??? variables count timesteps in vertical grid definitions These are not necessarily the same as the number of timesteps in either file Time-invariant hybrid or pure-pressure coordinates are valid vertical grids for timeseries Usually hybrid grids have as many timesteps in the grids as in the timeseries Usually pressure grids are time-invariant (as of 20190511 time-varying pure pressure grids are still not supported) This implementation interpolates timeseries to/from time-invariant vertical grids in one OpenMP call! */ if(tm_nbr_in > 1L || tm_nbr_out > 1L){ if(tm_nbr_in > tm_nbr_out) assert((float)tm_nbr_in/(float)tm_nbr_out == tm_nbr_in/tm_nbr_out); else assert((float)tm_nbr_out/(float)tm_nbr_in == tm_nbr_out/tm_nbr_in); } /* !tm_nbr_in */ tm_nbr=tm_nbr_in > tm_nbr_out ? tm_nbr_in : tm_nbr_out; /* Sanity checks */ if(grd_sz_in != grd_sz_out || tm_nbr_in != tm_nbr_out) (void)fprintf(stdout,"%s: ERROR %s reports that temporal or horizontal spatial dimensions differ: grd_sz_in = %ld != %ld = grd_sz_out, and/or tm_nbr_in = %ld != %ld = tm_nbr_out\n",nco_prg_nm_get(),fnc_nm,grd_sz_in,grd_sz_out,tm_nbr_in,tm_nbr_out); assert(grd_sz_in == grd_sz_out); assert(tm_nbr_in == tm_nbr_out); ps_in=(double *)nco_malloc_dbg(tm_nbr_in*grd_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() ps_in value buffer"); /* Surface pressure comes from either hybrid vertical grid-files, hybrid data files, or pressure data files that provide surface pressure */ if(flg_grd_in_hyb || (flg_grd_in_prs && ps_id_tpl == NC_MIN_INT)) rcd=nco_get_var(in_id,ps_id,ps_in,crd_typ_out); /* ECMWF distributes IFS forecasts with lnsp = log(surface pressure) */ if(flg_grd_hyb_ecmwf){ /* Convert ECMWF-provided log(surface_pressure) to surface_pressure */ const size_t ps_sz_in=tm_nbr_in*grd_sz_in; /* [nbr] Number of elements in ps_in */ for(size_t idx=0;idx<ps_sz_in;idx++) ps_in[idx]=exp(ps_in[idx]); } /* flg_grd_hyb_ecmwf */ /* Finally have enough information to allocate output pressure grid */ ps_out=(double *)nco_malloc_dbg(tm_nbr_out*grd_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() ps_out value buffer"); /* Get PS from output horizontal grid, if available, otherwise copy from input horizontal grid */ if(ps_id_tpl != NC_MIN_INT){ rcd=nco_get_var(tpl_id,ps_id_tpl,ps_out,crd_typ_out); /* NB: Here we read from tpl_id one last time */ }else{ memcpy(ps_out,ps_in,tm_nbr_in*grd_sz_in*nco_typ_lng(var_typ_rgr)); } /* !ps_id_tpl */ } /* ! */ /* Compare input and output surface pressure fields to determine whether subterranean extrapolation required */ nco_bool flg_add_msv_att; /* [flg] Extrapolation requires _FillValue */ flg_add_msv_att=False; /* Extrapolation type xtr_fll_msv may cause need to create _FillValue attributes */ if(xtr_mth == nco_xtr_fll_msv){ const size_t ps_sz=tm_nbr*grd_sz_in; // [nbr] Size of surface-pressure field double *prs_max_in=NULL; /* [Pa] Maximum midpoint pressure on input grid */ double *prs_max_out=NULL; /* [Pa] Maximum midpoint pressure on output grid */ double *prs_min_in=NULL; /* [Pa] Minimum midpoint pressure on input grid */ double *prs_min_out=NULL; /* [Pa] Minimum midpoint pressure on output grid */ long idx_lev_max; // [idx] Index of midpoint level with greatest pressure long idx_lev_min; // [idx] Index of midpoint level with lowest pressure size_t idx; // [idx] Counting index prs_max_in=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_max_in value buffer"); prs_max_out=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_max_out value buffer"); prs_min_in=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_min_in value buffer"); prs_min_out=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_min_out value buffer"); if(flg_grd_in_hyb){ // fxm: assumes hybrid grid has least/greatest pressure at top/bottom level idx_lev_max=lev_nbr_in-1; idx_lev_min=0L; for(tm_idx=0;tm_idx<tm_nbr;tm_idx++){ idx_fst=tm_idx*grd_sz_in; for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++){ prs_max_in[grd_idx+idx_fst]=p0_in*hyam_in[idx_lev_max]+ps_in[idx_fst+grd_idx]*hybm_in[idx_lev_max]; prs_min_in[grd_idx+idx_fst]=p0_in*hyam_in[idx_lev_min]+ps_in[idx_fst+grd_idx]*hybm_in[idx_lev_min]; } /* !grd_idx */ } /* !tm_idx */ } /* !flg_grd_in_hyb */ if(flg_grd_out_hyb){ // fxm: assumes hybrid grid has least/greatest pressure at top/bottom level idx_lev_max=lev_nbr_out-1; idx_lev_min=0L; for(tm_idx=0;tm_idx<tm_nbr;tm_idx++){ idx_fst=tm_idx*grd_sz_out; for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++){ prs_max_out[grd_idx+idx_fst]=p0_out*hyam_out[idx_lev_max]+ps_out[idx_fst+grd_idx]*hybm_out[idx_lev_max]; prs_min_out[grd_idx+idx_fst]=p0_out*hyam_out[idx_lev_min]+ps_out[idx_fst+grd_idx]*hybm_out[idx_lev_min]; } /* !grd_idx */ } /* !tm_idx */ } /* !flg_grd_out_hyb */ if(flg_grd_in_prs){ double lev_in_max; double lev_in_min; if(lev_in[0] < lev_in[1]) lev_in_max=lev_in[lev_nbr_in-1]; else lev_in_max=lev_in[0]; if(lev_in[0] < lev_in[1]) lev_in_min=lev_in[0]; else lev_in_max=lev_in[lev_nbr_in-1]; for(size_t idx_in=0;idx_in<ps_sz;idx_in++) prs_max_in[idx_in]=lev_in_max; for(size_t idx_in=0;idx_in<ps_sz;idx_in++) prs_min_in[idx_in]=lev_in_min; } /* !flg_grd_in_prs */ if(flg_grd_out_prs){ double lev_out_max; double lev_out_min; if(lev_out[0] < lev_out[1]) lev_out_max=lev_out[lev_nbr_out-1]; else lev_out_max=lev_out[0]; if(lev_out[0] < lev_out[1]) lev_out_min=lev_out[0]; else lev_out_min=lev_out[lev_nbr_out-1]; for(size_t idx_out=0;idx_out<ps_sz;idx_out++) prs_max_out[idx_out]=lev_out_max; for(size_t idx_out=0;idx_out<ps_sz;idx_out++) prs_min_out[idx_out]=lev_out_min; } /* !flg_grd_out_prs */ for(idx=0;idx<ps_sz;idx++) if(prs_max_out[idx] > prs_max_in[idx]) break; if(idx < ps_sz) flg_add_msv_att=True; for(idx=0;idx<ps_sz;idx++) if(prs_min_out[idx] < prs_min_in[idx]) break; if(idx < ps_sz) flg_add_msv_att=True; if(flg_add_msv_att && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports at least one point in at least one output level requires extrapolation (not interpolation). Will ensure that all interpolated fields have _FillValue attribute.\n",nco_prg_nm_get(),fnc_nm); if(prs_max_in) prs_max_in=(double *)nco_free(prs_max_in); if(prs_max_out) prs_max_out=(double *)nco_free(prs_max_out); if(prs_min_in) prs_min_in=(double *)nco_free(prs_min_in); if(prs_min_out) prs_min_out=(double *)nco_free(prs_min_out); } /* !xtr_mth */ /* Lay-out regridded file */ //(void)fprintf(stdout,"%s: DEBUG quark1 dmn_nbr_out = %d, dmn_nbr_ps = %d\n",nco_prg_nm_get(),dmn_nbr_out,dmn_nbr_ps); /* Use explicitly specified output names, if any, otherwise use template names (either explicitly specified or discovered by fuzzing) */ if(rgr->lev_nm_out) lev_nm_out=rgr->lev_nm_out; if(rgr->ilev_nm_out){ if(flg_grd_out_hyb) ilev_nm_out=rgr->ilev_nm_out; if(flg_grd_out_prs) lev_nm_out=rgr->ilev_nm_out; } /* !ilev_nm_out */ if(flg_grd_out_prs){ /* Unless user explicitly specifies output name, use same name as input */ if(!rgr->lev_nm_out) lev_nm_out=(char *)strdup(plev_nm_in); /* Hybrid-sigma/pressure interface variables, if any, must also be output to pure-pressure files on lev grid */ ilev_nm_out=(char *)strdup(lev_nm_out); } /* !flg_grd_out_prs */ /* Define new vertical dimensions before all else */ if(flg_grd_out_hyb){ rcd=nco_def_dim(out_id,ilev_nm_out,ilev_nbr_out,&dmn_id_ilev_out); rcd=nco_def_dim(out_id,lev_nm_out,lev_nbr_out,&dmn_id_lev_out); /* Horizontal dimensions necessary to define PS variable */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ if(ps_id_tpl != NC_MIN_INT){ rcd=nco_inq_dimname(tpl_id,dmn_ids_out[dmn_idx],dmn_nm); }else{ rcd=nco_inq_dimname(in_id,dmn_ids_in[dmn_idx],dmn_nm); rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_out+dmn_idx); } /* !ps_id_tpl */ if(flg_grd_hyb_cameam) rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_ids_out+dmn_idx); /* 20190602: ECMWF IFS PS variable has degenerate vertical dimension (lev_2). Avoid re-definition */ if(flg_grd_hyb_ecmwf) if(strcmp(dmn_nm,ilev_nm_out)) if(strcmp(dmn_nm,lev_nm_out)) rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_ids_out+dmn_idx); } /* !dmn_idx */ } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ rcd=nco_def_dim(out_id,lev_nm_out,lev_nbr_out,&dmn_id_lev_out); } /* !flg_grd_out_prs */ /* Do not extract grid variables (that are also extensive variables) like ilev, lev, hyai, hyam, hybi, hybm */ /* Exception list source: CAM: hyai, hyam, hybi, hybm, ilev, lev, P0, PS EAM: hyai, hyam, hybi, hybm, ilev, lev, P0, PS ECMWF: hyai, hyam, hybi, hybm, lev, lnsp NCEP: plev */ const int var_xcl_lst_nbr=10; /* [nbr] Number of objects on exclusion list */ const char *var_xcl_lst[]={"/hyai","/hyam","/hybi","/hybm","/ilev","/lev","/P0","/plev","/PS","/lnsp"}; int var_cpy_nbr=0; /* [nbr] Number of copied variables */ int var_rgr_nbr=0; /* [nbr] Number of regridded variables */ int var_xcl_nbr=0; /* [nbr] Number of deleted variables */ int var_crt_nbr=0; /* [nbr] Number of created variables */ long idx; /* [idx] Generic index */ unsigned int idx_tbl; /* [idx] Counter for traversal table */ const unsigned int trv_nbr=trv_tbl->nbr; /* [idx] Number of traversal table entries */ for(idx=0;idx<var_xcl_lst_nbr;idx++){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm_fll,var_xcl_lst[idx])) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* !idx_tbl */ } /* !idx */ /* 20191001: Do not automatically define plev_nm_in in pressure-grid output files The variable named lev_nm_out in the input data file is always defined in the output file So if plev_nm_in == lev_nm_out it will be defined anyway */ if(flg_grd_in_prs && flg_grd_out_prs && strcmp(plev_nm_in,lev_nm_out)){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm,plev_nm_in)) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* !idx_tbl */ } /* !idx */ char *var_nm; /* [sng] Variable name */ int *dmn_id_in=NULL; /* [id] Dimension IDs */ int *dmn_id_out=NULL; /* [id] Dimension IDs */ int var_id_in; /* [id] Variable ID */ int var_id_out; /* [id] Variable ID */ nc_type var_typ_out; /* [enm] Variable type to write to disk */ nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes "scale_factor", "add_offset" */ int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; dfl_lvl=rgr->dfl_lvl; fl_out_fmt=rgr->fl_out_fmt; /* Define new coordinates and grid variables in regridded file */ const int dmn_nbr_0D=0; /* [nbr] Rank of 0-D grid variables (scalars) */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ //const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ //const int dmn_nbr_3D=3; /* [nbr] Rank of 3-D grid variables */ //const int dmn_nbr_grd_max=dmn_nbr_3D; /* [nbr] Maximum rank of grid variables */ if(flg_grd_out_hyb){ rcd+=nco_def_var(out_id,"hyai",crd_typ_out,dmn_nbr_1D,&dmn_id_ilev_out,&hyai_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hyai_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"hyam",crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&hyam_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hyam_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"hybi",crd_typ_out,dmn_nbr_1D,&dmn_id_ilev_out,&hybi_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hybi_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"hybm",crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&hybm_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hybm_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,ilev_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_ilev_out,&ilev_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ilev_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lev_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&lev_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lev_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"P0",crd_typ_out,dmn_nbr_0D,(int *)NULL,&p0_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,p0_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; // for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ // rcd=nco_inq_dimname(out_id,dmn_ids_out[dmn_idx],dmn_nm); // (void)fprintf(stdout,"%s: DEBUG quark5 dmn_nbr_out = %d, dmn_nbr_ps = %d, dmn_idx = %d, dmn_ids_out[%d] = %d, dmn_nm = %s\n",nco_prg_nm_get(),dmn_nbr_out,dmn_nbr_ps,dmn_idx,dmn_idx,dmn_ids_out[dmn_idx],dmn_nm); // } /* !dmn_idx */ if(flg_grd_hyb_cameam) rcd+=nco_def_var(out_id,"PS",crd_typ_out,dmn_nbr_ps,dmn_ids_out,&ps_id); if(flg_grd_hyb_ecmwf){ /* Remove degenerate ECMWF vertical dimension so that output PS has dmn_nbr_ps-1 not dmn_nbr_ps dimensions */ int dmn_nbr_out_ecmwf=0; for(dmn_idx=0;dmn_idx<dmn_nbr_ps;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_ids_in[dmn_idx],dmn_nm); if(strcmp(dmn_nm,ilev_nm_out) && strcmp(dmn_nm,lev_nm_out) && strcmp(dmn_nm,"lev_2")) rcd=nco_inq_dimid(out_id,dmn_nm,dmn_ids_out+dmn_nbr_out_ecmwf++); } /* !dmn_idx */ rcd+=nco_def_var(out_id,"PS",crd_typ_out,dmn_nbr_out_ecmwf,dmn_ids_out,&ps_id); } /* !flg_grd_hyb_ecmwf */ if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ps_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; (void)nco_att_cpy(tpl_id,out_id,hyai_id_tpl,hyai_id,PCK_ATT_CPY); (void)nco_att_cpy(tpl_id,out_id,hyam_id_tpl,hyam_id,PCK_ATT_CPY); (void)nco_att_cpy(tpl_id,out_id,hybi_id_tpl,hybi_id,PCK_ATT_CPY); (void)nco_att_cpy(tpl_id,out_id,hybm_id_tpl,hybm_id,PCK_ATT_CPY); if(p0_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,p0_id_tpl,p0_id,PCK_ATT_CPY); /* p0 not expected to be in ECMWF grids */ if(ilev_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,ilev_id_tpl,ilev_id,PCK_ATT_CPY); else if(ilev_id_in != NC_MIN_INT) (void)nco_att_cpy(in_id,out_id,ilev_id_in,ilev_id,PCK_ATT_CPY); if(lev_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,lev_id_tpl,lev_id,PCK_ATT_CPY); else if(lev_id_in != NC_MIN_INT) (void)nco_att_cpy(in_id,out_id,lev_id_in,lev_id,PCK_ATT_CPY); if(ps_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,ps_id_tpl,ps_id,PCK_ATT_CPY); else (void)nco_att_cpy(in_id,out_id,ps_id_in,ps_id,PCK_ATT_CPY); } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ rcd+=nco_def_var(out_id,lev_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&lev_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lev_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; (void)nco_att_cpy(tpl_id,out_id,lev_id_tpl,lev_id,PCK_ATT_CPY); dmn_id_ilev_out=dmn_id_lev_out; } /* !flg_grd_out_prs */ /* No further access to template file, close it */ nco_close(tpl_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_tpl); char *dmn_nm_cp; /* [sng] Dimension name as char * to reduce indirection */ nco_bool has_ilev; /* [flg] Contains interface level dimension */ nco_bool has_lev; /* [flg] Contains midpoint level dimension */ nco_bool has_tm; /* [flg] Contains time dimension */ nco_bool need_prs_ntf=False; /* [flg] At least one variable to regrid is on interface levels */ nco_bool need_prs_mdp=False; /* [flg] At least one variable to regrid is on midpoint levels */ trv_sct trv; /* [sct] Traversal table object structure to reduce indirection */ /* Define regridding flag for each variable */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ dmn_nbr_in=trv_tbl->lst[idx_tbl].nbr_dmn; has_ilev=False; has_lev=False; for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ /* Pre-determine flags necessary during next loop */ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; /* fxm: Generalize to include any variable containing coordinates with "standard_name" = "atmosphere_hybrid_sigma_pressure_coordinate" */ if(!has_ilev && ilev_nm_in) has_ilev=!strcmp(dmn_nm_cp,ilev_nm_in); if(!has_lev) has_lev=!strcmp(dmn_nm_cp,lev_nm_in); } /* end loop over dimensions */ /* Regrid variables that contain either vertical dimension */ if(has_ilev || has_lev){ trv_tbl->lst[idx_tbl].flg_rgr=True; var_rgr_nbr++; if(has_ilev) need_prs_ntf=True; if(has_lev) need_prs_mdp=True; } /* endif */ assert(!(has_ilev && has_lev)); /* Copy all variables that are not regridded or omitted */ if(!trv_tbl->lst[idx_tbl].flg_rgr) var_cpy_nbr++; } /* end nco_obj_typ_var */ } /* end idx_tbl */ if(!var_rgr_nbr) (void)fprintf(stdout,"%s: WARNING %s reports no variables fit interpolation criteria. The vertical interpolator expects something to interpolate, and variables not interpolated are copied straight to output. HINT: If the name(s) of the input vertical grid dimensions (e.g., ilev and lev) do not match NCO's preset defaults (case-insensitive unambiguous forms and abbreviations of \"ilev\", \"lev\", and/or \"plev\", respectively) then change the dimension names that NCO looks for. Instructions are at http://nco.sf.net/nco.html#regrid. For hybrid-pressure coordinate grids, ensure that the \"ilev\" and \"lev\" variable names are known with, e.g., \"ncks --rgr ilev_nm=interface_level --rgr lev_nm=midpoint_level\" or \"ncremap -R '--rgr ilev=interface_level --rgr lev=midpoint_level'\". For pure pressure grids, ensure the \"plev\" coordinate name is defined with, e.g., \"ncks --rgr plev_nm=pressure_level\" or \"ncremap -R '--rgr plev=pressure_level'\".\n",nco_prg_nm_get(),fnc_nm); if(nco_dbg_lvl_get() >= nco_dbg_fl){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr) (void)fprintf(stderr,"Interpolate %s? %s\n",trv.nm,trv.flg_rgr ? "Yes" : "No"); } /* end idx_tbl */ } /* end dbg */ /* Pre-allocate dimension ID and cnt/srt space */ int dmn_nbr_max; /* [nbr] Maximum number of dimensions variable can have in input or output */ rcd+=nco_inq_ndims(in_id,&dmn_nbr_max); dmn_id_in=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); aed_sct aed_mtd_fll_val; char *att_nm_fll_val=strdup("_FillValue"); int flg_pck; /* [flg] Variable is packed on disk */ nco_bool has_mss_val; /* [flg] Has numeric missing value attribute */ float mss_val_flt; double mss_val_dbl; if(flg_add_msv_att){ aed_mtd_fll_val.att_nm=att_nm_fll_val; aed_mtd_fll_val.mode=aed_create; aed_mtd_fll_val.sz=1L; mss_val_dbl=NC_FILL_DOUBLE; mss_val_flt=NC_FILL_FLOAT; } /* !flg_add_msv_att */ /* Define interpolated and copied variables in output file */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ var_nm=trv.nm; /* Preserve input type in output type */ var_typ_out=trv.var_typ; dmn_nbr_in=trv.nbr_dmn; dmn_nbr_out=trv.nbr_dmn; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid_flg(out_id,var_nm,&var_id_out); /* If variable has not been defined, define it */ if(rcd != NC_NOERR){ if(trv.flg_rgr){ /* Interpolate */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); rcd=nco_inq_var_packing(in_id,var_id_in,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports variable \"%s\" is packed so results unpredictable. HINT: If regridded values seems weird, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,var_nm); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); if(ilev_nm_in && !strcmp(dmn_nm,ilev_nm_in)){ /* Change ilev dimension */ dmn_id_out[dmn_idx]=dmn_id_ilev_out; dmn_cnt_out[dmn_idx]=ilev_nbr_out; }else if(!strcmp(dmn_nm,lev_nm_in)){ /* Change lev dimension */ dmn_id_out[dmn_idx]=dmn_id_lev_out; dmn_cnt_out[dmn_idx]=lev_nbr_out; }else{ /* Dimensions ilev/lev_nm_in have already been defined as ilev/lev_nm_out, replicate all other dimensions */ rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx); } /* !ilev */ if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_out+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt_out[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_id_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ }else{ /* !flg_rgr */ /* Replicate non-interpolated variables */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_out+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt_out[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_id_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ } /* !flg_rgr */ rcd=nco_def_var(out_id,var_nm,var_typ_out,dmn_nbr_out,dmn_id_out,&var_id_out); /* Duplicate netCDF4 settings when possible */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC){ /* Deflation */ if(dmn_nbr_out > 0){ int dfl_lvl_in; /* [enm] Deflate level [0..9] */ rcd=nco_inq_var_deflate(in_id,var_id_in,&shuffle,&deflate,&dfl_lvl_in); /* Copy original deflation settings */ if(deflate || shuffle) (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl_in); /* Overwrite HDF Lempel-Ziv compression level, if requested */ if(dfl_lvl == 0) deflate=(int)False; else deflate=(int)True; /* Turn-off shuffle when uncompressing otherwise chunking requests may fail */ if(dfl_lvl == 0) shuffle=NC_NOSHUFFLE; /* Shuffle never, to my knowledge, increases filesize, so shuffle by default when manually deflating */ if(dfl_lvl >= 0) shuffle=NC_SHUFFLE; if(dfl_lvl >= 0) (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl); } /* !dmn_nbr_out */ } /* !NC_FORMAT_NETCDF4 */ (void)nco_att_cpy(in_id,out_id,var_id_in,var_id_out,PCK_ATT_CPY); /* Variables with subterranean levels and missing-value extrapolation must have _FillValue attribute */ if(flg_add_msv_att && trv.flg_rgr){ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); if(!has_mss_val){ nco_bool flg_att_chg; /* [flg] _FillValue attribute was written */ aed_mtd_fll_val.var_nm=var_nm; aed_mtd_fll_val.id=var_id_out; aed_mtd_fll_val.type=var_typ_out; if(var_typ_out == NC_FLOAT) aed_mtd_fll_val.val.fp=&mss_val_flt; else if(var_typ_out == NC_DOUBLE) aed_mtd_fll_val.val.dp=&mss_val_dbl; flg_att_chg=nco_aed_prc(out_id,var_id_out,aed_mtd_fll_val); if(!flg_att_chg && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: WARNING %s reports unsuccessful attempt to create _FillValue attribute for variable %s\n",nco_prg_nm_get(),fnc_nm,var_nm); } /* !has_mss_val */ } /* !flg_add_msv_att */ } /* !rcd */ } /* !var */ } /* end idx_tbl */ /* Free pre-allocated array space */ if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Begin data mode */ (void)nco_enddef(out_id); /* Copy all grid variables */ if(flg_grd_out_hyb){ (void)nco_put_var(out_id,hyai_id,hyai_out,crd_typ_out); (void)nco_put_var(out_id,hyam_id,hyam_out,crd_typ_out); (void)nco_put_var(out_id,hybi_id,hybi_out,crd_typ_out); (void)nco_put_var(out_id,hybm_id,hybm_out,crd_typ_out); (void)nco_put_var(out_id,ilev_id,ilev_out,crd_typ_out); (void)nco_put_var(out_id,lev_id,lev_out,crd_typ_out); (void)nco_put_var(out_id,p0_id,&p0_out,crd_typ_out); (void)nco_put_var(out_id,ps_id,ps_out,crd_typ_out); } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ (void)nco_put_var(out_id,lev_id,lev_out,crd_typ_out); } /* !flg_grd_out_prs */ nco_bool flg_ntp_log=True; /* [flg] Interpolate in log(vertical_coordinate) */ if(ntp_mth == nco_ntp_lnr) flg_ntp_log=False; size_t idx_in; /* [idx] Index into 3D input variables */ size_t idx_out; /* [idx] Index into 3D output variables */ size_t var_sz_in; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t var_sz_out; /* [nbr] Number of elements in variable (will be self-multiplied) */ /* Interpolate or copy variable values */ double *var_val_dbl_in=NULL; double *var_val_dbl_out=NULL; double *prs_ntp_in; /* [Pa] Interpolated pressure array on input grid */ double *prs_ntp_out; /* [Pa] Interpolated pressure array on output grid */ int lvl_idx_in; /* [idx] Level index on input grid */ int lvl_idx_out; /* [idx] Level index on output grid */ int lvl_nbr_in; /* [nbr] Number of levels for current interpolated variable on input grid */ int lvl_nbr_out; /* [nbr] Number of levels for current interpolated variable on output grid */ int thr_idx; /* [idx] Thread index */ size_t grd_nbr=grd_sz_in; /* [nbr] Horizonal grid size */ size_t idx_dbg=rgr->idx_dbg; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped as shared in parallel clause */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ /* Repeating above documentation for the forgetful: NB: tm_nbr is max(timesteps) in vertical grid definitions, not number of records in either file This implementation interpolates timeseries to/from time-invariant vertical grids in one OpenMP call! */ for(tm_idx=0;tm_idx<tm_nbr;tm_idx++){ /* Index-offset to current surface pressure timeslice */ idx_fst=tm_idx*grd_sz_in; if(need_prs_mdp){ /* Allocated and define midpoint pressures */ if(tm_idx == 0) prs_mdp_in=(double *)nco_malloc_dbg(grd_sz_in*lev_nbr_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_mdp_in value buffer"); if(tm_idx == 0) prs_mdp_out=(double *)nco_malloc_dbg(grd_sz_out*lev_nbr_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_mdp_out value buffer"); if(flg_grd_in_hyb) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_in;lev_idx++) prs_mdp_in[grd_idx+lev_idx*grd_sz_in]=p0_in*hyam_in[lev_idx]+ps_in[idx_fst+grd_idx]*hybm_in[lev_idx]; if(flg_grd_out_hyb) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_out;lev_idx++) prs_mdp_out[grd_idx+lev_idx*grd_sz_out]=p0_out*hyam_out[lev_idx]+ps_out[idx_fst+grd_idx]*hybm_out[lev_idx]; if(flg_grd_in_prs) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_in;lev_idx++) prs_mdp_in[grd_idx+lev_idx*grd_sz_in]=lev_in[lev_idx]; if(flg_grd_out_prs) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_out;lev_idx++) prs_mdp_out[grd_idx+lev_idx*grd_sz_out]=lev_out[lev_idx]; if(flg_ntp_log){ var_sz_in=grd_sz_in*lev_nbr_in; for(idx_in=0;idx_in<var_sz_in;idx_in++) prs_mdp_in[idx_in]=log(prs_mdp_in[idx_in]); var_sz_out=grd_sz_out*lev_nbr_out; for(idx_out=0;idx_out<var_sz_out;idx_out++) prs_mdp_out[idx_out]=log(prs_mdp_out[idx_out]); } /* !flg_ntp_log */ } /* !need_prs_mdp */ if(need_prs_ntf){ /* Allocate and define interface pressures */ if(tm_idx == 0) prs_ntf_in=(double *)nco_malloc_dbg(grd_sz_in*ilev_nbr_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_ntf_in value buffer"); if(tm_idx == 0) prs_ntf_out=(double *)nco_malloc_dbg(grd_sz_out*ilev_nbr_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_ntf_out value buffer"); if(flg_grd_in_hyb) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_in;ilev_idx++) prs_ntf_in[grd_idx+ilev_idx*grd_sz_in]=p0_in*hyai_in[ilev_idx]+ps_in[idx_fst+grd_idx]*hybi_in[ilev_idx]; if(flg_grd_out_hyb) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_out;ilev_idx++) prs_ntf_out[grd_idx+ilev_idx*grd_sz_out]=p0_out*hyai_out[ilev_idx]+ps_out[idx_fst+grd_idx]*hybi_out[ilev_idx]; if(flg_grd_in_prs) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_in;ilev_idx++) prs_ntf_in[grd_idx+ilev_idx*grd_sz_in]=lev_in[ilev_idx]; if(flg_grd_out_prs) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_out;ilev_idx++) prs_ntf_out[grd_idx+ilev_idx*grd_sz_out]=lev_out[ilev_idx]; if(flg_ntp_log){ var_sz_in=grd_sz_in*ilev_nbr_in; for(idx_in=0;idx_in<var_sz_in;idx_in++) prs_ntf_in[idx_in]=log(prs_ntf_in[idx_in]); var_sz_out=grd_sz_out*ilev_nbr_out; for(idx_out=0;idx_out<var_sz_out;idx_out++) prs_ntf_out[idx_out]=log(prs_ntf_out[idx_out]); } /* !flg_ntp_log */ } /* !need_prs_ntf */ /* Set firstprivate variables to initial values */ has_ilev=False; has_lev=False; has_tm=False; if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"Interpolation progress: # means interpolated, ~ means copied\n"); #ifdef __GNUG__ # define GCC_LIB_VERSION ( __GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__ ) # if GCC_LIB_VERSION < 490 # define GXX_OLD_OPENMP_SHARED_TREATMENT 1 # endif /* 480 */ # if GCC_LIB_VERSION >= 900 # define GXX_WITH_OPENMP5_GPU_SUPPORT 1 # endif /* 900 */ #endif /* !__GNUC__ */ #if defined( __INTEL_COMPILER) # pragma omp parallel for default(none) firstprivate(has_ilev,has_lev,has_tm,var_val_dbl_in,var_val_dbl_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_dbl,prs_ntp_in,prs_ntp_out,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_ilev_in,dmn_id_ilev_out,dmn_id_lev_in,dmn_id_lev_out,dmn_id_tm_in,flg_ntp_log,flg_vrt_tm,fnc_nm,grd_nbr,idx_dbg,ilev_nbr_in,ilev_nbr_out,lev_nbr_in,lev_nbr_out,out_id,prs_mdp_in,prs_mdp_out,prs_ntf_in,prs_ntf_out,tm_idx,xtr_mth) #else /* !__INTEL_COMPILER */ # ifdef GXX_OLD_OPENMP_SHARED_TREATMENT # pragma omp parallel for default(none) firstprivate(has_ilev,has_lev,has_tm,var_val_dbl_in,var_val_dbl_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_dbl,prs_ntp_in,prs_ntp_out,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_ilev_in,dmn_id_ilev_out,dmn_id_lev_in,dmn_id_lev_out,dmn_id_tm_in,flg_ntp_log,flg_vrt_tm,fnc_nm,grd_nbr,idx_dbg,ilev_nbr_in,ilev_nbr_out,lev_nbr_in,lev_nbr_out,out_id,prs_mdp_in,prs_mdp_out,prs_ntf_in,prs_ntf_out,tm_idx,xtr_mth) # else /* !old g++ */ # if defined(GXX_WITH_OPENMP5_GPU_SUPPORT) && 0 # pragma omp target teams distribute parallel for # else # pragma omp parallel for firstprivate(has_ilev,has_lev,has_tm,var_val_dbl_in,var_val_dbl_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_dbl,prs_ntp_in,prs_ntp_out,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_ilev_in,dmn_id_ilev_out,dmn_id_lev_in,dmn_id_lev_out,dmn_id_tm_in,flg_ntp_log,flg_vrt_tm,grd_nbr,idx_dbg,ilev_nbr_in,ilev_nbr_out,lev_nbr_in,lev_nbr_out,out_id,prs_mdp_in,prs_mdp_out,prs_ntf_in,prs_ntf_out,tm_idx,xtr_mth) # endif /* !GCC > 9.0 */ # endif /* !GCC < 4.9 */ #endif /* !__INTEL_COMPILER */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; thr_idx=omp_get_thread_num(); in_id=trv_tbl->in_id_arr[thr_idx]; #ifdef _OPENMP if(nco_dbg_lvl_get() >= nco_dbg_grp && !thr_idx && !idx_tbl) (void)fprintf(fp_stdout,"%s: INFO %s reports regrid loop uses %d thread%s\n",nco_prg_nm_get(),fnc_nm,omp_get_num_threads(),(omp_get_num_threads() > 1) ? "s" : ""); if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO thread = %d, idx_tbl = %d, nm = %s\n",nco_prg_nm_get(),thr_idx,idx_tbl,trv.nm); #endif /* !_OPENMP */ if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s%s ",trv.flg_rgr ? "#" : "~",trv.nm); if(trv.flg_rgr){ /* Interpolate variable */ var_nm=trv.nm; if(!strcmp(var_nm,"US") || !strcmp(var_nm,"VS")) (void)fprintf(fp_stdout,"%s: WARNING %s reports attempt to vertically interpolate a variable named \"%s\". If this variable is from a CESM CAM or E3SM EAM output or initial condition file on a rectangular grid (e.g., FV 0.9x1.25), then expect this program to fail and dump core when interpolating US and to produce slightly incorrect answers for VS. The vertical interpolation routine requires that interpolated variables be on the same horizontal grid as the supplied pressure field. However, the CAM/EAM US and VS variables from rectangular grid simulations are often on a horizontal grid, called the staggered grid, that is offset from the rest of the variables including the surface pressure. US usually sits on a grid that is staggered in latitude from, and is a slightly different size than, the surface pressure grid. This leads to a core dump. VS sits on a grid staggered in longitude from, though the same size as, the surface pressure field. The resulting interpolation will be based on surface pressure half a gridcell to the east rather than centered with VS. The correct procedure to vertically interpolate US and VS is to 1) horizontally regrid the supplied surface pressure (often \"PS\") to the staggered grid, then 2) vertically interpolate US and VS to the desired vertical grid based on the surface pressure on the staggered grid, then 3) re-combine the interpolated US and VS with the interpolated versions of the rest of the variables. The best solution to this dilemma is to script this workflow. Contact Charlie if you need help with this.\n",nco_prg_nm_get(),fnc_nm,var_nm); var_typ_rgr=NC_DOUBLE; /* NB: Perform regridding in double precision */ var_typ_out=trv.var_typ; /* NB: Output type in file is same as input type */ var_sz_in=1L; var_sz_out=1L; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid(out_id,var_nm,&var_id_out); rcd=nco_inq_varndims(in_id,var_id_in,&dmn_nbr_in); rcd=nco_inq_varndims(out_id,var_id_out,&dmn_nbr_out); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_id_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); rcd=nco_inq_vardimid(out_id,var_id_out,dmn_id_out); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_in+dmn_idx); if(dmn_id_in[dmn_idx] == dmn_id_ilev_in) has_ilev=True; if(dmn_id_in[dmn_idx] == dmn_id_lev_in) has_lev=True; if(dmn_id_in[dmn_idx] == dmn_id_tm_in) has_tm=True; if(flg_vrt_tm && has_tm && dmn_id_in[dmn_idx] == dmn_id_tm_in){ dmn_cnt_in[dmn_idx]=1L; dmn_srt[dmn_idx]=tm_idx; }else{ dmn_srt[dmn_idx]=0L; } /* !flg_vrt_tm */ var_sz_in*=dmn_cnt_in[dmn_idx]; } /* !dmn_idx */ var_val_dbl_in=(double *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() input value buffer"); rcd=nco_get_vara(in_id,var_id_in,dmn_srt,dmn_cnt_in,var_val_dbl_in,var_typ_rgr); for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ /* Dimension count vector is same as input except for lvl dimension */ dmn_cnt_out[dmn_idx]=dmn_cnt_in[dmn_idx]; if(has_ilev && dmn_id_out[dmn_idx] == dmn_id_ilev_out) dmn_cnt_out[dmn_idx]=ilev_nbr_out; if(has_lev && dmn_id_out[dmn_idx] == dmn_id_lev_out) dmn_cnt_out[dmn_idx]=lev_nbr_out; var_sz_out*=dmn_cnt_out[dmn_idx]; } /* !dmn_idx */ var_val_dbl_out=(double *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() output value buffer"); /* Missing value setup */ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); if(!has_mss_val) mss_val_dbl=NC_FILL_DOUBLE; if(has_ilev){ /* Interpolate current variable from input interface pressure grid to output interface pressure grid */ lvl_nbr_in=ilev_nbr_in; lvl_nbr_out=ilev_nbr_out; prs_ntp_in=prs_ntf_in; prs_ntp_out=prs_ntf_out; }else{ /* Interpolate current variable from input midpoint pressure grid to output midpoint pressure grid */ lvl_nbr_in=lev_nbr_in; lvl_nbr_out=lev_nbr_out; prs_ntp_in=prs_mdp_in; prs_ntp_out=prs_mdp_out; } /* !ilev */ /* Procedure: Extract input/output coordinate/data arrays into 1D column order This enables actual interpolation code to be written for, or take advantage of, 1D interpolation routines After interpolating into 1D sequential memory, copy back to ND output and repeat */ double *crd_in=NULL; /* Input vertical coordinate (must be monotonic) */ double *crd_out=NULL; /* Output vertical coordinate (must be monotonic) */ double *dat_in=NULL; /* Input data (to be interpolated) on input vertical coordinate grid */ double *dat_out=NULL; /* Output data (interpolated) output vertical coordinate grid (i.e., the answer) */ double *crd_in_mnt; /* Input vertical coordinate reversed if necessary to be monotonically increasing */ double *crd_out_mnt; /* Output vertical coordinate reversed if necessary to be monotonically increasing */ double *dat_in_mnt; /* Input data (to be interpolated) reversed if necessary along with input grid */ double *dat_out_mnt; /* Output data (interpolated) reversed if necessary along with output grid */ nco_xtr_sct xtr_LHS; nco_xtr_sct xtr_RHS; size_t brk_lft_idx; size_t brk_rgt_idx; size_t in_idx; size_t in_nbr; size_t out_nbr; size_t out_idx; /* Default extrapolation uses nearest valid neighbor */ xtr_LHS.xtr_fll=True; xtr_LHS.xtr_vrb=False; xtr_LHS.typ_fll=xtr_mth; xtr_RHS.xtr_fll=True; xtr_RHS.xtr_vrb=False; xtr_RHS.typ_fll=xtr_mth; /* Special-case extrapolation methods allowed for all except missing-value extrapolation types */ if(xtr_mth != nco_xtr_fll_msv){ if(!strcmp(var_nm,"T") || !strcmp(var_nm,"ta")) xtr_RHS.typ_fll=nco_xtr_fll_tpt; else if(!strcmp(var_nm,"Z3") || !strcmp(var_nm,"zg")) xtr_LHS.typ_fll=xtr_RHS.typ_fll=nco_xtr_fll_gph; } /* !xtr_mth */ crd_in=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); crd_out=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); dat_in=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); dat_out=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); in_nbr=lvl_nbr_in; out_nbr=lvl_nbr_out; nco_bool in_ncr; /* [flg] Input coordinate monotonically increases */ nco_bool out_ncr; /* [flg] Output coordinate monotonically increases */ /* Determine monotonicity direction only once, based on first vertical column */ if(prs_ntp_in[grd_nbr]-prs_ntp_in[0] > 0.0) in_ncr=True; else in_ncr=False; out_ncr=True; if(out_nbr > 1) if(prs_ntp_out[grd_nbr]-prs_ntp_out[0] < 0.0) out_ncr=False; /* If necessary, allocate (once, and re-use it) additional memory to hold reversed arrays */ if(!in_ncr){ crd_in_mnt=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); dat_in_mnt=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); } /* !in_ncr */ if(!out_ncr){ crd_out_mnt=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); dat_out_mnt=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); } /* !out_ncr */ /* Constants and parameters for extrapolation */ const double gamma_moist=6.5/10000.0; /* [K/Pa] Temperature extrapolation assumes constant moist adiabatic lower atmosphere lapse rate dT/dp=constant=(6.5 K)/(100 mb) = (6.5 K)/(10000 Pa) */ const double Rd_rcp_g0=287.0/9.81; /* [K/Pa] Geopotential height extrapolation uses hypsometric equation Z2-Z1=(Rd*Tv_avg/g0)*ln(p1/p2)=(Rd*Tv_avg/g0)*(ln(p1)-ln(p2)) */ const double tpt_vrt_avg=288.0; /* [K] Mean virtual temperature assumed for geopotential height extrapolation */ nco_bool FIRST_WARNING_LHS; /* [flg] First warning for LHS extrapolation */ nco_bool FIRST_WARNING_RHS; /* [flg] First warning for RHS extrapolation */ if(tm_idx == 0){ /* Only print extrapolation warnings for first timestep to prevent noisy output NB: Algorithm prevents any warnings for extrapolations that appear after first timestep */ FIRST_WARNING_LHS=True; FIRST_WARNING_RHS=True; } /* !tm_idx */ /* Outer loop over columns */ for(grd_idx=0;grd_idx<grd_nbr;grd_idx++){ /* Initialize pseudo-1D variables with consecutive memory addresses to avoid indirection */ for(lvl_idx_in=0;lvl_idx_in<lvl_nbr_in;lvl_idx_in++){ idx_in=grd_idx+lvl_idx_in*grd_nbr; crd_in[lvl_idx_in]=prs_ntp_in[idx_in]; dat_in[lvl_idx_in]=var_val_dbl_in[idx_in]; } /* !lvl_idx_in */ for(lvl_idx_out=0;lvl_idx_out<lvl_nbr_out;lvl_idx_out++){ idx_out=grd_idx+lvl_idx_out*grd_nbr; crd_out[lvl_idx_out]=prs_ntp_out[idx_out]; } /* !lvl_idx_out */ /* Interpolation code easier to write/debug if crd_in and crd_out both monotonically increase However, monotonically decreasing coordinates useful in many cases, such as depth coordinate, and pressure levels arranged largest to smallest (favored by CMIP) Next code block reverses array(s) if necessary so coordinates monotonically increase Code uses crd_in_mnt, dat_in_mnt, crd_out_mnt where "_mnt" reminds of "monotonically increasing" assumption Following code lifted from CSZ's libcsz.a library source code ~/sw/c++/vec.hh */ if(in_ncr){ crd_in_mnt=crd_in; dat_in_mnt=dat_in; }else{ for(in_idx=0;in_idx<in_nbr;in_idx++){ crd_in_mnt[in_idx]=crd_in[in_nbr-in_idx-1]; dat_in_mnt[in_idx]=dat_in[in_nbr-in_idx-1]; } /* !in_idx */ } /* !in_ncr */ if(out_ncr){ crd_out_mnt=crd_out; dat_out_mnt=dat_out; }else{ for(out_idx=0;out_idx<out_nbr;out_idx++) crd_out_mnt[out_idx]=crd_out[out_nbr-out_idx-1]; } /* !out_ncr */ // Initialize bracketing index brk_lft_idx=0; // Loop over desired output coordinates for(out_idx=0;out_idx<out_nbr;out_idx++){ // Order of conditions is important since second condition is illegal if brk_lft_idx >= in_nbr while((brk_lft_idx < in_nbr) && (crd_in_mnt[brk_lft_idx] < crd_out_mnt[out_idx])){ brk_lft_idx++; } // !while brk_lft_idx--; // Handle identity interpolation separately to preserve symmetry in extrapolation code if(brk_lft_idx != in_nbr-1){ if(crd_in_mnt[brk_lft_idx+1] == crd_out_mnt[out_idx]){ dat_out_mnt[out_idx]=dat_in_mnt[brk_lft_idx+1]; if(brk_lft_idx == -1) brk_lft_idx=0; // Reset brk_lft_idx to 0 so next while loop works continue; // Jump to next iteration } // !crd_in_mnt } // !brk_lft_idx if(brk_lft_idx == -1){ // LHS Extrapolation required // Degenerate case: crd_out_mnt[out_idx] < crd_in_mnt[0] brk_lft_idx=0; // Reset brk_lft_idx to 0 so next while loop works if(xtr_LHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: WARNING %s reports variable %s column %lu output value dat_out_mnt[%lu] at coordinate crd_out_mnt[%lu] = %g requires LHS extrapolation beyond leftmost valid coordinate at crd_in_mnt[%lu] = %g. Nearest valid datum is dat_in_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,var_nm,grd_idx,out_idx,out_idx,crd_out_mnt[out_idx],brk_lft_idx,crd_in_mnt[brk_lft_idx],brk_lft_idx,dat_in_mnt[brk_lft_idx]); // Extrapolation options are presented in decreasing order of preference if(!xtr_LHS.xtr_fll){ (void)fprintf(fp_stdout,"%s: ERROR %s Full LHS extrapolation required but not permitted\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; } /* !xtr_LHS.xtr_fll */ switch(xtr_LHS.typ_fll){ case nco_xtr_fll_nil: dat_out_mnt[out_idx]=0.0; break; case nco_xtr_fll_msv: dat_out_mnt[out_idx]=mss_val_dbl; break; case nco_xtr_fll_ngh: dat_out_mnt[out_idx]=dat_in_mnt[0]; break; case nco_xtr_fll_lnr: dat_out_mnt[out_idx]=dat_in_mnt[0]- (crd_in_mnt[0]-crd_out_mnt[out_idx])* (dat_in_mnt[1]-dat_in_mnt[0])/(crd_in_mnt[1]-crd_in_mnt[0]); break; case nco_xtr_fll_gph: if(flg_ntp_log) /* Coordinates are already logarithmic in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[0]+ Rd_rcp_g0*tpt_vrt_avg*(crd_in_mnt[0]-crd_out_mnt[out_idx]); else /* Interpolate with logarithm of pressure coordinates */ dat_out_mnt[out_idx]=dat_in_mnt[0]+ Rd_rcp_g0*tpt_vrt_avg*log(crd_in_mnt[0]/crd_out_mnt[out_idx]); if(FIRST_WARNING_LHS) (void)fprintf(fp_stdout,"%s: INFO %s geopotential height extrapolated upward towards space using hypsometric equation with constant global mean virtual temperature = %g for variable %s\n",nco_prg_nm_get(),fnc_nm,tpt_vrt_avg,var_nm); FIRST_WARNING_LHS=False; break; default: (void)fprintf(fp_stdout,"%s: ERROR %s Unknown xtr_LHS.typ_fll\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; break; } // !xtr_LHS.typ_fll if(xtr_LHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: INFO %s LHS extrapolation yields dat_out_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,out_idx,dat_out_mnt[out_idx]); }else if(brk_lft_idx < in_nbr-1){ // Normal case: crd_out_mnt is interpolable brk_rgt_idx=brk_lft_idx+1; // NB: brk_rgt_idx is ALWAYS greater than brk_lft_idx // This simulaneously meets two criteria: // 1. Divide-by-zero errors are impossible in the next step // 2. The identity interpolation is satisfied since crd_dlt == 0.0: // i.e., If crd_out_mnt[idx] == crd_in_mnt[brk_lft_idx] then dat_out_mnt[out_idx] := dat_in_mnt[brk_lft_idx] // Linearly interpolate dat_out_mnt[out_idx]= dat_in_mnt[brk_lft_idx]+ (crd_out_mnt[out_idx]-crd_in_mnt[brk_lft_idx])* (dat_in_mnt[brk_rgt_idx]-dat_in_mnt[brk_lft_idx])/ (crd_in_mnt[brk_rgt_idx]-crd_in_mnt[brk_lft_idx]); }else if(brk_lft_idx == in_nbr-1){ // RHS Extrapolation required // Degenerate case: brk_lft_idx is last element of crd_in_mnt brk_rgt_idx=brk_lft_idx; if(xtr_RHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: WARNING %s reports variable %s column %lu output value dat_out_mnt[%lu] at coordinate crd_out_mnt[%lu] = %g requires RHS extrapolation beyond rightmost valid coordinate at crd_in_mnt[%lu] = %g. Nearest valid datum is dat_in_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,var_nm,grd_idx,out_idx,out_idx,crd_out_mnt[out_idx],brk_rgt_idx,crd_in_mnt[brk_rgt_idx],brk_rgt_idx,dat_in_mnt[brk_rgt_idx]); // Extrapolation options are presented in decreasing order of preference if(!xtr_RHS.xtr_fll){ (void)fprintf(fp_stdout,"%s: ERROR %s Full RHS extrapolation required but not permitted\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; } /* !xtr_RHS.xtr_fll */ switch(xtr_RHS.typ_fll){ case nco_xtr_fll_nil: dat_out_mnt[out_idx]=0.0; break; case nco_xtr_fll_msv: dat_out_mnt[out_idx]=mss_val_dbl; break; case nco_xtr_fll_ngh: dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]; break; case nco_xtr_fll_lnr: dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]+ (crd_out_mnt[out_idx]-crd_in_mnt[in_nbr-1])* (dat_in_mnt[in_nbr-1]-dat_in_mnt[in_nbr-2])/ (crd_in_mnt[in_nbr-1]-crd_in_mnt[in_nbr-2]); break; case nco_xtr_fll_tpt: if(flg_ntp_log) /* Exponentiate so coordinates are linear in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]+ (exp(crd_out_mnt[out_idx])-exp(crd_in_mnt[in_nbr-1]))*gamma_moist; else /* Coordinates are already linear in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]+ (crd_out_mnt[out_idx]-crd_in_mnt[in_nbr-1])*gamma_moist; if(FIRST_WARNING_RHS) (void)fprintf(fp_stdout,"%s: INFO %s temperature extrapolated toward/into surface assuming constant moist adiabatic lapse rate = %g K/(100 mb) for variable %s\n",nco_prg_nm_get(),fnc_nm,gamma_moist*10000.0,var_nm); FIRST_WARNING_RHS=False; break; case nco_xtr_fll_gph: if(flg_ntp_log) /* Coordinates are already logarithmic in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]- Rd_rcp_g0*tpt_vrt_avg*(crd_out_mnt[out_idx]-crd_in_mnt[in_nbr-1]); else /* Interpolate with logarithm of pressure coordinates */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]- Rd_rcp_g0*tpt_vrt_avg*log(crd_out_mnt[out_idx]/crd_in_mnt[in_nbr-1]); if(FIRST_WARNING_RHS) (void)fprintf(fp_stdout,"%s: INFO %s geopotential height extrapolated toward/into surface using hypsometric equation with constant global mean virtual temperature = %g for variable %s\n",nco_prg_nm_get(),fnc_nm,tpt_vrt_avg,var_nm); FIRST_WARNING_RHS=False; break; default: (void)fprintf(fp_stdout,"%s: ERROR %s Unknown xtr_RHS\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; break; } // !xtr_RHS.typ_fll if(xtr_RHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: INFO %s RHS extrapolation yields dat_out_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,out_idx,dat_out_mnt[out_idx]); }else{ (void)fprintf(fp_stdout,"%s: ERROR %s Unforeseen value of brk_lft_idx\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; } // !RHS } // !out_idx /* Un-reverse output data to be on original grid */ if(!out_ncr) for(out_idx=0;out_idx<out_nbr;out_idx++) dat_out[out_idx]=dat_out_mnt[out_nbr-out_idx-1]; // End of vec.hh code /* Copy answers into output array */ for(lvl_idx_out=0;lvl_idx_out<lvl_nbr_out;lvl_idx_out++){ idx_out=grd_idx+lvl_idx_out*grd_nbr; var_val_dbl_out[idx_out]=dat_out[lvl_idx_out]; } /* !lvl_idx_out */ if(nco_dbg_lvl_get() >= nco_dbg_io && grd_idx == idx_dbg){ (void)fprintf(fp_stdout,"%s: DEBUG %s variable %s at idx_dbg = %lu\n",nco_prg_nm_get(),fnc_nm,var_nm,idx_dbg); for(out_idx=0;out_idx<out_nbr;out_idx++){ (void)fprintf(fp_stdout,"out_idx = %lu dat_out = %g\n",out_idx,dat_out[out_idx]); } /* !out_idx */ } /* !dbg */ } /* !grd_idx */ if(crd_in) crd_in=(double *)nco_free(crd_in); if(crd_out) crd_out=(double *)nco_free(crd_out); if(dat_in) dat_in=(double *)nco_free(dat_in); if(dat_out) dat_out=(double *)nco_free(dat_out); if(!in_ncr){ if(crd_in_mnt) crd_in_mnt=(double *)nco_free(crd_in_mnt); if(dat_in_mnt) dat_in_mnt=(double *)nco_free(dat_in_mnt); } /* !in_ncr */ if(!out_ncr){ if(crd_out_mnt) crd_out_mnt=(double *)nco_free(crd_out_mnt); if(dat_out_mnt) dat_out_mnt=(double *)nco_free(dat_out_mnt); } /* !out_ncr */ #pragma omp critical { /* begin OpenMP critical */ rcd=nco_put_vara(out_id,var_id_out,dmn_srt,dmn_cnt_out,var_val_dbl_out,var_typ_rgr); } /* end OpenMP critical */ if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(var_val_dbl_in) var_val_dbl_in=(double *)nco_free(var_val_dbl_in); if(var_val_dbl_out) var_val_dbl_out=(double *)nco_free(var_val_dbl_out); }else{ /* !trv.flg_rgr */ /* Use standard NCO copy routine for variables that are not regridded 20190511: Copy them only once */ if(tm_idx == 0){ #pragma omp critical { /* begin OpenMP critical */ (void)nco_cpy_var_val(in_id,out_id,(FILE *)NULL,(md5_sct *)NULL,trv.nm,trv_tbl); } /* end OpenMP critical */ } /* !tm_idx */ } /* !flg_rgr */ } /* !xtr */ } /* end (OpenMP parallel for) loop over idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"\n"); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s completion report: Variables interpolated = %d, copied unmodified = %d, omitted = %d, created = %d\n",nco_prg_nm_get(),fnc_nm,var_rgr_nbr,var_cpy_nbr,var_xcl_nbr,var_crt_nbr); } /* !tm_idx */ if(att_nm_fll_val) att_nm_fll_val=(char *)nco_free(att_nm_fll_val); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_ids_in) dmn_ids_in=(int *)nco_free(dmn_ids_in); if(dmn_ids_out) dmn_ids_out=(int *)nco_free(dmn_ids_out); if(ilev_nm_in) ilev_nm_in=(char *)nco_free(ilev_nm_in); if(lev_nm_in) lev_nm_in=(char *)nco_free(lev_nm_in); if(hyai_in) hyai_in=(double *)nco_free(hyai_in); if(hyam_in) hyam_in=(double *)nco_free(hyam_in); if(hybi_in) hybi_in=(double *)nco_free(hybi_in); if(hybm_in) hybm_in=(double *)nco_free(hybm_in); if(ps_in) ps_in=(double *)nco_free(ps_in); if(prs_mdp_in) prs_mdp_in=(double *)nco_free(prs_mdp_in); if(prs_ntf_in) prs_ntf_in=(double *)nco_free(prs_ntf_in); if(hyai_out) hyai_out=(double *)nco_free(hyai_out); if(hyam_out) hyam_out=(double *)nco_free(hyam_out); if(hybi_out) hybi_out=(double *)nco_free(hybi_out); if(hybm_out) hybm_out=(double *)nco_free(hybm_out); if(ilev_out) ilev_out=(double *)nco_free(ilev_out); if(lev_in) lev_in=(double *)nco_free(lev_in); if(lev_out) lev_out=(double *)nco_free(lev_out); if(ps_out) ps_out=(double *)nco_free(ps_out); if(prs_mdp_out) prs_mdp_out=(double *)nco_free(prs_mdp_out); if(prs_ntf_out) prs_ntf_out=(double *)nco_free(prs_ntf_out); return rcd; } /* !nco_ntp_vrt() */ int /* O [enm] Return code */ nco_rgr_wgt /* [fnc] Regrid with external weights */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Regrid fields using external weights contained in a mapfile Examine ESMF, SCRIP, Tempest map-files: ncks --cdl -M -m ${DATA}/scrip/rmp_T42_to_POP43_conserv.nc | m ncks --cdl -M -m ${DATA}/maps/map_t42_to_fv129x256_aave.20150621.nc | m ncks --cdl -M -m ${DATA}/maps/map_ne30np4_to_ne120np4_tps.20150618.nc | m Test ESMF, SCRIP, Tempest map-files: ncks -D 5 -O --map=${DATA}/scrip/rmp_T42_to_POP43_conserv.nc ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc ncks -D 5 -O --map=${DATA}/maps/map_t42_to_fv129x256_aave.20150621.nc ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc ncks -D 5 -O --map=${DATA}/maps/map_ne30np4_to_ne120np4_tps.20150618.nc ${DATA}/ne30/rgr/ne30_1D.nc ~/foo.nc Mapfile formats ESMF, GRIDSPEC, SCRIP, and UGRID described here: http://www.earthsystemmodeling.org/esmf_releases/public/ESMF_6_3_0rp1/ESMF_refdoc/node3.html#sec:fileformat:scrip Conventions: grid_size: Number of gridcells (product of lat*lon) address: Source and destination index for each link pair num_links: Number of unique address pairs in remapping, i.e., size of sparse matrix num_wgts: Number of weights per vertice for given remapping (we only handle num_wgts == 1 below) = 1 Bilinear Destination grid value determined by weights times known source grid values at vertices of source quadrilateral that bounds destination point P One weight per vertice guarantees fxm but is not conservative Bilinear requires logically rectangular grid = 1 Distance-based: Distance-weighted uses values at num_neighbors points The weight is inversely proportional to the angular distance from the destination point to each neighbor on the source grid = 3 Second-order conservative: Described in Jones, P. W. (1999), Monthly Weather Review, 127, 2204-2210 First-order conservative schemes assume fluxes are constant within gridcell Destination fluxes are simple summations of sources fluxes weighted by overlap areas Old clm and bds remappers use a first-order algorithm Second-order improves this by using a first-order Taylor expansion of flux Source flux is centroid value plus directional offset determined by dot product of directional gradient and vector pointing from vertice to centroid. Three weights per vertice are centroid weight, weight times local theta-gradient from centroid to vertice, and weight times local phi-gradient from centroid to vertice. = 4 Bicubic: The four weights are gradients in each direction plus a cross-gradient term Same principle as bilinear, but more weights per vertice Bicubic requires logically rectangular grid wgt: Maximum number of source cells contributing to destination cell is not a dimension in SCRIP remapping files because SCRIP stores everying in 1-D sparse matrix arrays Definition of sparse matrix formulations and normalization terminology, SCRIP manual p. 8, 13, 16: for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ // Remap source function f = 1 in all unmasked source gridcells, zero elsewhere, to function F on destination grid // Normalization: fractional area (fracarea) (F = 1 where destination overlaps umasked source grid) dst[ddr_dst[lnk_idx]]+=src[ddr_src[lnk_idx]]*remap_matrix[lnk_idx,0]; // Normalization: destination area (destarea) (weights in each destination cell sum to its area frcation) dst[ddr_dst[lnk_idx]]+=src[ddr_src[lnk_idx]]*remap_matrix[lnk_idx,0]/dst_area[ddr_dst[lnk_idx]]; // Normalization: none (F = angular area that participates in remapping) dst[ddr_dst[lnk_idx]]+=src[ddr_src[lnk_idx]]*remap_matrix[lnk_idx,0]/(dst_area[ddr_dst[lnk_idx]]*dst_frc[ddr_dst[lnk_idx]); } // end loop over lnk Documentation: NCL special cases described in popRemap.ncl, e.g., at https://github.com/yyr/ncl/blob/master/ni/src/examples/gsun/popRemap.ncl ESMF Regridding Status: https://www.earthsystemcog.org/projects/esmf Sample regrid T42->POP43, SCRIP: ncks -O --map=${DATA}/scrip/rmp_T42_to_POP43_conserv.nc ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc */ const char fnc_nm[]="nco_rgr_wgt()"; /* [sng] Function name */ char *fl_in; char *fl_pth_lcl=NULL; const double rdn2dgr=180.0/M_PI; const double dgr2rdn=M_PI/180.0; const double eps_rlt=1.0e-14; /* [frc] Round-off error tolerance */ double lat_wgt_ttl=0.0; /* [frc] Actual sum of quadrature weights */ double area_out_ttl=0.0; /* [frc] Exact sum of area */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int in_id; /* I [id] Input netCDF file ID */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int dmn_idx; /* [idx] Dimension index */ int dst_grid_corners_id; /* [id] Destination grid corners dimension ID */ int dst_grid_rank_id; /* [id] Destination grid rank dimension ID */ int dst_grid_size_id; /* [id] Destination grid size dimension ID */ int num_links_id; /* [id] Number of links dimension ID */ int num_wgts_id=NC_MIN_INT; /* [id] Number of weights dimension ID */ int src_grid_corners_id; /* [id] Source grid corners dimension ID */ int src_grid_rank_id; /* [id] Source grid rank dimension ID */ int src_grid_size_id; /* [id] Source grid size dimension ID */ long int lat_idx; long int lon_idx; short int bnd_idx; nco_bool FL_RTR_RMT_LCN; nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool flg_dgn_area_out=False; /* [flg] Diagnose area_out from grid boundaries */ nco_bool flg_bnd_1D_usable=False; /* [flg] Usable 1D cell vertices exist */ nco_bool flg_stg=rgr->flg_stg; /* [flg] Write staggered grid with FV output */ nco_grd_2D_typ_enm nco_grd_2D_typ=nco_grd_2D_nil; /* [enm] Two-dimensional grid-type enum */ nco_grd_lat_typ_enm nco_grd_lat_typ=nco_grd_lat_nil; /* [enm] Latitude grid-type enum */ nco_grd_lon_typ_enm nco_grd_lon_typ=nco_grd_lon_nil; /* [enm] Longitude grid-type enum */ nco_mpf_sct mpf; size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stderr,"%s: INFO %s obtaining mapping weights from %s\n",nco_prg_nm_get(),fnc_nm,rgr->fl_map); /* Duplicate (because nco_fl_mk_lcl() free()'s fl_in) */ fl_in=(char *)strdup(rgr->fl_map); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,&in_id); /* Identify mapping file type using string generated by weight-generator: ESMF: title = "ESMF Offline Regridding Weight Generator" ESMF_weight_only: title = "ESMF Regrid Weight Generator" NCO: Title = "netCDF Operators (NCO) Offline Regridding Weight Generator" SCRIP: conventions = "SCRIP" Tempest: Title = "TempestRemap Offline Regridding Weight Generator" */ char *att_val; char *att_cnv_val=NULL; char *att_gnr_val=NULL; char *att_ttl_val=NULL; char *cnv_sng=NULL; /* netCDF standard is uppercase Conventions, though some models user lowercase */ char att_sng_Cnv[]="Conventions"; /* [sng] Unidata standard string (uppercase) */ char att_sng_cnv[]="conventions"; /* [sng] Unidata non-standard string (lowercase) */ char att_sng_gnr[]="weight_generator"; /* [sng] CMIP6 standard string */ char att_sng_Ttl[]="Title"; /* [sng] NCO and Tempest use "Title" attribute, and Tempest does not use "Conventions" */ char att_sng_ttl[]="title"; /* [sng] ERWG 7.1 weight_only uses "title" not "Conventions" attribute */ char name0_sng[]="name0"; /* [sng] Attribute where Tempest stores least-rapidly-varying dimension name */ nco_rgr_mpf_typ_enm nco_rgr_mpf_typ=nco_rgr_mpf_nil; /* [enm] Type of remapping file */ nco_rgr_typ_enm nco_rgr_typ=nco_rgr_grd_nil; /* [enm] Type of grid conversion */ /* Look for map-type signature in [cC]onventions or [tT]itle attribute */ att_cnv_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_cnv); if(!att_cnv_val) att_cnv_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_Cnv); att_gnr_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_gnr); att_ttl_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_ttl); if(!att_ttl_val) att_ttl_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_Ttl); /* Either "[cC]onventions" or "[tT]itle" attribute determines map-file type... */ if(att_cnv_val && strstr(att_cnv_val,"SCRIP")) nco_rgr_mpf_typ=nco_rgr_mpf_SCRIP; if(nco_rgr_mpf_typ == nco_rgr_mpf_nil && att_ttl_val){ if(strstr(att_ttl_val,"ESMF Offline Regridding Weight Generator")) nco_rgr_mpf_typ=nco_rgr_mpf_ESMF; else if(strstr(att_ttl_val,"netCDF Operators")) nco_rgr_mpf_typ=nco_rgr_mpf_NCO; else if(strstr(att_ttl_val,"Tempest")) nco_rgr_mpf_typ=nco_rgr_mpf_Tempest; else if(strstr(att_ttl_val,"ESMF Regrid Weight Generator")) nco_rgr_mpf_typ=nco_rgr_mpf_ESMF_weight_only; } /* !att_ttl_val */ if(nco_rgr_mpf_typ == nco_rgr_mpf_nil && att_cnv_val){ if(strstr(att_cnv_val,"NCO")) nco_rgr_mpf_typ=nco_rgr_mpf_NCO; } /* !att_gnr_val */ if(nco_rgr_mpf_typ == nco_rgr_mpf_nil && att_gnr_val){ if(strstr(att_gnr_val,"NCO")) nco_rgr_mpf_typ=nco_rgr_mpf_NCO; } /* !att_gnr_val */ if(nco_rgr_mpf_typ == nco_rgr_mpf_nil){ (void)fprintf(stderr,"%s: WARNING %s unable to discern map-file type from global attributes \"[cC]onventions\" = \"%s\" and/or \"[tT]itle\" = \"%s\" and/or \"weight_generator\" = \"%s\"\n",nco_prg_nm_get(),fnc_nm,att_cnv_val ? att_cnv_val : "",att_ttl_val ? att_ttl_val : "",att_gnr_val ? att_gnr_val : ""); nco_rgr_mpf_typ=nco_rgr_mpf_unknown; } /* !nco_rgr_mpf_typ */ if(att_cnv_val) att_cnv_val=(char *)nco_free(att_cnv_val); if(att_gnr_val) att_gnr_val=(char *)nco_free(att_gnr_val); if(att_ttl_val) att_ttl_val=(char *)nco_free(att_ttl_val); switch(nco_rgr_mpf_typ){ case nco_rgr_mpf_SCRIP: rcd+=nco_inq_dimid(in_id,"src_grid_size",&src_grid_size_id); rcd+=nco_inq_dimid(in_id,"dst_grid_size",&dst_grid_size_id); rcd+=nco_inq_dimid(in_id,"src_grid_corners",&src_grid_corners_id); rcd+=nco_inq_dimid(in_id,"dst_grid_corners",&dst_grid_corners_id); rcd+=nco_inq_dimid(in_id,"src_grid_rank",&src_grid_rank_id); rcd+=nco_inq_dimid(in_id,"dst_grid_rank",&dst_grid_rank_id); rcd+=nco_inq_dimid(in_id,"num_links",&num_links_id); rcd+=nco_inq_dimid(in_id,"num_wgts",&num_wgts_id); break; case nco_rgr_mpf_ESMF_weight_only: rcd+=nco_inq_dimid(in_id,"n_s",&num_links_id); break; case nco_rgr_mpf_ESMF: case nco_rgr_mpf_NCO: case nco_rgr_mpf_Tempest: case nco_rgr_mpf_unknown: rcd+=nco_inq_dimid(in_id,"n_a",&src_grid_size_id); rcd+=nco_inq_dimid(in_id,"n_b",&dst_grid_size_id); rcd+=nco_inq_dimid(in_id,"nv_a",&src_grid_corners_id); rcd+=nco_inq_dimid(in_id,"nv_b",&dst_grid_corners_id); rcd+=nco_inq_dimid(in_id,"src_grid_rank",&src_grid_rank_id); rcd+=nco_inq_dimid(in_id,"dst_grid_rank",&dst_grid_rank_id); if(nco_rgr_mpf_typ != nco_rgr_mpf_Tempest){ rcd+=nco_inq_dimid_flg(in_id,"num_wgts",&num_wgts_id); if(rcd != NC_NOERR){ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s reports map-file does not contain \"num_wgts\" dimension. ERWG always produces this as an orphan dimension, so post-processing could have removed it without harming other map-file fields. No harm, no foul.\n",nco_prg_nm_get(),fnc_nm); rcd=NC_NOERR; } /* !rcd */ } /* !nco_rgr_mpf_Tempest */ rcd+=nco_inq_dimid(in_id,"n_s",&num_links_id); break; default: (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unknown map-file type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_generic_err(); /* NB: This return never executes because nco_dfl_case_generic_err() calls exit() Return placed here to suppress clang -Wsometimes-uninitialized warnings This is done many other times throughout the code, though explained only once, here */ return NCO_ERR; break; } /* end switch */ /* Use dimension IDs to get dimension sizes */ rcd+=nco_inq_dimlen(in_id,num_links_id,&mpf.num_links); if(nco_rgr_mpf_typ != nco_rgr_mpf_ESMF_weight_only){ rcd+=nco_inq_dimlen(in_id,src_grid_size_id,&mpf.src_grid_size); rcd+=nco_inq_dimlen(in_id,dst_grid_size_id,&mpf.dst_grid_size); rcd+=nco_inq_dimlen(in_id,src_grid_corners_id,&mpf.src_grid_corners); rcd+=nco_inq_dimlen(in_id,dst_grid_corners_id,&mpf.dst_grid_corners); rcd+=nco_inq_dimlen(in_id,src_grid_rank_id,&mpf.src_grid_rank); rcd+=nco_inq_dimlen(in_id,dst_grid_rank_id,&mpf.dst_grid_rank); /* TempestRemap does not generate num_wgts */ if(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || num_wgts_id == NC_MIN_INT){ mpf.num_wgts=int_CEWI; }else{ rcd+=nco_inq_dimlen(in_id,num_wgts_id,&mpf.num_wgts); } /* !num_wgts_id */ assert(mpf.src_grid_size < INT_MAX && mpf.dst_grid_size < INT_MAX); }else{ mpf.src_grid_size=long_CEWI; mpf.dst_grid_size=long_CEWI; mpf.src_grid_corners=long_CEWI; mpf.dst_grid_corners=long_CEWI; mpf.src_grid_rank=long_CEWI; mpf.dst_grid_rank=long_CEWI; mpf.num_wgts=int_CEWI; } /* !ESMF_weight_only */ cnv_sng=strdup("normalization"); nco_rgr_nrm_typ_enm nco_rgr_nrm_typ=nco_rgr_nrm_nil; att_val=nco_char_att_get(in_id,NC_GLOBAL,cnv_sng); if(att_val){ if(strstr(att_val,"fracarea")) nco_rgr_nrm_typ=nco_rgr_nrm_fracarea; /* 20190912: map_gx1v6T_to_1x1_bilin.nc and map_0.1T_tripole_to_0.1x0.1_bilin.nc store "fracarea" in normalization attribute. I think NCAR created both maps for POP, probably by running ERWG with option --norm_type=fracarea. Hence "fracarea" seems to be the NCAR-way of guaranteeing that ESMF re-normalization is not performed by default. */ if(strstr(att_val,"destarea")) nco_rgr_nrm_typ=nco_rgr_nrm_destarea; /* ESMF conserve "aave" and bilinear "bilin" generate "destarea" by default */ if(strstr(att_val,"none")) nco_rgr_nrm_typ=nco_rgr_nrm_none; if(att_val) att_val=(char *)nco_free(att_val); }else{ /* 20150712: Tempest does not store a normalization attribute 20170620: ESMF weight_only does not store a normalization attribute 20190312: NCO does not yet store a normalization attribute */ if(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || nco_rgr_mpf_typ == nco_rgr_mpf_NCO || nco_rgr_mpf_typ == nco_rgr_mpf_unknown || nco_rgr_mpf_typ == nco_rgr_mpf_ESMF_weight_only) nco_rgr_nrm_typ=nco_rgr_nrm_unknown; } /* endif normalization */ assert(nco_rgr_nrm_typ != nco_rgr_nrm_nil); if(cnv_sng) cnv_sng=(char *)nco_free(cnv_sng); cnv_sng=strdup("map_method"); nco_rgr_mth_typ_enm nco_rgr_mth_typ=nco_rgr_mth_nil; att_val=nco_char_att_get(in_id,NC_GLOBAL,cnv_sng); if(att_val){ if(strcasestr(att_val,"Conservative")) nco_rgr_mth_typ=nco_rgr_mth_conservative; if(strcasestr(att_val,"Bilinear")) nco_rgr_mth_typ=nco_rgr_mth_bilinear; if(strcasestr(att_val,"none")) nco_rgr_mth_typ=nco_rgr_mth_none; if(att_val) att_val=(char *)nco_free(att_val); }else{ /* Tempest does not store a map_method attribute */ if(nco_rgr_mpf_typ == nco_rgr_mpf_NCO || nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || nco_rgr_mpf_typ == nco_rgr_mpf_unknown) nco_rgr_mth_typ=nco_rgr_mth_unknown; } /* endif */ if(nco_rgr_mth_typ == nco_rgr_mth_nil) (void)fprintf(stdout,"%s: WARNING %s reports map global attribute %s = %s does not match SCRIP/ESMF conventions that support only values of \"Conservative\" and \"Bilinear\" for this attribute. Proceeding anyway...\n",nco_prg_nm_get(),fnc_nm,cnv_sng,att_val); if(cnv_sng) cnv_sng=(char *)nco_free(cnv_sng); if(nco_dbg_lvl_get() >= nco_dbg_scl){ (void)fprintf(stderr,"%s: INFO %s regridding input metadata and grid sizes: ",nco_prg_nm_get(),fnc_nm); (void)fprintf(stderr,"mapfile_generator = %s, map_method = %s, normalization = %s, src_grid_size = n_a = %li, dst_grid_size = n_b = %li, src_grid_corners = nv_a = %li, dst_grid_corners = nv_b = %li, src_grid_rank = %li, dst_grid_rank = %li, num_links = n_s = %li, num_wgts = %li\n",nco_rgr_mpf_sng(nco_rgr_mpf_typ),nco_rgr_mth_sng(nco_rgr_mth_typ),nco_rgr_nrm_sng(nco_rgr_nrm_typ),mpf.src_grid_size,mpf.dst_grid_size,mpf.src_grid_corners,mpf.dst_grid_corners,mpf.src_grid_rank,mpf.dst_grid_rank,mpf.num_links,mpf.num_wgts); } /* endif dbg */ /* 20190726: Allow normalization type to be "none" for bilinear regridding which UKMO SCRIP files set to "none"*/ if(nco_rgr_mth_typ == nco_rgr_mth_conservative && nco_rgr_nrm_typ == nco_rgr_nrm_none){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports requested normalization type = %s is not yet supported. Specifically, masks specified by a mask variable (dst_grid_imask,mask_b) are ignored. More specifically, any destination mask information is assumed to be built into the weight array so that no source points will contribute to masked locations. Talk to Charlie if you want this changed.\n",nco_prg_nm_get(),fnc_nm,nco_rgr_nrm_sng(nco_rgr_nrm_typ)); nco_exit(EXIT_FAILURE); } /* !msk */ /* Got to here in bullet-proofing code for weight-only map-files */ if(nco_rgr_mpf_typ == nco_rgr_mpf_ESMF_weight_only) (void)fprintf(stderr,"%s: WARNING %s reached end of ESMF_weight_only section\n",nco_prg_nm_get(),fnc_nm); assert(nco_rgr_mpf_typ != nco_rgr_mpf_ESMF_weight_only); /* Set type of grid conversion */ if(mpf.src_grid_rank == 1 && mpf.dst_grid_rank == 1) nco_rgr_typ=nco_rgr_grd_1D_to_1D; if(mpf.src_grid_rank == 1 && mpf.dst_grid_rank == 2) nco_rgr_typ=nco_rgr_grd_1D_to_2D; if(mpf.src_grid_rank == 2 && mpf.dst_grid_rank == 1) nco_rgr_typ=nco_rgr_grd_2D_to_1D; if(mpf.src_grid_rank == 2 && mpf.dst_grid_rank == 2) nco_rgr_typ=nco_rgr_grd_2D_to_2D; assert(nco_rgr_typ != nco_rgr_grd_nil); /* Save typing later */ nco_bool flg_grd_in_1D=False; nco_bool flg_grd_in_2D=False; nco_bool flg_grd_out_1D=False; nco_bool flg_grd_out_2D=False; if(nco_rgr_typ == nco_rgr_grd_1D_to_1D || nco_rgr_typ == nco_rgr_grd_1D_to_2D) flg_grd_in_1D=True; if(nco_rgr_typ == nco_rgr_grd_2D_to_1D || nco_rgr_typ == nco_rgr_grd_2D_to_2D) flg_grd_in_2D=True; if(nco_rgr_typ == nco_rgr_grd_1D_to_1D || nco_rgr_typ == nco_rgr_grd_2D_to_1D) flg_grd_out_1D=True; if(nco_rgr_typ == nco_rgr_grd_1D_to_2D || nco_rgr_typ == nco_rgr_grd_2D_to_2D) flg_grd_out_2D=True; int dmn_nbr_hrz_crd; /* [nbr] Number of horizontal dimensions in output grid */ if(flg_grd_out_2D) dmn_nbr_hrz_crd=2; else dmn_nbr_hrz_crd=1; /* Obtain grid values necessary to compute output latitude and longitude coordinates */ int area_dst_id; /* [id] Area variable ID */ int col_src_adr_id; /* [id] Source address (col) variable ID */ int dmn_sz_in_int_id; /* [id] Source grid dimension sizes ID */ int dmn_sz_out_int_id; /* [id] Destination grid dimension sizes ID */ int dst_grd_crn_lat_id; /* [id] Destination grid corner latitudes variable ID */ int dst_grd_crn_lon_id; /* [id] Destination grid corner longitudes variable ID */ int dst_grd_ctr_lat_id; /* [id] Destination grid center latitudes variable ID */ int dst_grd_ctr_lon_id; /* [id] Destination grid center longitudes variable ID */ int frc_dst_id; /* [id] Fraction variable ID */ int msk_dst_id=NC_MIN_INT; /* [id] Mask variable ID */ int row_dst_adr_id; /* [id] Destination address (row) variable ID */ int wgt_raw_id; /* [id] Remap matrix variable ID */ switch(nco_rgr_mpf_typ){ /* Obtain fields whose name depends on mapfile type */ case nco_rgr_mpf_SCRIP: rcd+=nco_inq_varid(in_id,"dst_grid_area",&area_dst_id); /* ESMF: area_b */ rcd+=nco_inq_varid(in_id,"dst_grid_center_lon",&dst_grd_ctr_lon_id); /* ESMF: xc_b */ rcd+=nco_inq_varid(in_id,"dst_grid_center_lat",&dst_grd_ctr_lat_id); /* ESMF: yc_b */ rcd+=nco_inq_varid(in_id,"dst_grid_corner_lon",&dst_grd_crn_lon_id); /* ESMF: xv_b */ rcd+=nco_inq_varid(in_id,"dst_grid_corner_lat",&dst_grd_crn_lat_id); /* ESMF: yv_b */ rcd+=nco_inq_varid(in_id,"dst_grid_frac",&frc_dst_id); /* ESMF: frac_b */ rcd+=nco_inq_varid(in_id,"dst_address",&row_dst_adr_id); /* ESMF: row */ rcd+=nco_inq_varid(in_id,"src_address",&col_src_adr_id); /* ESMF: col */ rcd+=nco_inq_varid(in_id,"remap_matrix",&wgt_raw_id); /* NB: remap_matrix[num_links,num_wgts] != S[n_s] */ break; case nco_rgr_mpf_ESMF: case nco_rgr_mpf_ESMF_weight_only: case nco_rgr_mpf_NCO: case nco_rgr_mpf_Tempest: case nco_rgr_mpf_unknown: if(nco_rgr_mpf_typ != nco_rgr_mpf_ESMF_weight_only){ rcd+=nco_inq_varid(in_id,"area_b",&area_dst_id); /* SCRIP: dst_grid_area */ rcd+=nco_inq_varid(in_id,"xc_b",&dst_grd_ctr_lon_id); /* SCRIP: dst_grid_center_lon */ rcd+=nco_inq_varid(in_id,"yc_b",&dst_grd_ctr_lat_id); /* SCRIP: dst_grid_center_lat */ rcd+=nco_inq_varid(in_id,"xv_b",&dst_grd_crn_lon_id); /* SCRIP: dst_grid_corner_lon */ rcd+=nco_inq_varid(in_id,"yv_b",&dst_grd_crn_lat_id); /* SCRIP: dst_grid_corner_lat */ rcd+=nco_inq_varid(in_id,"frac_b",&frc_dst_id); /* SCRIP: dst_grid_frac */ } /* !nco_rgr_mpf_ESMF_weight_only */ rcd+=nco_inq_varid(in_id,"row",&row_dst_adr_id); /* SCRIP: dst_address */ rcd+=nco_inq_varid(in_id,"col",&col_src_adr_id); /* SCRIP: src_address */ rcd+=nco_inq_varid(in_id,"S",&wgt_raw_id); /* NB: remap_matrix[num_links,num_wgts] != S[n_s] */ break; default: (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unknown map file type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_generic_err(); /* NB: This return never executes because nco_dfl_case_generic_err() calls exit() Return placed here to suppress clang -Wsometimes-uninitialized warnings This is done many other times throughout the code, though explained only once, here */ return NCO_ERR; break; } /* end switch */ /* Obtain fields whose presence depends on mapfile type */ nco_bool flg_msk_out=rgr->flg_msk_out; /* [flg] Add mask to output */ msk_dst_id=NC_MIN_INT; if(flg_msk_out){ switch(nco_rgr_mpf_typ){ case nco_rgr_mpf_ESMF: case nco_rgr_mpf_NCO: rcd+=nco_inq_varid(in_id,"mask_b",&msk_dst_id); /* SCRIP: dst_grid_imask */ break; case nco_rgr_mpf_SCRIP: rcd+=nco_inq_varid(in_id,"dst_grid_imask",&msk_dst_id); /* ESMF: mask_b */ break; case nco_rgr_mpf_Tempest: case nco_rgr_mpf_unknown: /* 20190315: TempestRemap did not propagate mask_b (or mask_a) until ~201902 */ rcd+=nco_inq_varid_flg(in_id,"mask_b",&msk_dst_id); if(rcd == NC_ENOTVAR){ (void)fprintf(stderr,"%s: INFO %s reports map-file lacks mask_b. %sContinuing anyway without masks...\n",nco_prg_nm_get(),fnc_nm,(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest) ? "Probably this TempestRemap map-file was created before ~201902 when TR began to propagate mask_a/b variables." : ""); } /* !rcd */ rcd=NC_NOERR; break; default: (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unknown map-file type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_generic_err(); } /* !nco_rgr_mpf_typ */ if(msk_dst_id == NC_MIN_INT) flg_msk_out=False; } /* !flg_msk_out */ /* Obtain fields whose names are independent of mapfile type */ rcd+=nco_inq_varid(in_id,"src_grid_dims",&dmn_sz_in_int_id); rcd+=nco_inq_varid(in_id,"dst_grid_dims",&dmn_sz_out_int_id); int lon_psn_src; /* [idx] Ordinal position of longitude in rectangular source grid dimension-size array */ int lat_psn_src; /* [idx] Ordinal position of latitude in rectangular source grid dimension-size array */ int lon_psn_dst=int_CEWI; /* [idx] Ordinal position of longitude in rectangular destination grid dimension-size array */ int lat_psn_dst=int_CEWI; /* [idx] Ordinal position of latitude in rectangular destination grid dimension-size array */ if(flg_grd_in_2D){ lon_psn_src=0; /* SCRIP introduced [lon,lat] convention because more natural for Fortran */ lat_psn_src=1; if(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest){ /* Until 20150814, Tempest stored [src/dst]_grid_dims as [lat,lon] unlike SCRIP's [lon,lat] order Newer behavior follows SCRIP [lon,lat] order Challenge: Support both older and newer Tempest mapfiles Tempest (unlike SCRIP and ESMF) annotates mapfile [src/dst]_grid_dims with attributes that identify axis to which each element of [src/dst]_grid_dims refers Solution: Use Tempest mapfile [src/dst]_grid_dims attributes "name0" and/or "name1" to determine if axes' positions follow old order */ att_val=nco_char_att_get(in_id,dmn_sz_in_int_id,name0_sng); if(att_val){ if(strstr(att_val,"lat")){ lon_psn_src=1; lat_psn_src=0; } /* !lat */ if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ } /* !Tempest */ } /* !flg_grd_in_2D */ if(flg_grd_out_2D){ lon_psn_dst=0; lat_psn_dst=1; if(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest){ att_val=nco_char_att_get(in_id,dmn_sz_in_int_id,name0_sng); if(att_val){ if(strstr(att_val,"lat")){ lon_psn_dst=1; lat_psn_dst=0; } /* !lat */ if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ } /* !Tempest */ } /* !flg_grd_out_2D */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ const int dmn_nbr_3D=3; /* [nbr] Rank of 3-D grid variables */ const int dmn_nbr_grd_max=dmn_nbr_3D; /* [nbr] Maximum rank of grid variables */ double *area_out; /* [sr] Area of destination grid */ double *frc_out=NULL; /* [frc] Fraction of destination grid */ double *lat_bnd_out=NULL_CEWI; /* [dgr] Latitude boundaries of rectangular destination grid */ double *lat_crn_out=NULL; /* [dgr] Latitude corners of rectangular destination grid */ double *lat_ctr_out=NULL_CEWI; /* [dgr] Latitude centers of rectangular destination grid */ double *lat_ntf_out=NULL; /* [dgr] Latitude interfaces of rectangular destination grid */ double *lat_wgt_out=NULL; /* [dgr] Latitude weights of rectangular destination grid */ double *lon_bnd_out=NULL_CEWI; /* [dgr] Longitude boundaries of rectangular destination grid */ double *lon_crn_out=NULL; /* [dgr] Longitude corners of rectangular destination grid */ double *lon_ctr_out=NULL_CEWI; /* [dgr] Longitude centers of rectangular destination grid */ double *lon_ntf_out=NULL; /* [dgr] Longitude interfaces of rectangular destination grid */ double *slat_ctr_out=NULL_CEWI; /* [dgr] Latitude centers of staggered FV destination grid */ double *slat_wgt_out=NULL_CEWI; /* [frc] Latitude weights of staggered FV destination grid */ double *slon_ctr_out=NULL_CEWI; /* [dgr] Longitude centers of staggered FV destination grid */ double *wgt_raw; /* [frc] Remapping weights */ int *col_src_adr; /* [idx] Source address (col) */ int *row_dst_adr; /* [idx] Destination address (row) */ int *msk_out=NULL; /* [flg] Mask on destination grid */ int *dmn_sz_in_int; /* [nbr] Array of dimension sizes of source grid */ int *dmn_sz_out_int; /* [nbr] Array of dimension sizes of destination grid */ long *dmn_cnt_in=NULL; long *dmn_cnt_out=NULL; long *dmn_cnt=NULL; long *dmn_srt=NULL; long *dmn_srd=NULL; long idx; /* [idx] Counting index for unrolled grids */ /* Allocate space to hold dimension metadata for destination grid */ dmn_srt=(long *)nco_malloc(dmn_nbr_grd_max*sizeof(long)); dmn_cnt=(long *)nco_malloc(dmn_nbr_grd_max*sizeof(long)); dmn_srd=(long *)nco_malloc(dmn_nbr_grd_max*sizeof(long)); dmn_srt[0]=0L; dmn_cnt[0]=mpf.src_grid_rank; dmn_sz_in_int=(int *)nco_malloc(mpf.src_grid_rank*nco_typ_lng((nc_type)NC_INT)); rcd=nco_get_vara(in_id,dmn_sz_in_int_id,dmn_srt,dmn_cnt,dmn_sz_in_int,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=mpf.dst_grid_rank; dmn_sz_out_int=(int *)nco_malloc(mpf.dst_grid_rank*nco_typ_lng((nc_type)NC_INT)); rcd=nco_get_vara(in_id,dmn_sz_out_int_id,dmn_srt,dmn_cnt,dmn_sz_out_int,(nc_type)NC_INT); /* Check-for and workaround faulty Tempest and MPAS-O/I grid sizes */ if(flg_grd_in_1D && (mpf.src_grid_size != dmn_sz_in_int[0])){ (void)fprintf(stdout,"%s: INFO %s reports input grid dimension sizes disagree: mpf.src_grid_size = %ld != %d = dmn_sz_in[0]. Problem may be caused by incorrect src_grid_dims variable. This is a known issue with some TempestRemap mapfiles generated prior to ~20150901, and in some ESMF mapfiles for MPAS-O/I. This problem can be safely ignored if workaround succeeds. Attempting workaround ...\n",nco_prg_nm_get(),fnc_nm,mpf.src_grid_size,dmn_sz_in_int[0]); dmn_sz_in_int[0]=mpf.src_grid_size; } /* !bug */ if(flg_grd_out_1D && (mpf.dst_grid_size != dmn_sz_out_int[0])){ (void)fprintf(stdout,"%s: INFO %s reports output grid dimension sizes disagree: mpf.dst_grid_size = %ld != %d = dmn_sz_out[0]. Problem may be caused by incorrect dst_grid_dims variable. This is a known issue with some TempestRemap mapfiles generated prior to ~20150901, and in some ESMF mapfiles for MPAS-O/I. This problem can be safely ignored if workaround succeeds. Attempting workaround ...\n",nco_prg_nm_get(),fnc_nm,mpf.dst_grid_size,dmn_sz_out_int[0]); dmn_sz_out_int[0]=mpf.dst_grid_size; } /* !bug */ long col_nbr_in; /* [idx] Number of columns in source grid */ long lon_nbr_in; /* [idx] Number of longitudes in rectangular source grid */ long lat_nbr_in; /* [idx] Number of latitudes in rectangular source grid */ const size_t grd_sz_in=mpf.src_grid_size; /* [nbr] Number of elements in single layer of input grid */ const size_t grd_sz_out=mpf.dst_grid_size; /* [nbr] Number of elements in single layer of output grid */ if(flg_grd_in_1D){ col_nbr_in=dmn_sz_in_int[0]; lon_nbr_in=dmn_sz_in_int[0]; lat_nbr_in=dmn_sz_in_int[0]; }else if(flg_grd_in_2D){ col_nbr_in=0; lon_nbr_in=dmn_sz_in_int[lon_psn_src]; lat_nbr_in=dmn_sz_in_int[lat_psn_src]; /* Sanity-check */ assert(lat_nbr_in*lon_nbr_in == (long)grd_sz_in); } /* !src_grid_rank */ const int bnd_tm_nbr_out=2; /* [nbr] Number of boundaries for output time */ int bnd_nbr_out=int_CEWI; /* [nbr] Number of boundaries for output time and rectangular grid coordinates, and number of vertices for output non-rectangular grid coordinates */ long col_nbr_out=long_CEWI; /* [nbr] Number of columns in destination grid */ long lon_nbr_out=long_CEWI; /* [nbr] Number of longitudes in rectangular destination grid */ long lat_nbr_out=long_CEWI; /* [nbr] Number of latitudes in rectangular destination grid */ long slat_nbr_out=long_CEWI; /* [nbr] Number of latitudes in staggered FV grid destination grid */ long slon_nbr_out=long_CEWI; /* [nbr] Number of longitudes in staggered FV grid destination grid */ if(flg_grd_out_1D){ bnd_nbr_out=mpf.dst_grid_corners; col_nbr_out=dmn_sz_out_int[0]; lat_nbr_out=dmn_sz_out_int[0]; lon_nbr_out=dmn_sz_out_int[0]; /* Sanity-check */ assert(col_nbr_out == (long)grd_sz_out); }else if(flg_grd_out_2D){ col_nbr_out=lat_nbr_out*lon_nbr_out; lat_nbr_out=dmn_sz_out_int[lat_psn_dst]; lon_nbr_out=dmn_sz_out_int[lon_psn_dst]; slat_nbr_out=lat_nbr_out-1L; slon_nbr_out=lon_nbr_out; /* Sanity-check */ assert(lat_nbr_out*lon_nbr_out == (long)grd_sz_out); } /* !dst_grid_rank */ /* Ensure coordinates are in degrees not radians for simplicity and CF-compliance NB: ${DATA}/scrip/rmp_T42_to_POP43_conserv.nc has [xy]?_a in degrees and [xy]?_b in radians! */ nco_bool flg_crd_rdn=False; /* [flg] Destination coordinates are in radians not degrees */ char unt_sng[]="units"; /* [sng] netCDF-standard units attribute name */ att_val=nco_char_att_get(in_id,dst_grd_ctr_lat_id,unt_sng); if(att_val){ /* Match "radian" and "radians" */ if(strstr(att_val,"radian")) flg_crd_rdn=True; if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ nco_bool flg_grd_out_crv=False; /* [flg] Curvilinear coordinates */ nco_bool flg_grd_out_rct=False; /* [flg] Rectangular coordinates */ const nc_type crd_typ_out=NC_DOUBLE; if(flg_grd_out_2D){ lon_ctr_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); lat_ctr_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); lon_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*grd_sz_out*nco_typ_lng(crd_typ_out)); lat_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*grd_sz_out*nco_typ_lng(crd_typ_out)); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lon_id,dmn_srt,dmn_cnt,lon_ctr_out,crd_typ_out); rcd=nco_get_vara(in_id,dst_grd_ctr_lat_id,dmn_srt,dmn_cnt,lat_ctr_out,crd_typ_out); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_out; dmn_cnt[1]=mpf.dst_grid_corners; rcd=nco_get_vara(in_id,dst_grd_crn_lon_id,dmn_srt,dmn_cnt,lon_crn_out,crd_typ_out); rcd=nco_get_vara(in_id,dst_grd_crn_lat_id,dmn_srt,dmn_cnt,lat_crn_out,crd_typ_out); /* User may specify curvilinear grid (with --rgr crv). Otherwise, manually test for curvilinear source grid. */ flg_grd_out_crv=rgr->flg_crv; /* [flg] Curvilinear coordinates */ if(flg_grd_out_crv){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Output grid specified to be %s\n",nco_prg_nm_get(),flg_grd_out_crv ? "Curvilinear" : "Rectangular"); }else{ long idx_tst=long_CEWI; /* [idx] Index of first latitude or longitude */ for(idx=0;idx<(long)grd_sz_out;idx++){ if(idx%lon_nbr_out == 0) idx_tst=idx; if(lat_ctr_out[idx] != lat_ctr_out[idx_tst]) break; // (void)fprintf(stdout,"%s: DEBUG lat_ctr_out[%li] = %g, lat_ctr_out[%li] = %g\n",nco_prg_nm_get(),idx,lat_ctr_out[idx],idx_tst,lat_ctr_out[idx_tst]); /* fxm: also test lon */ } /* !rectangular */ if(idx != (long)grd_sz_out) flg_grd_out_crv=True; else flg_grd_out_rct=True; if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO Output grid detected to be %s\n",nco_prg_nm_get(),flg_grd_out_crv ? "Curvilinear" : "Rectangular"); } /* !flg_grd_out_crv */ if(flg_grd_out_crv) bnd_nbr_out=mpf.dst_grid_corners; if(flg_grd_out_rct) bnd_nbr_out=2; /* NB: Assumes rectangular latitude and longitude and is invalid for other quadrilaterals */ } /* !flg_grd_out_2D */ if(nco_dbg_lvl_get() >= nco_dbg_scl){ (void)fprintf(stderr,"%s: INFO %s grid conversion type = %s with expected input and prescribed output grid sizes: ",nco_prg_nm_get(),fnc_nm,nco_rgr_grd_sng(nco_rgr_typ)); (void)fprintf(stderr,"lat_in = %li, lon_in = %li, col_in = %li, lat_out = %li, lon_out = %li, col_out = %li\n",lat_nbr_in,lon_nbr_in,col_nbr_in,lat_nbr_out,lon_nbr_out,col_nbr_out); } /* endif dbg */ /* Allocate space for and obtain coordinates */ if(flg_grd_out_1D){ lon_ctr_out=(double *)nco_malloc(col_nbr_out*nco_typ_lng(crd_typ_out)); lat_ctr_out=(double *)nco_malloc(col_nbr_out*nco_typ_lng(crd_typ_out)); lon_bnd_out=(double *)nco_malloc(col_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); lat_bnd_out=(double *)nco_malloc(col_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); } /* !flg_grd_out_1D */ if(flg_grd_out_rct){ if(lat_ctr_out) lat_ctr_out=(double *)nco_free(lat_ctr_out); if(lon_ctr_out) lon_ctr_out=(double *)nco_free(lon_ctr_out); if(lat_crn_out) lat_crn_out=(double *)nco_free(lat_crn_out); if(lon_crn_out) lon_crn_out=(double *)nco_free(lon_crn_out); lon_ctr_out=(double *)nco_malloc(lon_nbr_out*nco_typ_lng(crd_typ_out)); lat_ctr_out=(double *)nco_malloc(lat_nbr_out*nco_typ_lng(crd_typ_out)); lon_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*lon_nbr_out*nco_typ_lng(crd_typ_out)); lat_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*lat_nbr_out*nco_typ_lng(crd_typ_out)); lat_wgt_out=(double *)nco_malloc(lat_nbr_out*nco_typ_lng(crd_typ_out)); lon_ntf_out=(double *)nco_malloc((lon_nbr_out+1L)*nco_typ_lng(crd_typ_out)); lat_ntf_out=(double *)nco_malloc((lat_nbr_out+1L)*nco_typ_lng(crd_typ_out)); lon_bnd_out=(double *)nco_malloc(lon_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); lat_bnd_out=(double *)nco_malloc(lat_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); } /* !flg_grd_out_rct */ /* Arrays unroll into all longitudes for first latitude, then second latitude, ... Obtain longitudes by reading first block contiguously (unstrided) Obtain latitudes by reading unrolled data with stride of lon_nbr */ if(flg_grd_out_1D){ dmn_srt[0]=0L; dmn_cnt[0]=col_nbr_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lon_id,dmn_srt,dmn_cnt,lon_ctr_out,crd_typ_out); dmn_srt[0]=0L; dmn_cnt[0]=col_nbr_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lat_id,dmn_srt,dmn_cnt,lat_ctr_out,crd_typ_out); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr_out; dmn_cnt[1]=bnd_nbr_out; rcd=nco_get_vara(in_id,dst_grd_crn_lon_id,dmn_srt,dmn_cnt,lon_bnd_out,crd_typ_out); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr_out; dmn_cnt[1]=bnd_nbr_out; rcd=nco_get_vara(in_id,dst_grd_crn_lat_id,dmn_srt,dmn_cnt,lat_bnd_out,crd_typ_out); if(flg_crd_rdn){ for(idx=0;idx<col_nbr_out;idx++){ lon_ctr_out[idx]*=rdn2dgr; lat_ctr_out[idx]*=rdn2dgr; } /* !idx */ for(idx=0;idx<col_nbr_out*bnd_nbr_out;idx++){ lon_bnd_out[idx]*=rdn2dgr; lat_bnd_out[idx]*=rdn2dgr; } /* !idx */ } /* !rdn */ /* Is 1D interface information usable? Yes, unless if all interfaces are zeros NB: fxm Better algorithm for "usable" is that not all interfaces in any cell are equal */ flg_bnd_1D_usable=True; for(idx=0;idx<col_nbr_out*bnd_nbr_out;idx++) if(lon_bnd_out[idx] != 0.0) break; if(idx == col_nbr_out*bnd_nbr_out){ flg_bnd_1D_usable=False; }else{ for(idx=0;idx<col_nbr_out*bnd_nbr_out;idx++) if(lat_bnd_out[idx] != 0.0) break; if(idx == col_nbr_out*bnd_nbr_out) flg_bnd_1D_usable=False; } /* !usable */ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0;idx<lat_nbr_out;idx++){ (void)fprintf(stdout,"lat[%li] = %g, vertices = ",idx,lat_ctr_out[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr_out;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lat_bnd_out[bnd_nbr_out*idx+bnd_idx],bnd_idx == bnd_nbr_out-1 ? "]\n" : ", "); } /* end loop over lat */ for(idx=0;idx<lon_nbr_out;idx++){ (void)fprintf(stdout,"lon[%li] = %g, vertices = ",idx,lon_ctr_out[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr_out;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lon_bnd_out[bnd_nbr_out*idx+bnd_idx],bnd_idx == bnd_nbr_out-1 ? "]\n" : ", "); } /* end loop over lon */ } /* endif dbg */ } /* !flg_grd_out_1D */ if(flg_grd_out_rct){ /* fxm: sub-sample these from the already-read ctr/crn arrays */ dmn_srt[0L]=0L; dmn_cnt[0L]=lon_nbr_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lon_id,dmn_srt,dmn_cnt,lon_ctr_out,crd_typ_out); dmn_srt[0L]=0L; dmn_cnt[0L]=lat_nbr_out; dmn_srd[0L]=lon_nbr_out; rcd=nco_get_vars(in_id,dst_grd_ctr_lat_id,dmn_srt,dmn_cnt,dmn_srd,lat_ctr_out,crd_typ_out); dmn_srt[0L]=dmn_srt[1]=0L; dmn_cnt[0L]=lon_nbr_out; dmn_cnt[1]=mpf.dst_grid_corners; rcd=nco_get_vara(in_id,dst_grd_crn_lon_id,dmn_srt,dmn_cnt,lon_crn_out,crd_typ_out); dmn_srt[0L]=0L; dmn_cnt[0L]=lat_nbr_out; dmn_srd[0L]=lon_nbr_out; dmn_srt[1]=0L; dmn_cnt[1]=mpf.dst_grid_corners; dmn_srd[1]=1L; rcd=nco_get_vars(in_id,dst_grd_crn_lat_id,dmn_srt,dmn_cnt,dmn_srd,lat_crn_out,crd_typ_out); if(flg_crd_rdn){ for(idx=0L;idx<lon_nbr_out;idx++) lon_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<lat_nbr_out;idx++) lat_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<lon_nbr_out*mpf.dst_grid_corners;idx++) lon_crn_out[idx]*=rdn2dgr; for(idx=0L;idx<lat_nbr_out*mpf.dst_grid_corners;idx++) lat_crn_out[idx]*=rdn2dgr; } /* !rdn */ } /* !flg_grd_out_rct */ if(flg_grd_out_crv){ if(flg_crd_rdn){ for(idx=0L;idx<(long)grd_sz_out;idx++) lon_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<(long)grd_sz_out;idx++) lat_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<(long)grd_sz_out*mpf.dst_grid_corners;idx++) lon_crn_out[idx]*=rdn2dgr; for(idx=0L;idx<(long)grd_sz_out*mpf.dst_grid_corners;idx++) lat_crn_out[idx]*=rdn2dgr; } /* !rdn */ } /* !flg_grd_out_crv */ /* Allocate space for and obtain area, fraction, and mask, which are needed for both 1D and 2D grids */ area_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); dmn_srt[0L]=0L; dmn_cnt[0L]=grd_sz_out; rcd=nco_get_vara(in_id,area_dst_id,dmn_srt,dmn_cnt,area_out,crd_typ_out); frc_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); dmn_srt[0L]=0L; dmn_cnt[0L]=grd_sz_out; rcd=nco_get_vara(in_id,frc_dst_id,dmn_srt,dmn_cnt,frc_out,crd_typ_out); if(msk_dst_id != NC_MIN_INT){ msk_out=(int *)nco_malloc(grd_sz_out*nco_typ_lng(NC_INT)); dmn_srt[0L]=0L; dmn_cnt[0L]=grd_sz_out; rcd=nco_get_vara(in_id,msk_dst_id,dmn_srt,dmn_cnt,msk_out,(nc_type)NC_INT); } /* !msk */ /* Derive 2D interface boundaries from lat and lon grid-center values NB: Procedures to derive interfaces from midpoints on rectangular grids are theoretically possible However, ESMF often outputs interfaces values (e.g., yv_b) for midpoint coordinates (e.g., yc_b) For example, ACME standard map from ne120np4 to 181x360 has yc_b[0] = yv_b[0] = -90.0 Latitude = -90 is, by definition, not a midpoint coordinate This appears to be an artifact of the non-physical representation of the FV grid, i.e., a grid center located at the pole where longitudes collapse in the model, but cannot be represented as collapsed on a rectangular 2D grid with non-zero areas. Unfortunately, ESMF supports this nonsense by labeling the grid center as at the pole so that applications can easily diagnose an FV grid when they read-in datasets. A superior application could diagnose FV just fine from actual non-polar gridcell centers Maybe ESMF could introduce a flag or something to indicate/avoid this special case? Safer to read boundary interfaces directly from grid corner/vertice arrays in map file Derivation of boundaries xv_b, yv_b from _correct_ xc_b, yc_b is follows Do not implement this procedure until resolving midpoint/center issue described above: lon_ntf_out[0L]=0.5*(lon_ctr_out[0L]+lon_ctr_out[lon_nbr_out-1L])-180.0; // Extrapolation lat_ntf_out[0L]=lat_ctr_out[0L]-0.5*(lat_ctr_out[1L]-lat_ctr_out[0L]); // Extrapolation for(idx=1L;idx<lon_nbr_out;idx++) lon_ntf_out[idx]=0.5*(lon_ctr_out[idx-1L]+lon_ctr_out[idx]); for(idx=1L;idx<lat_nbr_out;idx++) lat_ntf_out[idx]=0.5*(lat_ctr_out[idx-1L]+lat_ctr_out[idx]); lon_ntf_out[lon_nbr_out]=lon_ntf_out[0L]+360.0; lat_ntf_out[lat_nbr_out]=lat_ctr_out[lat_nbr_out-1L]+0.5*(lat_ctr_out[lat_nbr_out-1L]-lat_ctr_out[lat_nbr_out-2L]); */ if(flg_grd_out_rct){ double lon_spn; /* [dgr] Longitude span */ double lat_spn; /* [dgr] Latitude span */ nco_bool flg_s2n=True; /* I [enm] Latitude grid-direction is South-to-North */ if(lat_ctr_out[1L] < lat_ctr_out[0L]) flg_s2n=False; /* Obtain 1-D rectangular interfaces from unrolled 1-D vertice arrays */ for(idx=0L;idx<lon_nbr_out;idx++) lon_ntf_out[idx]=lon_crn_out[mpf.dst_grid_corners*idx]; /* 20201009 The four possible CCW RLL orderings start with the ul, ll, lr, or ur vertice NCO grid generators store vertices in order (0,1,2,3)=(ul,ll,lr,ur) NCO final latitude is in upper vertices (0,3) for S2N grids, lower vertices (1,2) for N2S grids NCO final longitude is in RHS vertices (2,3) for S2N and N2S grids Need generic algorithm to pick easternmost longitude for any of the four CCW orderings What is ESMF vertice ordering? or does ESMF always copy from input grid? Most grid generators probably start with ul or ll so vertice 2 is good choice for easternmost */ // lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-(mpf.dst_grid_corners-1L)]; // ESMF? lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-2L]; // NCO lr if(lon_ntf_out[lon_nbr_out-1] == lon_ntf_out[lon_nbr_out]) lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-1L]; // NCO ur if(lon_ntf_out[lon_nbr_out-1] == lon_ntf_out[lon_nbr_out]) lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-3L]; // NCO ll assert(lon_ntf_out[lon_nbr_out-1] != lon_ntf_out[lon_nbr_out]); lon_spn=lon_ntf_out[lon_nbr_out]-lon_ntf_out[0L]; for(idx=0L;idx<lat_nbr_out;idx++) lat_ntf_out[idx]=lat_crn_out[mpf.dst_grid_corners*idx]; if(flg_s2n) lat_ntf_out[lat_nbr_out]=max_dbl(lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-1L],lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-2L]); else lat_ntf_out[lat_nbr_out]=min_dbl(lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-1L],lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-2L]); assert(lat_ntf_out[lat_nbr_out] != lat_ntf_out[lat_nbr_out-1]); lat_spn=fabs(lat_ntf_out[lat_nbr_out]-lat_ntf_out[0L]); /* Place 1-D rectangular interfaces into 2-D coordinate boundaries */ for(idx=0L;idx<lon_nbr_out;idx++){ lon_bnd_out[2L*idx]=lon_ntf_out[idx]; lon_bnd_out[2L*idx+1L]=lon_ntf_out[idx+1L]; } /* !lon_nbr_out */ for(idx=0L;idx<lat_nbr_out;idx++){ lat_bnd_out[2L*idx]=lat_ntf_out[idx]; lat_bnd_out[2L*idx+1L]=lat_ntf_out[idx+1L]; } /* !lat_nbr_out */ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0L;idx<lon_nbr_out;idx++) (void)fprintf(stdout,"lon[%li] = [%g, %g, %g]\n",idx,lon_bnd_out[2L*idx],lon_ctr_out[idx],lon_bnd_out[2L*idx+1L]); for(idx=0L;idx<lat_nbr_out;idx++) (void)fprintf(stdout,"lat[%li] = [%g, %g, %g]\n",idx,lat_bnd_out[2L*idx],lat_ctr_out[idx],lat_bnd_out[2L*idx+1L]); } /* endif dbg */ /* Global or regional grid? */ nco_grd_xtn_enm nco_grd_xtn; /* [enm] Extent of grid */ if((float)lon_spn == 360.0f && (float)lat_spn == 180.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; /* Diagnose type of latitude output grid by testing second latitude center against formulae */ double lat_ctr_tst_eqa; double lat_ctr_tst_fv; if(flg_s2n) lat_ctr_tst_eqa=lat_ntf_out[0L]+lat_spn*1.5/lat_nbr_out; else lat_ctr_tst_eqa=lat_ntf_out[0L]-lat_spn*1.5/lat_nbr_out; if(flg_s2n) lat_ctr_tst_fv=lat_ntf_out[0L]+lat_spn/(lat_nbr_out-1L); else lat_ctr_tst_fv=lat_ntf_out[0L]-lat_spn/(lat_nbr_out-1L); double lat_ctr_tst_gss; /* In diagnosing grids, agreement to slightly worse than single-precision is "good enough for government work" Hence some comparisons cast from double to float before comparison 20150526: T42 grid from SCRIP and related maps, and NCL-generated Gaussian grids for CESM, are accurate to at most ~eight digits 20150611: map_ne120np4_to_fv801x1600_bilin.150418.nc has yc_b[1600]=-89.775000006 not expected exact value lat_ctr[1]=-89.775000000000006 20170521: T62 grid from NCEP-NCAR Reanalysis 1 is worse than single precision, has yc_[192]=-86.6531 not expected exact value lat_ctr[1]=-86.6532 */ if((float)lat_ctr_out[1L] == (float)lat_ctr_tst_eqa) nco_grd_lat_typ=nco_grd_lat_eqa; if((float)lat_ctr_out[1L] == (float)lat_ctr_tst_fv) nco_grd_lat_typ=nco_grd_lat_fv; double *wgt_Gss_out=NULL; // [frc] Gaussian weights double precision if(nco_grd_lat_typ == nco_grd_lat_nil){ /* Check for Gaussian grid */ double *lat_sin_out; // [frc] Sine of Gaussian latitudes double precision lat_sin_out=(double *)nco_malloc(lat_nbr_out*sizeof(double)); wgt_Gss_out=(double *)nco_malloc(lat_nbr_out*sizeof(double)); (void)nco_lat_wgt_gss(lat_nbr_out,flg_s2n,lat_sin_out,wgt_Gss_out); lat_ctr_tst_gss=rdn2dgr*asin(lat_sin_out[1L]); /* Gaussian weights on output grid will be double-precision accurate Grid itself is kept as user-specified so area diagnosed by ESMF_RegridWeightGen may be slightly inconsistent with weights */ if(nco_dbg_lvl_get() >= nco_dbg_sbr) (void)fprintf(stderr,"%s: INFO %s reports lat_ctr_out[1] = %g, lat_ctr_tst_gss = %g\n",nco_prg_nm_get(),fnc_nm,lat_ctr_out[1L],lat_ctr_tst_gss); if((float)lat_ctr_out[1L] == (float)lat_ctr_tst_gss) nco_grd_lat_typ=nco_grd_lat_gss; if(lat_sin_out) lat_sin_out=(double *)nco_free(lat_sin_out); } /* !Gaussian */ if(nco_grd_lat_typ == nco_grd_lat_nil){ /* If still of unknown type, this 2D grid may be weird This occurs, e.g., with POP3 destination grid Change gridtype from nil (which means not-yet-set) to unknown (which means none of the others matched) */ nco_grd_lat_typ=nco_grd_lat_unk; } /* !nil */ /* Currently grd_lat_typ and grd_2D_typ are equivalent, though that may be relaxed in future */ if(nco_grd_lat_typ == nco_grd_lat_unk) nco_grd_2D_typ=nco_grd_2D_unk; else if(nco_grd_lat_typ == nco_grd_lat_gss) nco_grd_2D_typ=nco_grd_2D_gss; else if(nco_grd_lat_typ == nco_grd_lat_fv) nco_grd_2D_typ=nco_grd_2D_fv; else if(nco_grd_lat_typ == nco_grd_lat_eqa) nco_grd_2D_typ=nco_grd_2D_eqa; else assert(False); if(nco_grd_lon_typ == nco_grd_lon_nil){ /* NB: Longitude grid diagnosis is susceptible to mistakes when input mapfile embeds common faulty grids, e.g., ACME *150418* FV maps map_ne30np4_to_fv129x256_aave.150418.nc is diagnosed as regional grid of unknown type because of input grid flaws map_ne30np4_to_fv129x256_aave.20150901.nc is (correctly) diagnosed as global grid of with lon_Grn_ctr */ if( (float)lon_ctr_out[0L] == 0.0f && (float)lon_ctr_out[1L] == (float)(lon_ctr_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_Grn_ctr; else if((float)lon_ctr_out[0L] == -180.0f && (float)lon_ctr_out[1L] == (float)(lon_ctr_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_180_ctr; else if((float)lon_ntf_out[0L] == 0.0f && (float)lon_ntf_out[1L] == (float)(lon_ntf_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_Grn_wst; else if((float)lon_ntf_out[0L] == -180.0f && (float)lon_ntf_out[1L] == (float)(lon_ntf_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_180_wst; else if((float)lon_ctr_out[1L] == (float)(lon_ctr_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_bb; else nco_grd_lon_typ=nco_grd_lon_unk; } /* !nco_grd_lon_typ */ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s diagnosed output latitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lat_sng(nco_grd_lat_typ)); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s diagnosed output longitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lon_sng(nco_grd_lon_typ)); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s diagnosed output grid-extent: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_xtn_sng(nco_grd_xtn)); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ slat_ctr_out=(double *)nco_malloc(slat_nbr_out*nco_typ_lng(crd_typ_out)); slat_wgt_out=(double *)nco_malloc(slat_nbr_out*nco_typ_lng(crd_typ_out)); slon_ctr_out=(double *)nco_malloc(slon_nbr_out*nco_typ_lng(crd_typ_out)); for(idx=0L;idx<slat_nbr_out;idx++){ slat_ctr_out[idx]=lat_ntf_out[idx+1L]; slat_wgt_out[idx]=fabs(sin(dgr2rdn*lat_ctr_out[idx+1L])-sin(dgr2rdn*lat_ctr_out[idx])); /* fabs() ensures positive area in n2s grids */ } /* !lat_nbr_out */ for(idx=0L;idx<slon_nbr_out;idx++){ slon_ctr_out[idx]=lon_ntf_out[idx]; } /* !lat_nbr_out */ } /* !nco_grd_lat_fv */ switch(nco_grd_lat_typ){ case nco_grd_lat_eqa: case nco_grd_lat_fv: for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_out[idx]=fabs(sin(dgr2rdn*lat_bnd_out[2*idx+1L])-sin(dgr2rdn*lat_bnd_out[2*idx])); /* fabs() ensures positive area in n2s grids */ break; case nco_grd_lat_gss: for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_out[idx]=wgt_Gss_out[idx]; if(wgt_Gss_out) wgt_Gss_out=(double *)nco_free(wgt_Gss_out); break; case nco_grd_lat_unk: for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_out[idx]=0.0; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: WARNING %s reports unknown output latitude grid-type. Unable to guess what latitude weights should be.\n",nco_prg_nm_get(),fnc_nm); break; default: nco_dfl_case_generic_err(); break; } /* end nco_grd_lat_typ switch */ /* Fuzzy test of latitude weight normalization */ double lat_wgt_ttl_xpc; /* [frc] Expected sum of latitude weights */ lat_wgt_ttl=0.0; for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_ttl+=lat_wgt_out[idx]; lat_wgt_ttl_xpc=fabs(sin(dgr2rdn*lat_bnd_out[2L*(lat_nbr_out-1L)+1L])-sin(dgr2rdn*lat_bnd_out[0L])); /* fabs() ensures positive area in n2s grids */ if(nco_grd_lat_typ != nco_grd_lat_unk){ assert(1.0-lat_wgt_ttl/lat_wgt_ttl_xpc < eps_rlt); if(lat_wgt_ttl_xpc < 0.0) abort(); /* CEWI Use lat_wgt_ttl_xpc at least once outside of assert() to avoid gcc 4.8.2 set-but-not-used warning */ } /* !nco_grd_lat_unk */ } /* !flg_grd_out_rct */ /* When possible, ensure area_out is non-zero 20150722: ESMF documentation says "The grid area array is only output when the conservative remapping option is used" Actually, ESMF does (always?) output area, but area == 0.0 unless conservative remapping is used 20150721: ESMF bilinear interpolation map ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.150418.nc has area == 0.0 20150710: Tempest regionally refined grids like bilinearly interpolated CONUS for ACME RRM has area_out == 0 20150821: ESMF always outputs area_out == 0.0 for bilinear interpolation Check whether NCO must diagnose and provide its own area_out */ /* If area_out contains any zero... */ for(idx=0;idx<(long)grd_sz_out;idx++) if(area_out[idx] == 0.0) break; if(idx != (long)grd_sz_out){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Output grid detected with zero-valued output area(s) at idx = %ld (and likely others, too).\n",nco_prg_nm_get(),idx); } /* !zero */ for(idx=0;idx<(long)grd_sz_out;idx++) if(area_out[idx] != 0.0) break; if(idx == (long)grd_sz_out){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports area_out from mapfile is everywhere zero. This is expected for bilinearly interpolated output maps produced by ESMF_RegridWeightGen. ",nco_prg_nm_get(),fnc_nm); if(flg_grd_out_2D && flg_grd_out_rct && (bnd_nbr_out == 2 || bnd_nbr_out == 4)){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"Since the destination grid provides cell bounds information, NCO will diagnose area (and output it as a variable named \"%s\") from the destination gridcell boundaries. NCO diagnoses quadrilateral area for rectangular output grids from a formula that assumes that cell boundaries follow arcs of constant latitude and longitude. This differs from the area of cells with boundaries that follow great circle arcs (used by, e.g., ESMF_RegridWeightGen and TempestRemap). Be warned that NCO correctly diagnoses area for all convex polygons, yet not for most concave polygons. To determine whether the diagnosed areas are fully consistent with the output grid, one must know such exact details. If your grid has analytic areas that NCO does not yet diagnose correctly from provided cell boundaries, please contact us.\n",rgr->area_nm); flg_dgn_area_out=True; }else if(flg_grd_out_2D && flg_grd_out_crv && (bnd_nbr_out == 2 || bnd_nbr_out == 4)){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"Since the destination grid provides cell bounds information, NCO will diagnose area (and output it as a variable named \"%s\") from the destination gridcell boundaries. NCO diagnoses quadrilateral area for curvilinear output grids from formulae that assume that cell boundaries follow great circle arcs (as do, e.g., ESMF_RegridWeightGen and TempestRemap). This differs from the area of cells with boundaries that follow lines of constant latitude or longitude. Be warned that NCO correctly diagnoses area for all convex polygons, yet not for most concave polygons. To determine whether the diagnosed areas are fully consistent with the output grid, one must know such exact details. If your grid has analytic areas that NCO does not yet diagnose correctly from provided cell boundaries, please contact us.\n",rgr->area_nm); flg_dgn_area_out=True; }else if(flg_grd_out_1D && flg_bnd_1D_usable){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"Since the destination grid provides cell bounds information, NCO will diagnose area (and output it as a variable name \"%s\") from the destination gridcell boundaries. NCO diagnoses spherical polygon area for unstructured output grids from formulae that assume that cell boundaries follow great circle arcs (as do, e.g., ESMFRegridWeightGen and TempestRemap). This differs from the area of cells with boundaries that follow lines of constant latitude or longitude. Be warned that NCO correctly diagnoses area for all convex polygons, yet not for most concave polygons. To determine whether the diagnosed areas are fully consistent with the output grid, one must know such exact details. If your grid has analytic areas that NCO does not yet diagnose correctly from provided cell boundaries, please contact us.\n",rgr->area_nm); flg_dgn_area_out=True; }else{ /* !1D */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"However, NCO cannot find enough boundary information, or it is too stupid about spherical trigonometry, to diagnose area_out. NCO will output an area variable (named \"%s\") copied from the input mapfile. This area will be everywhere zero.\n",rgr->area_nm); } /* !2D */ } /* !area */ if(flg_dgn_area_out){ if(flg_grd_out_1D && flg_bnd_1D_usable){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"INFO: Diagnosing area_out for 1D grid\n"); /* Area of unstructured grids requires spherical trigonometry */ nco_sph_plg_area(rgr,lat_bnd_out,lon_bnd_out,col_nbr_out,bnd_nbr_out,area_out); } /* !1D */ if(flg_grd_out_crv){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"INFO: Diagnosing area_out for curvilinear grid\n"); /* Area of curvilinear grids requires spherical trigonometry */ nco_sph_plg_area(rgr,lat_crn_out,lon_crn_out,grd_sz_out,bnd_nbr_out,area_out); } /* !flg_grd_out_crv */ if(flg_grd_out_rct && nco_grd_2D_typ != nco_grd_2D_unk){ /* Mr. Enenstein and George O. Abell taught me the area of spherical zones Spherical zone area is exact and faithful to underlying rectangular equi-angular grid However, ESMF and Tempest approximate spherical polygons as connected by great circle arcs fxm: Distinguish spherical zone shapes (e.g., equi-angular) from great circle arcs (e.g., unstructured polygons) */ for(lat_idx=0;lat_idx<lat_nbr_out;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr_out;lon_idx++) area_out[lat_idx*lon_nbr_out+lon_idx]=fabs(dgr2rdn*(lon_bnd_out[2*lon_idx+1]-lon_bnd_out[2*lon_idx])*(sin(dgr2rdn*lat_bnd_out[2*lat_idx+1])-sin(dgr2rdn*lat_bnd_out[2*lat_idx]))); /* fabs() ensures positive area in n2s grids */ } /* !spherical zones */ } /* !flg_dgn_area_out */ if(rgr->tst == -1){ /* Passing --rgr tst=-1 causes regridder to fail here This failure should cause host climo script to abort */ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports regridder instructed to fail here. This tests failure mode in climo scripts...\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !tst */ /* Verify frc_out is sometimes non-zero ESMF: "The grid frac arrays (frac_a and frac_b) are calculated by ESMF_RegridWeightGen. For conservative remapping, the grid frac array returns the area fraction of the grid cell which participates in the remapping. For bilinear and patch remapping, the destination grid frac array [frac_b] is one where the grid point participates in the remapping and zero otherwise. For bilinear and patch remapping, the source grid frac array is always set to zero." SCRIP: Similar to ESMF For both ESMF+SCRIP frac_[ab] are computed by the weight-generation algorithm and are not specified as part of the input grids How does an input ocean grid indicate that, say, half the gridcell is land and half ocean? Does it use the area variable to tell the weight generation algorithm that a gridcell is fractional? In other words does it use grid_imask=1 and grid_area=0.5*full_gridcell_area and, e.g., T=273.0? */ for(idx=0;idx<(long)grd_sz_out;idx++) if(frc_out[idx] != 0.0) break; if(idx == (long)grd_sz_out){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports frc_out == frac_b contains all zeros\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !always zero */ /* Test whether frc_out is ever zero... */ for(idx=0;idx<(long)grd_sz_out;idx++) if(frc_out[idx] == 0.0) break; if(nco_dbg_lvl_get() >= nco_dbg_std) if(idx != (long)grd_sz_out) (void)fprintf(stdout,"%s: INFO %s reports frc_out == frac_b contains zero-elements (e.g., at 1D idx=%ld)\n",nco_prg_nm_get(),fnc_nm,idx); /* Normalizing by frc_out is redundant iff frc_out == 1.0, so we can save time without sacrificing accuracy However, frc_out is often (e.g., for CS <-> RLL maps) close but not equal to unity (ESMF_RegridWeightGen issue?) Hence, decide whether to normalize by frc_out by diagnosing the furthest excursion of frc_out from unity */ nco_bool flg_frc_out_one=True; /* [flg] Destination gridcell fraction frc_out == frac_b is in [1-epsilon,frc_out,1+epsilon] */ nco_bool flg_frc_out_wrt=False; /* [flg] Write destination gridcell fraction frc_out == frac_b to regridded files */ double frc_out_dff_one; /* [frc] Deviation of frc_out from 1.0 */ double frc_out_dff_one_max=0.0; /* [frc] Maximum deviation of frc_out from 1.0 */ long idx_max_dvn; /* [idx] Index of maximum deviation from 1.0 */ for(idx=0;idx<(long)grd_sz_out;idx++){ frc_out_dff_one=fabs(frc_out[idx]-1.0); if(frc_out_dff_one > frc_out_dff_one_max){ frc_out_dff_one_max=frc_out_dff_one; idx_max_dvn=idx; } /* !max */ } /* !idx */ if(frc_out_dff_one_max > eps_rlt) flg_frc_out_one=False; nco_bool flg_frc_nrm=False; /* [flg] Must normalize by frc_out == frac_b because frc_out is not always unity and specified normalization is destarea or none */ if(!flg_frc_out_one && /* If fraction is sometimes "far" from 1.0 and ... */ ((nco_rgr_mpf_typ == nco_rgr_mpf_ESMF && nco_rgr_mth_typ == nco_rgr_mth_conservative && (nco_rgr_nrm_typ == nco_rgr_nrm_destarea || nco_rgr_nrm_typ == nco_rgr_nrm_none)) || /* ESMF map-file specifies conservative regridding with "destarea" or "none" or ... */ (nco_rgr_mpf_typ != nco_rgr_mpf_ESMF)) /* 20191003: Weight-generator does not adhere to ESMF "normalization type" convention */ && True){ flg_frc_nrm=True; /* Avoid writing frc_out unless discrepancies are particularly egregious Otherwise would frc_out for standard remaps like ne30->fv129x256 for which eps=2.46e-13 */ double eps_rlt_wrt_thr=3.0e-13; /* 20181104: Never write frac_b for CMIP6! */ /* if(frc_out_dff_one_max > eps_rlt_wrt_thr) flg_frc_out_wrt=True; */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s reports global metadata specifies conservative remapping with normalization of type = %s. Furthermore, destination fractions frc_dst = dst_frac = frac_b = frc_out contain non-unity elements (maximum deviation from unity of %g exceeds hard-coded (in variable eps_rlt) relative-epsilon threshold of %g for frc_out[%ld] = %g). Thus normalization issues will be explicitly treated. Will apply \'destarea\' normalization (i.e., divide by non-zero frc_out[dst_idx]) to all regridded arrays.\n",nco_prg_nm_get(),fnc_nm,nco_rgr_nrm_sng(nco_rgr_nrm_typ),frc_out_dff_one_max,eps_rlt,idx_max_dvn,frc_out[idx_max_dvn]); if(nco_dbg_lvl_get() >= nco_dbg_std && flg_frc_out_wrt) (void)fprintf(stdout,"%s: INFO %s Maximum deviation %g exceeds threshold of %g that triggers automatic writing of fractional destination area as variable named frac_b in regridded output.\n",nco_prg_nm_get(),fnc_nm,frc_out_dff_one_max,eps_rlt_wrt_thr); } /* !sometimes non-unity */ if(flg_frc_nrm && rgr->flg_rnr){ // 20190918: Weaken from WARNING to INFO because NCO no longer renormalizes when using "destarea" maps unless specifically requested to with --rnr_thr (void)fprintf(stdout,"%s: INFO %s reports manual request to renormalize fields to preserve mean-values (rather than integral values) in destination gridcells that are incompletely covered by valid data in source gridcells (i.e., non-unity frc_dst = dst_frac = frac_b)\n",nco_prg_nm_get(),fnc_nm); //(void)fprintf(stdout,"%s: INFO %s reports manual request (with --rnr) to renormalize fields with non-unity frc_dst = dst_frac = frac_b at same time global metadata specifies normalization type = %s. Normalizing twice can be an error, depending on intent of each. Charlie is all ears on how NCO should handle this :)\n",nco_prg_nm_get(),fnc_nm,nco_rgr_nrm_sng(nco_rgr_nrm_typ)); //nco_exit(EXIT_FAILURE); } /* !flg_rnr */ /* Detailed summary of 2D grids now available including quality-checked coordinates and area */ if(flg_grd_out_2D && nco_dbg_lvl_get() >= nco_dbg_sbr){ lat_wgt_ttl=0.0; area_out_ttl=0.0; if(flg_grd_out_rct){ (void)fprintf(stderr,"%s: INFO %s reports destination rectangular latitude grid:\n",nco_prg_nm_get(),fnc_nm); for(idx=0;idx<lat_nbr_out;idx++) lat_wgt_ttl+=lat_wgt_out[idx]; } /* !flg_grd_out_rct */ for(lat_idx=0;lat_idx<lat_nbr_out;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr_out;lon_idx++) area_out_ttl+=area_out[lat_idx*lon_nbr_out+lon_idx]; (void)fprintf(stdout,"lat_wgt_ttl = %20.15f, frc_lat_wgt = %20.15f, area_ttl = %20.15f, frc_area = %20.15f\n",lat_wgt_ttl,lat_wgt_ttl/2.0,area_out_ttl,area_out_ttl/(4.0*M_PI)); if(flg_grd_out_rct){ for(idx=0;idx<lon_nbr_out;idx++) (void)fprintf(stdout,"lon[%li] = [%g, %g, %g]\n",idx,lon_bnd_out[2*idx],lon_ctr_out[idx],lon_bnd_out[2*idx+1]); for(idx=0;idx<lat_nbr_out;idx++) (void)fprintf(stdout,"lat[%li] = [%g, %g, %g]\n",idx,lat_bnd_out[2*idx],lat_ctr_out[idx],lat_bnd_out[2*idx+1]); for(idx=0;idx<lat_nbr_out;idx++) (void)fprintf(stdout,"lat[%li], wgt[%li] = %20.15f, %20.15f\n",idx,idx,lat_ctr_out[idx],lat_wgt_out[idx]); } /* !flg_grd_out_rct */ if(nco_dbg_lvl_get() > nco_dbg_crr) for(lat_idx=0;lat_idx<lat_nbr_out;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr_out;lon_idx++) (void)fprintf(stdout,"lat[%li] = %g, lon[%li] = %g, area[%li,%li] = %g\n",lat_idx,lat_ctr_out[lat_idx],lon_idx,lon_ctr_out[lon_idx],lat_idx,lon_idx,area_out[lat_idx*lon_nbr_out+lon_idx]); assert(area_out_ttl > 0.0); assert(area_out_ttl <= 4.0*M_PI + 5.0e-15); } /* !flg_grd_out_2D && !dbg */ /* Allocate space for and obtain weights and addresses */ wgt_raw=(double *)nco_malloc_dbg(mpf.num_links*nco_typ_lng(NC_DOUBLE),fnc_nm,"Unable to malloc() value buffer for remapping weights"); col_src_adr=(int *)nco_malloc_dbg(mpf.num_links*nco_typ_lng(NC_INT),fnc_nm,"Unable to malloc() value buffer for remapping addresses"); row_dst_adr=(int *)nco_malloc_dbg(mpf.num_links*nco_typ_lng(NC_INT),fnc_nm,"Unable to malloc() value buffer for remapping addresses"); /* Obtain remap matrix addresses and weights from map file */ dmn_srt[0]=0L; dmn_cnt[0]=mpf.num_links; rcd=nco_get_vara(in_id,col_src_adr_id,dmn_srt,dmn_cnt,col_src_adr,NC_INT); rcd=nco_get_vara(in_id,row_dst_adr_id,dmn_srt,dmn_cnt,row_dst_adr,NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=mpf.num_links; if(nco_rgr_mpf_typ != nco_rgr_mpf_SCRIP){ rcd=nco_get_vara(in_id,wgt_raw_id,dmn_srt,dmn_cnt,wgt_raw,NC_DOUBLE); }else{ /* SCRIP mapfiles store 2D weight array remap_matrix[num_links,num_wgts] Apply only first weight for first-order conservative accuracy (i.e., area overlap) Apply all three weights for second-order conservative accuracy (by including gradients from centroid to vertices) */ dmn_srd[0]=1L; dmn_srt[1]=0L; dmn_cnt[1]=1L; dmn_srd[1]=mpf.num_wgts; rcd=nco_get_vars(in_id,wgt_raw_id,dmn_srt,dmn_cnt,dmn_srd,wgt_raw,NC_DOUBLE); } /* !SCRIP */ /* Pre-subtract one from row/column addresses (stored, by convention, as Fortran indices) to optimize access with C indices */ size_t lnk_nbr; /* [nbr] Number of links */ size_t lnk_idx; /* [idx] Link index */ lnk_nbr=mpf.num_links; for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) row_dst_adr[lnk_idx]--; for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) col_src_adr[lnk_idx]--; if(nco_dbg_lvl_get() >= nco_dbg_io){ (void)fprintf(stdout,"idx row_dst col_src wgt_raw\n"); for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) (void)fprintf(stdout,"%li %d %d %g\n",lnk_idx,row_dst_adr[lnk_idx],col_src_adr[lnk_idx],wgt_raw[lnk_idx]); } /* endif dbg */ /* Free memory associated with input file */ if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt) dmn_cnt=(long *)nco_free(dmn_cnt); if(dmn_srd) dmn_srd=(long *)nco_free(dmn_srd); /* Close input netCDF file */ nco_close(in_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); /* Above this line, fl_in and in_id refer to map file Below this line, fl_in and in_id refer to input file to be regridded */ /* Initialize */ in_id=rgr->in_id; out_id=rgr->out_id; /* Sanity check that input data file matches expectations from mapfile */ char *col_nm_in=rgr->col_nm_in; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ char *lat_nm_in=rgr->lat_nm_in; /* [sng] Name of input dimension to recognize as latitude */ char *lon_nm_in=rgr->lon_nm_in; /* [sng] Name of input dimension to recognize as longitude */ int dmn_id_col=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lat; /* [id] Dimension ID */ int dmn_id_lon; /* [id] Dimension ID */ /* 20160503 Discover coordinates via CF Convention if indicated This copies method used in nco_grd_nfr() */ /* Begin CF-coordinates block */ cf_crd_sct *cf=NULL; char *rgr_var; /* [sng] Variable for special regridding treatment */ nco_bool flg_cf=False; /* [flg] Follow CF Coordinates convention to find and infer grid */ rgr_var=rgr->var_nm; if(rgr_var){ /* Infer grid from special variable Intended to be variable that has both horizontal dimensions and "coordinates" attribute, e.g., ncks --cdl -m ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc | grep coordinates 4LFTX_221_SPDY_S113:coordinates = "gridlat_221 gridlon_221" ; Usage: ncks -O -D 3 --rgr infer --rgr_var=ALBDO_221_SFC_S113 --rgr grid=${HOME}/grd_narr.nc ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc ~/foo.nc */ char crd_sng[]="coordinates"; /* CF-standard coordinates attribute name */ cf=(cf_crd_sct *)nco_malloc(sizeof(cf_crd_sct)); cf->crd=False; /* [flg] CF coordinates information is complete */ cf->crd_id[0]=NC_MIN_INT; /* [id] Coordinate ID, first */ cf->crd_id[1]=NC_MIN_INT; /* [id] Coordinate ID, second */ cf->crd_nm[0]=NULL; /* [sng] Coordinate name, first */ cf->crd_nm[1]=NULL; /* [sng] Coordinate name, second */ cf->crd_sng=NULL; /* [sng] Coordinates attribute value */ cf->dmn_id[0]=NC_MIN_INT; /* [id] Dimension ID, first */ cf->dmn_id[1]=NC_MIN_INT; /* [id] Dimension ID, second */ cf->dmn_nm[0]=NULL; /* [sng] Dimension name, first */ cf->dmn_nm[1]=NULL; /* [sng] Dimension name, second */ cf->unt_sng[0]=NULL; /* [sng] Units string, first coordinate */ cf->unt_sng[1]=NULL; /* [sng] Units string, second coordinate */ cf->var_id=NC_MIN_INT; /* [id] Coordinate variable ID */ cf->var_nm=NULL; /* [sng] Coordinates variable name */ cf->var_type=NC_NAT; /* [enm] Coordinates variable type */ if((rcd=nco_inq_varid_flg(in_id,rgr_var,&cf->var_id)) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports special \"coordinates\" variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd */ cf->crd_sng=nco_char_att_get(in_id,cf->var_id,crd_sng); if(cf->crd_sng){ cf->crd=True; }else{ /* !rcd && att_typ */ (void)fprintf(stderr,"%s: WARNING %s reports coordinates variable %s does not have character-valued \"coordinates\" attribute. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd && att_typ */ /* Valid coordinates attribute requires two coordinate names separated by space character */ char *crd_nm[NCO_MAX_CRD_PER_VAR]; /* [sng] Coordinate name start position */ char *crd_dpl; /* [sng] Modifiable duplicate of coordinates string */ char *spc_ptr; /* [sng] Pointer to space character (' ') */ int crd_nbr=0; /* [nbr] Number of names in coordinates attribute */ int crd_spt=0; /* [nbr] Number of "spatial-like" (that include "degree" in units) coordinates */ int crd_idx=0; /* [idx] Counter for coordinate names */ for(crd_idx=0;crd_idx<NCO_MAX_CRD_PER_VAR;crd_idx++) crd_nm[crd_idx]=NULL; crd_dpl=(char *)strdup(cf->crd_sng); /* Search for spaces starting from end of string */ while((spc_ptr=strrchr(crd_dpl,' '))){ crd_nm[crd_nbr]=spc_ptr+1L; crd_nbr++; /* NUL-terminate so next search ends here */ *spc_ptr='\0'; } /* !sbs_ptr */ /* Final coordinate name begins where coordinate string starts */ crd_nm[crd_nbr]=crd_dpl; /* Change crd_nbr from 0-based index to actual coordinate number */ crd_nbr++; if(crd_nbr < 2){ (void)fprintf(stderr,"%s: WARNING %s found only %d coordinate(s) in \"coordinates\" attribute \"%s\", at least two are required. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,crd_nbr,cf->crd_sng); goto skp_cf; } /* !crd_nbr */ /* If more than two coordinate names are present, choose first two (searching backwards from end) with "degree" in units attributes, otherwise just choose first two */ crd_idx=crd_spt=0; while(crd_spt < 2 && crd_idx < crd_nbr){ cf->crd_nm[crd_spt]=crd_nm[crd_idx]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[crd_spt],&cf->crd_id[crd_spt])) == NC_NOERR){ cf->unt_sng[crd_spt]=nco_char_att_get(in_id,cf->crd_id[crd_spt],unt_sng); if(cf->unt_sng[crd_spt]){ if(strcasestr(cf->unt_sng[crd_spt],"degree")){ /* Increment count of spatial-like coordinates... */ crd_spt++; }else{ /* ...or free() memory allocated during search */ cf->unt_sng[crd_spt]=(char *)nco_free(cf->unt_sng[crd_spt]); } /* !strcasestr() */ crd_idx++; } /* !rcd && att_typ */ } /* !rcd */ } /* !crd_spt */ /* If while()-loop above was successful, our search is over Otherwise, use first two coordinate names regardless of units, and print more diagnostics */ if(crd_spt < 2){ cf->crd_nm[0]=crd_nm[0]; cf->crd_nm[1]=crd_nm[1]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[0],&cf->crd_id[0])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s not found. Turning-off CF coordinates search for this file.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0]); goto skp_cf; } /* !rcd */ if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[1],&cf->crd_id[1])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s not found. Turning-off CF coordinates search for this file.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1]); goto skp_cf; } /* !rcd */ cf->unt_sng[0]=nco_char_att_get(in_id,cf->crd_id[0],unt_sng); if(cf->unt_sng[0]){ if(!strcasestr(cf->unt_sng[0],"degrees_")) (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->unt_sng[0]); } /* !rcd && att_typ */ cf->unt_sng[1]=nco_char_att_get(in_id,cf->crd_id[1],unt_sng); if(cf->unt_sng[1]){ if(!strcasestr(cf->unt_sng[1],"degrees_")) (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1],cf->unt_sng[1]); } /* !rcd && att_typ */ } /* !crd_spt */ int crd_rnk; /* [nbr] Coordinate rank */ rcd=nco_inq_varndims(in_id,cf->crd_id[0],&crd_rnk); if(crd_rnk != 2){ (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s has %i dimension(s). Skipping CF coordinates method.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],crd_rnk); goto skp_cf; } /* !crd_rnk */ rcd=nco_inq_vardimid(in_id,cf->crd_id[0],cf->dmn_id); cf->dmn_nm[0]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); cf->dmn_nm[1]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); rcd=nco_inq_dimname(in_id,cf->dmn_id[0],cf->dmn_nm[0]); rcd=nco_inq_dimname(in_id,cf->dmn_id[1],cf->dmn_nm[1]); /* "coordinates" convention does not guarantee lat, lon are specified in that order Use "units" values, if any, to determine order In absence of "units", assume order is lat, lon */ nco_bool crd0_is_lat=False; /* [flg] First coordinate is latitude */ nco_bool crd0_is_lon=False; /* [flg] First coordinate is longitude */ nco_bool crd1_is_lat=False; /* [flg] Second coordinate is latitude */ nco_bool crd1_is_lon=False; /* [flg] Second coordinate is longitude */ if(cf->unt_sng[0]){ if(!strcasecmp(cf->unt_sng[0],"degrees_north")) crd0_is_lat=True; if(!strcasecmp(cf->unt_sng[0],"degrees_east")) crd0_is_lon=True; } /* endif */ if(cf->unt_sng[1]){ if(!strcasecmp(cf->unt_sng[1],"degrees_north")) crd1_is_lat=True; if(!strcasecmp(cf->unt_sng[1],"degrees_east")) crd1_is_lon=True; } /* endif */ assert((crd0_is_lat && crd1_is_lon) || (crd0_is_lon && crd1_is_lat)); int idx_lat; int idx_lon; if(crd0_is_lat && crd1_is_lon){ idx_lat=0; idx_lon=1; }else{ idx_lat=1; idx_lon=0; } /* endif */ /* Dimensions and coordinates have been vetted. Store as primary lookup names. Dimensions are always returned in order [LRV,MRV]=[0,1] LRV is along-track direction, and MRV is across-track (at least in NASA data) Internally we label LRV as "lat" and MRV as "lon" so that code looks similar for curvilinear and rectangular grids */ dmn_id_lat=cf->dmn_id[0]; dmn_id_lon=cf->dmn_id[1]; /* Subtlety: lat_nm_in is coordinate (variable+dimension) name when specified from command-line (as in nco_grd_nfr()), dimension name when found through CF-method (as in nco_rgr_wgt()). This confusing distinction could be avoided by passing command-line dimension names through-to nco_rgr_wgt(). However, that route would require complex priorities for what to do when passing command-line coordinate names not dimension names and visa-versa. */ lat_nm_in=strdup(cf->dmn_nm[0]); lon_nm_in=strdup(cf->dmn_nm[1]); //lat_nm_in=strdup(cf->crd_nm[idx_lat]); //lon_nm_in=strdup(cf->crd_nm[idx_lon]); /* Next four lines unnecessary in nco_rgr_wgt() which only needs dimension names (it reads input coordinates from map-file not data-file) */ //lat_ctr_id=cf->crd_id[idx_lat]; //lon_ctr_id=cf->crd_id[idx_lon]; //lat_dmn_nm=strdup(cf->dmn_nm[0]); //lon_dmn_nm=strdup(cf->dmn_nm[1]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s \"coordinates\" attribute \"%s\" points to coordinates %s and %s. Latitude coordinate \"%s\" has dimensions \"%s\" and \"%s\". Longitude coordinate \"%s\" has dimensions \"%s\" and \"%s\".\n",nco_prg_nm_get(),fnc_nm,rgr_var,cf->crd_sng,cf->crd_nm[0],cf->crd_nm[1],cf->crd_nm[idx_lat],cf->dmn_nm[idx_lat],cf->dmn_nm[idx_lon],cf->crd_nm[idx_lon],cf->dmn_nm[idx_lat],cf->dmn_nm[idx_lon]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s Coordinates %s and %s \"units\" values are \"%s\" and \"%s\", respectively.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->crd_nm[1],cf->unt_sng[0] ? cf->unt_sng[0] : "(non-existent)",cf->unt_sng[1] ? cf->unt_sng[1] : "(non-existent)"); /* Clean-up CF coordinates memory */ if(crd_dpl) crd_dpl=(char *)nco_free(crd_dpl); if(cf->crd_sng) cf->crd_sng=(char *)nco_free(cf->crd_sng); if(cf->dmn_nm[0]) cf->dmn_nm[0]=(char *)nco_free(cf->dmn_nm[0]); if(cf->dmn_nm[1]) cf->dmn_nm[1]=(char *)nco_free(cf->dmn_nm[1]); if(cf->unt_sng[0]) cf->unt_sng[0]=(char *)nco_free(cf->unt_sng[0]); if(cf->unt_sng[1]) cf->unt_sng[1]=(char *)nco_free(cf->unt_sng[1]); // if(foo) foo=(char *)nco_free(foo); } /* !rgr_var */ /* goto skp_cf */ skp_cf: /* free() any abandoned cf structure now */ if(!flg_cf) if(cf) cf=(cf_crd_sct *)nco_free(cf); rcd=NC_NOERR; /* End CF-coordinates block */ if(flg_grd_in_1D){ long col_nbr_in_dat; /* [nbr] Number of columns in input datafile */ /* Check default or command-line option first, then search usual suspects, and if that fails then guess unstructured dimension is dimension in input file with size n_a expected by input map file, suggested by PJCS Using internal database names first ensures users can pick between multiple dimensions of size n_a 20180313: fxm New PJCS algorithm is superior, should eliminate internal database for unstructured grids? Database is necessary for 2D grids because otherwise no good way to disambiguate latitude from longitude */ if(col_nm_in && (rcd=nco_inq_dimid_flg(in_id,col_nm_in,&dmn_id_col)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"lndgrid",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("lndgrid"); /* CLM */ else if((rcd=nco_inq_dimid_flg(in_id,"nCells",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("nCells"); /* MPAS-O/I */ else if((rcd=nco_inq_dimid_flg(in_id,"nEdges",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("nEdges"); /* MPAS-O/I */ else if((rcd=nco_inq_dimid_flg(in_id,"ncol_d",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("ncol_d"); /* EAM dynamics grid */ else if((rcd=nco_inq_dimid_flg(in_id,"ncol_p",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("ncol_d"); /* EAM physics grid */ else if((rcd=nco_inq_dimid_flg(in_id,"sounding_id",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("sounding_id"); /* OCO2 */ /* 20180605: Database matches to above names may be false-positives ALM/CLM/CTSM/ELM store all possible dimension names that archived variables could use NCO only prints dimensions used in variables, while ncdump prints all dimensions From ncdump we find usually unused ALM/CLM/CTSM/ELM dimensions: gridcell, lndunit, column, pft, levurb, numrad, levsno Check that matched dimension has expected size: */ if(dmn_id_col != NC_MIN_INT){ rcd=nco_inq_dimlen(in_id,dmn_id_col,&col_nbr_in_dat); if(col_nbr_in != col_nbr_in_dat){ dmn_id_col=NC_MIN_INT; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s database-prioritized unstructured dimension candidate \"%s\" has size not expected by supplied map-file: mapfile col_nbr_in = %ld != %ld = col_nbr_in from datafile. HINT: Check that source grid (i.e., \"grid A\") used to create mapfile matches grid on which data are stored in input datafile.\n",nco_prg_nm_get(),fnc_nm,col_nm_in,col_nbr_in,col_nbr_in_dat); } /* !col_nbr_in */ }else{ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s expects data on an unstructured grid yet cannot find a dimension name that matches the usual suspects for unstructured dimensions (ncol, gridcell, lndgrid, nCells, nEdges, sounding_id). Consider specifying horizontal dimension name to ncks with \"--rgr col_nm=foo\" or to ncremap with \"ncremap -R '--rgr col_nm=foo'\", and consider requesting the NCO project to add this horizontal dimension name to its internal database.\n",nco_prg_nm_get(),fnc_nm); } /* !dmn_id_col */ if(dmn_id_col == NC_MIN_INT){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s Proceeding with fallback algorithm to guess unstructured dimension as first dimension in data file of equal size to that expected by supplied map-file...\n",nco_prg_nm_get(),fnc_nm); /* 20180312: Unstructured dimension must have same size as input map file, suggested by PJCS */ int *dmn_ids_in; /* [nbr] Input file dimension IDs */ int dmn_nbr_in; /* [nbr] Number of dimensions in input file */ const int flg_prn=0; /* [enm] Parent flag */ rcd=nco_inq_dimids(in_id,&dmn_nbr_in,NULL,flg_prn); dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); rcd=nco_inq_dimids(in_id,NULL,dmn_ids_in,flg_prn); /* Find dimension, if any, with same size as map "a" src_grid_dims[0] = n_a dimension */ for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ dmn_id_col=dmn_ids_in[dmn_idx]; rcd=nco_inq_dimlen(in_id,dmn_id_col,&col_nbr_in_dat); if(col_nbr_in == col_nbr_in_dat){ rcd=nco_inq_dimname(in_id,dmn_id_col,col_nm_in); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s found that dimension %s in datafile has same size (n_a = %ld) expected by map-file. Assuming %s is the unstructured dimension.\n",nco_prg_nm_get(),fnc_nm,col_nm_in,col_nbr_in,col_nm_in); break; } /* !col_nbr_in */ } /* !dmn_idx */ if(dmn_ids_in) dmn_ids_in=(int *)nco_free(dmn_ids_in); if(dmn_idx == dmn_nbr_in){ dmn_id_col=NC_MIN_INT; (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") expects data on an unstructured grid but cannot find a dimension in the input data file (or, with ncremap, a possibly already subsetted intermediate file) that matches the size of the unstructured dimension in the supplied map-file = src_grd_dims[0] = n_a = %ld.\nHINT: Ensure at least one member of the variable extraction list has a spatial dimension of size = %ld\n",nco_prg_nm_get(),fnc_nm,col_nbr_in,col_nbr_in); nco_exit(EXIT_FAILURE); } /* !dmn_idx */ } /* !col_nm_in */ } /* !1D */ if(flg_grd_in_2D){ long lat_nbr_in_dat; /* [nbr] Number of latitudes in input datafile */ if(lat_nm_in && (rcd=nco_inq_dimid_flg(in_id,lat_nm_in,&dmn_id_lat)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"latitude",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("latitude"); else if((rcd=nco_inq_dimid_flg(in_id,"lat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("lat"); else if((rcd=nco_inq_dimid_flg(in_id,"Latitude",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Latitude"); else if((rcd=nco_inq_dimid_flg(in_id,"Lat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Lat"); else if((rcd=nco_inq_dimid_flg(in_id,"south_north",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("south_north"); /* WRF */ else if((rcd=nco_inq_dimid_flg(in_id,"south_north_stag",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("south_north_stag"); else if((rcd=nco_inq_dimid_flg(in_id,"YDim:location",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("YDim:location"); /* AIRS L3 */ else if((rcd=nco_inq_dimid_flg(in_id,"YDim:MOD_Grid_monthly_CMG_VI",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("YDim:MOD_Grid_monthly_CMG_VI"); /* MODIS MOD13C2 */ else if((rcd=nco_inq_dimid_flg(in_id,"natrack",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("natrack"); /* MODIS DeepBlue SeaWiFS L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"nj",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nj"); /* CICE RTM */ else if((rcd=nco_inq_dimid_flg(in_id,"nlat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nlat"); /* POP */ else if((rcd=nco_inq_dimid_flg(in_id,"rlat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("rlat"); /* RACMO */ else if((rcd=nco_inq_dimid_flg(in_id,"nscan",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nscan"); /* AMSR, TRMM */ else if((rcd=nco_inq_dimid_flg(in_id,"nTimes",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nTimes"); /* OMI L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"number_of_lines",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("number_of_lines"); /* DSCOVR L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoTrack",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("GeoTrack"); /* AIRS L2 DAP NC */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoTrack:L2_Standard_atmospheric&surface_product",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("GeoTrack:L2_Standard_atmospheric&surface_product"); /* AIRS L2 HDF */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Along_Swath:mod04",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Cell_Along_Swath:mod04"); /* MODIS MOD04 L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Along_Swath_mod04",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Cell_Along_Swath_mod04"); /* MODIS MOD04 L2 (ncl_convert2nc changes colon to underscore) */ else if((rcd=nco_inq_dimid_flg(in_id,"CO_Latitude",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("CO_Latitude"); else if((rcd=nco_inq_dimid_flg(in_id,"j",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("j"); /* CMIP5 NorESM1 ocean */ else if((rcd=nco_inq_dimid_flg(in_id,"latitude0",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("latitude0"); /* Oxford */ else if((rcd=nco_inq_dimid_flg(in_id,"y",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("y"); /* NEMO */ else if((rcd=nco_inq_dimid_flg(in_id,"x",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("x"); /* NSIDC polar stereographic (NB: unfortunate incompatible conflict between NEMO & NSIDC names) */ else if((rcd=nco_inq_dimid_flg(in_id,"y1",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("y1"); /* NSIDC EASE */ else if((rcd=nco_inq_dimid_flg(in_id,"ygrid_0",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("ygrid_0"); /* NWS HRRR */ else{ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports unable to find latitude dimension in input file. Tried the usual suspects. HINT: Inform regridder of input latitude dimension name with \"ncks --rgr lat_nm_in=name\" or \"ncremap -R '--rgr lat_nm_in=name'\"\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !lat */ rcd=nco_inq_dimlen(in_id,dmn_id_lat,&lat_nbr_in_dat); if(lat_nbr_in != lat_nbr_in_dat){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports mapfile and data file dimension sizes disagree: mapfile lat_nbr_in = %ld != %ld = lat_nbr_in from datafile. HINT: Check that source grid (i.e., \"grid A\") used to create mapfile matches grid on which data are stored in input datafile.\n",nco_prg_nm_get(),fnc_nm,lat_nbr_in,lat_nbr_in_dat); nco_exit(EXIT_FAILURE); } /* !err */ long lon_nbr_in_dat; /* [nbr] Number of longitudes in input datafile */ if(lon_nm_in && (rcd=nco_inq_dimid_flg(in_id,lon_nm_in,&dmn_id_lon)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"longitude",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("longitude"); else if((rcd=nco_inq_dimid_flg(in_id,"lon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("lon"); else if((rcd=nco_inq_dimid_flg(in_id,"Longitude",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Longitude"); else if((rcd=nco_inq_dimid_flg(in_id,"Lon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Lon"); else if((rcd=nco_inq_dimid_flg(in_id,"west_east",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("west_east"); /* WRF */ else if((rcd=nco_inq_dimid_flg(in_id,"west_east_stag",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("west_east_stag"); else if((rcd=nco_inq_dimid_flg(in_id,"XDim:location",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("XDim:location"); /* AIRS L3 */ else if((rcd=nco_inq_dimid_flg(in_id,"XDim:MOD_Grid_monthly_CMG_VI",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("XDim:MOD_Grid_monthly_CMG_VI"); /* MODIS MOD13C2 */ else if((rcd=nco_inq_dimid_flg(in_id,"ni",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("ni"); /* CICE RTM */ else if((rcd=nco_inq_dimid_flg(in_id,"nlon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("nlon"); /* POP */ else if((rcd=nco_inq_dimid_flg(in_id,"rlon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("rlon"); /* POP */ else if((rcd=nco_inq_dimid_flg(in_id,"npix",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("npix"); /* AMSR */ else if((rcd=nco_inq_dimid_flg(in_id,"npixel",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("npixel"); /* TRMM */ else if((rcd=nco_inq_dimid_flg(in_id,"nxtrack",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("nxtrack"); /* MODIS DeepBlue SeaWiFS L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"nXtrack",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("nXtrack"); /* OMI L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"number_of_pixels",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("number_of_pixels"); /* DSCOVR L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoXTrack",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("GeoXTrack"); /* AIRS L2 DAP NC */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoXTrack:L2_Standard_atmospheric&surface_product",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("GeoXTrack:L2_Standard_atmospheric&surface_product"); /* AIRS L2 HDF */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Across_Swath:mod04",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Cell_Across_Swath:mod04"); /* MODIS MOD04 L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Across_Swath_mod04",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Cell_Across_Swath_mod04"); /* MODIS MOD04 L2 (ncl_convert2nc changes colon to underscore) */ else if((rcd=nco_inq_dimid_flg(in_id,"i",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("i"); /* CMIP5 NorESM1 ocean */ else if((rcd=nco_inq_dimid_flg(in_id,"longitude0",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("longitude0"); /* Oxford */ else if((rcd=nco_inq_dimid_flg(in_id,"x",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("x"); /* NEMO */ else if((rcd=nco_inq_dimid_flg(in_id,"y",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("y"); /* NSIDC polar stereographic (NB: unfortunate incompatible conflict between NEMO & NSIDC names) */ else if((rcd=nco_inq_dimid_flg(in_id,"x1",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("x1"); /* NSIDC EASE */ else if((rcd=nco_inq_dimid_flg(in_id,"xgrid_0",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("xgrid_0"); /* NWS HRRR */ else{ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports unable to find longitude dimension in input file. Tried the usual suspects. HINT: Inform regridder of input longitude dimension name with \"ncks --rgr lon_nm_in=name\" or \"ncremap -R '--rgr lon_nm_in=name'\"\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !lat */ rcd=nco_inq_dimlen(in_id,dmn_id_lon,&lon_nbr_in_dat); if(lon_nbr_in != lon_nbr_in_dat){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports mapfile and data file dimension sizes disagree: mapfile lon_nbr_in = %ld != %ld = lon_nbr_in from datafile. HINT: Check that source grid (i.e., \"grid A\") used to create mapfile matches grid on which data are stored in input datafile.\n",nco_prg_nm_get(),fnc_nm,lon_nbr_in,lon_nbr_in_dat); nco_exit(EXIT_FAILURE); } /* !err */ } /* !2D */ /* Do not extract grid variables (that are also extensive variables) like lon, lat, area, and masks If necessary, use remap data to diagnose them from scratch Other extensive variables (like counts, population) will be extracted and summed not averaged */ /* Exception list source: ALM/CLM: landmask (20170504: Debatable, including erroneous mask may be better than completely excluding an expected mask) (20170504: must keep landfrac since regridded by ncremap for SGS option) AMSR: Latitude, Longitude CAM, CERES, CMIP5: lat, lon CAM, CMIP5: gw, lat_bnds, lon_bnds CAM-FV: slon, slat, w_stag (w_stag is weights for slat grid, analagous to gw for lat grid) CAM-SE, EAM, MOSART: area CICE: latt_bounds, lont_bounds, latu_bounds, lonu_bounds, TLAT, TLON, ULAT, ULON (NB: CICE uses ?LON and POP uses ?LONG) (aice is ice area, tmask is state-variable mask, both not currently excluded, although all binary masks like tmask should be recomputed on new grid) DSCOVR L2: latitude, longitude ESMF: gridcell_area GPM: S1_Latitude, S1_Longitude HIRDLS: Latitude MAR/RACMO: LAT, LON MLS: CO_Latitude MPAS-O/I/LI: areaCell, latCell, lonCell and others that are all handled by separated MPAS convention implementation below NCO: lat_vertices, lon_vertices NEMO: nav_lat, nav_lon NWS HRRR: gridlat_0, gridlon_0 OCO2: latitude_bnds, longitude_bnds OMI DOMINO: Latitude, LatitudeCornerpoints, Longitude, LongitudeCornerpoints Oxford: global_latitude0, global_longitude0, latitude0, longitude0 POP: TLAT, TLONG, ULAT, ULONG (NB: CICE uses ?LON and POP uses ?LONG) (POP does not archive spatial bounds) RACMO: rlat, rlon TRMM: Latitude, Longitude UV-CDAT regridder: bounds_lat, bounds_lon Unknown: XLAT_M, XLONG_M WRF: XLAT, XLONG */ const int var_xcl_lst_nbr=51; /* [nbr] Number of objects on exclusion list */ const char *var_xcl_lst[]={"/area","/gridcell_area","/gw","/LAT","/lat","/Latitude","/latitude","/nav_lat","/global_latitude0","gridlat_0","/latitude0","/rlat","/slat","/TLAT","/ULAT","/XLAT","/XLAT_M","/CO_Latitude","/S1_Latitude","/lat_bnds","/lat_vertices","/latt_bounds","/latu_bounds","/latitude_bnds","/LatitudeCornerpoints","/bounds_lat","/LON","/lon","/Longitude","/longitude","/nav_lon","/global_longitude0","gridlon_0","/longitude0","/rlon","/slon","/TLON","/TLONG","/ULON","/ULONG","/XLONG","/XLONG_M","/CO_Longitude","/S1_Longitude","/lon_bnds","/lon_vertices","/lont_bounds","/lonu_bounds","/longitude_bnds","/LongitudeCornerpoints","/bounds_lon","/w_stag"}; int var_cpy_nbr=0; /* [nbr] Number of copied variables */ int var_rgr_nbr=0; /* [nbr] Number of regridded variables */ int var_xcl_nbr=0; /* [nbr] Number of deleted variables */ int var_crt_nbr=0; /* [nbr] Number of created variables */ int var_xtn_nbr=0; /* [nbr] Number of extensive variables */ unsigned int idx_tbl; /* [idx] Counter for traversal table */ const unsigned int trv_nbr=trv_tbl->nbr; /* [idx] Number of traversal table entries */ for(idx=0;idx<var_xcl_lst_nbr;idx++){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm_fll,var_xcl_lst[idx])) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* endif */ } /* !idx */ cnv_sct *cnv; /* [sct] Convention structure */ /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id); if(cnv->MPAS){ /* 20160228: MPAS has a host of mysterious grid and extensive variables that should probably not be regridded 20180206: Add from MPAS-LI xCell, yCell, zCell, and [xyz]Edge, and [xyz]Vertex 20180917: Restrict exclusion list to a subset of variables with nCells-dimension Six nCells-variables may be valuable when regridded to lat/lon mpas_xcl_lst in nco_rgr_wgt() and MPAS var_xcl_lst in nco_var_is_fix() differ by these six variables: areaCell for comparison to area(lat,lon) cellMask for area-weighted mask maxLevelCell for area-weighted underwater topographic mask xCell, yCell, zCell for area-weighted cartesian coordinates 20180918: Regridder currently only works on cell-based coordinates Decided regridder will omit not copy fields on vertex- or edge-based coordinates until it can regrid them Regridding vertex- or edge-based fields would require new sparse matrix for vertices or edges How would ERWG or TempestRemap handle that? MPAS geophysical variables on vertex-based (not cell-based) coordinates include: avg_airStressVertexUGeo_1, avg_airStressVertexVGeo_1, uOceanVelocityVertexGeo_1, uVelocityGeo_1, vOceanVelocityVertexGeo_1, vVelocityGeo_1 MPAS geophysical variables on edge-based (not cell-based) coordinates include: principalStress1Var_1, principalStress2Var_1 */ const int mpas_xcl_lst_nbr=35; const char *mpas_xcl_lst[]={"/angleEdge","/areaTriangle","/cellsOnCell","/cellsOnEdge","/cellsOnVertex","/dcEdge","/dvEdge","/edgeMask","/edgesOnCell","/edgesOnEdge","/edgesOnVertex","/indexToCellID","/indexToEdgeID","/indexToVertexID","/kiteAreasOnVertex","/latCell","/latEdge","/latVertex","/lonCell","/lonEdge","/lonVertex","/maxLevelEdgeTop","/meshDensity","/nEdgesOnCell","/nEdgesOnEdge","/vertexMask","/verticesOnCell","/verticesOnEdge","/weightsOnEdge","/xEdge","/yEdge","/zEdge","/xVertex","/yVertex","/zVertex"}; for(idx=0;idx<mpas_xcl_lst_nbr;idx++){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm_fll,mpas_xcl_lst[idx])) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined MPAS exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* endif */ } /* !idx */ } /* !MPAS */ char *dmn_nm_cp; /* [sng] Dimension name as char * to reduce indirection */ int dmn_nbr_in; /* [nbr] Number of dimensions in input variable */ int dmn_nbr_out; /* [nbr] Number of dimensions in output variable */ nco_bool has_lon; /* [flg] Contains longitude dimension */ nco_bool has_lat; /* [flg] Contains latitude dimension */ trv_sct trv; /* [sct] Traversal table object structure to reduce indirection */ /* Define regridding flag for each variable */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; dmn_nbr_in=trv_tbl->lst[idx_tbl].nbr_dmn; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ has_lon=False; has_lat=False; if(flg_grd_in_2D){ for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ /* Pre-determine flags necessary during next loop */ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; /* fxm: Generalize to include any variable containing two coordinates with "standard_name" = "latitude" and "longitude" */ if(!has_lon) has_lon=!strcmp(dmn_nm_cp,lon_nm_in); if(!has_lat) has_lat=!strcmp(dmn_nm_cp,lat_nm_in); } /* end loop over dimensions */ } /* !flg_grd_in_2D */ for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; /* Regrid variables containing the horizontal spatial dimension on 1D grids, and both latitude and longitude on 2D grids */ if(!strcmp(dmn_nm_cp,col_nm_in) || (has_lon && has_lat)){ trv_tbl->lst[idx_tbl].flg_rgr=True; var_rgr_nbr++; break; } /* endif */ } /* end loop over dimensions */ if(dmn_idx == dmn_nbr_in){ /* Not regridded, so must be omitted or copied... */ if(flg_grd_in_2D && (has_lon || has_lat)){ /* Single spatial dimensional variables on 2D input grids are likely extensive (e.g., grd_mrd_lng from bds) These could be salvaged with explicit rules or implicit assumptions */ trv_tbl->lst[idx_tbl].flg_xtr=False; var_xcl_nbr++; if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) extensive-seeming (e.g., 1D spatial variable in 2D input grid, or 2D spatial variable without primary grid dimensions from multi-grid file (e.g., west_east_stag or south_north_stag instead of west_east or south_north)) variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); }else{ /* !omitted */ /* Copy all variables that are not regridded or omitted */ var_cpy_nbr++; } /* !omitted */ } /* endif not regridded */ } /* end nco_obj_typ_var */ } /* end idx_tbl */ if(!var_rgr_nbr) (void)fprintf(stdout,"%s: WARNING %s reports no variables fit regridding criteria. The regridder expects something to regrid, and variables not regridded are copied straight to output. HINT: If the name(s) of the input horizontal spatial dimensions to be regridded (e.g., latitude and longitude or column) do not match NCO's preset defaults (case-insensitive unambiguous forms and abbreviations of \"latitude\", \"longitude\", and \"ncol\", respectively) then change the dimension names that NCO looks for. Instructions are at http://nco.sf.net/nco.html#regrid, e.g., \"ncks --rgr col=lndgrid --rgr lat=north\" or \"ncremap -R '--rgr col=lndgrid --rgr lat=north'\".\n",nco_prg_nm_get(),fnc_nm); for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.flg_rgr){ for(int xtn_idx=0;xtn_idx<rgr->xtn_nbr;xtn_idx++){ /* 20150927: Extensive variable treatments are still in alpha-development Currently testing on AIRS TSurfStd_ct (by summing not averaging) In future may consider variables that need more complex (non-summing) extensive treatment MPAS-O/I has a zillion of these [xyz]Cell, cellsOnCell, fCell, indexToCellID, maxLevelCell, meshDensity Not to mention the variables that depend on nEdges and nVertices... */ if(!strcmp(trv.nm,rgr->xtn_var[xtn_idx])){ trv_tbl->lst[idx_tbl].flg_xtn=True; var_xtn_nbr++; if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO Variable %s will be treated as extensive (summed not averaged)\n",nco_prg_nm_get(),trv.nm_fll); } /* !strcmp */ } /* !xtn_idx */ } /* !flg_rgr */ } /* !idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_sbr){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr) (void)fprintf(stderr,"Regrid %s? %s\n",trv.nm,trv.flg_rgr ? "Yes" : "No"); } /* end idx_tbl */ } /* end dbg */ /* Lay-out regridded file */ aed_sct aed_mtd; char *area_nm_out; char *att_nm; char *bnd_nm_out; char *bnd_tm_nm_out; char *col_nm_out; char *frc_nm_out; char *lat_bnd_nm_out; char *lat_dmn_nm_out; char *lat_nm_out; char *lat_wgt_nm; char *lon_bnd_nm_out; char *lon_dmn_nm_out; char *lon_nm_out; char *msk_nm_out; char *slat_nm_out=NULL; char *slat_wgt_nm_out=NULL; char *slon_nm_out=NULL; int dmn_id_bnd; /* [id] Dimension ID */ int dmn_id_bnd_tm; /* [id] Dimension ID */ int dmn_id_slat; /* [id] Dimension ID */ int dmn_id_slon; /* [id] Dimension ID */ int area_out_id; /* [id] Variable ID for area */ int frc_out_id; /* [id] Variable ID for fraction */ int lon_out_id; /* [id] Variable ID for longitude */ int lat_out_id; /* [id] Variable ID for latitude */ int lat_wgt_id; /* [id] Variable ID for latitude weight */ int lon_bnd_id; /* [id] Variable ID for lon_bnds/lon_vertices */ int lat_bnd_id; /* [id] Variable ID for lat_bnds/lat_vertices */ int msk_out_id; /* [id] Variable ID for mask */ int slat_out_id; /* [id] Variable ID for staggered latitude */ int slat_wgt_id; /* [id] Variable ID for staggered latitude weight */ int slon_out_id; /* [id] Variable ID for staggered longitude */ int dmn_ids_out[dmn_nbr_grd_max]; /* [id] Dimension IDs array for output variable */ long dmn_srt_out[dmn_nbr_grd_max]; long dmn_cnt_tuo[dmn_nbr_grd_max]; /* Name output dimensions/variables */ area_nm_out=rgr->area_nm; bnd_tm_nm_out=rgr->bnd_tm_nm; frc_nm_out=rgr->frc_nm; lat_bnd_nm_out=rgr->lat_bnd_nm; lat_wgt_nm=rgr->lat_wgt_nm; lon_bnd_nm_out=rgr->lon_bnd_nm; msk_nm_out=rgr->msk_nm; /* Use explicitly specified output names, if any, otherwise use input names (either explicitly specified or discovered by fuzzing) */ if(rgr->col_nm_out) col_nm_out=rgr->col_nm_out; else col_nm_out=col_nm_in; if(rgr->lat_dmn_nm) lat_dmn_nm_out=rgr->lat_dmn_nm; else lat_dmn_nm_out=lat_nm_in; if(rgr->lon_dmn_nm) lon_dmn_nm_out=rgr->lon_dmn_nm; else lon_dmn_nm_out=lon_nm_in; if(rgr->lat_nm_out) lat_nm_out=rgr->lat_nm_out; else lat_nm_out=lat_nm_in; if(rgr->lon_nm_out) lon_nm_out=rgr->lon_nm_out; else lon_nm_out=lon_nm_in; if(flg_grd_out_1D){ bnd_nm_out=rgr->vrt_nm; lat_bnd_nm_out=rgr->lat_vrt_nm; lon_bnd_nm_out=rgr->lon_vrt_nm; } /* !flg_grd_out_1D */ if(flg_grd_out_crv){ bnd_nm_out=rgr->bnd_nm; } /* !flg_grd_out_crv */ if(flg_grd_out_rct){ bnd_nm_out=rgr->bnd_tm_nm; /* NB: default to bnd_tm_nm for spatial bounds */ } /* !flg_grd_out_rct */ if(flg_grd_out_2D){ lat_bnd_nm_out=rgr->lat_bnd_nm; lon_bnd_nm_out=rgr->lon_bnd_nm; } /* !flg_grd_out_2D */ if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ slat_nm_out=strdup("slat"); slat_wgt_nm_out=strdup("w_stag"); slon_nm_out=strdup("slon"); } /* !nco_grd_lat_fv */ /* Ensure temporal bounds dimension name is distinct from spatial bounds when their sizes differ */ if(bnd_nbr_out != bnd_tm_nbr_out){ if(!strcmp(bnd_nm_out,bnd_tm_nm_out)){ (void)fprintf(stdout,"%s: INFO %s reports spatial and temporal output bounds dimensions are identical (and named \"%s\") by default for rectangular output grids because both can be stored as 2D arrays. That cannot work for this mapping because temporal and spatial bounds dimensions sizes differ (bnd_nbr_out = %d, bnd_tm_nbr_out = %d). Using fall-back spatial bounds name \"%s\" instead. HINT: You may change one or both manually with \"ncks --rgr bnd_nm=name\" or \"ncks --rgr bnd_tm_nm=name\", or, using ncremap, with \"ncremap -R '--rgr bnd_nm=name'\" or \"ncremap -R '--rgr bnd_tm_nm=name'\"\n",nco_prg_nm_get(),fnc_nm,bnd_tm_nm_out,bnd_nbr_out,bnd_tm_nbr_out,bnd_nm_out); } /* !strcmp() */ } /* !bnd_nbr_out */ /* Persistent metadata */ aed_sct aed_mtd_crd; char *att_val_crd=NULL; char *att_nm_crd=NULL; att_nm_crd=strdup("coordinates"); aed_mtd_crd.att_nm=att_nm_crd; if(flg_grd_out_1D || flg_grd_out_crv) aed_mtd_crd.mode=aed_overwrite; else aed_mtd_crd.mode=aed_delete; aed_mtd_crd.type=NC_CHAR; aed_mtd_crd.sz=strlen(lat_nm_out)+strlen(lon_nm_out)+1L; att_val_crd=(char *)nco_malloc((aed_mtd_crd.sz+1L)*nco_typ_lng(aed_mtd_crd.type)); (void)sprintf(att_val_crd,"%s %s",lat_nm_out,lon_nm_out); aed_mtd_crd.val.cp=att_val_crd; /* Reminder: Regridder area_out options, e.g., --rgr area_out, set flg_area_out to control adding "area" variable to regridded output Regridder cll_msr options, --rgr cll_msr, set flg_cll_msr to control adding "cell_measures" attribute to regridded output ncks & ncra cll_msr options, --cll_msr, set EXTRACT_CLL_MSR to control adding "cell_measures" variables (e.g., area) to extraction list of input file EXTRACT_CLL_MSR supercedes --rgr area_out in determining whether to add "area" to regridded output */ nco_bool flg_area_out=rgr->flg_area_out; /* [flg] Add area to output */ nco_bool flg_cll_msr=rgr->flg_cll_msr; /* [flg] Add cell_measures attribute */ aed_sct aed_mtd_cll_msr; char *att_nm_cll_msr=NULL; char *att_val_cll_msr=NULL; if(flg_cll_msr){ att_nm_cll_msr=strdup("cell_measures"); aed_mtd_cll_msr.att_nm=att_nm_cll_msr; aed_mtd_cll_msr.mode=aed_overwrite; aed_mtd_cll_msr.type=NC_CHAR; att_val_cll_msr=(char *)nco_malloc((strlen(area_nm_out)+6L+1L)*nco_typ_lng(aed_mtd_cll_msr.type)); (void)sprintf(att_val_cll_msr,"area: %s",area_nm_out); aed_mtd_cll_msr.sz=strlen(att_val_cll_msr); aed_mtd_cll_msr.val.cp=att_val_cll_msr; } /* !flg_cll_msr */ /* Define new horizontal dimensions before all else */ if(flg_grd_out_1D){ rcd+=nco_def_dim(out_id,col_nm_out,col_nbr_out,&dmn_id_col); } /* !flg_grd_out_1D */ if(flg_grd_out_2D){ rcd+=nco_def_dim(out_id,lat_dmn_nm_out,lat_nbr_out,&dmn_id_lat); rcd+=nco_def_dim(out_id,lon_dmn_nm_out,lon_nbr_out,&dmn_id_lon); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ rcd+=nco_def_dim(out_id,slat_nm_out,slat_nbr_out,&dmn_id_slat); rcd+=nco_def_dim(out_id,slon_nm_out,slon_nbr_out,&dmn_id_slon); } /* !nco_grd_lat_fv */ } /* !flg_grd_out_2D */ /* If dimension has not been defined, define it */ rcd=nco_inq_dimid_flg(out_id,bnd_tm_nm_out,&dmn_id_bnd_tm); if(rcd != NC_NOERR) rcd=nco_def_dim(out_id,bnd_tm_nm_out,bnd_tm_nbr_out,&dmn_id_bnd_tm); /* If dimension has not been defined, define it */ rcd=nco_inq_dimid_flg(out_id,bnd_nm_out,&dmn_id_bnd); if(rcd != NC_NOERR) rcd=nco_def_dim(out_id,bnd_nm_out,bnd_nbr_out,&dmn_id_bnd); char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ char *var_nm; /* [sng] Variable name */ int *dmn_id_in=NULL; /* [id] Dimension IDs */ int *dmn_id_out=NULL; /* [id] Dimension IDs */ int var_id_in; /* [id] Variable ID */ int var_id_out; /* [id] Variable ID */ nc_type var_typ_out; /* [enm] Variable type to write to disk */ nc_type var_typ_rgr; /* [enm] Variable type used during regridding */ nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes "scale_factor", "add_offset" */ int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; dfl_lvl=rgr->dfl_lvl; fl_out_fmt=rgr->fl_out_fmt; /* Define new coordinates and grid variables in regridded file */ if(flg_grd_out_1D){ rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_col; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lat_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_col; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lon_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd+=nco_def_var(out_id,frc_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,frc_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd+=nco_def_var(out_id,msk_nm_out,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_col,&msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_msk_out */ } /* !flg_grd_out_1D */ if(flg_grd_out_crv){ dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_lon; rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd+=nco_def_var(out_id,frc_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,frc_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd+=nco_def_var(out_id,msk_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_msk_out */ dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_lon; dmn_ids_out[2]=dmn_id_bnd; rcd+=nco_def_var(out_id,lat_bnd_nm_out,crd_typ_out,dmn_nbr_3D,dmn_ids_out,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_bnd_nm_out,crd_typ_out,dmn_nbr_3D,dmn_ids_out,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_grd_out_crv */ if(flg_grd_out_rct){ rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lat,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lon,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ rcd+=nco_def_var(out_id,slat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_slat,&slat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,slat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,slat_wgt_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_slat,&slat_wgt_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,slat_wgt_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,slon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_slon,&slon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,slon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !nco_grd_lat_fv */ dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lat_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_lon; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lon_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lat_wgt_nm,crd_typ_out,dmn_nbr_1D,&dmn_id_lat,&lat_wgt_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_wgt_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_lon; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd+=nco_def_var(out_id,frc_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,frc_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd+=nco_def_var(out_id,msk_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_msk_out */ } /* !flg_grd_out_rct */ /* Pre-allocate dimension ID and cnt/srt space */ int dmn_nbr_max; /* [nbr] Maximum number of dimensions variable can have in input or output */ int dmn_in_fst; /* [idx] Offset of input- relative to output-dimension due to non-MRV dimension insertion */ int dmn_nbr_rec; /* [nbr] Number of unlimited dimensions */ int *dmn_ids_rec=NULL; /* [id] Unlimited dimension IDs */ rcd+=nco_inq_ndims(in_id,&dmn_nbr_max); dmn_nbr_max++; /* Safety in case regridding adds dimension */ dmn_id_in=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* Identify all record-dimensions in input file */ rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ int flg_pck; /* [flg] Variable is packed on disk */ nco_bool has_mss_val; /* [flg] Has numeric missing value attribute */ double mss_val_dbl; /* Define regridded and copied variables in output file */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv_tbl->lst[idx_tbl].flg_mrv=True; trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ var_nm=trv.nm; /* Preserve input type in output type */ var_typ_out=trv.var_typ; /* Demote DP to SP to save space. fxm: missing value type will then be inconsistent if copied without demotion */ //if(trv.var_typ == NC_DOUBLE) var_typ_out=NC_FLOAT; else var_typ_out=trv.var_typ; dmn_nbr_in=trv.nbr_dmn; dmn_nbr_out=trv.nbr_dmn; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid_flg(out_id,var_nm,&var_id_out); /* If variable has not been defined, define it */ if(rcd != NC_NOERR){ if(trv.flg_rgr){ /* Regrid */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); dmn_in_fst=0; rcd=nco_inq_var_packing(in_id,var_id_in,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports variable \"%s\" is packed so results unpredictable. HINT: If regridded values seems weird, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,var_nm); has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,(double *)NULL); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); /* Is horizontal dimension last, i.e., most-rapidly-varying? */ if(flg_grd_in_1D && !strcmp(dmn_nm,col_nm_in)){ if(dmn_idx != dmn_nbr_in-1){ /* Unstructured input grid has col in non-MRV location (expect this with, e.g., MPAS-O/I native grid dimension-ordering */ (void)fprintf(stdout,"%s: WARNING %s reports unstructured grid spatial coordinate %s is (zero-based) dimension %d of input variable to be regridded %s which has %d dimensions. The NCO regridder does not support unstructured spatial dimensions that are not the last (i.e., most rapidly varying) dimension of an input variable, so results are likely garbage.\nHINT: Re-arrange input file dimensions to place horizontal dimension(s) last with, e.g., \'ncpdq -a time,lev,%s in.nc out.nc\' prior to calling the regridder. E3SM users: If this is an MPAS dataset with a new (unknown to ncremap) dimension, please ask Charlie to add the dimension to the ncremap dimension permutation list.\n",nco_prg_nm_get(),fnc_nm,dmn_nm,dmn_idx,var_nm,dmn_nbr_in,dmn_nm); trv_tbl->lst[idx_tbl].flg_mrv=False; } /* !dmn_idx */ } /* !flg_grd_in_1D */ if(flg_grd_in_2D && (!strcmp(dmn_nm,lat_nm_in) || !strcmp(dmn_nm,lon_nm_in))){ /* Are horizontal dimensions most-rapidly-varying? */ if(dmn_idx != dmn_nbr_in-1 && dmn_idx != dmn_nbr_in-2){ /* NB: Lat/lon input grid has lat/lon in non-MRV location (expect this with, e.g., AIRS L2 grid dimension-ordering */ (void)fprintf(stdout,"%s: WARNING %s reports lat-lon grid spatial coordinate %s is (zero-based) dimension %d of input variable to be regridded %s which has %d dimensions. The NCO regridder does not support rectangular lat-lon dimension(s) that are not the last two (i.e., most rapidly varying) dimensions of an input variable, so results are likely garbage.\nHINT: Re-arrange input file dimensions to place horizontal dimensions last with, e.g., \'ncpdq -a time,lev,lat,lon in.nc out.nc\' prior to calling the regridder.\n",nco_prg_nm_get(),fnc_nm,dmn_nm,dmn_idx,var_nm,dmn_nbr_in); trv_tbl->lst[idx_tbl].flg_mrv=False; } /* !dmn_idx */ } /* !flg_grd_in_2D */ if(flg_grd_out_1D){ if((nco_rgr_typ == nco_rgr_grd_2D_to_1D) && (!strcmp(dmn_nm,lat_nm_in) || !strcmp(dmn_nm,lon_nm_in))){ /* Replace orthogonal horizontal dimensions by unstructured horizontal dimension already defined */ if(!strcmp(dmn_nm,lat_nm_in)){ /* Replace lat with col */ dmn_id_out[dmn_idx]=dmn_id_col; dmn_cnt[dmn_idx]=col_nbr_out; } /* endif lat */ if(!strcmp(dmn_nm,lon_nm_in)){ /* Assume non-MRV dimensions are ordered lat/lon. Replace lat with col. Shift MRV dimensions to left after deleting lon. */ dmn_id_out[dmn_idx]=NC_MIN_INT; dmn_cnt[dmn_idx]=NC_MIN_INT; dmn_nbr_out--; /* Reduce output dimension position of all subsequent input dimensions by one */ if(!trv_tbl->lst[idx_tbl].flg_mrv) dmn_in_fst=-1; } /* endif lon */ }else{ /* Dimension col_nm_in has already been defined as col_nm_out, replicate all other dimensions */ if(!strcmp(dmn_nm,col_nm_in)) rcd=nco_inq_dimid_flg(out_id,col_nm_out,dmn_id_out+dmn_idx); else rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx+dmn_in_fst); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt+dmn_idx+dmn_in_fst); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt[dmn_idx+dmn_in_fst]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt[dmn_idx+dmn_in_fst],dmn_id_out+dmn_idx+dmn_in_fst); } /* !rcd */ } /* !lat && !lon */ } /* !flg_grd_out_1D */ if(flg_grd_out_2D){ if(nco_rgr_typ == nco_rgr_grd_1D_to_2D && !strcmp(dmn_nm,col_nm_in)){ /* Replace unstructured horizontal dimension by orthogonal horizontal dimensions already defined */ dmn_id_out[dmn_idx]=dmn_id_lat; dmn_id_out[dmn_idx+1]=dmn_id_lon; dmn_cnt[dmn_idx]=lat_nbr_out; dmn_cnt[dmn_idx+1]=lon_nbr_out; dmn_nbr_out++; /* Increase output dimension position of all subsequent input dimensions by one */ if(!trv_tbl->lst[idx_tbl].flg_mrv) dmn_in_fst=1; }else{ /* Dimensions lat/lon_nm_in have already been defined as lat/lon_nm_out, replicate all other dimensions */ if(!strcmp(dmn_nm,lat_nm_in)) rcd=nco_inq_dimid_flg(out_id,lat_dmn_nm_out,dmn_id_out+dmn_idx); else if(!strcmp(dmn_nm,lon_nm_in)) rcd=nco_inq_dimid_flg(out_id,lon_dmn_nm_out,dmn_id_out+dmn_idx); else rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx+dmn_in_fst); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt+dmn_idx+dmn_in_fst); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt[dmn_idx+dmn_in_fst]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt[dmn_idx+dmn_in_fst],dmn_id_out+dmn_idx+dmn_in_fst); } /* !rcd */ } /* !col */ } /* !1D_to_2D */ } /* !dmn_idx */ }else{ /* !flg_rgr */ /* Replicate non-regridded variables */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt[dmn_idx],dmn_id_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ } /* !flg_rgr */ rcd=nco_def_var(out_id,var_nm,var_typ_out,dmn_nbr_out,dmn_id_out,&var_id_out); /* Duplicate netCDF4 settings when possible */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC){ /* Deflation */ if(dmn_nbr_out > 0){ int dfl_lvl_in; /* [enm] Deflate level [0..9] */ rcd=nco_inq_var_deflate(in_id,var_id_in,&shuffle,&deflate,&dfl_lvl_in); /* Copy original deflation settings */ if(deflate || shuffle) (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl_in); /* Overwrite HDF Lempel-Ziv compression level, if requested */ if(dfl_lvl == 0) deflate=(int)False; else deflate=(int)True; /* Turn-off shuffle when uncompressing otherwise chunking requests may fail */ if(dfl_lvl == 0) shuffle=NC_NOSHUFFLE; /* Shuffle never, to my knowledge, increases filesize, so shuffle by default when manually deflating */ if(dfl_lvl >= 0) shuffle=NC_SHUFFLE; if(dfl_lvl >= 0) (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl); } /* !dmn_nbr_out */ } /* !NC_FORMAT_NETCDF4 */ (void)nco_att_cpy(in_id,out_id,var_id_in,var_id_out,PCK_ATT_CPY); if(trv.flg_rgr){ aed_mtd_crd.var_nm=var_nm; aed_mtd_crd.id=var_id_out; (void)nco_aed_prc(out_id,var_id_out,aed_mtd_crd); if(flg_cll_msr){ aed_mtd_cll_msr.var_nm=var_nm; aed_mtd_cll_msr.id=var_id_out; (void)nco_aed_prc(out_id,var_id_out,aed_mtd_cll_msr); } /* !flg_cll_msr */ } /* !flg_rgr */ } /* !rcd */ } /* !var */ } /* end idx_tbl */ /* Free pre-allocated array space */ /* col_nm_in will not otherwise be free'd if it was guessed as usual suspect */ if(col_nm_in != rgr->col_nm_in) col_nm_in=(char *)nco_free(col_nm_in); if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt) dmn_cnt=(long *)nco_free(dmn_cnt); if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); /* Define new metadata in regridded file */ if(flg_area_out){ rcd=nco_char_att_put(out_id,area_nm_out,"long_name","Solid angle subtended by gridcell"); rcd=nco_char_att_put(out_id,area_nm_out,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm_out,"units","steradian"); if(flg_grd_out_1D || flg_grd_out_crv) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); att_val=(char *)nco_calloc((strlen(lat_dmn_nm_out)+strlen(lon_dmn_nm_out)+8L),sizeof(char)); (void)sprintf(att_val,"%s, %s: sum",lat_dmn_nm_out,lon_dmn_nm_out); rcd=nco_char_att_put(out_id,area_nm_out,"cell_mathods",att_val); if(att_val) att_val=(char *)nco_free(att_val); } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd=nco_char_att_put(out_id,frc_nm_out,"long_name","Fraction of gridcell valid on destination grid"); if(flg_grd_out_1D || flg_grd_out_crv) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); att_val=(char *)nco_calloc((strlen(lat_dmn_nm_out)+strlen(lon_dmn_nm_out)+8L),sizeof(char)); (void)sprintf(att_val,"%s, %s: sum",lat_dmn_nm_out,lon_dmn_nm_out); rcd=nco_char_att_put(out_id,frc_nm_out,"cell_mathods",att_val); } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd=nco_char_att_put(out_id,msk_nm_out,"long_name","Mask (0 = invalid destination, 1 = valid destination)"); if(flg_grd_out_1D || flg_grd_out_crv) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); } /* !flg_msk_out */ rcd=nco_char_att_put(out_id,lat_nm_out,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lat_nm_out,"standard_name","latitude"); rcd=nco_char_att_put(out_id,lat_nm_out,"units","degrees_north"); // 20200205: Attach "axis" attribute to single-dimensional geospatial coordinates not to two-dimensional coordinate variables per CF Conventions section 5.2 if(!flg_grd_out_crv) rcd=nco_char_att_put(out_id,lat_nm_out,"axis","Y"); double vld_min; vld_min=-90.0; att_nm=strdup("valid_min"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lat_nm_out; aed_mtd.id=lat_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_min; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lat_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); double vld_max; vld_max=90.0; att_nm=strdup("valid_max"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lat_nm_out; aed_mtd.id=lat_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_max; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lat_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,lat_nm_out,"bounds",lat_bnd_nm_out); if(flg_grd_out_rct) att_val=strdup("Gridcell latitude interfaces"); else att_val=strdup("Gridcell latitude vertices"); rcd=nco_char_att_put(out_id,lat_bnd_nm_out,"long_name",att_val); rcd=nco_char_att_put(out_id,lon_nm_out,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lon_nm_out,"standard_name","longitude"); rcd=nco_char_att_put(out_id,lon_nm_out,"units","degrees_east"); // 20200205: Attach "axis" attribute to single-dimensional geospatial coordinates not to two-dimensional coordinate variables per CF Conventions section 5.2 if(!flg_grd_out_crv) rcd=nco_char_att_put(out_id,lon_nm_out,"axis","X"); /* UGRID Conventions define "topology" and "modulo" attributes https://github.com/ugrid-conventions/ugrid-conventions My understanding is these should only be utilized for global grids */ if(nco_rgr_typ == nco_rgr_grd_2D_to_2D){ /* fxm: change this to check whether lon_spn >= 360 or nco_grd_xtn == global */ att_nm=strdup("modulo"); double modulo=360.0; aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&modulo; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,lon_nm_out,"topology","circular"); } /* !nco_rgr_grd_2D_to_2D */ if(lon_ctr_out[0] >= 0.0) vld_min=0.0; else vld_min=-180.0; att_nm=strdup("valid_min"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_min; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); if(lon_ctr_out[0] >= 0.0) vld_max=360.0; else vld_max=180.0; att_nm=strdup("valid_max"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_max; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,lon_nm_out,"bounds",lon_bnd_nm_out); att_nm=strdup("bounds"); att_val=lon_bnd_nm_out; aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=strlen(att_val); aed_mtd.type=NC_CHAR; aed_mtd.val.cp=att_val; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); if(flg_grd_out_rct) att_val=strdup("Gridcell longitude interfaces"); else att_val=strdup("Gridcell longitude vertices"); rcd=nco_char_att_put(out_id,lon_bnd_nm_out,"long_name",att_val); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ rcd=nco_char_att_put(out_id,slat_nm_out,"long_name","Latitude for staggered FV grid"); rcd=nco_char_att_put(out_id,slat_nm_out,"units","degrees_north"); rcd=nco_char_att_put(out_id,slat_wgt_nm_out,"long_name","Latitude weights for staggered FV grid"); rcd=nco_char_att_put(out_id,slon_nm_out,"long_name","Longitude for staggered FV grid"); rcd=nco_char_att_put(out_id,slon_nm_out,"units","degrees_east"); } /* !nco_grd_lat_fv */ if(flg_grd_out_rct) rcd=nco_char_att_put(out_id,lat_wgt_nm,"long_name","Latitude quadrature weights (normalized to sum to 2.0 on global grids)"); rcd=nco_char_att_put(out_id,NULL,"map_file",fl_in); rcd=nco_char_att_put(out_id,NULL,"input_file",rgr->fl_in); /* Annotate persistent metadata that should appear last in attribute list */ if(flg_grd_out_1D){ if(flg_area_out) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); if(flg_frc_out_wrt) rcd=nco_char_att_put(out_id,frc_nm_out,att_nm_crd,att_val_crd); if(flg_msk_out) rcd=nco_char_att_put(out_id,msk_nm_out,att_nm_crd,att_val_crd); } /* !flg_grd_out_1D */ /* Persistent metadata */ if(att_nm_crd) att_nm_crd=(char *)nco_free(att_nm_crd); if(att_val_crd) att_val_crd=(char *)nco_free(att_val_crd); if(flg_cll_msr){ if(att_nm_cll_msr) att_nm_cll_msr=(char *)nco_free(att_nm_cll_msr); if(att_val_cll_msr) att_val_cll_msr=(char *)nco_free(att_val_cll_msr); } /* !flg_cll_msr */ if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ if(slat_nm_out) slat_nm_out=(char *)nco_free(slat_nm_out); if(slat_wgt_nm_out) slat_wgt_nm_out=(char *)nco_free(slat_wgt_nm_out); if(slon_nm_out) slon_nm_out=(char *)nco_free(slon_nm_out); } /* !nco_grd_lat_fv */ /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Begin data mode */ (void)nco_enddef(out_id); /* Write new coordinates and variables to regridded file */ if(flg_grd_out_1D){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,lat_out_id,dmn_srt_out,dmn_cnt_tuo,lat_ctr_out,crd_typ_out); dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,lon_out_id,dmn_srt_out,dmn_cnt_tuo,lon_ctr_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=col_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt_out,dmn_cnt_tuo,lat_bnd_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=col_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt_out,dmn_cnt_tuo,lon_bnd_out,crd_typ_out); if(flg_area_out){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,area_out_id,dmn_srt_out,dmn_cnt_tuo,area_out,crd_typ_out); } /* !flg_area_out */ if(flg_msk_out){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,msk_out_id,dmn_srt_out,dmn_cnt_tuo,msk_out,crd_typ_out); } /* !flg_msk_out */ } /* !flg_grd_out_1D */ if(flg_grd_out_crv){ dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=lon_nbr_out; (void)nco_put_vara(out_id,lat_out_id,dmn_srt_out,dmn_cnt_tuo,lat_ctr_out,crd_typ_out); (void)nco_put_vara(out_id,lon_out_id,dmn_srt_out,dmn_cnt_tuo,lon_ctr_out,crd_typ_out); if(flg_area_out){ (void)nco_put_vara(out_id,area_out_id,dmn_srt_out,dmn_cnt_tuo,area_out,crd_typ_out); } /* !flg_area_out */ if(flg_frc_out_wrt){ (void)nco_put_vara(out_id,frc_out_id,dmn_srt_out,dmn_cnt_tuo,frc_out,crd_typ_out); } /* !flg_frc_out_wrt */ if(flg_msk_out){ (void)nco_put_vara(out_id,msk_out_id,dmn_srt_out,dmn_cnt_tuo,msk_out,crd_typ_out); } /* !flg_msk_out */ dmn_srt_out[0]=dmn_srt_out[1]=dmn_srt_out[2]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=lon_nbr_out; dmn_cnt_tuo[2]=bnd_nbr_out; /* NB: 20160803 Semantically confusing---curvilinear grids must write *_crn_out data into *_bnd_out arrays */ (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt_out,dmn_cnt_tuo,lat_crn_out,crd_typ_out); (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt_out,dmn_cnt_tuo,lon_crn_out,crd_typ_out); } /* !flg_grd_out_crv */ if(flg_grd_out_rct){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=lat_nbr_out; (void)nco_put_vara(out_id,lat_out_id,dmn_srt_out,dmn_cnt_tuo,lat_ctr_out,crd_typ_out); dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=lon_nbr_out; (void)nco_put_vara(out_id,lon_out_id,dmn_srt_out,dmn_cnt_tuo,lon_ctr_out,crd_typ_out); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=slat_nbr_out; (void)nco_put_vara(out_id,slat_out_id,dmn_srt_out,dmn_cnt_tuo,slat_ctr_out,crd_typ_out); (void)nco_put_vara(out_id,slat_wgt_id,dmn_srt_out,dmn_cnt_tuo,slat_wgt_out,crd_typ_out); dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=slon_nbr_out; (void)nco_put_vara(out_id,slon_out_id,dmn_srt_out,dmn_cnt_tuo,slon_ctr_out,crd_typ_out); if(slat_ctr_out) slat_ctr_out=(double *)nco_free(slat_ctr_out); if(slat_wgt_out) slat_wgt_out=(double *)nco_free(slat_wgt_out); if(slon_ctr_out) slon_ctr_out=(double *)nco_free(slon_ctr_out); } /* !nco_grd_lat_fv */ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=lat_nbr_out; (void)nco_put_vara(out_id,lat_wgt_id,dmn_srt_out,dmn_cnt_tuo,lat_wgt_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt_out,dmn_cnt_tuo,lat_bnd_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lon_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt_out,dmn_cnt_tuo,lon_bnd_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=lon_nbr_out; if(flg_area_out){ (void)nco_put_vara(out_id,area_out_id,dmn_srt_out,dmn_cnt_tuo,area_out,crd_typ_out); } /* !flg_area_out */ if(flg_frc_out_wrt){ (void)nco_put_vara(out_id,frc_out_id,dmn_srt_out,dmn_cnt_tuo,frc_out,crd_typ_out); } /* !flg_frc_out_wrt */ if(flg_msk_out){ (void)nco_put_vara(out_id,msk_out_id,dmn_srt_out,dmn_cnt_tuo,msk_out,crd_typ_out); } /* !flg_msk_out */ } /* !flg_grd_out_rct */ /* Regrid or copy variable values */ const double wgt_vld_thr=rgr->wgt_vld_thr; /* [frc] Weight threshold for valid destination value */ const nco_bool flg_rnr=rgr->flg_rnr; /* [flg] Renormalize destination values by valid area */ char *sgs_frc_nm=NULL; char *sgs_msk_nm=NULL; double *sgs_frc_in=NULL; double *sgs_frc_out=NULL; double *var_val_dbl_in=NULL; double *var_val_dbl_out=NULL; double *wgt_vld_out=NULL; double var_val_crr; int *tally=NULL; /* [nbr] Number of valid (non-missing) values */ int lvl_idx; /* [idx] Level index */ int lvl_nbr; /* [nbr] Number of levels */ int thr_idx; /* [idx] Thread index */ size_t dst_idx; size_t idx_in; /* [idx] Input grid index */ size_t idx_out; /* [idx] Output grid index */ size_t var_sz_in; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t var_sz_out; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t val_in_fst; /* [nbr] Number of elements by which current N-D slab input values are offset from origin */ size_t val_out_fst; /* [nbr] Number of elements by which current N-D slab output values are offset from origin */ /* 20190322: Prior to entering OpenMP loop, collect specified SGS information */ const double sgs_nrm=rgr->sgs_nrm; /* [frc] Sub-gridscale normalization */ if(rgr->sgs_frc_nm){ /* Normalization test: fl_in=20181217.CNTL_CNPCTC1850_OIBGC.ne30_oECv3.edison.clm2.h0.2000-12.nc /bin/cp -f ${DATA}/hdf/${fl_in} ~/elm_raw.nc ncremap -P sgs -v FSDS,TBOT,GPP -a aave -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/cmip6_180x360_scrip.20181001.nc ~/elm_raw.nc ~/elm_sgs.nc # Original SGS method ncks -A -v grid_area ${DATA}/grids/ne30np4_pentagons.091226.nc ~/elm_sgs.nc ncremap -P gsg -v FSDS,TBOT,GPP -m ${DATA}/maps/map_ne30np4_to_cmip6_180x360_aave.20181001.nc ~/elm_raw.nc ~/elm_gsg.nc # New SGS method */ if(rgr->sgs_msk_nm) sgs_msk_nm=(char *)strdup(rgr->sgs_msk_nm); sgs_frc_nm=(char *)strdup(rgr->sgs_frc_nm); var_nm=sgs_frc_nm; var_typ_rgr=NC_DOUBLE; /* NB: Regrid in double precision */ var_typ_out=NC_DOUBLE; /* NB: sgs_frc_out must be double precision */ var_sz_in=1L; /* Compute from scratch to be sure it matches grd_sz_in */ var_sz_out=grd_sz_out; /* Assume this holds */ char *fl_sgs=NULL; /* [sng] External sub-gridscale file name */ int sgs_id; /* [id] netCDF file ID for external sub-gridscale file */ sgs_id=in_id; if((rcd=nco_inq_varid_flg(sgs_id,var_nm,&var_id_in)) != NC_NOERR){ /* If sgs_frc_nm is not in input file then search for it in external area file */ char *sls_ptr; /* [sng] Pointer to last slash character (' ') */ sls_ptr=strrchr(var_nm,'/'); if(!sls_ptr){ (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unable to find sgs_frc_nm = %s in current input file, and unable to identify filename (ending with slash '/') portion of that string to serve as local external file for sgs_frc input, exiting\n",nco_prg_nm_get(),fnc_nm,sgs_frc_nm); nco_exit(EXIT_FAILURE); } /* !sls_ptr */ sgs_frc_nm=(char *)strdup(sls_ptr+1L); /* Copy variable-name portion of string */ *sls_ptr='\0'; /* NULL-terminate filename */ fl_sgs=(char *)strdup(var_nm); var_nm=sgs_frc_nm; /* NB: too tricky? */ rcd=nco_open(fl_sgs,NC_NOWRITE,&sgs_id); if((rcd=nco_inq_varid_flg(sgs_id,var_nm,&var_id_in)) != NC_NOERR){ (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unable to find sgs_frc_nm = \"%s\" in local external file %s, exiting\n",nco_prg_nm_get(),fnc_nm,sgs_frc_nm,fl_sgs); nco_exit(EXIT_FAILURE); } /* !rcd */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s obtaining sgs_frc = %s from file %s\n",nco_prg_nm_get(),fnc_nm,sgs_frc_nm,fl_sgs); } /* !rcd */ rcd=nco_inq_varndims(sgs_id,var_id_in,&dmn_nbr_in); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_id_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(sgs_id,var_id_in,dmn_id_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(sgs_id,dmn_id_in[dmn_idx],dmn_cnt_in+dmn_idx); var_sz_in*=dmn_cnt_in[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ if(var_sz_in != grd_sz_in){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") requires that sgs_frc = %s be same size as spatial grid but var_sz_in = %lu != %lu = grd_sz_in\n",nco_prg_nm_get(),fnc_nm,var_nm,var_sz_in,grd_sz_in); nco_exit(EXIT_FAILURE); } /* !var_sz_in */ /* Missing value setup (NB: ELM landfrac has _FillValue and is _FillValue where masked */ has_mss_val=nco_mss_val_get_dbl(sgs_id,var_id_in,&mss_val_dbl); sgs_frc_in=(double *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() sgs_frc_in value buffer"); rcd=nco_get_vara(sgs_id,var_id_in,dmn_srt,dmn_cnt_in,sgs_frc_in,var_typ_rgr); /* If sgs_frc comes from external local file, close it now */ if(fl_sgs){ rcd=nco_close(sgs_id); fl_sgs=(char *)nco_free(fl_sgs); } /* !fl_sgs */ /* Initialize output */ sgs_frc_out=(double *)nco_malloc_dbg(grd_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() sgs_frc_out value buffer"); /* Initialize and regrid sgs_frc_out 20190907: sgs_frc_in (landfrac) is _FillValue (1.0e36) for ELM datasets in all masked gridcells, and is always positive definite (never zero) in all unmasked gridcells because it it a true area. ELM sgs_frc_out is always positive definite gridcell area everywhere, with no missing values and no zero values. 20190910: MPAS-Seaice datasets have no mask, and sgs_frc_in (timeMonthly_avg_iceAreaCell) is never (ncatted-appended) _FillValue (-9.99999979021477e+33) and is usually zero because it is time-mean area-fraction of sea ice which only exists in polar regions. MPAS-Seaice sgs_frc_out is zero in all gridcells without sea-ice. Regardless of input source, following blocks guarantee that sgs_frc_out is defined everywhere, is never a missing value (sgs_frc_out is zero where sgs_frc_in may have been _FillValue), and is always safe to multiply and normalize by sgs_frc_out in main regridding loop */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) sgs_frc_out[dst_idx]=0.0; if(!has_mss_val) for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) sgs_frc_out[row_dst_adr[lnk_idx]]+=sgs_frc_in[col_src_adr[lnk_idx]]*wgt_raw[lnk_idx]; if(has_mss_val) for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) if((var_val_crr=sgs_frc_in[col_src_adr[lnk_idx]]) != mss_val_dbl) sgs_frc_out[row_dst_adr[lnk_idx]]+=var_val_crr*wgt_raw[lnk_idx]; /* Sanity check sgs_frc_out */ if(nco_dbg_lvl_get() >= nco_dbg_fl){ /* 20190326: sgs_frc expressed as a fraction must never exceed sgs_nrm CICE expresses sgs_frc (aice) in percent, i.e., sgs_nrm=100.0 Sum total value of sgs_frc (as opposed to gridcell_area) depends on grid resolution */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ /* 20190907: Approximate comparison because rounding causes frequent exceedances of sgs_nrm by epsilon ~ 1.0e-15 */ if((float)sgs_frc_out[dst_idx] > sgs_nrm) (void)fprintf(stdout,"%s: INFO %s reports sgs_frc_out[%lu] = %19.15f > %g = sgs_nrm\n",nco_prg_nm_get(),fnc_nm,dst_idx,sgs_frc_out[dst_idx],sgs_nrm); } /* !dst_idx */ } /* !dbg */ // for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ // (void)fprintf(stdout,"%s: INFO %s reports sgs_frc_out[%lu] = %19.15f\n",nco_prg_nm_get(),fnc_nm,dst_idx,sgs_frc_out[dst_idx]); // } /* !dst_idx */ if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); } /* !sgs_frc_nm */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"Regridding progress: # means regridded, ~ means copied\n"); /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped as shared in parallel clause */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ /* OpenMP notes: default(none): GCC9.x does not accept this (https://github.com/nco/nco/issues/114) perhaps because of fp_stdout/stderr? Intel accepts it. firstprivate(): Pointers that could be inadvertently free()'d if they lost their NULL-initialization private(): Almost everything else shared(): uggh...shared clause depends on both compiler and compiler-version 1. All const variables are default shared for gcc >= 4.9.2, 2. fnc_nm (only!) must be explicit shared for g++ 4.6.3 (travis) 3. flg_rnr,fnc_nm,wgt_vld_thr must be explicit shared for icc 13.1.3 (rhea) 4. assert() cannot be used in OpenMP blocks 5. Good discussion of "const" variables in shared() clause here http://jakascorner.com/blog/2016/07/omp-default-none-and-const.html 20200221: fxm Revisit default(none) in light of above article */ #ifdef __GNUG__ # define GCC_LIB_VERSION ( __GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__ ) # if GCC_LIB_VERSION < 490 # define GXX_OLD_OPENMP_SHARED_TREATMENT 1 # endif /* 480 */ # if GCC_LIB_VERSION >= 900 # define GXX_WITH_OPENMP5_GPU_SUPPORT 1 # endif /* 900 */ #endif /* !__GNUC__ */ #if defined( __INTEL_COMPILER) # pragma omp parallel for default(none) firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_frc_nrm,flg_rnr,fnc_nm,frc_out,lnk_nbr,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw,wgt_vld_thr) #else /* !__INTEL_COMPILER */ # ifdef GXX_OLD_OPENMP_SHARED_TREATMENT # pragma omp parallel for default(none) firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_frc_nrm,fnc_nm,frc_out,lnk_nbr,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw) # else /* !old g++ */ # if defined(GXX_WITH_OPENMP5_GPU_SUPPORT) && 0 # pragma omp target teams distribute parallel for firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_frc_nrm,frc_out,lnk_nbr,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw) # else # pragma omp parallel for firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_frc_nrm,frc_out,lnk_nbr,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw) # endif /* !GCC >= 9.0 */ # endif /* !GCC < 4.9 */ #endif /* !__INTEL_COMPILER */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; thr_idx=omp_get_thread_num(); in_id=trv_tbl->in_id_arr[thr_idx]; #ifdef _OPENMP if(nco_dbg_lvl_get() >= nco_dbg_grp && !thr_idx && !idx_tbl) (void)fprintf(fp_stdout,"%s: INFO %s reports regrid loop uses %d thread%s\n",nco_prg_nm_get(),fnc_nm,omp_get_num_threads(),(omp_get_num_threads() > 1) ? "s" : ""); if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO thread = %d, idx_tbl = %d, nm = %s\n",nco_prg_nm_get(),thr_idx,idx_tbl,trv.nm); #endif /* !_OPENMP */ if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s%s ",trv.flg_rgr ? "#" : "~",trv.nm); if(trv.flg_rgr){ /* Regrid variable */ var_nm=trv.nm; var_typ_rgr=NC_DOUBLE; /* NB: Perform regridding in double precision */ var_typ_out=trv.var_typ; /* NB: Output type in file is same as input type */ var_sz_in=1L; var_sz_out=1L; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid(out_id,var_nm,&var_id_out); rcd=nco_inq_varndims(in_id,var_id_in,&dmn_nbr_in); rcd=nco_inq_varndims(out_id,var_id_out,&dmn_nbr_out); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_id_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); rcd=nco_inq_vardimid(out_id,var_id_out,dmn_id_out); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_in+dmn_idx); var_sz_in*=dmn_cnt_in[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ rcd=nco_inq_dimlen(out_id,dmn_id_out[dmn_idx],dmn_cnt_out+dmn_idx); if(dmn_cnt_out[dmn_idx] == 0L){ /* No records have been written, so overwrite zero output record size with input record size */ char dmn_rec_nm[NC_MAX_NAME]; /* [sng] Record dimension name */ int dmn_rec_id_in; rcd=nco_inq_dimname(out_id,dmn_id_out[dmn_idx],dmn_rec_nm); rcd=nco_inq_dimid(in_id,dmn_rec_nm,&dmn_rec_id_in); rcd=nco_inq_dimlen(in_id,dmn_rec_id_in,dmn_cnt_out+dmn_idx); } /* !dmn_cnt_out */ var_sz_out*=dmn_cnt_out[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ /* Compute number and size of non-lat/lon or non-col dimensions (e.g., level, time, species, wavelength) Denote their convolution by level or 'lvl' for shorthand There are lvl_nbr elements for each lat/lon or col position 20151011: Until today assume lat/lon and col are most-rapidly varying dimensions 20151011: Until today lvl_nbr missed last non-spatial dimension for 1D output */ lvl_nbr=1; /* Simple prescription of lvl_nbr works when horizontal dimension(s) is/are MRV */ for(dmn_idx=0;dmn_idx<dmn_nbr_out-dmn_nbr_hrz_crd;dmn_idx++) lvl_nbr*=dmn_cnt_out[dmn_idx]; /* Missing value setup */ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); /* Memory requirements of next four malloc's (i.e., exclusive of wgt_raw) sum to ~7*sizeof(uncompressed var) for NC_FLOAT and ~3.5*sizeof(uncompressed var) for NC_DOUBLE */ var_val_dbl_in=(double *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() input value buffer"); var_val_dbl_out=(double *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() output value buffer"); if(has_mss_val) tally=(int *)nco_malloc_dbg(var_sz_out*nco_typ_lng(NC_INT),fnc_nm,"Unable to malloc() tally buffer"); if(has_mss_val && flg_rnr) wgt_vld_out=(double *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() output renormalization weight buffer"); /* Initialize output */ (void)memset(var_val_dbl_out,0,var_sz_out*nco_typ_lng(var_typ_rgr)); if(has_mss_val) (void)memset(tally,0,var_sz_out*nco_typ_lng(NC_INT)); if(wgt_vld_out) (void)memset(wgt_vld_out,0,var_sz_out*nco_typ_lng(var_typ_rgr)); /* Obtain input variable */ rcd=nco_get_vara(in_id,var_id_in,dmn_srt,dmn_cnt_in,var_val_dbl_in,var_typ_rgr); /* 20150914: Intensive variables require normalization, extensive do not Intensive variables (temperature, wind speed, mixing ratio) do not depend on gridcell boundaries Extensive variables (population, counts, numbers of things) depend on gridcell boundaries Extensive variables are the exception in models, yet are commonly used for sampling information, e.g., number of photons, number of overpasses Pass extensive variable list to NCO with, e.g., --xtn=TSurfStd_ct,... 20190420: Remove languishing, unfinished intensive variable code */ clock_t tm_srt; /* [us] Microseconds at start */ clock_t tm_end; /* [us] Microseconds at end */ float tm_drn; /* [s] Seconds elapsed */ if(nco_dbg_lvl_get() >= nco_dbg_var) tm_srt=clock(); /* This first block is for "normal" variables without sub-gridscale fractions */ if(!sgs_frc_out){ /* Apply weights */ if(!has_mss_val){ if(lvl_nbr == 1){ /* Weight single-level fields without missing values */ #ifdef ENABLE_GPU # pragma omp target data map(to:col_src_adr[0:lnk_nbr],row_dst_adr[0:lnk_nbr],var_val_dbl_in[0:var_sz_in],wgt_raw[0:lnk_nbr]) map(tofrom:var_val_dbl_out[0:var_sz_out]) # pragma omp target teams distribute parallel for simd schedule(static,1) #else /* !ENABLE_GPU */ # if ( __GNUC__ >= 8 ) || ( __clang_major__ >= 8 ) # pragma omp simd # endif /* !__GNUC__ */ #endif /* !ENABLE_GPU */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) var_val_dbl_out[row_dst_adr[lnk_idx]]+=var_val_dbl_in[col_src_adr[lnk_idx]]*wgt_raw[lnk_idx]; }else{ val_in_fst=0L; val_out_fst=0L; /* Weight multi-level fields without missing values */ #ifdef ENABLE_GPU # pragma omp target data map(to:col_src_adr[0:lnk_nbr],row_dst_adr[0:lnk_nbr],var_val_dbl_in[0:var_sz_in],wgt_raw[0:lnk_nbr]) map(tofrom:var_val_dbl_out[0:var_sz_out]) # pragma omp parallel for reduction(+:val_in_fst,val_out_fst) #endif /* !ENABLE_GPU */ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ //if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(fp_stdout,"%s lvl_idx = %d val_in_fst = %li, val_out_fst = %li\n",trv.nm,lvl_idx,val_in_fst,val_out_fst); #ifdef ENABLE_GPU # pragma omp target teams distribute parallel for simd schedule(static,1) #else /* !ENABLE_GPU */ # if ( __GNUC__ >= 8 ) || ( __clang_major__ >= 8 ) # pragma omp simd # endif /* !__GNUC__ */ #endif /* !ENABLE_GPU */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) var_val_dbl_out[row_dst_adr[lnk_idx]+val_out_fst]+=var_val_dbl_in[col_src_adr[lnk_idx]+val_in_fst]*wgt_raw[lnk_idx]; val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ }else{ /* has_mss_val */ if(lvl_nbr == 1){ /* Weight single-level fields with missing values */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]; idx_out=row_dst_adr[lnk_idx]; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]; if(wgt_vld_out) wgt_vld_out[idx_out]+=wgt_raw[lnk_idx]; tally[idx_out]++; } /* !mss_val_dbl */ } /* !lnk_idx */ }else{ /* lvl_nbr > 1 */ val_in_fst=0L; val_out_fst=0L; /* Weight multi-level fields with missing values */ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]+val_in_fst; idx_out=row_dst_adr[lnk_idx]+val_out_fst; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]; if(wgt_vld_out) wgt_vld_out[idx_out]+=wgt_raw[lnk_idx]; tally[idx_out]++; } /* !mss_val_dbl */ } /* !lnk_idx */ val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ } /* !has_mss_val */ if(!has_mss_val){ /* frc_dst = frc_out = dst_frac = frac_b contains non-unity elements and normalization type is "destarea" or "dstarea" or "none" When this occurs for conservative remapping, follow "destarea" normalization procedure See SCRIP manual p. 11 and http://www.earthsystemmodeling.org/esmf_releases/public/last, specifically http://www.earthsystemmodeling.org/esmf_releases/public/last/ESMF_refdoc/node3.html#SECTION03029000000000000000 "frac_a: When a conservative regridding method is used, this contains the fraction of each source cell that participated in the regridding. When a non-conservative regridding method is used, this array is set to 0.0. frac_b: When a conservative regridding method is used, this contains the fraction of each destination cell that participated in the regridding. When a non-conservative regridding method is used, this array is set to 1.0 where the point participated in the regridding (i.e. was within the unmasked source grid), and 0.0 otherwise. If the first-order conservative interpolation method is specified ("-m conserve") then the destination field may need to be adjusted by the destination fraction (frac_b). This should be done if the normalization type is ``dstarea'' (sic, really "destarea") and if the destination grid extends outside the unmasked source grid. If it isn't known if the destination extends outside the source, then it doesn't hurt to apply the destination fraction. (If it doesn't extend outside, then the fraction will be 1.0 everywhere anyway.) The following code shows how to adjust an already interpolated destination field (dst_field) by the destination fraction. The variables n_b, and frac_b are from the weight file: ! Adjust destination field by fraction do i=1, n_b if (frac_b(i) .ne. 0.0) then dst_field(i)=dst_field(i)/frac_b(i) endif enddo" NB: Non-conservative interpolation methods (e.g., bilinear) should NOT apply this normalization (theoretically there is no danger in doing so because frc_out == 1 always for all gridcells that participate in bilinear remapping and frc_out == 0 otherwise) NCO's renormalization procedure below is similar to the ESMF-recommended procedure above. However, users can control NCO renormalization with, e.g., --rnr_thr=0.1, or override it completely with --rnr_thr=none. Moreover, frac_b == frc_dst is determined solely by solely by gridcell binary mask overlaps during weight generation. It is time-invariant and 2D. Missing values (e.g., AOD) can vary in time and can be 3D (or N-D) and so can wgt_vld_out. Hence NCO renormalization is more flexible. flg_frc_nrm (i.e., ESMF-recommended) normalization makes fields pretty for graphics, yet is non-conservative because e.g., MPAS Ocean gridcells projected onto global uniform grids would have their SSTs normalized for prettiness on coastal gridpoints, which is inherently non-conservative. 20190912: Make "ESMF renormalization" of fields without missing values (i.e., "destarea") opt-in rather than default "destarea" and frac_b = frc_dst together set flg_frc_nrm Formerly flg_frc_nrm triggered ESMF renormalization by default Now flg_frc_nrm and user-explicitly-set --rnr_thr to [0.0,1.0] must both be true to trigger it This keep conservative maps conservative by default NB: This "ESMF renormalization" normalizes by frac_b == frc_dst (not by wgt_vld_out) regardless of rnr_thr 20151018: Avoid double-normalizing by only executing fractional normalization (flg_frc_nrm) block when !has_mss_val, and valid area normalization when has_mss_val */ if(flg_frc_nrm){ /* Only renormalize when frac_b < 1.0 (because frac_b == 1.0 does nothing) */ if(flg_rnr){ /* 20190912: Only renormalize when user explicitly requests it (because renormalization is non-conservative). Prior to today, renormalization was by default, henceforth it is opt-in. */ if(lvl_nbr == 1){ /* Fractionally renormalize single-level fields without missing values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]/=frc_out[dst_idx]; }else{ /* Fractionally renormalize multi-level fields without missing values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ if(frc_out[dst_idx] != 0.0){ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ var_val_dbl_out[dst_idx+lvl_idx*grd_sz_out]/=frc_out[dst_idx]; } /* !lvl_idx */ } /* !frc_out */ } /* !dst_idx */ } /* lvl_nbr > 1 */ } /* !flg_rnr */ } /* !flg_frc_nrm */ } /* !has_mss_val */ if(has_mss_val){ /* NCL and ESMF treatment of weights and missing values described at https://www.ncl.ucar.edu/Applications/ESMF.shtml#WeightsAndMasking http://earthsystemmodeling.org/esmf_releases/non_public/ESMF_6_1_1/ESMF_refdoc/node5.html#SECTION05012600000000000000 NCO implements one of two procedures: "conservative" or "renormalized" The "conservative" algorithm uses all valid data from the input grid on the output grid Destination cells receive the weighted valid values of the source cells This is conservative because the global integrals of the source and destination fields are equal The "renormalized" algorithm divides the destination value by the sum of the valid weights This returns "reasonable" values, i.e., the mean of the valid input values However, renormalization is equivalent to extrapolating valid data to missing regions Hence the input and output integrals are unequal and the regridding is not conservative */ /* In fields with missing value, destination cells with no accumulated weight are missing value */ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(!tally[dst_idx]) var_val_dbl_out[dst_idx]=mss_val_dbl; if(flg_rnr){ // if(nco_dbg_lvl_get() >= nco_dbg_quiet) (void)fprintf(fp_stdout,"%s: DEBUG renormalization for %s uses flg_rnr block\n",nco_prg_nm_get(),var_nm); if(wgt_vld_thr == 0.0){ /* Renormalize cells with no threshold by valid accumulated weight */ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(tally[dst_idx]) var_val_dbl_out[dst_idx]/=wgt_vld_out[dst_idx]; }else{ /* Renormalize cells with threshold by valid accumulated weight if weight exceeds threshold */ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(wgt_vld_out[dst_idx] >= wgt_vld_thr){var_val_dbl_out[dst_idx]/=wgt_vld_out[dst_idx];}else{var_val_dbl_out[dst_idx]=mss_val_dbl;} } /* !wgt_vld_thr */ } /* !flg_rnr */ } /* !has_mss_val */ } /* !sgs_frc_out */ /* Variables with sub-gridscale fractions require "double-weighting" and normalization */ if(sgs_frc_out){ if(!strcmp(var_nm,sgs_frc_nm)){ /* Copy shared variable sgs_frc_out that was regridded before OpenMP loop 20190911: Reasons to copy sgs_frc_out into sgs_frc_nm data include speed, consistency, and well-definedness of sgs_frc_out. One reason to regrid sgs_frc_nm here is consistency with original, raw dataset: ELM landfrac is masked so regridding it here (rather than using sgs_frc_out) would produce a regridded dataset more identical to raw ELM output. The same can be said for CICE (I think). MPAS cellMask and timeMonthly_avg_iceAreaCell are not masked, and so should produce the same values as sgs_frc_out if regridded here. */ memcpy(var_val_dbl_out,sgs_frc_out,grd_sz_out*nco_typ_lng(var_typ_rgr)); }else if(sgs_msk_nm && !strcmp(var_nm,sgs_msk_nm)){ /* Compute binary mask directly from shared sgs_frc_out (guaranteed to be all valid values) */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]=1.0; }else{ /* !sgs_msk_nm */ /* "Double-weight" all other sub-gridscale input values by sgs_frc_in and overlap weight, normalize by sgs_frc_out */ if(!has_mss_val){ if(lvl_nbr == 1){ /* SGS-regrid single-level fields without missing values */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) var_val_dbl_out[row_dst_adr[lnk_idx]]+=var_val_dbl_in[col_src_adr[lnk_idx]]*wgt_raw[lnk_idx]*sgs_frc_in[col_src_adr[lnk_idx]]; /* NB: MPAS-Seaice dataset sgs_frc_out is usually zero in non-polar regions */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]/=sgs_frc_out[dst_idx]; }else{ /* lvl_nbr > 1 */ /* SGS-regrid multi-level fields without missing values */ val_in_fst=0L; val_out_fst=0L; for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]; idx_out=row_dst_adr[lnk_idx]; var_val_dbl_out[idx_out+val_out_fst]+=var_val_dbl_in[idx_in+val_in_fst]*wgt_raw[lnk_idx]*sgs_frc_in[idx_in]; } /* !lnk_idx */ /* Normalize current level values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx+val_out_fst]/=sgs_frc_out[dst_idx]; val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ }else{ /* !has_mss_val */ if(lvl_nbr == 1){ /* SGS-regrid single-level fields with missing values */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]; idx_out=row_dst_adr[lnk_idx]; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]*sgs_frc_in[idx_in]; tally[idx_out]++; } /* !mss_val_dbl */ } /* !lnk_idx */ /* NB: Normalization clause is complex to support sgs_frc_out from both ELM and MPAS-Seaice */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(!tally[dst_idx]){var_val_dbl_out[dst_idx]=mss_val_dbl;}else{if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]/=sgs_frc_out[dst_idx];} }else{ /* lvl_nbr > 1 */ /* SGS-regrid multi-level fields with missing values */ val_in_fst=0L; val_out_fst=0L; for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]+val_in_fst; idx_out=row_dst_adr[lnk_idx]+val_out_fst; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]*sgs_frc_in[col_src_adr[lnk_idx]]; tally[idx_out]++; } /* !mss_val_dbl */ } /* !lnk_idx */ /* Normalize current level values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ idx_out=dst_idx+val_out_fst; if(!tally[idx_out]){var_val_dbl_out[idx_out]=mss_val_dbl;}else{if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[idx_out]/=sgs_frc_out[dst_idx];} } /* dst_idx */ val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ } /* !has_mss_val */ } /* !sgs_msk_nm */ } /* !sgs_frc_out */ if(nco_dbg_lvl_get() >= nco_dbg_var){ tm_end=clock(); tm_drn=(float)(tm_end-tm_srt)/CLOCKS_PER_SEC; (void)fprintf(fp_stdout,"%s: INFO Compute time for %s (thread %d/%d): %g s\n",nco_prg_nm_get(),trv.nm,thr_idx,omp_get_num_threads(),tm_drn); } /* !dbg */ #pragma omp critical { /* begin OpenMP critical */ // rcd=nco_put_var(out_id,var_id_out,var_val_dbl_out,var_typ_rgr); rcd=nco_put_vara(out_id,var_id_out,dmn_srt,dmn_cnt_out,var_val_dbl_out,var_typ_rgr); } /* end OpenMP critical */ if(dmn_id_in) dmn_id_out=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(tally) tally=(int *)nco_free(tally); if(var_val_dbl_out) var_val_dbl_out=(double *)nco_free(var_val_dbl_out); if(var_val_dbl_in) var_val_dbl_in=(double *)nco_free(var_val_dbl_in); if(wgt_vld_out) wgt_vld_out=(double *)nco_free(wgt_vld_out); }else{ /* !trv.flg_rgr */ /* Use standard NCO copy routine for variables that are not regridded */ #pragma omp critical { /* begin OpenMP critical */ (void)nco_cpy_var_val(in_id,out_id,(FILE *)NULL,(md5_sct *)NULL,trv.nm,trv_tbl); } /* end OpenMP critical */ } /* !flg_rgr */ } /* !xtr */ } /* end (OpenMP parallel for) loop over idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"\n"); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s completion report: Variables regridded = %d (%d extensive), copied unmodified = %d, omitted = %d, created = %d\n",nco_prg_nm_get(),fnc_nm,var_rgr_nbr,var_xtn_nbr,var_cpy_nbr,var_xcl_nbr,var_crt_nbr); /* Free memory allocated for grid reading/writing */ if(area_out) area_out=(double *)nco_free(area_out); if(col_src_adr) col_src_adr=(int *)nco_free(col_src_adr); if(dmn_sz_in_int) dmn_sz_in_int=(int *)nco_free(dmn_sz_in_int); if(dmn_sz_out_int) dmn_sz_out_int=(int *)nco_free(dmn_sz_out_int); if(frc_out) frc_out=(double *)nco_free(frc_out); if(lat_bnd_out) lat_bnd_out=(double *)nco_free(lat_bnd_out); if(lat_crn_out) lat_crn_out=(double *)nco_free(lat_crn_out); if(lat_ctr_out) lat_ctr_out=(double *)nco_free(lat_ctr_out); if(lat_ntf_out) lat_ntf_out=(double *)nco_free(lat_ntf_out); if(lat_wgt_out) lat_wgt_out=(double *)nco_free(lat_wgt_out); if(lon_bnd_out) lon_bnd_out=(double *)nco_free(lon_bnd_out); if(lon_crn_out) lon_crn_out=(double *)nco_free(lon_crn_out); if(lon_ctr_out) lon_ctr_out=(double *)nco_free(lon_ctr_out); if(lon_ntf_out) lon_ntf_out=(double *)nco_free(lon_ntf_out); if(msk_out) msk_out=(int *)nco_free(msk_out); if(row_dst_adr) row_dst_adr=(int *)nco_free(row_dst_adr); if(sgs_frc_nm) sgs_frc_nm=(char *)nco_free(sgs_frc_nm); if(sgs_frc_in) sgs_frc_in=(double *)nco_free(sgs_frc_in); if(sgs_frc_out) sgs_frc_out=(double *)nco_free(sgs_frc_out); if(sgs_msk_nm) sgs_msk_nm=(char *)nco_free(sgs_msk_nm); if(wgt_raw) wgt_raw=(double *)nco_free(wgt_raw); return rcd; } /* end nco_rgr_wgt() */ void nco_bsl_zro /* Return Bessel function zeros */ (const int bsl_zro_nbr, /* O [nbr] Order of Bessel function */ double * const bsl_zro) /* O [frc] Bessel zero */ { /* Purpose: Return Bessel function zeros Source: CCM code /fs/cgd/csm/models/atm/ccm3.5.8/src/ccmlsm_share/bsslzr.F Return bsl_zro_nbr zeros (or if bsl_zro_nbr > 50, approximate zeros), of the Bessel function j0 First 50 zeros are given exactly, and remaining zeros are computed by extrapolation, and therefore are not exact Original version: CCM1 Standardized: J. Rosinski, June 1992 Reviewed: J. Hack, D. Williamson, August 1992 Reviewed: J. Hack, D. Williamson, April 1996 Modified 19970123 by Jim Rosinski to use double precision arithmetic ~2000: Converted to Fortran9X by C. Zender, changed all real*16 statements to double precision (real*8) 20150530: Converted to C99 by C. Zender */ const char fnc_nm[]="nco_bsl_zro()"; /* [sng] Function name */ const double pi=M_PI; // [frc] 3 const double bsl_zro_tbl[]={ // Zeros of Bessel functions of order 1 to 50 -1.e36, 2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086, 18.0710639679, 21.2116366299, 24.3524715308, 27.4934791320, 30.6346064684, 33.7758202136, 36.9170983537, 40.0584257646, 43.1997917132, 46.3411883717, 49.4826098974, 52.6240518411, 55.7655107550, 58.9069839261, 62.0484691902, 65.1899648002, 68.3314693299, 71.4729816036, 74.6145006437, 77.7560256304, 80.8975558711, 84.0390907769, 87.1806298436, 90.3221726372, 93.4637187819, 96.6052679510, 99.7468198587, 102.8883742542, 106.0299309165, 109.1714896498, 112.3130502805, 115.4546126537, 118.5961766309, 121.7377420880, 124.8793089132, 128.0208770059, 131.1624462752, 134.3040166383, 137.4455880203, 140.5871603528, 143.7287335737, 146.8703076258, 150.0118824570, 153.1534580192, 156.2950342685}; const int bsl_zro_tbl_nbr_max=50; /* [nbr] */ int bsl_idx; /* [idx] Counting index */ /* Main Code */ if(nco_dbg_lvl_get() >= nco_dbg_sbr) (void)fprintf(stdout,"%s: DEBUG Entering %s\n",nco_prg_nm_get(),fnc_nm); /* NB: Initialize bsl_zro[0] but (in C) never use it Initialization prevents uninitialized memory warnings */ for(bsl_idx=0;bsl_idx<=bsl_zro_nbr;bsl_idx++) if(bsl_idx <= bsl_zro_tbl_nbr_max) bsl_zro[bsl_idx]=bsl_zro_tbl[bsl_idx]; if(bsl_zro_nbr > bsl_zro_tbl_nbr_max) for(bsl_idx=bsl_zro_tbl_nbr_max+1;bsl_idx<=bsl_zro_nbr;bsl_idx++) bsl_zro[bsl_idx]=bsl_zro[bsl_idx-1]+pi; if(nco_dbg_lvl_get() == nco_dbg_old){ (void)fprintf(stdout,"%s: DEBUG %s reports bsl_zro_nbr = %d\n",nco_prg_nm_get(),fnc_nm,bsl_zro_nbr); (void)fprintf(stdout,"idx\tbsl_zro\n"); for(bsl_idx=1;bsl_idx<=bsl_zro_nbr;bsl_idx++) (void)fprintf(stdout,"%d\t%g\n",bsl_idx,bsl_zro[bsl_idx]); } /* endif dbg */ return; } /* end nco_bsl_zro() */ void nco_lat_wgt_gss /* [fnc] Compute and return sine of Gaussian latitudes and their weights */ (const int lat_nbr, /* I [nbr] Latitude number */ const nco_bool flg_s2n, /* I [enm] Latitude grid-direction is South-to-North */ double * const lat_sin, /* O [frc] Sine of latitudes */ double * const wgt_Gss) /* O [frc] Gaussian weights */ { /* Purpose: Compute and return sine of Gaussian latitudes and their weights Returned arrays are ordered south-to-north (S->N), not (N->S) Source: CCM /fs/cgd/csm/models/atm/ccm3.5.8/src/ccmlsm_share/gauaw.F Calculate sine of latitudes lat_sin(lat_nbr) and weights wgt_Gss(lat_nbr) for Gaussian quadrature Algorithm described in Davis and Rabinowitz, Journal of Research of the NBS, V 56, Jan 1956 Zeros of Bessel function j0, obtained from nco_bsl_zro(), are first guess for abscissae Original version: CCM1 Standardized: L. Bath, Jun 1992 L. Buja, Feb 1996 Reviewed: D. Williamson, J. Hack, Aug 1992 D. Williamson, J. Hack, Feb 1996 19970123 Modified by Jim Rosinski to use real*16 arithmetic in order to achieve (nearly) identical weights and latitudes on all machines. ~2000: Converted to Fortran9X by C. Zender, changed all real*16 statements to double precision (real*8) 20150530: Converted to C99 by C. Zender 20150725: Verified against tabulation at http://pomax.github.io/bezierinfo/legendre-gauss.html#n64 */ const char fnc_nm[]="nco_lat_wgt_gss()"; /* [sng] Function name */ const double eps_rlt=1.0e-16; // Convergence criterion (NB: Threshold was 1.0d-27 in real*16, 1.0e-15 fine for real*8, 1.0e-16 pushes double precision to the brink) const double pi=M_PI; // [frc] 3 const int itr_nbr_max=20; // [nbr] Maximum number of iterations double c_cff; // Constant combination coefficient double lat_idx_dbl; // Latitude index, double precision double lat_nnr_idx_dbl; // Inner latitude index, double precision double lat_nbr_dbl; // [nbr] Number of latitudes, double precision double pk=double_CEWI; // Polynomial double pkm1; // Polynomial double pkm2; // Polynomial double pkmrk; // Polynomial double sp; // Current iteration latitude increment double xz; // Abscissa estimate double cos_arg; // Intermediate parameter introduced while attempting to eliminate valgrind "uninitialised value" warnings int itr_cnt; // Iteration counter int lat_idx; // [idx] Counting index (latitude) int lat_sym_idx; // [idx] Counting index (symmetric latitude) int lat_nnr_idx; // [idx] Counting index (inner latitude loop) int lat_nbr_rcp2; // lat_nbr/2 (number of latitudes in hemisphere) double *lat_sin_p1; // Sine of Gaussian latitudes double precision double *wgt_Gss_p1; // Gaussian weights double precision /* Main Code */ if(nco_dbg_lvl_get() >= nco_dbg_sbr) (void)fprintf(stdout,"%s: DEBUG Entering %s\n",nco_prg_nm_get(),fnc_nm); /* Arrays with Fortran indexing (indicated by "plus one" = "_p1") keep numerical algorithm in C identical to Fortran */ lat_sin_p1=(double *)nco_malloc((lat_nbr+1)*sizeof(double)); // Sine of Gaussian latitudes double precision wgt_Gss_p1=(double *)nco_malloc((lat_nbr+1)*sizeof(double)); // Gaussian weights double precision /* Use Newton iteration to find abscissae */ c_cff=0.25*(1.0-4.0/(pi*pi)); lat_nbr_dbl=lat_nbr; lat_nbr_rcp2=lat_nbr/2; // NB: Integer arithmetic (void)nco_bsl_zro(lat_nbr_rcp2,lat_sin_p1); for(lat_idx=1;lat_idx<=lat_nbr_rcp2;lat_idx++){ // NB: Loop starts at 1 // 20150713: Introduce intermediate parameter cos_arg in attempt to eliminate valgrind "uninitialised value" warnings emitted by cos() (actually __cos_sse()) // Warnings occur with gcc-compiled code, not with clang-compiled code cos_arg=lat_sin_p1[lat_idx]/sqrt((lat_nbr_dbl+0.5)*(lat_nbr_dbl+0.5)+c_cff); xz=cos(cos_arg); /* First approximation to xz */ itr_cnt=0; /* goto label_73 */ label_73: pkm2=1.0; pkm1=xz; if(++itr_cnt > itr_nbr_max){ (void)fprintf(stdout,"%s: ERROR %s reports convergence only %g after %d iterations for lat_idx = %d\n",nco_prg_nm_get(),fnc_nm,fabs(sp),itr_nbr_max,lat_idx); nco_exit(EXIT_FAILURE); } /* endif */ /* Compute Legendre polynomial */ for(lat_nnr_idx=2;lat_nnr_idx<=lat_nbr;lat_nnr_idx++){ lat_nnr_idx_dbl=lat_nnr_idx; pk=((2.0*lat_nnr_idx_dbl-1.0)*xz*pkm1-(lat_nnr_idx_dbl-1.0)*pkm2)/lat_nnr_idx_dbl; pkm2=pkm1; pkm1=pk; } /* end inner loop over lat_nnr */ pkm1=pkm2; pkmrk=(lat_nbr_dbl*(pkm1-xz*pk))/(1.0-xz*xz); sp=pk/pkmrk; xz=xz-sp; /* NB: Easy to introduce bug here by not replacing Fortran abs() with C fabs() */ if(fabs(sp) > eps_rlt) goto label_73; lat_sin_p1[lat_idx]=xz; wgt_Gss_p1[lat_idx]=(2.0*(1.0-xz*xz))/((lat_nbr_dbl*pkm1)*(lat_nbr_dbl*pkm1)); } /* end outer loop over lat */ if(lat_nbr != lat_nbr_rcp2*2){ /* When lat_nbr is odd, compute weight at Equator */ lat_sin_p1[lat_nbr_rcp2+1]=0.0; pk=2.0/(lat_nbr_dbl*lat_nbr_dbl); for(lat_idx=2;lat_idx<=lat_nbr;lat_idx+=2){ lat_idx_dbl=lat_idx; pk=pk*lat_idx_dbl*lat_idx_dbl/((lat_idx_dbl-1.0)*(lat_idx_dbl-1.0)); } /* end loop over lat */ wgt_Gss_p1[lat_nbr_rcp2+1]=pk; } /* endif lat_nbr is odd */ /* Complete sets of abscissas and weights, using symmetry properties */ for(lat_idx=1;lat_idx<=lat_nbr_rcp2;lat_idx++){ lat_sym_idx=lat_nbr-lat_idx+1; lat_sin_p1[lat_sym_idx]=-lat_sin_p1[lat_idx]; wgt_Gss_p1[lat_sym_idx]=wgt_Gss_p1[lat_idx]; } /* end loop over lat */ /* Shift by one to remove Fortran offset in p1 arrays */ //memcpy(lat_sin,lat_sin_p1,lat_nbr*sizeof(double)); //memcpy(wgt_Gss,wgt_Gss_p1,lat_nbr*sizeof(double)); /* Reverse and shift arrays because original CCM code algorithm computes latitudes from north-to-south Shift by one to remove Fortran offset in p1 arrays */ if(flg_s2n){ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ lat_sin[lat_idx]=lat_sin_p1[lat_nbr-lat_idx]; wgt_Gss[lat_idx]=wgt_Gss_p1[lat_nbr-lat_idx]; } /* end loop over lat */ }else{ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ lat_sin[lat_idx]=lat_sin_p1[lat_idx+1]; wgt_Gss[lat_idx]=wgt_Gss_p1[lat_idx+1]; } /* end loop over lat */ } /* !flg_s2n */ if(nco_dbg_lvl_get() == nco_dbg_old){ (void)fprintf(stdout,"%s: DEBUG %s reports lat_nbr = %d\n",nco_prg_nm_get(),fnc_nm,lat_nbr); (void)fprintf(stdout,"idx\tasin\tngl_rad\tngl_dgr\tgw\n"); for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) (void)fprintf(stdout,"%d\t%g\t%g\t%g%g\n",lat_idx,lat_sin[lat_idx],asin(lat_sin[lat_idx]),180.0*asin(lat_sin[lat_idx])/pi,wgt_Gss[lat_idx]); } /* endif dbg */ if(wgt_Gss_p1) wgt_Gss_p1=(double *)nco_free(wgt_Gss_p1); if(lat_sin_p1) lat_sin_p1=(double *)nco_free(lat_sin_p1); return; } /* end nco_lat_wgt_gss() */ void nco_sph_plg_area /* [fnc] Compute area of spherical polygon */ (rgr_sct * const rgr, /* I [sct] Regridding structure */ const double * const lat_bnd, /* [dgr] Latitude boundaries of rectangular grid */ const double * const lon_bnd, /* [dgr] Longitude boundaries of rectangular grid */ const long col_nbr, /* [nbr] Number of columns in grid */ const int bnd_nbr, /* [nbr] Number of bounds in gridcell */ double * const area) /* [sr] Gridcell area */ { /* Purpose: Compute area of spherical polygon */ /* Computing triangular area accurately is hard in corner cases Spherical triangle suffer from at least as many issues as planar, which are described by "Miscalculating Area and Angles of a Needle-like Triangle" by W. Kahan, UC Berkeley In particular, the Law of Cosines and Heron's formula can be ill-conditioned For spherical triangles L'Huilier's Theorem is superior to Girard's Formula: http://mathworld.wolfram.com/LHuiliersTheorem.html Girard's formula depends on pi-minus-angle and angle is usually quite small in our applications so precision would be lost L'Huilier's theorem depends only on angles (a,b,c) and semi-perimeter (s) and is well-conditioned for small angles semi-perimeter = half-perimeter of triangle = 0.5*(a+b+c) Spherical Excess (SE) difference between the sum of the angles of a spherical triangle area and a planar triangle area with same interior angles (that sum to pi) SE is also the solid angle subtended by the spherical triangle and that's, well, astonishing and pretty cool Wikipedia shows a better SE formula for triangles that are ill-conditioned for L'Huilier's formula because a = b ~ 0.5c https://en.wikipedia.org/wiki/Spherical_trigonometry#Area_and_spherical_excess See also interesting discussion of L'Huilier by Charles Karney who suggests his own alternative: http://osgeo-org.1560.x6.nabble.com/Area-of-a-spherical-polygon-td3841625.html The discussion mentions Mil94 Robert D. Miller, Computing the area of a spherical polygon, Graphic Gems IV, chapter II.4, pages 132-137. http://books.google.com/books?id=CCqzMm_-WucC&pg=PA132&lpg=PA132&dq=miller+area+spherical+polygon+gems&source=bl&ots=mrnvZ6NJcm&sig=CMg8eaD8dzP5snMaPeCQzgoFWUk&hl=sv&ei=4G-YTKv5GsWZOI-mmZQP&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBQQ6AEwAA#v=onepage&q&f=false Mil94 contains similar ideas to my method for spherical polygons (decomposing into adjacent multiple triangles from single vertex) However, his method places single vertex at pole, then adds signed areas to obtain full polygon area His method may suffer from degraded precision because of roundoff error and long side-lengths So-called "proper" spherical triangle are those for which all angles are less than pi, so a+b+c<3*pi Cartesian coordinates of (lat,lon)=(theta,phi) are (x,y,z)=(cos(theta)*cos(phi),cos(theta)*sin(phi),sin(theta)) Dot-product rule for vectors gives interior angle/arc length between two points: cos(a)=u dot v=cos(theta1)*cos(phi1)*cos(theta2)*cos(phi2)+cos(theta1)*sin(phi1)*cos(theta2)*sin(phi2)+sin(theta1)*sin(theta2) Spherical law of cosines relates interior angles/arc-lengths (a,b,c) to surface angles (A,B,C) in spherical triangle: https://en.wikipedia.org/wiki/Spherical_law_of_cosines cos(a)=cos(b)*cos(c)+sin(b)*sin(c)*cos(A) cos(b)=cos(c)*cos(a)+sin(c)*sin(a)*cos(B) cos(c)=cos(a)*cos(b)+sin(a)*sin(b)*cos(C) cos(A)=[cos(a)-cos(b)*cos(c)]/[sin(b)*sin(c)] cos(B)=[cos(b)-cos(c)*cos(a)]/[sin(c)*sin(a)] cos(C)=[cos(c)-cos(a)*cos(b)]/[sin(a)*sin(b)] Bounds information on unstructured grids will use bounds_nbr=maximum(vertice_nbr) Unused vertices are stored as either repeated points (ACME does this) or, conceiveably, as missing values Given (lat,lon) for N-points algorithm to find area of spherical polygon is: 1. Any decomposition, Girard areas: Loses precision due to mismatch between pi and small spherical excesses A. Find interior angles/arc-lengths (a,b,c,d...) using spherical law of cosines along each edge B. Apply generalized Girard formula SE_n = Sum(A_n) - (N-2) - pi 2. CSZ decomposition (N-2 triangles) with L'Huilier areas, Convert polygon into triangles by cycling spoke through all sides from common apex This method requires computation of N-2 (not N) triangles, though fewer sides due to optimization It works on all convex polygons (interior angles less than 180) but not, in general, concave polygons Whether it works or not on concave polygons depends upon their exact shape and the choice of apex point A. First three non-identical points form first triangle with sides A,B,C (first+second point define A, etc.) i. First vertice anchors all triangles ii. Third vertice of preceding triangle becomes second vertice of next triangle iii. Next non-identical point becomes last vertice of next triangle iv. Side C of previous triangle is side A of next triangle B. For each triangle, compute area with L'Huilier formula unless A = B ~ 0.5*C then use SAS formula 3. centroidal decomposition, N triangle version by Taylor, L'Huilier areas: Compute polygon centroid and treat this as hub from which spokes are drawn to all vertices This method requires computation of N triangles, though fewer sides due to optimization Moreover, it works on all convex polygons and on slightly concave polygons Centroid/hub has clear view of interior of most simple concave polygons 4. Any decomposition but with exact RLL grids by Zender and Agress 20160918 A. Decompose polygon into triangles via any method (e.g., method 2 or 3 above) B. Determine whether triangle is spherical or contains RLL (constant latitude) C. Spherical triangles use L'Huilier, RLL triangles use series expansion */ const char fnc_nm[]="nco_sph_plg_area()"; const double dgr2rdn=M_PI/180.0; int bnd_nbr_ttl; /* [nbr] Number of bounds in gridcell accounting for possibility of centroid information */ long idx; /* [idx] Counting index for unrolled grids */ short int bnd_idx; /* Shift to this method once we pass rgr into nco_sph_plg_area() */ nco_bool flg_mth_csz=False; /* [flg] Use CSZ's advancing polygon bisector method */ nco_bool flg_mth_ctr=False; /* [flg] Use centroid method to compute polygon area */ nco_edg_typ_enm edg_typ; /* [enm] Arc-type for triangle edges */ nco_ply_tri_mth_typ_enm ply_tri_mth; /* [enm] Polygon decomposition method */ if(rgr->edg_typ == nco_edg_nil) rgr->edg_typ=nco_edg_gtc; edg_typ=rgr->edg_typ; /* [enm] Arc-type for triangle edges */ ply_tri_mth=rgr->ply_tri_mth; /* [enm] Polygon decomposition method */ if(ply_tri_mth == nco_ply_tri_mth_csz) flg_mth_csz=True; if(ply_tri_mth == nco_ply_tri_mth_ctr) flg_mth_ctr=True; assert(flg_mth_ctr != flg_mth_csz); bnd_nbr_ttl=bnd_nbr; // Allocate space for one extra boundary to store centroid information if necessary if(flg_mth_ctr) bnd_nbr_ttl=bnd_nbr+1; double *lat_bnd_rdn=NULL_CEWI; /* [rdn] Latitude boundaries of rectangular destination grid */ double *lon_bnd_rdn=NULL_CEWI; /* [rdn] Longitude boundaries of rectangular destination grid */ double *lat_bnd_sin=NULL_CEWI; /* [frc] Sine of latitude boundaries of rectangular destination grid */ double *lon_bnd_sin=NULL_CEWI; /* [frc] Sine of longitude boundaries of rectangular destination grid */ double *lat_bnd_cos=NULL_CEWI; /* [frc] Cosine of latitude boundaries of rectangular destination grid */ double *lon_bnd_cos=NULL_CEWI; /* [frc] Cosine of longitude boundaries of rectangular destination grid */ /* Allocate one extra space for some arrays to store polygon centroid values for each column for ply_tri_mth=ctr */ lon_bnd_rdn=(double *)nco_malloc(col_nbr*bnd_nbr_ttl*sizeof(double)); lat_bnd_rdn=(double *)nco_malloc(col_nbr*bnd_nbr_ttl*sizeof(double)); lon_bnd_cos=(double *)nco_malloc(col_nbr*bnd_nbr*sizeof(double)); lat_bnd_cos=(double *)nco_malloc(col_nbr*bnd_nbr_ttl*sizeof(double)); lon_bnd_sin=(double *)nco_malloc(col_nbr*bnd_nbr*sizeof(double)); lat_bnd_sin=(double *)nco_malloc(col_nbr*bnd_nbr*sizeof(double)); memcpy(lat_bnd_rdn,lat_bnd,col_nbr*bnd_nbr*sizeof(double)); memcpy(lon_bnd_rdn,lon_bnd,col_nbr*bnd_nbr*sizeof(double)); for(idx=0;idx<col_nbr*bnd_nbr;idx++){ lon_bnd_rdn[idx]*=dgr2rdn; lat_bnd_rdn[idx]*=dgr2rdn; lon_bnd_cos[idx]=cos(lon_bnd_rdn[idx]); lat_bnd_cos[idx]=cos(lat_bnd_rdn[idx]); lon_bnd_sin[idx]=sin(lon_bnd_rdn[idx]); lat_bnd_sin[idx]=sin(lat_bnd_rdn[idx]); } /* !idx */ double area_smc_crc; /* [sr] Small-circle correction to spherical triangle area */ double area_smc; /* [sr] Gridcell area allowing for latitude-triangles */ double area_ttl; /* [sr] Total area of input polygon list assuming spherical triangles */ double area_smc_ttl; /* [sr] Total area of input polygon list allowing for latitude-triangles */ double area_smc_crc_ttl; /* [sr] Latitude-triangle correction (should be small) to total area of input polygon list */ double area_smc_crc_abs_ttl; /* [sr] Latitude-triangle absolute correction (no compensation of positive/negative contributions, should be no smaller than above) to total area of input polygon list */ double lat_ctr; /* [dgr] Latitude of polygon centroid */ double lon_ctr; /* [dgr] Longitude of polygon centroid */ double lat_ctr_rdn; /* [rdn] Latitude of polygon centroid */ double lon_ctr_rdn; /* [rdn] Longitude of polygon centroid */ double lat_ctr_cos; /* [frc] Cosine latitude of polygon centroid */ double lat_dlt; /* [rdn] Latitudinal difference */ double lon_dlt; /* [rdn] Longitudinal difference */ double ngl_a; /* [rdn] Interior angle/great circle arc a */ double ngl_b; /* [rdn] Interior angle/great circle arc b */ double ngl_c; /* [rdn] Interior angle/great circle arc c */ double ngl_ltr_a; /* [rdn] Interior angle/small circle arc a, canonical latitude-triangle geometry */ double ngl_ltr_b; /* [rdn] Interior angle/great circle arc b, canonical latitude-triangle geometry */ double ngl_ltr_c; /* [rdn] Interior angle/great circle arc c, canonical latitude-triangle geometry */ double prm_smi; /* [rdn] Semi-perimeter of triangle */ double sin_hlf_tht; /* [frc] Sine of half angle/great circle arc theta connecting two points */ double xcs_sph; /* [sr] Spherical excess */ int tri_nbr; /* [nbr] Number of triangles in polygon */ long bnd_vld_nbr=NC_MIN_INT; /* [idx] Number of valid (non-duplicative) vertices in each triangle */ long *a_idx; /* [idx] Point A 1-D indices for each triangle in polygon */ long *b_idx; /* [idx] Point B 1-D indices for each triangle in polygon */ long *c_idx; /* [idx] Point C 1-D indices for each triangle in polygon */ long *vrt_vld=NULL; /* [idx] Absolute 1-D indices of valid vertices */ long idx_a; /* [idx] Point A 1-D index */ long idx_b; /* [idx] Point B 1-D index */ long idx_c; /* [idx] Point C 1-D index */ nco_bool flg_sas_ndl=False; /* [flg] L'Huilier's formula will fail due to needle where one side exceeds semi-perimeter */ nco_bool flg_sas_isc=False; /* [flg] L'Huilier's formula is ill-conditioned due to flat, near-isoceles triangle */ nco_bool flg_sas_a=False; /* [flg] Use SAS triangle formula with central angle a */ nco_bool flg_sas_b=False; /* [flg] Use SAS triangle formula with central angle b */ nco_bool flg_sas_c=False; /* [flg] Use SAS triangle formula with central angle c */ nco_bool flg_ply_has_smc; /* [flg] Any triangle in polygon has small-circle edge */ nco_bool flg_tri_crr_smc; /* [flg] Current triangle has small_circle edge */ /* Initialize global accumulators */ area_ttl=0.0; area_smc_ttl=0.0; area_smc_crc_ttl=0.0; area_smc_crc_abs_ttl=0.0; for(long col_idx=0;col_idx<col_nbr;col_idx++){ /* Initialize local properties and accumulators for this cell/polygon */ flg_ply_has_smc=False; ngl_c=double_CEWI; /* Otherwise compiler unsure ngl_c is initialized first use */ area[col_idx]=0.0; area_smc=0.0; tri_nbr=0; if(col_idx == 0){ a_idx=(long *)nco_calloc(bnd_nbr,sizeof(long)); b_idx=(long *)nco_calloc(bnd_nbr,sizeof(long)); c_idx=(long *)nco_calloc(bnd_nbr,sizeof(long)); vrt_vld=(long *)nco_calloc(bnd_nbr,sizeof(long)); } /* !col_idx */ /* Safety re-initialization to ease debugging, not strictly necessary */ for(bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++){ vrt_vld[bnd_idx]=NC_MIN_INT; a_idx[bnd_idx]=NC_MIN_INT; b_idx[bnd_idx]=NC_MIN_INT; c_idx[bnd_idx]=NC_MIN_INT; } /* !bnd_idx */ if(flg_mth_ctr){ double lon_dff; /* [dgr] Longitude difference */ long bnd_srt_idx; /* [idx] Absolute starting index of vertices in polygon */ long bnd_idx; /* [idx] Offset of current valid vertex index from starting index */ long bnd_vld_idx; /* [idx] Absolute index of last valid vertex */ /* First vertice is always valid */ bnd_srt_idx=bnd_nbr*col_idx; bnd_vld_idx=bnd_srt_idx; vrt_vld[0]=bnd_vld_idx; lat_ctr=lat_bnd[bnd_srt_idx]; lon_ctr=lon_bnd[bnd_srt_idx]; bnd_vld_nbr=1; /* First guess for next valid index */ bnd_idx=1; /* bnd_idx labels offset from first vertex of next valid (i.e., non-duplicative) vertex */ while(bnd_idx<bnd_nbr){ /* Skip repeated points that must occur when polygon has fewer than allowed vertices */ while(lon_bnd[bnd_vld_idx] == lon_bnd[bnd_srt_idx+bnd_idx] && lat_bnd[bnd_srt_idx] == lat_bnd[bnd_srt_idx+bnd_idx]){ /* Next valid vertice must not duplicate first vertex */ bnd_idx++; /* Have we already found all valid vertices? */ if(bnd_idx == bnd_nbr) break; } /* !while */ /* Jump to normalization when all valid vertices found */ if(bnd_idx == bnd_nbr) break; /* Current vertex is valid (non-duplicative) */ bnd_vld_idx=bnd_srt_idx+bnd_idx; vrt_vld[bnd_vld_nbr]=bnd_vld_idx; bnd_vld_nbr++; if(nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: DEBUG %s reports centroidal decomposition col_idx=%lu, bnd_nbr=%d, bnd_idx=%ld, bnd_vld_idx=%ld, bnd_vld_nbr=%ld\n",nco_prg_nm_get(),fnc_nm,col_idx,bnd_nbr,bnd_idx,bnd_vld_idx,bnd_vld_nbr); assert(bnd_vld_nbr <= bnd_nbr); lat_ctr+=lat_bnd[bnd_vld_idx]; lon_ctr+=lon_bnd[bnd_vld_idx]; lon_dff=lon_bnd[bnd_vld_idx]-lon_bnd[0]; if(lon_dff >= 180.0){ lon_ctr-=360.0; }else if(lon_dff <= -180.0){ lon_ctr+=360.0; } /* !lon_dff */ /* Search for next valid vertice in next iteration */ bnd_idx++; } /* !bnd_idx */ /* Compute centroid */ lat_ctr/=bnd_vld_nbr; lon_ctr/=bnd_vld_nbr; /* Centroid can become point A of bnd_nbr polygons or optimize algorithm: 1. Skip sub-dividing polygon into centroid-based triangles for bnd_vld_nbr == 3 2. Split quadrilaterals into two (non-centroid) triangles for bnd_vld_nbr == 4 3. Use full centroid-based triangle algorithm for bnd_vld_nbr >= 5 */ lat_ctr_rdn=lat_ctr*dgr2rdn; lon_ctr_rdn=lon_ctr*dgr2rdn; lat_ctr_cos=cos(lat_ctr_rdn); /* Place centroid values in extended arrays for easy access */ lat_bnd_rdn[(col_idx+1)*bnd_nbr_ttl-1L]=lat_ctr_rdn; lon_bnd_rdn[(col_idx+1)*bnd_nbr_ttl-1L]=lon_ctr_rdn; lat_bnd_cos[(col_idx+1)*bnd_nbr_ttl-1L]=lat_ctr_cos; /* Polygon centroid and valid vertices are now known */ assert(bnd_vld_nbr > 2); if(bnd_vld_nbr == 3){ /* Three vertices only means polygon is already decomposed into a triangle */ tri_nbr=1; a_idx[0]=vrt_vld[0]; b_idx[0]=vrt_vld[1]; c_idx[0]=vrt_vld[2]; }else if(bnd_vld_nbr == 4){ /* Bisect quadrilateral into two triangles rather than use centroid and have four triantles */ tri_nbr=2; a_idx[0]=vrt_vld[0]; b_idx[0]=vrt_vld[1]; c_idx[0]=vrt_vld[2]; a_idx[1]=vrt_vld[0]; /* NB: Order is important. This way side C of triangle[0] = side A of trangle[1] */ b_idx[1]=vrt_vld[2]; c_idx[1]=vrt_vld[3]; }else if(bnd_vld_nbr >= 5){ /* Centroid method has as many triangles as valid vertices */ tri_nbr=bnd_vld_nbr; for(int tri_idx=0;tri_idx<tri_nbr;tri_idx++){ a_idx[tri_idx]=(col_idx+1)*bnd_nbr_ttl-1L; /* A is always centroid, store values at end of arrays */ b_idx[tri_idx]=vrt_vld[tri_idx]; c_idx[tri_idx]=vrt_vld[(tri_idx+1)%tri_nbr]; } /* !tri_idx */ } /* !bnd_vld_nbr */ } /* !flg_mth_ctr */ if(flg_mth_csz){ /* A is always first vertice of all triangles */ idx_a=bnd_nbr*col_idx; /* Start search for B at next vertice */ bnd_idx=1; /* bnd_idx labels offset from point A of potential location of triangle points B and C We know that bnd_idx(A) == 0, bnd_idx(B) < bnd_nbr-1, bnd_idx(C) < bnd_nbr */ while(bnd_idx<bnd_nbr-1){ /* Only first triangle must search for B, subsequent triangles recycle previous C as current B */ if(tri_nbr == 0){ /* Skip repeated points that must occur when polygon has fewer than allowed vertices */ /* 20200115: Prior to today we never skipped polar points (same latitudes but different longitudes) That worked fine in practice for spherical triangles partly because triangles from CSZ decomposition (aka hub-and-spoke decomposition) are additive, even with multiple points on the same great circle, and partly due to luck (a starting vertex surrounded by points on the same geodesic would break it). Moreover, repeated polar points pose no issues for L'Huilier's (or Girard's) method which depends only on the interior angles and side lengths, not the longitudes of polar points. Small circles change that last part, and we must now eliminate repeated polar points. */ if(edg_typ == nco_edg_smc){ /* Skip repeated numerically identical points */ while(lon_bnd[idx_a] == lon_bnd[idx_a+bnd_idx] && lat_bnd[idx_a] == lat_bnd[idx_a+bnd_idx]){ /* Next vertice may not duplicate A */ bnd_idx++; /* If there is no room for C then all triangles found */ if(bnd_idx == bnd_nbr-1) break; } /* !while */ /* Skip geometrically identical (i.e., repeated polar) points */ while((fabs(lat_bnd[idx_a]) == 90.0) && (fabs(lat_bnd[idx_a+bnd_idx]) == 90.0)){ bnd_idx++; if(bnd_idx == bnd_nbr-1) break; } /* !while */ }else if(edg_typ != nco_edg_smc){ /* Spherical polygongs can use simpler, pre-20200116 algorithm to eliminate repeated points */ while(lon_bnd[idx_a] == lon_bnd[idx_a+bnd_idx] && lat_bnd[idx_a] == lat_bnd[idx_a+bnd_idx]){ /* Next vertice may not duplicate A */ bnd_idx++; /* If there is no room for C then all triangles found */ if(bnd_idx == bnd_nbr-1) break; } /* !while */ }else{ abort(); } /* !edg_typ */ /* Jump to next column when all triangles found */ if(bnd_idx == bnd_nbr-1) break; } /* !tri_nbr */ idx_b=idx_a+bnd_idx; /* Search for C at next vertice */ bnd_idx++; /* fxm */ while(lon_bnd[idx_b] == lon_bnd[idx_a+bnd_idx] && lat_bnd[idx_b] == lat_bnd[idx_a+bnd_idx]){ /* Next vertice may not duplicate B */ bnd_idx++; /* If there is no room for C then all triangles found */ if(bnd_idx == bnd_nbr) break; } /* !while */ /* Jump to next column when all triangles found */ if(bnd_idx == bnd_nbr) break; idx_c=idx_a+bnd_idx; /* Valid triangle, vertices are known and labeled */ a_idx[tri_nbr]=idx_a; b_idx[tri_nbr]=idx_b; c_idx[tri_nbr]=idx_c; tri_nbr++; /* Begin search for next B at current C */ bnd_idx=idx_c-idx_a; } /* !bnd_idx */ } /* !flg_mth_csz */ /* Triangles are known for requested decomposition method Compute and accumulate their area Optimized algorithm recycles previous arc c as current arc a (after first triangle) */ for(int tri_idx=0;tri_idx<tri_nbr;tri_idx++){ idx_a=a_idx[tri_idx]; idx_b=b_idx[tri_idx]; idx_c=c_idx[tri_idx]; if(nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: DEBUG %s reports triangle vertices: col_idx=%lu, tri_idx=%d, idx_a=%ld, idx_b=%ld, idx_c=%ld\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,idx_a,idx_b,idx_c); /* Compute interior angle/great circle arc a for first triangle; subsequent triangles recycle previous arc c */ if(tri_idx == 0){ /* 20150831: Test by computing ncol=0 area in conus chevrons grid, compare to MAT results ncremap -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/257x512_SCRIP.20150901.nc -m ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.20150901.nc ncremap -s ${DATA}/grids/257x512_SCRIP.20150901.nc -g ${DATA}/grids/conusx4v1np4_chevrons_scrip_c150815.nc -m ${DATA}/maps/map_fv257x512_to_conusx4v1np4_chevrons_bilin.20150901.nc ncks -O -D 5 -v FSNT --map ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.150418.nc ${DATA}/ne30/raw/famipc5_ne30_v0.3_00003.cam.h0.1979-01.nc ${DATA}/ne30/rgr/fv_FSNT.nc ncks -O -D 5 -v FSNT --rgr diagnose_area --map ${DATA}/maps/map_fv257x512_to_conusx4v1np4_chevrons_bilin.20150901.nc ${DATA}/ne30/rgr/fv_FSNT.nc ${DATA}/ne30/rgr/dogfood.nc ncks -O -D 1 --rgr infer#diagnose_area --rgr grid=${HOME}/grd.nc ${DATA}/ne30/rgr/dogfood.nc ~/foo.nc ncks -H -s %20.15e, -v area -d ncol,0 ${DATA}/ne30/rgr/dogfood.nc ncks -H -s %20.15e, -v grid_area -d grid_size,0 ${DATA}/grids/conusx4v1np4_chevrons_scrip_c150815.nc ncks -H -s %20.15e, -v grid_area -d grid_size,0 ${HOME}/grd.nc ncol=0 on conus chevrons file: 3.653857995295246e-05 raw GLL weight 3.653857995294305e-05 ESMF weight (area_b from map-file) 3.653857995294302e-05 matlab CSZ decomposition (N-2 triangles) computed at SNL by MAT 3.653857995294301e-05 matlab centroidal decomposition (N triangles) computed at SNL by MAT 3.653857995294258e-05 NCO CSZ _and_ centroidal decompositions (new haversine) 3.653857995289623e-05 NCO CSZ decomposition (old acos) 20191011: Tested this same polygon in ESMF and NCO weight-generator NCO maps begin with first destination gridcell, find next ESMF gridcell by searching for first col: ncks --trd -C -v col ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc | egrep "=1 " ncks -H --trd -s %20.15e -C -d n_b,0 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc 3.653857995294305e-05 ncks -H --trd -s '%20.15e, ' -C -d n_b,0 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc 3.653857995295246e-05 ESMF and NCO weight-generators produce nearly identical S results to double-precision: ncks -H --trd -s '%20.15e, ' -C -d n_s,0,1 -v S ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc 2.181999640069480e-03, 1.309571213636605e-02 ncks -H --trd -s %20.15e -C -d n_s,207436 -d n_s,209617 -v S ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc 2.181999640069454e-03, 1.309571213636510e-02 Compare first five polygon areas: ncks --trd -H -C -s '%20.15e, ' -d n_b,0,4 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc ncks --trd -H -C -s '%20.15e, ' -d n_b,0,4 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc 3.653857995294305e-05, 1.250459284052488e-04, 1.448204605591709e-04, 8.223598867312266e-05, 8.585831933875070e-05, # aave 3.653857995294258e-05, 1.250459284052470e-04, 1.448204605591675e-04, 8.223598867312247e-05, 8.585831933875186e-05, Compare total areas: ncwa -O -y ttl -v area.? ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc ~/foo_aave.nc ncwa -O -y ttl -v area.? ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc ~/foo_nco.nc ncks --trd -H -C -s '%20.15e, ' -v area.? ~/foo_aave.nc ncks --trd -H -C -s '%20.15e, ' -v area.? ~/foo_nco.nc aave: 1.256637061435867e+01, 1.256637061435973e+01 nco: 1.256637061435857e+01, 1.256637061435955e+01 4*pi: 1.25663706143591729538e+01 Does (tru_glb_ttl/NCO_glb_ttl)*NCO_lcl = ESMF_lcl ? (1.25663706143591729538/1.256637061435857)*3.653857995294258=3.6538579952944333 No, normalization alone does not explain differences between ESMF and NCO It does not appear that ESMF does a global normalization of areas/weights */ /* Computing great circle arcs over small arcs requires care since central angle is near 0 degrees Cosine small angles changes slowly for such angles, and leads to precision loss Use haversine formula instead of spherical law of cosines formula https://en.wikipedia.org/wiki/Great-circle_distance */ /* Interior angle/great circle arc a, spherical law of cosines formula (loses precision): cos_a=lat_bnd_cos[idx_a]*lon_bnd_cos[idx_a]*lat_bnd_cos[idx_b]*lon_bnd_cos[idx_b]+ lat_bnd_cos[idx_a]*lon_bnd_sin[idx_a]*lat_bnd_cos[idx_b]*lon_bnd_sin[idx_b]+ lat_bnd_sin[idx_a]*lat_bnd_sin[idx_b];ngl_a=acos(cos_a); */ /* Interior angle/great circle arc a, haversine formula: */ // 20160918: Use branch cut rules for longitude lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_a],lon_bnd_rdn[idx_b])); lat_dlt=fabs(lat_bnd_rdn[idx_a]-lat_bnd_rdn[idx_b]); sin_hlf_tht=sqrt(pow(sin(0.5*lat_dlt),2)+lat_bnd_cos[idx_a]*lat_bnd_cos[idx_b]*pow(sin(0.5*lon_dlt),2)); ngl_a=2.0*asin(sin_hlf_tht); }else{ /* !tri_idx == 0 */ ngl_a=ngl_c; } /* !tri_idx == 0 */ /* Interior angle/great circle arc b */ lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_b],lon_bnd_rdn[idx_c])); lat_dlt=fabs(lat_bnd_rdn[idx_b]-lat_bnd_rdn[idx_c]); sin_hlf_tht=sqrt(pow(sin(0.5*lat_dlt),2)+lat_bnd_cos[idx_b]*lat_bnd_cos[idx_c]*pow(sin(0.5*lon_dlt),2)); ngl_b=2.0*asin(sin_hlf_tht); /* Interior angle/great circle arc c */ lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_c],lon_bnd_rdn[idx_a])); lat_dlt=fabs(lat_bnd_rdn[idx_c]-lat_bnd_rdn[idx_a]); sin_hlf_tht=sqrt(pow(sin(0.5*lat_dlt),2)+lat_bnd_cos[idx_c]*lat_bnd_cos[idx_a]*pow(sin(0.5*lon_dlt),2)); ngl_c=2.0*asin(sin_hlf_tht); /* Semi-perimeter */ prm_smi=0.5*(ngl_a+ngl_b+ngl_c); /* L'Huilier's formula results in NaN if any side exceeds semi-perimeter This can occur in needle-shaped triangles due to rounding errors in derived arc lengths a, b, c 20200203: Problematic needles occurs a few dozen times in ne120pg2 -> cmip6 maps Problematic isoceles triangles are much rarer than problematic needles Therefore look for needle-issues first, then, if none found, look for isoceles issues Wikipedia recommends treating ill-conditioned triangles by Side-Angle-Side (SAS) formula https://en.wikipedia.org/wiki/Spherical_trigonometry Diagnose needles beforehand and call SAS routines as above to avoid NaN in L'Huilier Label problematic needle triangles by shortest side, e.g., "flg_sas_a" means (b ~ c) and a ~ 0.0 */ flg_sas_ndl=flg_sas_isc=flg_sas_a=flg_sas_b=flg_sas_c=False; if(ngl_a > prm_smi){if(ngl_b > ngl_c) flg_sas_c=True; else flg_sas_b=True;} /* a exceeds semi-perimeter */ else if(ngl_b > prm_smi){if(ngl_c > ngl_a) flg_sas_a=True; else flg_sas_c=True;} /* b exceeds semi-perimeter */ else if(ngl_c > prm_smi){if(ngl_a > ngl_b) flg_sas_b=True; else flg_sas_a=True;} /* c exceeds semi-perimeter */ if(flg_sas_a || flg_sas_b || flg_sas_c) flg_sas_ndl=True; if(!flg_sas_ndl){ /* L'Huilier's formula becomes ill-conditioned when two sides are one half the third side This occurs for flat, isoceles-shaped triangles Label problematic isoceles triangles by longest side, e.g., "flg_sas_a" means (b ~ c) ~ 0.5*a */ /* Sensitivity tests on ~20191014 showed that triangular ill-conditioning treatment (i.e., switching to SAS method) does not improve (and may degrade) accuracy for eps_ill_cnd > 1.0e-15 */ const double eps_ill_cnd=1.0e-15; /* [frc] Ill-conditioned tolerance for interior angle/great circle arcs in triangle */ const double eps_ill_cnd_dbl=2.0*eps_ill_cnd; /* [frc] Ill-conditioned tolerance for interior angle/great circle arcs in triangle */ if((fabs(ngl_a-ngl_b) < eps_ill_cnd) && (fabs(ngl_a-0.5*ngl_c) < eps_ill_cnd_dbl)) flg_sas_c=True; /* c is twice a and b */ else if((fabs(ngl_b-ngl_c) < eps_ill_cnd) && (fabs(ngl_b-0.5*ngl_a) < eps_ill_cnd_dbl)) flg_sas_a=True; /* a is twice b and c */ else if((fabs(ngl_c-ngl_a) < eps_ill_cnd) && (fabs(ngl_c-0.5*ngl_b) < eps_ill_cnd_dbl)) flg_sas_b=True; /* b is twice c and a */ if(flg_sas_a || flg_sas_b || flg_sas_c) flg_sas_isc=True; } /* !flg_sas_ndl */ if(flg_sas_isc || flg_sas_ndl){ /* Compute area using SAS formula */ double cos_hlf_C; /* [frc] Cosine of half of canoncal surface angle C */ //double sin_hlf_C; /* [frc] Sine of half of canoncal surface angle C */ double ngl_sfc_ltr_C; /* [rdn] Canonical surface angle/great circle arc C */ double tan_hlf_a_tan_hlf_b; /* [frc] Product of tangents of one-half of nearly equal canoncal sides */ double xcs_sph_hlf_tan; /* [frc] Tangent of one-half the spherical excess */ /* Transform sides into canonical order for formula where C is surface angle between arcs a and b */ if(flg_sas_c){ ngl_ltr_a=ngl_a; ngl_ltr_b=ngl_b; ngl_ltr_c=ngl_c; } /* !flg_sas_c */ if(flg_sas_a){ ngl_ltr_a=ngl_b; ngl_ltr_b=ngl_c; ngl_ltr_c=ngl_a; } /* !flg_sas_a */ if(flg_sas_b){ ngl_ltr_a=ngl_c; ngl_ltr_b=ngl_a; ngl_ltr_c=ngl_b; } /* !flg_sas_b */ if(flg_sas_ndl && (nco_dbg_lvl_get() >= nco_dbg_scl)) (void)fprintf(stdout,"%s: INFO %s reports col_idx = %li triangle %d is needle-shaped triangle with a side that exceeds semi-perimeter = %0.16e. Eschew L'Huilier's formula for spherical excess to avoid NaN. Could use SAS formula with canonical central interior arc c = %0.16e.\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,prm_smi,ngl_ltr_c); if(flg_sas_isc && (nco_dbg_lvl_get() >= nco_dbg_scl)) (void)fprintf(stdout,"%s: INFO %s reports col_idx = %li triangle %d is nearly flat isoceles-shaped triangle. Canonical arcs a and b differ by %0.16e. Eschew L'Huilier's formula for spherical excess to avoid low precision. Could use SAS formula.\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,fabs(ngl_ltr_a-ngl_ltr_b)); /* Determine canonical surface angle C To find any angle given three spherical triangle sides, Wikipedia opines: "The cosine rule may be used to give the angles A, B, and C but, to avoid ambiguities, the half-angle formulae are preferred." Half-angle formulae include two applicable variants that yield the sine or cosine of half C Then C is determined as twice the asin() or acos() function, respectively For needle-shaped triangles, RHS sin formula is ~ sin^2(0)/sin(a)*sin(b) ~ 0.0 For needle-shaped triangles, RHS cos formula is ~ sin^2(s)/sin(a)*sin(b) ~ 0.5 For flat isoceles triangles, RHS sin formula is ~ sin^2(0)/sin(a)*sin(b) ~ 0.0 For flat isoceles triangles, RHS cos formula is ~ sin(s)*sin(0)/sin(a)*sin(b) ~ 0.0 Use sin formula since both needle- and isoceles-shaped triangles have RHS ~ 0.0 where arcsin() is most precise 20200203: Half-angle sine formula gives NaNs, and half-angle cosine formula works on ne120pg2->cmip. Why? Adopting cosine formula because it works */ //sin_hlf_C=sqrt(sin(prm_smi-ngl_ltr_a)*sin(prm_smi-ngl_ltr_b)/(sin(ngl_ltr_a)*sin(ngl_ltr_b))); // Half-angle sine formula cos_hlf_C=sqrt(sin(prm_smi)*sin(prm_smi-ngl_ltr_c)/(sin(ngl_ltr_a)*sin(ngl_ltr_b))); // Half-angle cosine formula //ngl_sfc_ltr_C=2.0*asin(sin_hlf_C); ngl_sfc_ltr_C=2.0*acos(cos_hlf_C); /* SAS formula */ tan_hlf_a_tan_hlf_b=tan(0.5*ngl_ltr_a)*tan(0.5*ngl_ltr_b); xcs_sph_hlf_tan=tan_hlf_a_tan_hlf_b*sin(ngl_sfc_ltr_C)/(1.0+tan_hlf_a_tan_hlf_b*cos(ngl_sfc_ltr_C)); assert(fabs(xcs_sph_hlf_tan) != M_PI_2); xcs_sph=2.0*atan(xcs_sph_hlf_tan); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO SAS area formula for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16e, %0.16e, %0.16e). Spherical excess = %0.16e.\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c,xcs_sph); // Single-line version // xcs_sph=2.0*atan(tan(0.5*ngl_ltr_a)*tan(0.5*ngl_ltr_b)*sin(2.0*acos(sqrt(sin(prm_smi)*sin(prm_smi-ngl_c)/(sin(ngl_a)*sin(ngl_b)))))/(1.0+tan_hlf_a_tan_hlf_b*cos(2.0*acos(sqrt(sin(prm_smi)*sin(prm_smi-ngl_c)/(sin(ngl_a)*sin(ngl_b))))))); /* Above procedure for problematic needle-shaped and isoceles-shaped triangles degrades statistics For ne30pg2, ne120pg2 -> cmip, setting area = 0.0 _greatly_ improves area statistics (Why?) Set spherical excess to zero for problematic needle-shaped and isoceles-shaped triangles */ /* fxm: Make zeroing skinny needles/isoceles-shaped triangle-areas a command-line option? */ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO Setting SAS area = 0.0\n",nco_prg_nm_get()); xcs_sph=0.0; /* !flg_sas */ }else{ double xcs_sph_qtr_tan; /* [frc] Tangent of one-quarter the spherical excess */ xcs_sph_qtr_tan=sqrt(tan(0.5*prm_smi)*tan(0.5*(prm_smi-ngl_a))*tan(0.5*(prm_smi-ngl_b))*tan(0.5*(prm_smi-ngl_c))); assert(fabs(xcs_sph_qtr_tan) != M_PI_2); xcs_sph=4.0*atan(xcs_sph_qtr_tan); /* 20191014: Aggregate all previous area-related commands into one, gigantic, unreadable, possibly more precise command (tested and it is more obfuscated but not more precise) */ // xcs_sph=4.0*atan(sqrt(tan(0.5*0.5*(ngl_a+ngl_b+ngl_c))*tan(0.5*(0.5*(ngl_a+ngl_b+ngl_c)-ngl_a))*tan(0.5*(0.5*(ngl_a+ngl_b+ngl_c)-ngl_b))*tan(0.5*(0.5*(ngl_a+ngl_b+ngl_c)-ngl_c)))); } /* !flg_sas */ if(isnan(xcs_sph)){ const double eps_ngl_skn=1.0e-13; /* [frc] Angles skinnier than this form needles whose area ~ 0.0 */ /* Categorize reason for NaN */ (void)fprintf(stdout,"%s: WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\nUnxpected NaN polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16e, %0.16e, %0.16e).\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); if( /* Side exceeds semi-perimeter */ (ngl_a > prm_smi) || (ngl_b > prm_smi) || (ngl_c > prm_smi) ){ (void)fprintf(stdout,"%s: WARNING Triangle side exceeds semi-perimeter = %0.16e polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16e, %0.16e, %0.16e). Assigned triangle area = 0.0.\n",nco_prg_nm_get(),prm_smi,col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); }else if( /* Are angles too skinny? Quite often on ne30pg2, ne120pg2 */ (ngl_a < eps_ngl_skn) || (ngl_b < eps_ngl_skn) || (ngl_c < eps_ngl_skn) ){ (void)fprintf(stdout,"%s: WARNING Triangle has at least one skinny angles < %g [rdn] for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16f, %0.16f, %0.16f). Assigned triangle area = 0.0.\n",nco_prg_nm_get(),eps_ngl_skn,col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); }else if( /* Are two vertices identical to double-precision? Never on ne30pg2, ne120pg2 */ ((lat_bnd[idx_a] == lat_bnd[idx_b]) && (lon_bnd[idx_a] == lon_bnd[idx_b])) || ((lat_bnd[idx_b] == lat_bnd[idx_c]) && (lon_bnd[idx_b] == lon_bnd[idx_c])) || ((lat_bnd[idx_c] == lat_bnd[idx_a]) && (lon_bnd[idx_c] == lon_bnd[idx_a])) ){ (void)fprintf(stdout,"%s: WARNING Triangle has repeated points for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g). Assigned triangle area = 0.0.\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c]); }else{ (void)fprintf(stdout,"%s: WARNING Triangle area formula yields NaN for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16f, %0.16f, %0.16f). Are points co-linear? Assigned triangle area = 0.0.\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); } /* !co-linear */ xcs_sph=0.0; } /* !NaN */ area[col_idx]+=xcs_sph; /* Accumulate spherical triangle area into reported polygon area and adjust below */ area_smc+=xcs_sph; /* Accumulate spherical triangle area into small-circle polygon area and adjust below */ area_ttl+=xcs_sph; /* Accumulate spherical triangle area into spherical polygon area */ area_smc_ttl+=xcs_sph; /* Accumulate spherical triangle area into total polygon area and adjust below */ /* 20160918 from here to end of loop is non-spherical work 20170217: Temporarily turn-off latitude circle diagnostics because Sungduk's POP case breaks them Canonical latitude-triangle geometry has point A at apex and points B and C at same latitude ncremap --dbg=1 --alg_typ=nco --grd_src=${DATA}/grids/ne30np4_pentagons.091226.nc --grd_dst=${DATA}/grids/cmip6_180x360_scrip.20181001.nc --map=${DATA}/maps/map_ne30np4_to_cmip6_180x360_nco.20190601.nc ncremap --dbg=1 -R 'edg_typ=smc' --alg_typ=nco --grd_src=${DATA}/grids/ne30np4_pentagons.091226.nc --grd_dst=${DATA}/grids/cmip6_180x360_scrip.20181001.nc --map=${DATA}/maps/map_ne30np4_to_cmip6_180x360_smc.20190601.nc */ flg_tri_crr_smc=False; if(lat_bnd_rdn[idx_a] == lat_bnd_rdn[idx_b] || lat_bnd_rdn[idx_b] == lat_bnd_rdn[idx_c] || lat_bnd_rdn[idx_c] == lat_bnd_rdn[idx_a]){ /* Set flag only if triangle is not degenerate. Degenerate triangles (3 points on a geodesic) have zero area */ if(xcs_sph != 0.0) flg_ply_has_smc=flg_tri_crr_smc=True; if(nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: DEBUG Found small circle triangle with vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c]); } /* endif */ if((edg_typ == nco_edg_smc) && flg_tri_crr_smc){ double ngl_plr; /* [rdn] Polar angle (co-latitude) */ long idx_ltr_a; /* [idx] Point A (apex) of canonical latitude-triangle geometry, 1-D index */ long idx_ltr_b; /* [idx] Point B (base) of canonical latitude-triangle geometry, 1-D index */ long idx_ltr_c; /* [idx] Point C (base) of canonical latitude-triangle geometry, 1-D index */ /* Rotate labels to standard position with vertex A, equi-latitude points B and C */ if(lat_bnd_rdn[idx_a] == lat_bnd_rdn[idx_b]){ idx_ltr_a=idx_c; idx_ltr_b=idx_a; idx_ltr_c=idx_b; ngl_ltr_a=ngl_c; ngl_ltr_b=ngl_a; ngl_ltr_c=ngl_b; ngl_plr=fabs(M_PI_2-lat_bnd_rdn[idx_a]); }else if(lat_bnd_rdn[idx_b] == lat_bnd_rdn[idx_c]){ idx_ltr_a=idx_a; idx_ltr_b=idx_b; idx_ltr_c=idx_c; ngl_ltr_a=ngl_a; ngl_ltr_b=ngl_b; ngl_ltr_c=ngl_c; ngl_plr=fabs(M_PI_2-lat_bnd_rdn[idx_b]); }else if(lat_bnd_rdn[idx_c] == lat_bnd_rdn[idx_a]){ idx_ltr_a=idx_b; idx_ltr_b=idx_c; idx_ltr_c=idx_a; ngl_ltr_a=ngl_b; ngl_ltr_b=ngl_c; ngl_ltr_c=ngl_a; ngl_plr=fabs(M_PI_2-lat_bnd_rdn[idx_c]); }else{ (void)fprintf(stdout,"%s: ERROR latitudes not equal in small circle section. Vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c]); abort(); } /* endif */ /* 20160918: Compute exact area of latitude triangle wedge */ double xpn_x; /* [frc] Expansion parameter */ lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_ltr_b],lon_bnd_rdn[idx_ltr_c])); assert(lon_dlt != 0.0); // Latitude triangles must have bases with distinct longitudes if(lon_dlt != M_PI){ /* Normal clause executed for small-circle triangles */ /* Numeric conditioning uncertain. Approaches divide-by-zero when lon_dlt << 1 */ xpn_x=lat_bnd_sin[idx_ltr_b]*(1.0-cos(lon_dlt))/sin(lon_dlt); assert(fabs(xpn_x) != M_PI_2); area_smc_crc=2.0*atan(xpn_x); /* 20170217: Sungduk's POP regrid triggers following abort(): ncremap -D 1 -i ~/pop_g16.nc -d ~/cam_f19.nc -o ~/foo.nc */ //assert(xpn_x >= 0.0); //if(lat_bnd[idx_ltr_b] > 0.0) area_smc_crc+=-lon_dlt*lat_bnd_sin[idx_ltr_b]; else area_smc_crc+=+lon_dlt*lat_bnd_sin[idx_ltr_b]; area_smc_crc+=-lon_dlt*lat_bnd_sin[idx_ltr_b]; }else{ /* 20200228: Latitude triangles may have bases with longitudes that differ by 180 degrees Consider a quadrilateral with four equidistant vertices in longitude, and that caps a pole: CSZ decomposition technique divides this into two triangles each with three co-latitudinal points and no vertex at pole Solution candidates: 1. Divide such quadrilaterals using centroid technique Just realized current implementation of centroid decomposition fails on polar caps Failure occurs because centroid latitude is +/- ~90 not mean of vertices' latitudes Must impute "pseudo-centroid" with latitude +/- 90 instead of averaging vertex latitudes Requires testing each polygon to determine if it contains pole <- Too difficult/expensive 2. Assume latitude triangles whose base is 180 degrees are at pole Compute area exactly using analytic formula for annular lune */ (void)fprintf(stdout,"%s: INFO longitudes differ by pi in small circle section. Vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_ltr_a],lon_bnd[idx_ltr_a],lat_bnd[idx_ltr_b],lon_bnd[idx_ltr_b],lat_bnd[idx_ltr_c],lon_bnd[idx_ltr_c]); (void)fprintf(stdout,"%s: DEBUG col_nbr=%lu, bnd_nbr=%d, col_idx=%ld, area=%g. Vertices [0..bnd_nbr-1] in format idx (lat,lon)\n",nco_prg_nm_get(),col_nbr,bnd_nbr,col_idx,xcs_sph); for(int bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%2d (%g, %g)\n",bnd_idx,lat_bnd[bnd_nbr*col_idx+bnd_idx],lon_bnd[bnd_nbr*col_idx+bnd_idx]); (void)fprintf(stdout,"%s: INFO Assuming this triangle is decomposed from polar cap polygon. Treating area with analytic formula for annular lune\n",nco_prg_nm_get()); /* Compute small circle correction as difference between spherical triangle area and standard annuular lune formula Small circle correction is positive-definite for polar triangles so use fabs(sin(lat_bnd_sin)) */ area_smc_crc=lon_dlt*fabs(lat_bnd_sin[idx_ltr_b])-area_smc; } /* !lon_dlt */ // Adjust diagnostic areas by small-circle area correction area_smc+=area_smc_crc; area_smc_ttl+=area_smc_crc; area_smc_crc_ttl+=area_smc_crc; area_smc_crc_abs_ttl+=fabs(area_smc_crc); // 20200109: Adjust area reported to calling code by small-circle area correction area[col_idx]+=area_smc_crc; if(0){ /* 20160918: Approximate area of latitude triangle wedge. Use truncated power expansion of exact formula. */ double xpn_x_sqr; /* [frc] Expansion parameter squared */ double xpn_sum; /* [frc] Expansion sum */ double xpn_nmr; /* [frc] Expansion term numerator */ double xpn_trm; /* [frc] Expansion term */ double xpn_dnm; /* [frc] Expansion term denominator */ const unsigned short int rdr_xpn=3; /* [nbr] Order of N in trigonometric series expansion */ unsigned short int idx_xpn; /* [idx] Index in series expansion */ xpn_x=cos(ngl_plr)*(1.0-cos(lon_dlt))/sin(lon_dlt); xpn_x_sqr=xpn_x*xpn_x; xpn_nmr=xpn_x; xpn_dnm=1.0; xpn_trm=xpn_nmr/xpn_dnm; xpn_sum+=xpn_trm; for(idx_xpn=3;idx_xpn<=rdr_xpn;idx_xpn+=2){ xpn_nmr*=xpn_x_sqr; xpn_dnm*=(idx_xpn-1)*idx_xpn; xpn_trm=xpn_nmr/xpn_dnm; xpn_sum+=xpn_trm; } /* !idx_xpn */ (void)fprintf(stdout,"%s: Small-circle area using series approximation...not implemented yet\n",nco_prg_nm_get()); } /* !0 */ if(nco_dbg_lvl_get() >= nco_dbg_scl){ (void)fprintf(stdout,"%s: INFO %s col_idx = %li triangle %d spherical area, latitude-triangle area, %% difference: %g, %g, %g%%\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,xcs_sph,xcs_sph+area_smc_crc,100.0*area_smc_crc/xcs_sph); if(fabs(area_smc_crc/xcs_sph) > 0.1){ (void)fprintf(stdout,"%s: DEBUG Non-spherical correction exceeds 10%% for current triangle with vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_ltr_a],lon_bnd[idx_ltr_a],lat_bnd[idx_ltr_b],lon_bnd[idx_ltr_b],lat_bnd[idx_ltr_c],lon_bnd[idx_ltr_c]); } /* !fabs */ } /* !dbg */ } /* !edg_typ && flg_tri_crr_smc */ } /* !tri_idx */ if(edg_typ == nco_edg_smc && flg_ply_has_smc){ /* Current gridcell contained at least one latitude-triangle */ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO %s col_idx = %li spherical area, small circle area, %% difference: %g, %g, %g%%\n",nco_prg_nm_get(),fnc_nm,col_idx,area[col_idx],area_smc,100.0*(area_smc-area[col_idx])/area[col_idx]); } /* !edg_typ && !flg_ply_has_smc */ } /* !col_idx */ if(edg_typ == nco_edg_smc && nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO %s total spherical area, small circle area, %% difference, crc_ttl, crc_abs_ttl: %g, %g, %g%%, %g, %g\n",nco_prg_nm_get(),fnc_nm,area_ttl,area_smc_ttl,100.0*(area_smc_ttl-area_ttl)/area_ttl,area_smc_crc_ttl,area_smc_crc_abs_ttl); if(vrt_vld) vrt_vld=(long *)nco_free(vrt_vld); if(a_idx) a_idx=(long *)nco_free(a_idx); if(b_idx) b_idx=(long *)nco_free(b_idx); if(c_idx) c_idx=(long *)nco_free(c_idx); if(lat_bnd_rdn) lat_bnd_rdn=(double *)nco_free(lat_bnd_rdn); if(lon_bnd_rdn) lon_bnd_rdn=(double *)nco_free(lon_bnd_rdn); if(lat_bnd_cos) lat_bnd_cos=(double *)nco_free(lat_bnd_cos); if(lon_bnd_cos) lon_bnd_cos=(double *)nco_free(lon_bnd_cos); if(lat_bnd_sin) lat_bnd_sin=(double *)nco_free(lat_bnd_sin); if(lon_bnd_sin) lon_bnd_sin=(double *)nco_free(lon_bnd_sin); } /* !nco_sph_plg_area() */ int /* O [enm] Return code */ nco_rgr_tps /* [fnc] Regrid using TempestRemap library */ (rgr_sct * const rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Regrid fields using TempestRemap "library" (more precisely, executables) Routine was originally written to call Tempest executables However, that functionality was all placed into the ncremap shell script Thus this C-interface is currently unused TempestRemap2 has a library that may be accessed on-line Test Tempest library: no way to activate yet export DATA_TEMPEST='/data/zender/rgr';ncks -O --rgr=Y ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc */ const char fnc_nm[]="nco_rgr_tps()"; const int fmt_chr_nbr=6; const char *cmd_rgr_fmt; char *cmd_rgr; char fl_grd_dst[]="/tmp/foo_outRLLMesh.g"; char *fl_grd_dst_cdl; int rcd_sys; int lat_nbr_rqs=180; int lon_nbr_rqs=360; nco_rgr_tps_cmd nco_tps_cmd; /* [enm] TempestRemap command enum */ char *nvr_DATA_TEMPEST; /* [sng] Directory where Tempest grids, meshes, and weights are stored */ nvr_DATA_TEMPEST=getenv("DATA_TEMPEST"); rgr->drc_tps= (nvr_DATA_TEMPEST && strlen(nvr_DATA_TEMPEST) > 0L) ? (char *)strdup(nvr_DATA_TEMPEST) : (char *)strdup("/tmp"); if(nco_dbg_lvl_get() >= nco_dbg_crr){ (void)fprintf(stderr,"%s: INFO %s reports\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stderr,"drc_tps = %s, ",rgr->drc_tps ? rgr->drc_tps : "NULL"); (void)fprintf(stderr,"\n"); } /* endif dbg */ /* Allow for whitespace characters in fl_grd_dst Assume CDL translation results in acceptable name for shell commands */ fl_grd_dst_cdl=nm2sng_fl(fl_grd_dst); /* Construct and execute regridding command */ nco_tps_cmd=nco_rgr_GenerateRLLMesh; cmd_rgr_fmt=nco_tps_cmd_fmt_sng(nco_tps_cmd); cmd_rgr=(char *)nco_malloc((strlen(cmd_rgr_fmt)+strlen(fl_grd_dst_cdl)-fmt_chr_nbr+1UL)*sizeof(char)); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stderr,"%s: %s reports generating %d by %d RLL mesh in %s...\n",nco_prg_nm_get(),fnc_nm,lat_nbr_rqs,lon_nbr_rqs,fl_grd_dst); (void)sprintf(cmd_rgr,cmd_rgr_fmt,lat_nbr_rqs,lon_nbr_rqs,fl_grd_dst_cdl); rcd_sys=system(cmd_rgr); if(rcd_sys == -1){ (void)fprintf(stdout,"%s: ERROR %s unable to complete TempestRemap regridding command \"%s\"\n",nco_prg_nm_get(),fnc_nm,cmd_rgr); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"done\n"); /* Clean-up memory */ if(fl_grd_dst_cdl) fl_grd_dst_cdl=(char *)nco_free(fl_grd_dst_cdl); if(cmd_rgr) cmd_rgr=(char *)nco_free(cmd_rgr); return NCO_NOERR; } /* end nco_rgr_tps() */ const char * /* O [sng] String describing two-dimensional grid-type */ nco_grd_2D_sng /* [fnc] Convert two-dimensional grid-type enum to string */ (const nco_grd_2D_typ_enm nco_grd_2D_typ) /* I [enm] Two-dimensional grid-type enum */ { /* Purpose: Convert two-dimensional grid-type enum to string */ switch(nco_grd_2D_typ){ case nco_grd_2D_unk: return "Unknown, unclassified, or unrepresentable 2D grid type (e.g., unstructured, curvilinear, POP displaced-pole)"; case nco_grd_2D_gss: return "Gaussian latitude grid. Used by spectral transform models, e.g., CCM 1-3, CAM 1-3, ECMWF Forecast, LSM, MATCH, NCEP (R1, R2), UCICTM."; case nco_grd_2D_fv: return "Cap-latitude grid, aka FV-scalar grid (in Lin-Rood representation). When global (not regional) in extent and with odd number of latitudes, poles are considered at (and labeled as) centers of first and last gridcells. For example lat_ctr=-90,-89,-88,... and lat_crn=-89.5,-88.5,-87.5,... Thus pole-gridcells span half the equi-angular latitude increment of the rest of the grid. Used by CAM FV (i.e., CAM 4-6), ECMWF (ERA-I, ERA40, ERA5), GEOS-CHEM, UCICTM, UKMO."; case nco_grd_2D_eqa: return "Uniform/Equi-Angular latitude grid. Uniform/Equi-angle (everywhere) latitude grid. When global (not regional) in extent and with even number of latitudes, poles are at corners/edges of first and last gridcells. For example lat_ctr=-89.5,-88.5,-87.5,... and lat_crn=-90,-89,-88,.... When global, forms valid FV-staggered (aka FV-velocity, aka offset) grid (for Lin-Rood representation). Used by CIESIN/SEDAC, IGBP-DIS, TOMS AAI, WOCE."; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_2D_sng() */ const char * /* O [sng] String describing latitude grid-type */ nco_grd_lat_sng /* [fnc] Convert latitude grid-type enum to string */ (const nco_grd_lat_typ_enm nco_grd_lat_typ) /* I [enm] Latitude grid-type enum */ { /* Purpose: Convert latitude grid-type enum to string */ switch(nco_grd_lat_typ){ case nco_grd_lat_unk: return "Unknown, unclassified, or unrepresentable latitude grid type (e.g., unstructured, curvilinear, POP3)"; case nco_grd_lat_gss: return "Gaussian latitude grid used by global spectral models: CCM 1-3, CAM 1-3, ECMWF Forecast, LSM, MATCH, NCEP (R1, R2), UCICTM."; case nco_grd_lat_fv: return "Cap-latitude grid, aka FV-scalar grid (in Lin-Rood representation). When global (not regional) in extent and with odd number of latitudes, poles are considered at (and labeled as) centers of first and last gridcells. For example lat_ctr=-90,-89,-88,... and lat_crn=-89.5,-88.5,-87.5,... Thus pole-gridcells span half the equi-angular latitude increment of the rest of the grid. Used by CAM FV (i.e., CAM 4-6), ECMWF (ERA-I, ERA40, ERA5), GEOS-CHEM, UCICTM, UKMO."; case nco_grd_lat_eqa: return "Uniform/Equi-Angular latitude grid. Uniform/Equi-angle (everywhere) latitude grid. When global (not regional) in extent and with even number of latitudes, poles are at corners/edges of first and last gridcells. For example lat_ctr=-89.5,-88.5,-87.5,... and lat_crn=-90,-89,-88,.... When global, forms valid FV-staggered (aka FV-velocity, aka offset) grid (for Lin-Rood representation). Used by CIESIN/SEDAC, IGBP-DIS, TOMS AAI, WOCE."; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_lat_sng() */ const char * /* O [sng] String describing longitude grid-type */ nco_grd_lon_sng /* [fnc] Convert longitude grid-type enum to string */ (const nco_grd_lon_typ_enm nco_grd_lon_typ) /* I [enm] Longitude grid-type enum */ { /* Purpose: Convert longitude grid-type enum to string */ switch(nco_grd_lon_typ){ case nco_grd_lon_unk: return "Unknown, unclassified, or unrepresentable longitude grid type (e.g., unstructured, curvilinear)"; case nco_grd_lon_180_wst: return "Date line at west edge of first longitude cell"; case nco_grd_lon_180_ctr: return "Date line at center of first longitude cell"; case nco_grd_lon_Grn_wst: return "Greenwich at west edge of first longitude cell"; case nco_grd_lon_Grn_ctr: return "Greenwich at center of first longitude cell"; case nco_grd_lon_bb: return "Longitude grid determined by bounding box (lon_wst/lon_est) and gridcell number (lon_nbr)"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_lon_sng() */ const char * /* O [sng] String describing grid extent */ nco_grd_xtn_sng /* [fnc] Convert two-dimensional grid-extent enum to string */ (const nco_grd_xtn_enm nco_grd_xtn) /* I [enm] Grid-extent enum */ { /* Purpose: Convert grid-extent enum to string */ switch(nco_grd_xtn){ case nco_grd_xtn_nil: return "Unknown"; case nco_grd_xtn_glb: return "Global"; case nco_grd_xtn_rgn: return "Regional"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_xtn_sng() */ const char * /* O [sng] String describing grid conversion */ nco_rgr_grd_sng /* [fnc] Convert grid conversion enum to string */ (const nco_rgr_typ_enm nco_rgr_typ) /* I [enm] Grid conversion enum */ { /* Purpose: Convert grid conversion enum to string */ switch(nco_rgr_typ){ case nco_rgr_grd_1D_to_1D: return "1D_to_1D"; case nco_rgr_grd_1D_to_2D: return "1D_to_2D"; case nco_rgr_grd_2D_to_1D: return "2D_to_1D"; case nco_rgr_grd_2D_to_2D: return "2D_to_2D"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_grd_sng() */ const char * /* O [sng] String describing regridding method */ nco_rgr_mth_sng /* [fnc] Convert regridding method enum to string */ (const nco_rgr_mth_typ_enm nco_rgr_mth_typ) /* I [enm] Regridding method enum */ { /* Purpose: Convert regridding method enum to string */ switch(nco_rgr_mth_typ){ case nco_rgr_mth_conservative: return "Conservative remapping"; case nco_rgr_mth_bilinear: return "Bilinear remapping"; case nco_rgr_mth_none: return "none"; case nco_rgr_mth_unknown: return "Unknown (TempestRemap or ESMF_weight_only)"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_mth_sng() */ const char * /* O [sng] String describing mapfile generator */ nco_rgr_mpf_sng /* [fnc] Convert mapfile generator enum to string */ (const nco_rgr_mpf_typ_enm nco_rgr_mpf_typ) /* I [enm] Mapfile generator enum */ { /* Purpose: Convert mapfile generator enum to string */ switch(nco_rgr_mpf_typ){ case nco_rgr_mpf_ESMF: return "ESMF Offline Regridding Weight Generator (ERWG), either from ESMF_RegridWeightGen directly or via NCL"; case nco_rgr_mpf_SCRIP: return "SCRIP (original LANL package)"; case nco_rgr_mpf_Tempest: return "TempestRemap (GenerateOfflineMap)"; case nco_rgr_mpf_ESMF_weight_only: return "ESMF Offline Regridding Weight Generator (ERWG), either from ESMF_RegridWeightGen directly or via NCL, with --weight_only option from ERWG 7.1+"; case nco_rgr_mpf_NCO: return "netCDF Operators (NCO) Offline Regridding Weight Generator"; case nco_rgr_mpf_unknown: return "Unknown Weight Generator"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_mpf_sng() */ const char * /* O [sng] String describing regridding normalization */ nco_rgr_nrm_sng /* [fnc] Convert regridding normalization enum to string */ (const nco_rgr_nrm_typ_enm nco_rgr_nrm_typ) /* I [enm] Regridding normalization enum */ { /* Purpose: Convert regridding normalization enum to string */ switch(nco_rgr_nrm_typ){ case nco_rgr_nrm_fracarea: return "fracarea"; case nco_rgr_nrm_destarea: return "destarea"; case nco_rgr_nrm_none: return "none"; case nco_rgr_nrm_unknown: return "Unknown (possibilities include ESMF_weight_only, NCO, and TempestRemap)"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_nrm_sng() */ const char * /* O [sng] String containing regridding command and format */ nco_tps_cmd_fmt_sng /* [fnc] Convert TempestRemap command enum to command string */ (const nco_rgr_tps_cmd nco_tps_cmd) /* I [enm] TempestRemap command enum */ { /* Purpose: Convert TempestRemap command enum to command string and format */ switch(nco_tps_cmd){ case nco_rgr_ApplyOfflineMap: return "ApplyOfflineMap"; case nco_rgr_CalculateDiffNorms: return "CalculateDiffNorms"; case nco_rgr_GenerateCSMesh: return "GenerateCSMesh --res %d --file %s"; case nco_rgr_GenerateGLLMetaData: return "GenerateGLLMetaData"; case nco_rgr_GenerateICOMesh: return "GenerateICOMesh"; case nco_rgr_GenerateLambertConfConicMesh: return "GenerateLambertConfConicMesh"; case nco_rgr_GenerateOfflineMap: return "GenerateOfflineMap --in_mesh %s --out_mesh %s --ov_mesh %s --in_data %s --out_data %s"; case nco_rgr_GenerateOverlapMesh: return "GenerateOverlapMesh --a %s --b %s --out %s"; case nco_rgr_GenerateRLLMesh: return "GenerateRLLMesh --lat %d --lon %d --file %s"; case nco_rgr_GenerateTestData: return "GenerateTestData --mesh %s --np %d --test %d --out %s"; case nco_rgr_MeshToTxt: return "MeshToTxt"; case nco_rgr_AAA_nil: case nco_rgr_ZZZ_last: default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_tps_cmd_fmt_sng() */ const char * /* O [sng] String containing regridding command name */ nco_tps_cmd_sng /* [fnc] Convert TempestRemap command enum to command name */ (const nco_rgr_tps_cmd nco_tps_cmd) /* I [enm] TempestRemap command enum */ { /* Purpose: Convert TempestRemap command enum to command string */ switch(nco_tps_cmd){ case nco_rgr_ApplyOfflineMap: return "ApplyOfflineMap"; case nco_rgr_CalculateDiffNorms: return "CalculateDiffNorms"; case nco_rgr_GenerateCSMesh: return "GenerateCSMesh"; case nco_rgr_GenerateGLLMetaData: return "GenerateGLLMetaData"; case nco_rgr_GenerateICOMesh: return "GenerateICOMesh"; case nco_rgr_GenerateLambertConfConicMesh: return "GenerateLambertConfConicMesh"; case nco_rgr_GenerateOfflineMap: return "GenerateOfflineMap"; case nco_rgr_GenerateOverlapMesh: return "GenerateOverlapMesh"; case nco_rgr_GenerateRLLMesh: return "GenerateRLLMesh"; case nco_rgr_GenerateTestData: return "GenerateTestData"; case nco_rgr_MeshToTxt: return "MeshToTxt"; case nco_rgr_AAA_nil: case nco_rgr_ZZZ_last: default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_tps_cmd_sng() */ int /* O [enm] Return code */ nco_grd_mk /* [fnc] Create SCRIP-format grid file */ (rgr_sct * const rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Use grid information to create SCRIP-format grid file Spherical geometry terminology: spherical cap = spherical dome = volume cut-off by plane spherical lune = digon = area bounded by two half-great circles = base of spherical wedge spherical segment = volume defined by cutting sphere with pair parallel planes spherical sector = volume subtended by lat1 spherical wedge = ungula = volume subtended by lon2-lon1 spherical zone = area of spherical segment excluding bases spherical quadrangle = area of intersection of spherical zone and lune (i.e., area of bearing = angle from true north geodesic = shortest path between points on a surface great circle = orthodrome = "straight path" = geodesic of the sphere convergency = difference (in azimuth?) between great circle tracks at two different positions conversion angle = angle between geodesic and rhumb line rhumb line = loxodrome = "oblique (or slanted) path" = line of constant azimuth Formulae: http://www.movable-type.co.uk/scripts/latlong.html # On-line Javascript implementation http://williams.best.vwh.net/avform.htm ACME: https://acme-svn2.ornl.gov/acme-repo/acme/mapping/grids https://acme-svn2.ornl.gov/acme-repo/acme/inputdata/cpl/gridmaps NCAR: yellowstone.ucar.edu:/glade/p/cesm/cseg/mapping/grids yellowstone.ucar.edu:/glade/p_old/cesm/cseg/mapping/grids Global RLL grids: ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr grid=${DATA}/grids/180x360_SCRIP.20150901.nc --rgr latlon=180,360 --rgr lat_typ=eqa --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Equiangular grid 90x180' --rgr grid=${DATA}/grids/90x180_SCRIP.20150901.nc --rgr latlon=90,180 --rgr lat_typ=eqa --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc Maps for global RLL grids: ESMF_RegridWeightGen -s ${DATA}/grids/180x360_SCRIP.20150901.nc -d ${DATA}/grids/90x180_SCRIP.20150901.nc -w ${DATA}/maps/map_180x360_to_90x180.20150901.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/90x180_SCRIP.20150901.nc -d ${DATA}/grids/180x360_SCRIP.20150901.nc -w ${DATA}/maps/map_90x180_to_180x360.20150901.nc --method conserve ACME grids: ncks -O -D 1 --rgr ttl='FV-scalar grid 129x256' --rgr grid=${DATA}/grids/129x256_SCRIP.20150910.nc --rgr latlon=129,256 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='FV-scalar grid 257x512' --rgr grid=${DATA}/grids/257x512_SCRIP.20150910.nc --rgr latlon=257,512 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='FV-scalar grid 801x1600' --rgr grid=${DATA}/grids/801x1600_SCRIP.20150910.nc --rgr latlon=801,1600 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ACME maps: ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/129x256_SCRIP.20150910.nc -w ${DATA}/maps/map_ne30np4_to_fv129x256_aave.20150910.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/257x512_SCRIP.20150910.nc -w ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.20150910.nc --method bilinear ESMF_RegridWeightGen -s ${DATA}/grids/ne120np4_pentagons.100310.nc -d ${DATA}/grids/257x512_SCRIP.20150910.nc -w ${DATA}/maps/map_ne120np4_to_fv257x512_aave.20150910.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne120np4_pentagons.100310.nc -d ${DATA}/grids/801x1600_SCRIP.20150910.nc -w ${DATA}/maps/map_ne120np4_to_fv801x1600_bilin.20150910.nc --method bilinear AMWG grids: AMWG diagnostics (until ~2016) mis-diagnose FV grids with odd numbers of latitudes as Gaussian Grids ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 96x144 for horizontal resolution 1.9x2.5 degrees' --rgr grid=${DATA}/grids/96x144_SCRIP.20160301.nc --rgr latlon=96,144 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 192x288 for horizontal resolution 0.9x1.25 degrees' --rgr grid=${DATA}/grids/192x288_SCRIP.20160301.nc --rgr latlon=192,288 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 128x256 for horizontal resolution 1.4x1.4 degrees' --rgr grid=${DATA}/grids/128x256_SCRIP.20160301.nc --rgr latlon=128,256 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 256x512 for horizontal resolution 0.7x0.7 degrees' --rgr grid=${DATA}/grids/256x512_SCRIP.20160301.nc --rgr latlon=256,512 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 800x1600 for horizontal resolution 0.225x0.225 degrees' --rgr grid=${DATA}/grids/800x1600_SCRIP.20160301.nc --rgr latlon=800,1600 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Equiangular grid 360x720 produced by RTM' --rgr grid=${DATA}/grids/360x720rtm_SCRIP.20160301.nc --rgr latlon=360,720 --rgr lat_typ=eqa --rgr lon_typ=180_wst ~/nco/data/in.nc ~/foo.nc AMWG maps old method (no provenance archived): ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/128x256_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv128x256_aave.20160301.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/256x512_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv256x512_bilin.20160301.nc --method bilinear ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/256x512_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv256x512_aave.20160301.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/800x1600_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv800x1600_bilin.20160301.nc --method bilinear AMWG maps with ncremap (preferred method): ncremap -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/128x256_SCRIP.20160301.nc -m ${DATA}/maps/map_ne30np4_to_fv128x256_aave.20160301.nc -w esmf -a conserve ncremap -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/256x512_SCRIP.20160301.nc -m ${DATA}/maps/map_ne30np4_to_fv256x512_bilin.20160301.nc -w esmf -a bilinear ncremap -s ${DATA}/grids/ne120np4_pentagons.100310.nc -g ${DATA}/grids/256x512_SCRIP.20160301.nc -m ${DATA}/maps/map_ne120np4_to_fv256x512_aave.20160301.nc -w esmf -a conserve ncremap -s ${DATA}/grids/ne120np4_pentagons.100310.nc -g ${DATA}/grids/800x1600_SCRIP.20160301.nc -m ${DATA}/maps/map_ne120np4_to_fv800x1600_bilin.20160301.nc -w esmf -a bilinear MPAS grids: NCO cannot yet generate MPAS grids, but given an MPAS grid it can generate appropriate maps MPAS maps: ncremap -s ${DATA}/grids/oEC60to30.SCRIP.150729.nc -g ${DATA}/grids/t62_SCRIP.20150901.nc -m ${DATA}/maps/map_oEC60to30_to_t62_aave.20160301.nc -w esmf -a conserve ncremap -s ${DATA}/grids/oEC60to30.SCRIP.150729.nc -g ${DATA}/grids/t62_SCRIP.20150901.nc -m ${DATA}/maps/map_oEC60to30_to_t62_bilin.20160301.nc -w esmf -a bilinear Regional RLL grids: ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr grid=${DATA}/sld/rgr/grd_dst.nc --rgr latlon=100,100 --rgr snwe=30.0,70.0,-120.0,-90.0 ~/nco/data/in.nc ~/foo.nc Global RLL skeleton: ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr skl=${DATA}/sld/rgr/skl_180x360.nc --rgr grid=${DATA}/grids/180x360_SCRIP.20150901.nc --rgr latlon=180,360#lat_typ=eqa#lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc Curvilinear grids: ncks -O -D 1 --rgr ttl='Curvilinear grid 10x20. Degenerate case.' --rgr crv --rgr lon_crv=0.0 --rgr skl=${DATA}/sld/rgr/skl_crv.nc --rgr grid=${DATA}/sld/rgr/grd_crv.nc --rgr latlon=10,20 --rgr snwe=-5.0,5.0,-10.0,10.0 ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Curvilinear grid 10x20. Curvilinearity = 1.0 lon' --rgr lon_crv=1.0 --rgr skl=${DATA}/sld/rgr/skl_crv.nc --rgr grid=${DATA}/sld/rgr/grd_crv.nc --rgr latlon=10,20 --rgr snwe=-5.0,5.0,-10.0,10.0 ~/nco/data/in.nc ~/foo.nc 1-D Latitude (no longitude) grids: ncks -O -D 1 --rgr ttl='Latitude-only zonal grid' --rgr skl=${DATA}/sld/rgr/skl_lat_10dgr_uni.nc --rgr grid=${DATA}/sld/rgr/grd_lat_10dgr_uni.nc --rgr latlon=18,1 --rgr snwe=-90,90,0,360 ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Latitude-only zonal grid' --rgr skl=${DATA}/sld/rgr/skl_lat_05dgr_cap.nc --rgr grid=${DATA}/sld/rgr/grd_lat_05dgr_cap.nc --rgr latlon=37,1 --rgr snwe=-90,90,0,360 ~/nco/data/in.nc ~/foo.nc ncremap -i ${DATA}/sld/rgr/skl_lat_10dgr_uni.nc -d ${DATA}/sld/rgr/skl_lat_05dgr_cap.nc -m ${DATA}/maps/map_lat10uni_to_lat05cap_aave.nc -o ~/rgr/lat10to05.nc ESMF_RegridWeightGen -s ${DATA}/sld/rgr/grd_lat_10dgr_uni.nc -d ${DATA}/sld/rgr/grd_lat_05dgr_cap.nc -w ${DATA}/maps/map_lat10uni_to_lat05cap_aave.nc --method conserve */ const char fnc_nm[]="nco_grd_mk()"; /* [sng] Function name */ const double rdn2dgr=180.0/M_PI; const double dgr2rdn=M_PI/180.0; const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ const int dmn_nbr_3D=3; /* [nbr] Rank of 3-D grid variables */ const int dmn_nbr_grd_max=dmn_nbr_3D; /* [nbr] Maximum rank of grid variables */ const int itr_nbr_max=20; // [nbr] Maximum number of iterations const nc_type crd_typ=NC_DOUBLE; char *fl_out_tmp=NULL_CEWI; char *fl_out; char grd_area_nm[]="grid_area"; /* 20150830: NB ESMF_RegridWeightGen --user_areas looks for variable named "grid_area" */ char dmn_sz_nm[]="grid_dims"; char grd_crn_lat_nm[]="grid_corner_lat"; char grd_crn_lon_nm[]="grid_corner_lon"; char grd_crn_nm[]="grid_corners"; char grd_ctr_lat_nm[]="grid_center_lat"; char grd_ctr_lon_nm[]="grid_center_lon"; char grd_rnk_nm[]="grid_rank"; char grd_sz_nm[]="grid_size"; char msk_nm[]="grid_imask"; double *grd_ctr_lat; /* [dgr] Latitude centers of grid */ double *grd_ctr_lon; /* [dgr] Longitude centers of grid */ double *grd_crn_lat; /* [dgr] Latitude corners of grid */ double *grd_crn_lon; /* [dgr] Longitude corners of grid */ double *area; /* [sr] Area of grid */ double *lat_bnd=NULL_CEWI; /* [dgr] Latitude boundaries of rectangular grid */ double *lat_crn=NULL; /* [dgr] Latitude corners of rectangular grid */ double *lat_ctr=NULL_CEWI; /* [dgr] Latitude centers of rectangular grid */ double *lat_ntf=NULL; /* [dgr] Latitude interfaces of rectangular grid */ double *lat_wgt=NULL; /* [dgr] Latitude weights of rectangular grid */ double *lon_bnd=NULL_CEWI; /* [dgr] Longitude boundaries of rectangular grid */ double *lon_crn=NULL; /* [dgr] Longitude corners of rectangular grid */ double *lon_ctr=NULL_CEWI; /* [dgr] Longitude centers of rectangular grid */ double *lon_ntf=NULL; /* [dgr] Longitude interfaces of rectangular grid */ double area_ttl=0.0; /* [frc] Exact sum of area */ double lat_crv; /* [dgr] Latitudinal curvilinearity */ double lon_crv; /* [dgr] Longitudinal curvilinearity */ double lat_nrt; /* [dgr] Latitude of northern edge of grid */ double lat_sth; /* [dgr] Latitude of southern edge of grid */ double lat_wgt_ttl=0.0; /* [frc] Actual sum of quadrature weights */ double lat_wgt_gss; /* [frc] Latitude weight estimated from interface latitudes */ double lon_est; /* [dgr] Longitude of eastern edge of grid */ double lon_wst; /* [dgr] Longitude of western edge of grid */ double lon_ncr; /* [dgr] Longitude increment */ double lat_ncr; /* [dgr] Latitude increment */ double lon_spn; /* [dgr] Longitude span */ double lat_spn; /* [dgr] Latitude span */ double *wgt_Gss=NULL; // [frc] Gaussian weights double precision int *msk=NULL; /* [flg] Mask of grid */ int *dmn_sz_int; /* [nbr] Array of dimension sizes of grid */ int dmn_ids[dmn_nbr_grd_max]; /* [id] Dimension IDs array for output variable */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NC_FORMAT_CLASSIC; /* [enm] Output file format */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int area_id; /* [id] Area variable ID */ int dmn_id_grd_crn; /* [id] Grid corners dimension ID */ int dmn_id_grd_rnk; /* [id] Grid rank dimension ID */ int dmn_id_grd_sz; /* [id] Grid size dimension ID */ int dmn_sz_int_id; /* [id] Grid dimension sizes ID */ int grd_crn_lat_id; /* [id] Grid corner latitudes variable ID */ int grd_crn_lon_id; /* [id] Grid corner longitudes variable ID */ int grd_ctr_lat_id; /* [id] Grid center latitudes variable ID */ int grd_ctr_lon_id; /* [id] Grid center longitudes variable ID */ int itr_cnt; /* Iteration counter */ int msk_id; /* [id] Mask variable ID */ long dmn_srt[dmn_nbr_grd_max]; long dmn_cnt[dmn_nbr_grd_max]; long bnd_nbr; /* [nbr] Number of bounds in gridcell */ long col_nbr; /* [nbr] Number of columns in grid */ long crn_idx; /* [idx] Counting index for corners */ long grd_crn_nbr; /* [nbr] Number of corners in gridcell */ long grd_rnk_nbr; /* [nbr] Number of dimensions in grid */ long grd_sz_nbr; /* [nbr] Number of gridcells in grid */ long idx2; /* [idx] Counting index for unrolled grids */ long idx; /* [idx] Counting index for unrolled grids */ long lat_idx2; /* [idx] Counting index for unrolled latitude */ long lat_idx; long lat_nbr; /* [nbr] Number of latitudes in grid */ long lon_idx2; /* [idx] Counting index for unrolled longitude */ long lon_idx; long lon_nbr; /* [nbr] Number of longitudes in grid */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=True; /* Option O */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=rgr->flg_uio; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool WRT_TMP_FL=False; /* [flg] Write output to temporary file */ nco_bool flg_grd_1D=False; nco_bool flg_grd_2D=False; nco_bool flg_grd_crv=False; nco_bool flg_s2n=True; /* I [enm] Latitude grid-direction is South-to-North */ nco_grd_2D_typ_enm grd_typ; /* [enm] Grid-type enum */ nco_grd_lat_drc_enm lat_drc; /* [enm] Latitude grid-direction enum */ nco_grd_lat_typ_enm lat_typ; /* [enm] Latitude grid-type enum */ nco_grd_lon_typ_enm lon_typ; /* [enm] Longitude grid-type enum */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ dfl_lvl=rgr->dfl_lvl; grd_typ=rgr->grd_typ; /* [enm] Grid type */ fl_out=rgr->fl_grd; fl_out_fmt=rgr->fl_out_fmt; lat_drc=rgr->lat_drc; /* [enm] Latitude grid direction */ lat_typ=rgr->lat_typ; /* [enm] Latitude grid type */ lon_typ=rgr->lon_typ; /* [enm] Longitude grid type */ lat_nbr=rgr->lat_nbr; /* [nbr] Number of latitudes in grid */ lon_nbr=rgr->lon_nbr; /* [nbr] Number of longitudes in grid */ lat_crv=rgr->lat_crv; /* [dgr] Latitude curvilinearity */ lon_crv=rgr->lon_crv; /* [dgr] Longitude curvilinearity */ lat_sth=rgr->lat_sth; /* [dgr] Latitude of southern edge of grid */ lon_wst=rgr->lon_wst; /* [dgr] Longitude of western edge of grid */ lat_nrt=rgr->lat_nrt; /* [dgr] Latitude of northern edge of grid */ lon_est=rgr->lon_est; /* [dgr] Longitude of eastern edge of grid */ /* Use curvilinear coordinates (lat and lon are 2D arrays) if flg_crv already set or it lat_crv or lon_crv set */ if(lat_crv != 0.0 || lon_crv != 0.0 || rgr->flg_crv) flg_grd_crv=True; if(lat_drc == nco_grd_lat_drc_n2s) flg_s2n=False; /* Assume 2D grid */ flg_grd_2D=True; grd_rnk_nbr=dmn_nbr_2D; /* Assume quadrilaterals */ grd_crn_nbr=4; /* Assume rectangles */ bnd_nbr=2; col_nbr=lat_nbr*lon_nbr; grd_sz_nbr=lat_nbr*lon_nbr; /* Allocate space for output data */ area=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); dmn_sz_int=(int *)nco_malloc(grd_rnk_nbr*nco_typ_lng((nc_type)NC_INT)); msk=(int *)nco_malloc(grd_sz_nbr*nco_typ_lng((nc_type)NC_INT)); lat_bnd=(double *)nco_malloc(lat_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(lat_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lon_bnd=(double *)nco_malloc(lon_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(lon_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(lon_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); wgt_Gss=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); grd_ctr_lat=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_ctr_lon=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lat=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lon=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); /* Define variable values */ int lon_psn=int_CEWI; /* [idx] Ordinal position of longitude in rectangular grid dimension-size array */ int lat_psn=int_CEWI; /* [idx] Ordinal position of latitude in rectangular grid dimension-size array */ if(grd_rnk_nbr == dmn_nbr_2D){ lon_psn=0; /* SCRIP introduced [lon,lat] convention because more natural for Fortran */ lat_psn=1; } /* !flg_grd_in_2D */ dmn_sz_int[lon_psn]=lon_nbr; dmn_sz_int[lat_psn]=lat_nbr; for(idx=0;idx<grd_sz_nbr;idx++) msk[idx]=1; /* Compute rectangular arrays NB: Much is a more-generic rewrite of map/map_grd.F90:map_grd_mk() */ /* 20150827: Old rule: Longitude grid was entirely specified by one of four longitude map tokens: Grn_ctr,Grn_wst,180_ctr,180_wst New rule: User may specify bounds (lon_wst,lon_est,lat_sth,lat_nrt) independently of grid token Such bounds ALWAYS refer bounding box interface edges, NEVER to centers of first last gridcells Bounds and number of gridcells completely determine uniform grid so former longitude-type tokens have no effect when bounds specified (so letting grid-type tokens affect grid would over-determine grid and lead to errors) Hence, grid-type tokens may be used as short-hand to specify grids but may not be required to exist later (because regional grids would not have specified them) Grid grid-type tokens lon_bb/lat_bb imply bounding box was originally used to specify bounds 1x1 degree global grid with first longitude centered at Greenwich: --lon_nbr=360 --lon_typ Grn_ctr --lon_nbr=360 --lon_wst=-0.5 --lon_est=359.5 1x1 degree global grid with Greenwich at west edge of first longitude: --lon_nbr=360 --lon_typ Grn_wst --lon_nbr=360 --lon_wst=0.0 --lon_est=360.0 1x1 degree regional grid, total size 9x9 degrees, Greenwich at center of middle gridcell: --lon_nbr=9 --lon_wst=-4.5 --lon_est=4.5 1x1 degree regional grid, total size 10x10 degrees, Greenwich at east/west edges of middle two gridcells --lon_nbr=10 --lon_wst=-5.0 --lon_est=5.0 */ /* Were east/west longitude bounds set explicitly or implicitly? NB: This is redundant since it was done in nco_rgr_ini(), yet better safe than sorry */ if(lon_wst != NC_MAX_DOUBLE || lon_est != NC_MAX_DOUBLE) lon_typ=rgr->lon_typ=nco_grd_lon_bb; if(lon_wst == NC_MAX_DOUBLE){ /* Precomputed longitude grids begin with longitude 0.0 or -180.0 degrees */ switch(lon_typ){ case nco_grd_lon_bb: case nco_grd_lon_Grn_ctr: case nco_grd_lon_Grn_wst: lon_wst=0.0; break; case nco_grd_lon_180_ctr: case nco_grd_lon_180_wst: lon_wst=-180.0; break; default: nco_dfl_case_generic_err(); break; } /* !lon_typ */ } /* !lon */ if(lon_est == NC_MAX_DOUBLE){ /* Precomputed longitude grids end with longitude 360.0 or 180.0 degrees */ switch(lon_typ){ case nco_grd_lon_bb: case nco_grd_lon_Grn_ctr: case nco_grd_lon_Grn_wst: lon_est=360.0; break; case nco_grd_lon_180_ctr: case nco_grd_lon_180_wst: lon_est=180.0; break; default: nco_dfl_case_generic_err(); break; } /* !lon_typ */ } /* !lon */ /* Determine longitude increment from span of pre-centered bounding box (centering will not change span) */ lon_spn=lon_est-lon_wst; lon_ncr=lon_spn/lon_nbr; /* Centering: If user did not set explicit longitude bounds then... */ if(lon_typ != nco_grd_lon_bb) /* map_lon_ctr_typ determines whether lon_wst refers to cell center or Western edge */ if((lon_typ == nco_grd_lon_Grn_ctr) || (lon_typ == nco_grd_lon_180_ctr)) lon_wst=lon_wst-(lon_ncr/2.0); /* Re-derive lon_est from lon_wst and lon_nbr (more fundamental properties) */ lon_est=lon_wst+lon_ncr*lon_nbr; /* lon_wst and lon_est have been set and will not change */ assert(lon_wst < lon_est); lon_ntf[0L]=lon_wst; lon_ntf[lon_nbr]=lon_est; for(lon_idx=1L;lon_idx<lon_nbr;lon_idx++) lon_ntf[lon_idx]=lon_ntf[0L]+lon_idx*lon_ncr; /* Ensure rounding errors do not produce unphysical grid */ lon_ntf[lon_nbr]=lon_ntf[0L]+lon_spn; /* Finished with longitude, now tackle latitude */ /* Were south/north latitude bounds set explicitly or implicitly? */ // if(lat_sth != NC_MAX_DOUBLE || lat_nrt != NC_MAX_DOUBLE) lon_typ=rgr->lat_typ=nco_grd_lat_bb; if(lat_sth == NC_MAX_DOUBLE) lat_sth=-90.0; if(lat_nrt == NC_MAX_DOUBLE) lat_nrt=90.0; /* Determine latitude increment from span of pre-centered bounding box (centering will not change span) */ lat_spn=lat_nrt-lat_sth; lat_ncr=lat_spn/lat_nbr; const long lat_nbr_hlf=lat_nbr/2L; // [nbr] Half number of latitudes (e.g., lat_nbr_hlf=32 for lat_nbr=64 and 65) double *lat_sin=NULL; // [frc] Sine of Gaussian latitudes double precision /* Create S->N grid. If user requested N->S, flip grid at end */ // if(flg_s2n) lat_ntf[0L]=lat_sth; else lat_ntf[0L]=lat_nrt; lat_ntf[0L]=lat_sth; switch(lat_typ){ case nco_grd_lat_fv: lat_ncr=lat_spn/(lat_nbr-1L); lat_ntf[1L]=lat_ntf[0L]+0.5*lat_ncr; for(lat_idx=2L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=lat_ntf[1L]+(lat_idx-1L)*lat_ncr; break; case nco_grd_lat_eqa: lat_ncr=lat_spn/lat_nbr; for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=lat_ntf[0L]+lat_idx*lat_ncr; break; case nco_grd_lat_gss: lat_sin=(double *)nco_malloc(lat_nbr*sizeof(double)); (void)nco_lat_wgt_gss(lat_nbr,True,lat_sin,wgt_Gss); for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=rdn2dgr*asin(lat_sin[lat_idx]); /* First guess for lat_ntf is midway between Gaussian abscissae */ for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=0.5*(lat_ctr[lat_idx-1L]+lat_ctr[lat_idx]); /* Iterate guess until area between interfaces matches Gaussian weight (compute for one hemisphere, make other symmetric) */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++){ double fofx_at_x0; /* [frc] Function to iterate evaluated at current guess */ double dfdx_at_x0; /* [frc] Derivative of equation evaluated at current guess */ const double eps_rlt_cnv=1.0e-15; // Convergence criterion (1.0e-16 pushes double precision to the brink) itr_cnt=0; lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; while(fabs(fofx_at_x0) > eps_rlt_cnv){ /* Newton-Raphson iteration: Let x=lat_ntf[lat_idx], y0=lat_ntf[lat_idx-1L], gw = Gaussian weight (exact solution) f(x)=sin(dgr2rdn*x)-sin(dgr2rdn*y0)-gw=0 # s2n grid f(x)=sin(dgr2rdn*y0)-sin(dgr2rdn*x)-gw=0 # n2s grid dfdx(x)= dgr2rdn*cos(dgr2rdn*x) # s2n grid dfdx(x)=-dgr2rdn*cos(dgr2rdn*x) # n2s grid x_better=x0-f(x0)/f'(x0) */ dfdx_at_x0=dgr2rdn*cos(dgr2rdn*lat_ntf[lat_idx]); /* 20190613: n2s latitudes are constructed s2n and flipped to n2s later Hence next line is commented-out in construction mode but used in infer mode */ // if(!flg_s2n) dfdx_at_x0=-dfdx_at_x0; lat_ntf[lat_idx]+=fofx_at_x0/dfdx_at_x0; /* NB: not sure why this is minus not plus but it works :) */ lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; if(++itr_cnt > itr_nbr_max){ (void)fprintf(stdout,"%s: ERROR %s reports convergence only %g after %d iterations for lat_idx = %ld\n",nco_prg_nm_get(),fnc_nm,fabs(fofx_at_x0),itr_nbr_max,lat_idx); nco_exit(EXIT_FAILURE); } /* endif */ } /* !while */ } /* !lat_idx */ /* Use Gaussian grid symmetry to obtain same interfaces in both hemispheres (avoids cumulative rounding errors) */ if(lat_nbr%2){ /* lat_nbr is odd */ for(lat_idx=1L;lat_idx<=lat_nbr_hlf+1L;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx+1L]; }else{ /* lat_nbr is even */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx]; } /* !flg_lat_evn */ break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ /* Ensure rounding errors do not produce unphysical grid */ lat_ntf[lat_nbr]=lat_nrt; if(nco_dbg_lvl_get() > nco_dbg_old){ (void)fprintf(stderr,"%s: DEBUG %s Gaussian abscissae/interfaces for lat_nbr=%ld\n",nco_prg_nm_get(),fnc_nm,lat_nbr); (void)fprintf(stderr,"idx\tlat_ctr\tlat_ntf\tntf_p1\n"); for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ (void)fprintf(stderr,"%ld\t%20.15f\t%20.15f\t%20.15f\n",lat_idx,lat_ctr[lat_idx],lat_ntf[lat_idx],lat_ntf[lat_idx+1L]); } /* !lat_idx */ } /* !dbg */ /* Always define longitude centers midway between interfaces */ for(lon_idx=0L;lon_idx<=lon_nbr-1L;lon_idx++) lon_ctr[lon_idx]=0.5*(lon_ntf[lon_idx]+lon_ntf[lon_idx+1L]); /* Many grids have center latitude equally spaced between interfaces */ if(lat_typ != nco_grd_lat_fv && lat_typ != nco_grd_lat_gss){ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=0.5*(lat_ntf[lat_idx]+lat_ntf[lat_idx+1L]); } /* !lat_typ */ /* Cap grids excepted---they place centers of first/last gridcells at poles */ if(lat_typ == nco_grd_lat_fv){ lat_ctr[0L]=lat_ntf[0L]; for(lat_idx=1L;lat_idx<lat_nbr-1L;lat_idx++) lat_ctr[lat_idx]=0.5*(lat_ntf[lat_idx]+lat_ntf[lat_idx+1L]); lat_ctr[lat_nbr-1L]=lat_ntf[lat_nbr]; } /* !cap */ /* Gaussian grid centerpoints are defined by solutions to Legendre polynomials */ if(lat_typ == nco_grd_lat_gss){ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=rdn2dgr*asin(lat_sin[lat_idx]); } /* !Gaussian */ for(idx=0L;idx<lon_nbr;idx++){ lon_bnd[2*idx]=lon_ntf[idx]; lon_bnd[2*idx+1L]=lon_ntf[idx+1L]; } /* !idx */ for(idx=0L;idx<lat_nbr;idx++){ lat_bnd[2*idx]=lat_ntf[idx]; lat_bnd[2*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0L;idx<lat_nbr;idx++){ (void)fprintf(stdout,"lat[%li] = %g, vertices = ",idx,lat_ctr[idx]); for(int bnd_idx=0L;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lat_bnd[bnd_nbr*idx+bnd_idx],bnd_idx == bnd_nbr-1 ? "]\n" : ", "); } /* end loop over lat */ } /* endif dbg */ /* Use centers and boundaries to diagnose latitude weights */ switch(lat_typ){ case nco_grd_lat_eqa: case nco_grd_lat_fv: for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=fabs(sin(dgr2rdn*lat_ntf[lat_idx+1L])-sin(dgr2rdn*lat_ntf[lat_idx])); break; case nco_grd_lat_gss: for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=wgt_Gss[lat_idx]; break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ /* Fuzzy test of latitude weight normalization 20180903 Tolerance threshold of eps_rlt_max=1.0e-14 is too strict for Gaussian grids somewhere lat_nbr >~ 150 20180904 Tolerance threshold of eps_rlt_max=1.0e-12 allows Gaussian grids like ECMWF O1280 Newton-Raphson method of interface determination may need improvement to fix that Tolerance threshold of 1.0e-14 works for all relevant E3SM Uniform and Cap grids */ //const double eps_rlt_max=1.0e-14; /* [frc] Round-off error tolerance: Used 1.0e-14 until 20180904 */ const double eps_rlt_max=1.0e-12; /* [frc] Round-off error tolerance: Used 1.0e-12 since 20180904 */ double lat_wgt_ttl_xpc; /* [frc] Expected sum of latitude weights */ lat_wgt_ttl=0.0; for(idx=0L;idx<lat_nbr;idx++) lat_wgt_ttl+=lat_wgt[idx]; lat_wgt_ttl_xpc=fabs(sin(dgr2rdn*lat_bnd[2*(lat_nbr-1)+1L])-sin(dgr2rdn*lat_bnd[0L])); if(grd_typ != nco_grd_2D_unk && 1.0-lat_wgt_ttl/lat_wgt_ttl_xpc > eps_rlt_max){ (void)fprintf(stdout,"%s: ERROR %s reports grid normalization does not meet precision tolerance eps_rlt_max = %20.15f\nlat_wgt_ttl = %20.15f, lat_wgt_ttl_xpc = %20.15f, lat_wgt_frc = %20.15f, eps_rlt = %20.15f\n",nco_prg_nm_get(),fnc_nm,eps_rlt_max,lat_wgt_ttl,lat_wgt_ttl_xpc,lat_wgt_ttl/lat_wgt_ttl_xpc,1.0-lat_wgt_ttl/lat_wgt_ttl_xpc); nco_exit(EXIT_FAILURE); } /* !imprecise */ /* 20180831 Code above assumes grids run S->N User can request N->S grids with --rgr lat_drc=n2s If so, flip grid before unrolling into output arrays */ if(!flg_s2n){ double *lat_ctr_tmp=NULL_CEWI; /* [dgr] Temporary Latitude centers of rectangular grid */ double *lat_wgt_tmp=NULL; /* [dgr] Temporary Latitude weights of rectangular grid */ double *lat_ntf_tmp=NULL; /* [dgr] Temporary Latitude interfaces of rectangular grid */ lat_ctr_tmp=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lat_ntf_tmp=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt_tmp=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); long tmp_idx; /* [idx] Temporary index for swapping values */ for(idx=0L;idx<lat_nbr;idx++){ lat_ctr_tmp[idx]=lat_ctr[idx]; lat_wgt_tmp[idx]=lat_wgt[idx]; } /* !idx */ for(idx=0L;idx<lat_nbr;idx++){ tmp_idx=lat_nbr-idx-1L; lat_ctr[idx]=lat_ctr_tmp[tmp_idx]; lat_wgt[idx]=lat_wgt_tmp[tmp_idx]; } /* !idx */ for(idx=0L;idx<lat_nbr+1L;idx++){ lat_ntf_tmp[idx]=lat_ntf[idx]; } /* !idx */ for(idx=0L;idx<lat_nbr+1L;idx++){ tmp_idx=lat_nbr+1L-idx-1L; /* NB: Subtle index difference */ lat_ntf[idx]=lat_ntf_tmp[tmp_idx]; } /* !idx */ for(idx=0L;idx<lat_nbr;idx++){ lat_bnd[2*idx]=lat_ntf[idx]; lat_bnd[2*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ if(lat_ctr_tmp) lat_ctr_tmp=(double *)nco_free(lat_ctr_tmp); if(lat_ntf_tmp) lat_ntf_tmp=(double *)nco_free(lat_ntf_tmp); if(lat_wgt_tmp) lat_wgt_tmp=(double *)nco_free(lat_wgt_tmp); } /* !flg_s2n */ assert(grd_crn_nbr == 4); for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++){ idx=grd_crn_nbr*lon_idx; lon_crn[idx]=lon_ntf[lon_idx]; lon_crn[idx+1L]=lon_ntf[lon_idx+1L]; lon_crn[idx+2L]=lon_ntf[lon_idx+1L]; lon_crn[idx+3L]=lon_ntf[lon_idx]; } /* !lon_idx */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ idx=grd_crn_nbr*lat_idx; lat_crn[idx]=lat_ntf[lat_idx]; lat_crn[idx+1L]=lat_ntf[lat_idx]; lat_crn[idx+2L]=lat_ntf[lat_idx+1L]; lat_crn[idx+3L]=lat_ntf[lat_idx+1L]; } /* !lat_idx */ /* Stuff rectangular arrays into unrolled arrays */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++){ idx=lat_idx*lon_nbr+lon_idx; grd_ctr_lat[idx]=lat_ctr[lat_idx]; grd_ctr_lon[idx]=lon_ctr[lon_idx]; for(crn_idx=0L;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; lat_idx2=lat_idx*grd_crn_nbr+crn_idx; lon_idx2=lon_idx*grd_crn_nbr+crn_idx; grd_crn_lat[idx2]=lat_crn[lat_idx2]; grd_crn_lon[idx2]=lon_crn[lon_idx2]; } /* !crn */ } /* !lon */ } /* !lat */ if(flg_grd_crv){ /* Impose curvilinearity by adding lon_crv offset to each row relative to previous row, and lat_crv offset to each column relative to previous column */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++){ idx=lat_idx*lon_nbr+lon_idx; grd_ctr_lat[idx]+=lon_idx*lat_crv; grd_ctr_lon[idx]+=lat_idx*lon_crv; for(crn_idx=0L;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; lat_idx2=lat_idx*grd_crn_nbr+crn_idx; lon_idx2=lon_idx*grd_crn_nbr+crn_idx; grd_crn_lat[idx2]=lat_crn[lat_idx2]; grd_crn_lon[idx2]=lon_crn[lon_idx2]; if(crn_idx == 0L || crn_idx == 1L){ grd_crn_lat[idx2]+=lat_idx*lat_crv; /* LL, LR */ grd_crn_lon[idx2]+=lat_idx*lon_crv; /* LL, LR */ }else if(crn_idx == 2L || crn_idx == 3L){ grd_crn_lat[idx2]+=(lat_idx+1L)*lat_crv; /* UL, UR */ grd_crn_lon[idx2]+=(lat_idx+1L)*lon_crv; /* UL, UR */ } /* !crn */ } /* !crn */ } /* !lon */ } /* !lat */ } /* !flg_grd_crv */ /* 20190613: Convert CW quadrilaterals to CCW quadrilaterals so TempestRemap accepts grids Default construction/inferral method orders corners CCW and CW for s2n and n2s grids, respectively */ if(!flg_s2n){ nco_bool flg_ccw; /* [flg] Gridcell is CCW */ const int rcr_lvl=1; /* [nbr] Recursion level (1 is top level, 2 and greater are recursed */ const int idx_ccw=0; /* [idx] Index of starting vertice for CCW check (Point A = tail side AB) */ for(idx=0L;idx<grd_sz_nbr;idx++){ idx2=grd_crn_nbr*idx; flg_ccw=nco_ccw_chk(grd_crn_lat+idx2,grd_crn_lon+idx2,grd_crn_nbr,idx_ccw,rcr_lvl); if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_vec) (void)fprintf(stderr,"%s: DEBUG %s reports nco_ccw_chk() tried to change idx = %lu from CW to CCW\n",nco_prg_nm_get(),fnc_nm,idx); } /* !idx */ } /* !flg_s2n */ if(nco_dbg_lvl_get() >= nco_dbg_std){ long int idx_crn_ll; long int idx_crn_lr; long int idx_crn_ur; long int idx_crn_ul; long idx_dbg; idx_dbg=rgr->idx_dbg; idx_crn_ll=grd_crn_nbr*idx_dbg+0L; idx_crn_lr=grd_crn_nbr*idx_dbg+1L; idx_crn_ur=grd_crn_nbr*idx_dbg+2L; idx_crn_ul=grd_crn_nbr*idx_dbg+3L; (void)fprintf(stderr,"%s: INFO %s idx_dbg = %li, Center [lat,lon]=[%g,%g]; Corners LL [%g,%g] LR [%g,%g] UR [%g,%g] UL [%g,%g]\n",nco_prg_nm_get(),fnc_nm,idx_dbg,grd_ctr_lat[idx_dbg],grd_ctr_lon[idx_dbg],grd_crn_lat[idx_crn_ll],grd_crn_lon[idx_crn_ll],grd_crn_lat[idx_crn_lr],grd_crn_lon[idx_crn_lr],grd_crn_lat[idx_crn_ur],grd_crn_lon[idx_crn_ur],grd_crn_lat[idx_crn_ul],grd_crn_lon[idx_crn_ul]); } /* !dbg */ if(flg_grd_crv){ /* Area of arbitrary curvilinear grids requires spherical trigonometry */ nco_sph_plg_area(rgr,grd_crn_lat,grd_crn_lon,grd_sz_nbr,grd_crn_nbr,area); }else{ /* Area of rectangular spherical zones from elementary calculus results 20150906: Half-angle formulae for better conditioning improve area normalization for 801x1600 by 2.0e-15 area[lat_idx*lon_nbr+lon_idx]=dgr2rdn*(lon_bnd[2*lon_idx+1L]-lon_bnd[2*lon_idx])*2.0*(sin(0.5*dgr2rdn*lat_bnd[2*lat_idx+1L])*cos(0.5*dgr2rdn*lat_bnd[2*lat_idx+1L])-sin(0.5*dgr2rdn*lat_bnd[2*lat_idx])*cos(0.5*dgr2rdn*lat_bnd[2*lat_idx])); Gain not worth the extra complexity */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++) /* fabs() ensures positive area in n2s grids */ area[lat_idx*lon_nbr+lon_idx]=fabs(dgr2rdn*(lon_bnd[2*lon_idx+1L]-lon_bnd[2*lon_idx])*(sin(dgr2rdn*lat_bnd[2*lat_idx+1L])-sin(dgr2rdn*lat_bnd[2*lat_idx]))); } /* !flg_grd_2D */ if(nco_dbg_lvl_get() >= nco_dbg_sbr){ lat_wgt_ttl=0.0; area_ttl=0.0; if(flg_grd_2D){ (void)fprintf(stderr,"%s: INFO %s reports destination rectangular latitude grid:\n",nco_prg_nm_get(),fnc_nm); for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_wgt_ttl+=lat_wgt[lat_idx]; } /* !flg_grd_2D */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++) area_ttl+=area[lat_idx*lon_nbr+lon_idx]; (void)fprintf(stdout,"lat_wgt_ttl = %20.15f, frc_lat_wgt = %20.15f, area_ttl = %20.15f, frc_area = %20.15f\n",lat_wgt_ttl,lat_wgt_ttl/2.0,area_ttl,area_ttl/(4.0*M_PI)); assert(area_ttl > 0.0); assert(area_ttl <= 4.0*M_PI); } /* endif dbg */ /* Open grid file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Define dimensions */ rcd=nco_def_dim(out_id,grd_crn_nm,grd_crn_nbr,&dmn_id_grd_crn); rcd=nco_def_dim(out_id,grd_sz_nm,grd_sz_nbr,&dmn_id_grd_sz); rcd=nco_def_dim(out_id,grd_rnk_nm,grd_rnk_nbr,&dmn_id_grd_rnk); int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; /* Define variables */ (void)nco_def_var(out_id,dmn_sz_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_rnk,&dmn_sz_int_id); /* NB: Too small to deflate */ (void)nco_def_var(out_id,grd_area_nm,(nc_type)crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,msk_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_sz,&msk_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lat_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lon_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lon_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_grd_sz; dmn_ids[1]=dmn_id_grd_crn; (void)nco_def_var(out_id,grd_crn_lat_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lat_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_grd_sz; dmn_ids[1]=dmn_id_grd_crn; (void)nco_def_var(out_id,grd_crn_lon_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lon_id,shuffle,deflate,dfl_lvl); /* Define global and "units" attributes */ char *att_val; rcd=nco_char_att_put(out_id,NULL,"title",rgr->grd_ttl); rcd=nco_char_att_put(out_id,NULL,"Conventions","SCRIP"); const char usr_cpp[]=TKN2SNG(USER); /* [sng] Hostname from C pre-processor */ rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); rcd=nco_char_att_put(out_id,NULL,"grid_generator","NCO"); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,NULL,"latitude_grid_type",nco_grd_lat_sng(lat_typ)); rcd=nco_char_att_put(out_id,NULL,"longitude_grid_type",nco_grd_lon_sng(lon_typ)); rcd=nco_char_att_put(out_id,dmn_sz_nm,"long_name","Size(s) of horizontal dimensions (in Fortran storage order for historical reasons)"); rcd=nco_char_att_put(out_id,grd_area_nm,"long_name","Solid Angle Subtended on Source Grid"); rcd=nco_char_att_put(out_id,grd_area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,grd_area_nm,"units","steradian"); rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"standard_name","latitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"bounds",grd_crn_lat_nm); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"standard_name","longitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees_east"); else rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"bounds",grd_crn_lon_nm); rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"long_name","Latitude of Grid Cell Vertices"); rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"standard_name","latitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"long_name","Longitude of Grid Cell Vertices"); rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"standard_name","longitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees_east"); else rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,msk_nm,"long_name","Binary Integer Mask for Grid"); rcd=nco_char_att_put(out_id,msk_nm,"units","none"); /* Begin data mode */ (void)nco_enddef(out_id); /* Write variables */ dmn_srt[0]=0L; dmn_cnt[0]=grd_rnk_nbr; rcd=nco_put_vara(out_id,dmn_sz_int_id,dmn_srt,dmn_cnt,dmn_sz_int,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,msk_id,dmn_srt,dmn_cnt,msk,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lat_id,dmn_srt,dmn_cnt,grd_ctr_lat,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lon_id,dmn_srt,dmn_cnt,grd_ctr_lon,crd_typ); dmn_srt[0]=0L; dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lat_id,dmn_srt,dmn_cnt,grd_crn_lat,crd_typ); dmn_srt[0]=0L; dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lon_id,dmn_srt,dmn_cnt,grd_crn_lon,crd_typ); /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); fl_out=rgr->fl_skl; if(fl_out){ /* Write skeleton data file on requested grid Skeleton file can then be populated with data for testing */ char *area_nm; char *bnd_nm; // char *bnd_tm_nm; char *col_nm_out; char *lat_nm_out; /* [sng] Name of output dimension for latitude */ char *lat_wgt_nm; char *lon_nm_out; /* [sng] Name of variable to recognize as longitude */ char *lat_bnd_nm; /* [sng] Name of latitude boundary variable */ char *lon_bnd_nm; /* [sng] Name of longitude boundary variable */ // int area_id; /* [id] Variable ID for area */ int dmn_id_bnd; /* [id] Dimension ID */ //int dmn_id_bnd_tm; /* [id] Dimension ID */ int dmn_id_col; /* [id] Dimension ID */ int dmn_id_lat; /* [id] Dimension ID */ int dmn_id_lon; /* [id] Dimension ID */ int lat_bnd_id; /* [id] Variable ID for lat_bnds/lat_vertices */ int lat_id; /* [id] Variable ID for latitude */ int lat_wgt_id; /* [id] Variable ID for latitude weight */ int lon_bnd_id; /* [id] Variable ID for lon_bnds/lon_vertices */ int lon_id; /* [id] Variable ID for longitude */ /* Use explicitly specified output names, if any, otherwise use input names (either explicitly specified or discovered by fuzzing) */ if(rgr->lat_nm_out) lat_nm_out=rgr->lat_nm_out; else lat_nm_out=(char *)strdup("lat"); if(rgr->lon_nm_out) lon_nm_out=rgr->lon_nm_out; else lon_nm_out=(char *)strdup("lon"); if(rgr->col_nm_out) col_nm_out=rgr->col_nm_out; else col_nm_out=(char *)strdup("ncol"); /* Name output dimensions */ area_nm=rgr->area_nm; bnd_nm=rgr->bnd_nm; //bnd_tm_nm=rgr->bnd_tm_nm; lat_bnd_nm=rgr->lat_bnd_nm; lat_wgt_nm=rgr->lat_wgt_nm; lon_bnd_nm=rgr->lon_bnd_nm; /* Use names discovered by fuzzing */ if(flg_grd_1D){ bnd_nm=rgr->vrt_nm; lat_bnd_nm=rgr->lat_vrt_nm; lon_bnd_nm=rgr->lon_vrt_nm; } /* !flg_grd_1D */ if(flg_grd_2D){ bnd_nm=rgr->bnd_nm; lat_bnd_nm=rgr->lat_bnd_nm; lon_bnd_nm=rgr->lon_bnd_nm; } /* !flg_grd_2D */ /* Open grid file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Define dimensions */ if(flg_grd_crv){ rcd=nco_def_dim(out_id,bnd_nm,grd_crn_nbr,&dmn_id_bnd); }else{ rcd=nco_def_dim(out_id,bnd_nm,bnd_nbr,&dmn_id_bnd); } /* !flg_grd_crv */ if(flg_grd_1D){ rcd=nco_def_dim(out_id,col_nm_out,col_nbr,&dmn_id_col); } /* !flg_grd_1D */ if(flg_grd_2D){ rcd=nco_def_dim(out_id,lat_nm_out,lat_nbr,&dmn_id_lat); rcd=nco_def_dim(out_id,lon_nm_out,lon_nbr,&dmn_id_lon); } /* !flg_grd_2D */ /* Define new coordinates and variables in regridded file */ if(flg_grd_1D){ (void)nco_def_var(out_id,lat_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_col,&lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_col,&lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_col; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lat_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_col; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lon_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_1D,&dmn_id_col,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); } /* !flg_grd_1D */ if(flg_grd_crv){ dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_lon; (void)nco_def_var(out_id,lat_nm_out,crd_typ,dmn_nbr_2D,dmn_ids,&lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_nm_out,crd_typ,dmn_nbr_2D,dmn_ids,&lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_2D,dmn_ids,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_lon; dmn_ids[2]=dmn_id_bnd; (void)nco_def_var(out_id,lat_bnd_nm,crd_typ,dmn_nbr_3D,dmn_ids,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_bnd_nm,crd_typ,dmn_nbr_3D,dmn_ids,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); }else if(flg_grd_2D){ (void)nco_def_var(out_id,lat_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_lat,&lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_lon,&lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lat_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lon; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lon_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lat_wgt_nm,crd_typ,dmn_nbr_1D,&dmn_id_lat,&lat_wgt_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_wgt_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_lon; (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_2D,dmn_ids,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); } /* !flg_grd_2D */ /* Define attributes */ rcd=nco_char_att_put(out_id,NULL,"title",rgr->grd_ttl); rcd=nco_char_att_put(out_id,NULL,"Conventions","CF-1.6"); rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,NULL,"latitude_grid_type",nco_grd_lat_sng(lat_typ)); rcd=nco_char_att_put(out_id,NULL,"longitude_grid_type",nco_grd_lon_sng(lon_typ)); rcd=nco_char_att_put(out_id,area_nm,"long_name","Solid angle subtended by gridcell"); rcd=nco_char_att_put(out_id,area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm,"units","steradian"); rcd=nco_char_att_put(out_id,lat_nm_out,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lat_nm_out,"standard_name","latitude"); rcd=nco_char_att_put(out_id,lat_nm_out,"units","degrees_north"); rcd=nco_char_att_put(out_id,lat_nm_out,"axis","Y"); rcd=nco_char_att_put(out_id,lat_nm_out,"bounds",lat_bnd_nm); if(flg_grd_2D) att_val=strdup("Gridcell latitude interfaces"); else att_val=strdup("Gridcell latitude vertices"); rcd=nco_char_att_put(out_id,lat_bnd_nm,"long_name",att_val); if(flg_grd_2D) rcd=nco_char_att_put(out_id,lat_wgt_nm,"long_name","Latitude quadrature weights (normalized to sum to 2.0 on global grids)"); rcd=nco_char_att_put(out_id,lon_nm_out,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lon_nm_out,"standard_name","longitude"); rcd=nco_char_att_put(out_id,lon_nm_out,"units","degrees_east"); rcd=nco_char_att_put(out_id,lon_nm_out,"axis","X"); rcd=nco_char_att_put(out_id,lon_nm_out,"bounds",lon_bnd_nm); if(flg_grd_2D) att_val=strdup("Gridcell longitude interfaces"); else att_val=strdup("Gridcell longitude vertices"); rcd=nco_char_att_put(out_id,lon_bnd_nm,"long_name",att_val); /* Begin data mode */ (void)nco_enddef(out_id); /* Write new coordinates and variables to regridded file */ if(flg_grd_1D){ dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; (void)nco_put_vara(out_id,lat_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; (void)nco_put_vara(out_id,lon_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; (void)nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); } /* !flg_grd_1D */ if(flg_grd_crv){ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; (void)nco_put_vara(out_id,lat_id,dmn_srt,dmn_cnt,grd_ctr_lat,crd_typ); (void)nco_put_vara(out_id,lon_id,dmn_srt,dmn_cnt,grd_ctr_lon,crd_typ); (void)nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); dmn_srt[0]=dmn_srt[1]=0L;dmn_srt[2]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; dmn_cnt[2]=grd_crn_nbr; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt,dmn_cnt,grd_crn_lat,crd_typ); (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt,dmn_cnt,grd_crn_lon,crd_typ); }else if(flg_grd_2D){ dmn_srt[0]=0L; dmn_cnt[0]=lat_nbr; (void)nco_put_vara(out_id,lat_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=lon_nbr; (void)nco_put_vara(out_id,lon_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=lat_nbr; (void)nco_put_vara(out_id,lat_wgt_id,dmn_srt,dmn_cnt,lat_wgt,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lon_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; (void)nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); } /* !flg_grd_2D */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); } /* !fl_out */ /* Free memory associated with input file */ if(dmn_sz_int) dmn_sz_int=(int *)nco_free(dmn_sz_int); if(msk) msk=(int *)nco_free(msk); if(area) area=(double *)nco_free(area); if(grd_ctr_lat) grd_ctr_lat=(double *)nco_free(grd_ctr_lat); if(grd_ctr_lon) grd_ctr_lon=(double *)nco_free(grd_ctr_lon); if(grd_crn_lat) grd_crn_lat=(double *)nco_free(grd_crn_lat); if(grd_crn_lon) grd_crn_lon=(double *)nco_free(grd_crn_lon); if(lat_bnd) lat_bnd=(double *)nco_free(lat_bnd); if(lat_crn) lat_crn=(double *)nco_free(lat_crn); if(lat_ctr) lat_ctr=(double *)nco_free(lat_ctr); if(lat_ntf) lat_ntf=(double *)nco_free(lat_ntf); if(lat_sin) lat_sin=(double *)nco_free(lat_sin); if(lat_wgt) lat_wgt=(double *)nco_free(lat_wgt); if(lon_bnd) lon_bnd=(double *)nco_free(lon_bnd); if(lon_crn) lon_crn=(double *)nco_free(lon_crn); if(lon_ctr) lon_ctr=(double *)nco_free(lon_ctr); if(lon_ntf) lon_ntf=(double *)nco_free(lon_ntf); if(wgt_Gss) wgt_Gss=(double *)nco_free(wgt_Gss); return rcd; } /* !nco_grd_mk() */ int /* O [enm] Return code */ nco_grd_nfr /* [fnc] Infer SCRIP-format grid file from input data file */ (rgr_sct * const rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Use grid information and guesswork to create SCRIP-format grid file from input data file Test curvilinear grids: ncks -O -D 1 --rgr infer --rgr grid=${DATA}/sld/rgr/grd_airs.nc ${DATA}/sld/raw/AIRS.2014.10.01.202.L2.TSurfStd.Regrid010.1DLatLon.nc ~/foo.nc ncks -O -D 1 --rgr infer --rgr grid=${DATA}/sld/rgr/grd_airs.nc ${DATA}/sld/raw/AIRS.2014.10.01.202.L2.TSurfStd.Regrid010.1DLatLon.hole.nc ~/foo.nc */ const char fnc_nm[]="nco_grd_nfr()"; /* [sng] Function name */ const double rdn2dgr=180.0/M_PI; const double dgr2rdn=M_PI/180.0; const int dmn_nbr_0D=0; /* [nbr] Rank of 0-D grid variables */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ const int dmn_nbr_grd_max=4; /* [nbr] Maximum rank of grid variables (msk_[src/dst] could be rank 4) */ const int itr_nbr_max=20; // [nbr] Maximum number of iterations const int idx_ccw=0; /* [idx] Index of starting vertice for CCW check (Point A = tail side AB) */ const int rcr_lvl=1; /* [nbr] Recursion level (1 is top level, 2 and greater are recursed */ const nc_type crd_typ=NC_DOUBLE; char *area_nm_in=NULL; char *fl_in; char *fl_out; char *fl_out_tmp=NULL_CEWI; char *fl_pth_lcl=NULL; char *msk_nm_in=NULL; char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ /* SCRIP-format grid names are non-negotiable and thus fixed not dynamic */ char area_nm[]="grid_area"; /* 20150830: NB ESMF_RegridWeightGen --user_areas looks for variable named "grid_area" */ char dmn_sz_nm[]="grid_dims"; char grd_crn_lat_nm[]="grid_corner_lat"; char grd_crn_lon_nm[]="grid_corner_lon"; char grd_crn_nm[]="grid_corners"; char grd_ctr_lat_nm[]="grid_center_lat"; char grd_ctr_lon_nm[]="grid_center_lon"; char grd_rnk_nm[]="grid_rank"; char grd_sz_nm[]="grid_size"; char msk_nm[]="grid_imask"; char unt_sng[]="units"; /* netCDF-standard units attribute name */ double *grd_ctr_lat; /* [dgr] Latitude centers of grid */ double *grd_ctr_lon; /* [dgr] Longitude centers of grid */ double *grd_crn_lat; /* [dgr] Latitude corners of grid */ double *grd_crn_lon; /* [dgr] Longitude corners of grid */ double *area; /* [sr] Area of grid */ double *lat_bnd=NULL_CEWI; /* [dgr] Latitude boundaries of rectangular grid */ double *lat_crn=NULL; /* [dgr] Latitude corners of rectangular grid */ double *lat_ctr=NULL_CEWI; /* [dgr] Latitude centers of rectangular grid */ double *lat_ntf=NULL; /* [dgr] Latitude interfaces of rectangular grid */ double *lat_wgt=NULL; /* [dgr] Latitude weights of rectangular grid */ double *lon_bnd=NULL_CEWI; /* [dgr] Longitude boundaries of rectangular grid */ double *lon_crn=NULL; /* [dgr] Longitude corners of rectangular grid */ double *lon_ctr=NULL_CEWI; /* [dgr] Longitude centers of rectangular grid */ double *lon_ntf=NULL; /* [dgr] Longitude interfaces of rectangular grid */ double *vrt_lat=NULL; /* [rdn] MPAS latitude boundary variable latVertex */ double *vrt_lon=NULL; /* [rdn] MPAS longitude boundary variable lonVertex */ double area_ttl=0.0; /* [frc] Exact sum of area */ //double lat_nrt; /* [dgr] Latitude of northern edge of grid */ double lat_sth; /* [dgr] Latitude of southern edge of grid */ double lat_wgt_ttl=0.0; /* [frc] Actual sum of quadrature weights */ double lat_wgt_gss; /* [frc] Latitude weight estimated from interface latitudes */ // double lon_est; /* [dgr] Longitude of eastern edge of grid */ double lon_wst; /* [dgr] Longitude of western edge of grid */ double lon_ncr; /* [dgr] Longitude increment */ double lat_ncr; /* [dgr] Latitude increment */ double lon_spn; /* [dgr] Longitude span */ double lat_spn; /* [dgr] Latitude span */ double mss_val_area_dbl; double mss_val_ctr_dbl; double mss_val_msk_dbl; int *msk=NULL; /* [flg] Mask of grid */ int *vrt_cll=NULL; /* [enm] MPAS variable verticesOnCell */ int *dmn_sz_int; /* [nbr] Array of dimension sizes of grid */ int dmn_ids[dmn_nbr_grd_max]; /* [id] Dimension IDs array for output variable */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int dmn_idx; /* [idx] Dimension index */ int fl_out_fmt=NC_FORMAT_CLASSIC; /* [enm] Output file format */ int in_id; /* I [id] Input netCDF file ID */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int area_id=NC_MIN_INT; /* [id] Area variable ID */ int dmn_id_grd_crn; /* [id] Grid corners dimension ID */ int dmn_id_grd_rnk; /* [id] Grid rank dimension ID */ int dmn_id_grd_sz; /* [id] Grid size dimension ID */ int dmn_sz_int_id; /* [id] Grid dimension sizes ID */ int grd_crn_lat_id; /* [id] Grid corner latitudes variable ID */ int grd_crn_lon_id; /* [id] Grid corner longitudes variable ID */ int grd_ctr_lat_id; /* [id] Grid center latitudes variable ID */ int grd_ctr_lon_id; /* [id] Grid center longitudes variable ID */ int itr_cnt; /* Iteration counter */ int lat_rnk; /* [nbr] Rank of latitude coordinate */ int lon_rnk; /* [nbr] Rank of longitude coordinate */ int lat_ctr_id=NC_MIN_INT; /* [id] Latitude centers of rectangular grid variable ID */ int lon_ctr_id=NC_MIN_INT; /* [id] Longitude centers of rectangular grid variable ID */ int lat_bnd_id=NC_MIN_INT; /* [id] Latitude centers of rectangular grid variable ID */ int lon_bnd_id=NC_MIN_INT; /* [id] Longitude centers of rectangular grid variable ID */ int msk_id=NC_MIN_INT; /* [id] Mask variable ID */ int msk_rnk_nbr; /* [id] Mask rank */ int mss_val_int_out=NC_MIN_INT; /* [nbr] Value that can be non-erroneously pointed to */ int val_two=2; /* [nbr] Value that can be non-erroneously pointed to */ int val_zero=0; /* [nbr] Value that can be non-erroneously pointed to */ int var_id; /* [id] Current variable ID */ int vrt_cll_id=NC_MIN_INT; /* [id] MPAS variable verticesOnCell ID */ int vrt_lat_id=NC_MIN_INT; /* [id] MPAS latitude boundary variable latVertex ID */ int vrt_lon_id=NC_MIN_INT; /* [id] MPAS longitude boundary variable lonVertex ID */ long dmn_srt[dmn_nbr_grd_max]; long dmn_cnt[dmn_nbr_grd_max]; long bnd_idx; long bnd_nbr=NC_MIN_INT; /* [nbr] Number of bounds in gridcell */ long col_idx; long col_nbr; /* [nbr] Number of columns in grid */ long crn_idx; /* [idx] Counting index for corners */ long ttl_idx; /* [idx] Total (unrolled) counting index for grid+corners */ long dmn_sz; /* [nbr] Size of current dimension */ long grd_crn_nbr; /* [nbr] Number of corners in gridcell */ long grd_rnk_nbr=int_CEWI; /* [nbr] Number of dimensions in grid */ long grd_sz_nbr; /* [nbr] Number of gridcells in grid */ long idx2; /* [idx] Counting index for unrolled grids */ long idx; /* [idx] Counting index for unrolled grids */ long idx_crn; long idx_ctr; long idx_fst; /* [idx] Index offset */ long idx_tmp; /* [idx] Temporary index */ long lat_idx2; /* [idx] Counting index for unrolled latitude */ long lat_idx; long lat_nbr; /* [nbr] Number of latitudes in grid */ long lon_idx2; /* [idx] Counting index for unrolled longitude */ long lon_idx; long lon_nbr; /* [nbr] Number of longitudes in grid */ long vrt_idx; /* [idx] Counting index for vertices */ long vrt_nbr; /* [nbr] Number of vertices in MPAS grid */ long int idx_crn_ll; long int idx_crn_lr; long int idx_crn_ur; long int idx_crn_ul; nco_bool FL_RTR_RMT_LCN; nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=True; /* Option O */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=rgr->flg_uio; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=False; /* [flg] Write output to temporary file */ nco_bool flg_1D_mpas_bnd=False; /* [flg] Unstructured input grid with MPAS bounds */ nco_bool flg_1D_psd_rct_bnd=False; /* [flg] Unstructured input grid with pseudo-rectangular bounds */ nco_bool flg_ccw; /* [flg] Gridcell is CCW */ nco_bool flg_grd_1D=False; nco_bool flg_grd_2D=False; nco_bool flg_grd_crv=False; nco_bool flg_s2n=True; /* [enm] Latitude grid-direction is South-to-North */ nco_bool flg_wrt_crn=True; nco_bool flg_crn_grd_lat_lon=False; /* [flg] Curvilinear corner array ordered non-canonically as grd_nbr,lat_nbr,lon_nbr */ nco_bool use_mss_val_area=False; nco_bool has_mss_val_area=False; nco_bool has_mss_val_bnd=False; nco_bool has_mss_val_ctr=False; nco_bool has_mss_val_msk=False; nco_grd_2D_typ_enm grd_typ; /* [enm] Grid-type enum */ nco_grd_lat_typ_enm lat_typ; /* [enm] Latitude grid-type enum */ nco_grd_lon_typ_enm lon_typ; /* [enm] Longitude grid-type enum */ nco_grd_xtn_enm nco_grd_xtn=nco_grd_xtn_nil; /* [enm] Grid-extent enum */ nc_type msk_typ; ptr_unn msk_unn; size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ /* Algorithm: Read grid information from input data file (aka *_in) Close input file Once grid dimensions known, allocate output grid arrays (aka *_out) Open output file (aka grid-file) Use guesswork and standard algorithms to fill-in output arrays */ /* Duplicate (because nco_fl_mk_lcl() free()'s fl_in) */ fl_in=(char *)strdup(rgr->fl_in); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,&in_id); char *bnd_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as bounds */ char *col_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as column */ char *lat_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as latitude */ char *lon_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as longitude */ char *lat_nm_in=NULL_CEWI; /* [sng] Name of variable to recognize as latitude */ char *lon_nm_in=NULL_CEWI; /* [sng] Name of variable to recognize as longitude */ char *lat_bnd_nm=NULL_CEWI; /* [sng] Name of latitude boundary variable */ char *lon_bnd_nm=NULL_CEWI; /* [sng] Name of longitude boundary variable */ char *vrt_dmn_nm=NULL_CEWI; /* [sng] Name of MPAS vertices dimension nVertices */ char *vrt_cll_nm=NULL_CEWI; /* [sng] Name of MPAS variable verticesOnCell */ char *vrt_lat_nm=NULL_CEWI; /* [sng] Name of MPAS latitude boundary variable latVertex */ char *vrt_lon_nm=NULL_CEWI; /* [sng] Name of MPAS longitude boundary variable lonVertex */ int dmn_id_bnd=NC_MIN_INT; /* [id] Dimension ID for spatial bounds */ int dmn_id_col=NC_MIN_INT; /* [id] Dimension ID for unstructured grids */ int dmn_id_lat=NC_MIN_INT; /* [id] Dimension ID for latitude */ int dmn_id_lon=NC_MIN_INT; /* [id] Dimension ID for longitude */ int dmn_id_vrt=NC_MIN_INT; /* [id] Dimension ID for MPAS vertices */ /* Begin CF-coordinates block */ cf_crd_sct *cf=NULL; char *rgr_var; /* [sng] Variable for special regridding treatment */ nco_bool flg_cf=False; /* [flg] Follow CF Coordinates convention to find and infer grid */ rgr_var=rgr->var_nm; if(rgr_var){ /* Infer grid from special variable Intended to be variable that has both horizontal dimensions and "coordinates" attribute, e.g., ncks --cdl -m ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc | grep coordinates 4LFTX_221_SPDY_S113:coordinates = "gridlat_221 gridlon_221" ; Usage: ncks -O -D 3 --rgr infer --rgr_var=4LFTX_221_SPDY_S113 --rgr grid=~/grd_narr.nc ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc ~/foo.nc */ char crd_sng[]="coordinates"; /* CF-standard coordinates attribute name */ cf=(cf_crd_sct *)nco_malloc(sizeof(cf_crd_sct)); cf->crd=False; /* [flg] CF coordinates information is complete */ cf->crd_id[0]=NC_MIN_INT; /* [id] Coordinate ID, first */ cf->crd_id[1]=NC_MIN_INT; /* [id] Coordinate ID, second */ cf->crd_nm[0]=NULL; /* [sng] Coordinate name, first */ cf->crd_nm[1]=NULL; /* [sng] Coordinate name, second */ cf->crd_sng=NULL; /* [sng] Coordinates attribute value */ cf->dmn_id[0]=NC_MIN_INT; /* [id] Dimension ID, first */ cf->dmn_id[1]=NC_MIN_INT; /* [id] Dimension ID, second */ cf->dmn_nm[0]=NULL; /* [sng] Dimension name, first */ cf->dmn_nm[1]=NULL; /* [sng] Dimension name, second */ cf->unt_sng[0]=NULL; /* [sng] Units string, first coordinate */ cf->unt_sng[1]=NULL; /* [sng] Units string, second coordinate */ cf->var_id=NC_MIN_INT; /* [id] Coordinate variable ID */ cf->var_nm=NULL; /* [sng] Coordinates variable name */ cf->var_type=NC_NAT; /* [enm] Coordinates variable type */ if((rcd=nco_inq_varid_flg(in_id,rgr_var,&cf->var_id)) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports special \"coordinates\" variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd */ cf->crd_sng=nco_char_att_get(in_id,cf->var_id,crd_sng); if(cf->crd_sng){ cf->crd=True; }else{ /* !rcd && att_typ */ (void)fprintf(stderr,"%s: WARNING %s reports coordinates variable %s does not have character-valued \"coordinates\" attribute. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd && att_typ */ /* Valid coordinates attribute requires two coordinate names separated by space character */ char *crd_nm[NCO_MAX_CRD_PER_VAR]; /* [sng] Coordinate name start position */ char *crd_dpl; /* [sng] Modifiable duplicate of coordinates string */ char *spc_ptr; /* [sng] Pointer to space character (' ') */ int crd_nbr=0; /* [nbr] Number of names in coordinates attribute */ int crd_spt=0; /* [nbr] Number of "spatial-like" (that include "degree" in units) coordinates */ int crd_idx=0; /* [idx] Counter for coordinate names */ for(crd_idx=0;crd_idx<NCO_MAX_CRD_PER_VAR;crd_idx++) crd_nm[crd_idx]=NULL; crd_dpl=(char *)strdup(cf->crd_sng); /* Search for spaces starting from end of string */ while((spc_ptr=strrchr(crd_dpl,' '))){ crd_nm[crd_nbr]=spc_ptr+1L; crd_nbr++; /* NUL-terminate so next search ends here */ *spc_ptr='\0'; } /* !sbs_ptr */ /* Final coordinate name begins where coordinate string starts */ crd_nm[crd_nbr]=crd_dpl; /* Change crd_nbr from 0-based index to actual coordinate number */ crd_nbr++; if(crd_nbr < 2){ (void)fprintf(stderr,"%s: WARNING %s found only %d coordinate(s) in \"coordinates\" attribute \"%s\", at least two are required. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,crd_nbr,cf->crd_sng); goto skp_cf; } /* !crd_nbr */ /* If more than two coordinate names are present, choose first two (searching backwards from end) with "degree" in units attributes, otherwise just choose first two */ crd_idx=crd_spt=0; while(crd_spt < 2 && crd_idx < crd_nbr){ cf->crd_nm[crd_spt]=crd_nm[crd_idx]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[crd_spt],&cf->crd_id[crd_spt])) == NC_NOERR){ cf->unt_sng[crd_spt]=nco_char_att_get(in_id,cf->crd_id[crd_spt],unt_sng); if(cf->unt_sng[crd_spt]){ if(strcasestr(cf->unt_sng[crd_spt],"degree")){ /* Increment count of spatial-like coordinates... */ crd_spt++; }else{ /* ...or free() memory allocated during search */ cf->unt_sng[crd_spt]=(char *)nco_free(cf->unt_sng[crd_spt]); } /* !strcasestr() */ crd_idx++; } /* !rcd && att_typ */ } /* !rcd */ } /* !crd_spt */ /* If while()-loop above was successful, our search is over Otherwise, use first two coordinate names regardless of units, and print more diagnostics */ if(crd_spt < 2){ cf->crd_nm[0]=crd_nm[0]; cf->crd_nm[1]=crd_nm[1]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[0],&cf->crd_id[0])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0]); goto skp_cf; } /* !rcd */ if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[1],&cf->crd_id[1])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1]); goto skp_cf; } /* !rcd */ cf->unt_sng[0]=nco_char_att_get(in_id,cf->crd_id[0],unt_sng); if(cf->unt_sng[0]){ if(!strcasestr(cf->unt_sng[0],"degree")) (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->unt_sng[0]); } /* !rcd && att_typ */ cf->unt_sng[1]=nco_char_att_get(in_id,cf->crd_id[1],unt_sng); if(cf->unt_sng[1]){ if(!strcasestr(cf->unt_sng[1],"degree")) (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1],cf->unt_sng[1]); } /* !rcd && att_typ */ } /* !crd_spt */ int crd_rnk; /* [nbr] Coordinate rank */ rcd=nco_inq_varndims(in_id,cf->crd_id[0],&crd_rnk); if(crd_rnk != 2){ (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s has %i dimension(s). Skipping CF coordinates method.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],crd_rnk); goto skp_cf; } /* !crd_rnk */ rcd=nco_inq_vardimid(in_id,cf->crd_id[0],cf->dmn_id); cf->dmn_nm[0]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); cf->dmn_nm[1]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); rcd=nco_inq_dimname(in_id,cf->dmn_id[0],cf->dmn_nm[0]); rcd=nco_inq_dimname(in_id,cf->dmn_id[1],cf->dmn_nm[1]); /* "coordinates" convention does not guarantee lat, lon are specified in that order Use "units" values, if any, to determine order In absence of "units", assume order is lat, lon */ nco_bool crd0_is_lat=False; /* [flg] First coordinate is latitude */ nco_bool crd0_is_lon=False; /* [flg] First coordinate is longitude */ nco_bool crd1_is_lat=False; /* [flg] Second coordinate is latitude */ nco_bool crd1_is_lon=False; /* [flg] Second coordinate is longitude */ if(cf->unt_sng[0]){ if(!strcasecmp(cf->unt_sng[0],"degrees_north") || !strcasecmp(cf->unt_sng[0],"degree_north") || !strcasecmp(cf->unt_sng[0],"degree_N") || !strcasecmp(cf->unt_sng[0],"degrees_N") || !strcasecmp(cf->unt_sng[0],"degreeN") || !strcasecmp(cf->unt_sng[0],"degreesN")) crd0_is_lat=True; if(!strcasecmp(cf->unt_sng[0],"degrees_east") || !strcasecmp(cf->unt_sng[0],"degree_east") || !strcasecmp(cf->unt_sng[0],"degree_E") || !strcasecmp(cf->unt_sng[0],"degrees_E") || !strcasecmp(cf->unt_sng[0],"degreeE") || !strcasecmp(cf->unt_sng[0],"degreesE")) crd0_is_lon=True; } /* endif */ if(cf->unt_sng[1]){ if(!strcasecmp(cf->unt_sng[1],"degrees_north") || !strcasecmp(cf->unt_sng[1],"degree_north") || !strcasecmp(cf->unt_sng[1],"degree_N") || !strcasecmp(cf->unt_sng[1],"degrees_N") || !strcasecmp(cf->unt_sng[1],"degreeN") || !strcasecmp(cf->unt_sng[1],"degreesN")) crd1_is_lat=True; if(!strcasecmp(cf->unt_sng[1],"degrees_east") || !strcasecmp(cf->unt_sng[1],"degree_east") || !strcasecmp(cf->unt_sng[1],"degree_E") || !strcasecmp(cf->unt_sng[1],"degrees_E") || !strcasecmp(cf->unt_sng[1],"degreeE") || !strcasecmp(cf->unt_sng[1],"degreesE")) crd1_is_lon=True; } /* endif */ assert((crd0_is_lat && crd1_is_lon) || (crd0_is_lon && crd1_is_lat)); int idx_lat; int idx_lon; if(crd0_is_lat && crd1_is_lon){ idx_lat=0; idx_lon=1; }else{ idx_lat=1; idx_lon=0; } /* endif */ /* Dimensions and coordinates have been vetted. Store as primary lookup names. Dimensions are always returned in order [LRV,MRV]=[0,1] LRV is along-track direction, and MRV is across-track (at least in NASA data) Internally we label LRV as "lat" and MRV as "lon" so that code looks similar for curvilinear and rectangular grids */ dmn_id_lat=cf->dmn_id[0]; dmn_id_lon=cf->dmn_id[1]; /* Subtlety: lat_nm_in is coordinate (variable+dimension) name when specified from command-line (as in nco_grd_nfr()), dimension name when found through CF-method (as in nco_rgr_wgt()). This confusing distinction could be avoided by passing command-line dimension names through-to nco_rgr_wgt(). However, that route would require complex priorities for what to do when passing command-line coordinate names not dimension names and visa-versa. */ //lat_nm_in=strdup(cf->dmn_nm[0]); //lon_nm_in=strdup(cf->dmn_nm[1]); lat_nm_in=strdup(cf->crd_nm[idx_lat]); lon_nm_in=strdup(cf->crd_nm[idx_lon]); /* Next four lines unnecessary in nco_rgr_wgt() which only needs dimension names (it reads input coordinates from map- not data-file) */ lat_ctr_id=cf->crd_id[idx_lat]; lon_ctr_id=cf->crd_id[idx_lon]; lat_dmn_nm=strdup(cf->dmn_nm[0]); lon_dmn_nm=strdup(cf->dmn_nm[1]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s \"coordinates\" attribute \"%s\" points to coordinates %s and %s. Latitude coordinate \"%s\" has LRV (along-track) and MRV (across-track) dimensions \"%s\" and \"%s\", respectively.\n",nco_prg_nm_get(),fnc_nm,rgr_var,cf->crd_sng,cf->crd_nm[0],cf->crd_nm[1],cf->crd_nm[idx_lat],cf->dmn_nm[0],cf->dmn_nm[1]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s Coordinates %s and %s \"units\" values are \"%s\" and \"%s\", respectively.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->crd_nm[1],cf->unt_sng[0] ? cf->unt_sng[0] : "(non-existent)",cf->unt_sng[1] ? cf->unt_sng[1] : "(non-existent)"); /* Clean-up CF coordinates memory */ if(crd_dpl) crd_dpl=(char *)nco_free(crd_dpl); if(cf->crd_sng) cf->crd_sng=(char *)nco_free(cf->crd_sng); if(cf->dmn_nm[0]) cf->dmn_nm[0]=(char *)nco_free(cf->dmn_nm[0]); if(cf->dmn_nm[1]) cf->dmn_nm[1]=(char *)nco_free(cf->dmn_nm[1]); if(cf->unt_sng[0]) cf->unt_sng[0]=(char *)nco_free(cf->unt_sng[0]); if(cf->unt_sng[1]) cf->unt_sng[1]=(char *)nco_free(cf->unt_sng[1]); // if(foo) foo=(char *)nco_free(foo); } /* !rgr_var */ /* goto skp_cf */ skp_cf: /* free() any abandoned cf structure now */ if(!flg_cf) if(cf) cf=(cf_crd_sct *)nco_free(cf); rcd=NC_NOERR; /* End CF-coordinates block */ /* Locate fields that must be present in input file Required variables are usually latitude and longitude Currently these variables must be in root group This fails for, e.g., OMI L2 which has coordinates /GEOLOCATION_DATA/[Latitude,Longitude] fxm: Generalize with traversal table so usual suspect coordinates may be in any group */ if(lat_ctr_id == NC_MIN_INT){ if(rgr->lat_nm_in && (rcd=nco_inq_varid_flg(in_id,rgr->lat_nm_in,&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup(rgr->lat_nm_in); else if((rcd=nco_inq_varid_flg(in_id,"latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("latitude"); else if((rcd=nco_inq_varid_flg(in_id,"Latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("Latitude"); /* AMSR, HIRDLS, TRMM */ else if((rcd=nco_inq_varid_flg(in_id,"lat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("lat"); /* CAM */ else if((rcd=nco_inq_varid_flg(in_id,"lat_d",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("lat_d"); /* EAM dynamics grid */ else if((rcd=nco_inq_varid_flg(in_id,"Lat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("Lat"); else if((rcd=nco_inq_varid_flg(in_id,"XLAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("XLAT"); /* WRF */ else if((rcd=nco_inq_varid_flg(in_id,"XLAT_M",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("XLAT_M"); /* Unknown */ else if((rcd=nco_inq_varid_flg(in_id,"LAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("LAT"); /* MAR/RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"TLAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("TLAT"); /* CICE, POP */ else if((rcd=nco_inq_varid_flg(in_id,"ULAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("ULAT"); /* CICE, POP */ else if((rcd=nco_inq_varid_flg(in_id,"latCell",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("latCell"); /* MPAS-O/I */ else if((rcd=nco_inq_varid_flg(in_id,"nav_lat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("nav_lat"); /* NEMO */ else if((rcd=nco_inq_varid_flg(in_id,"rlat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("rlat"); /* RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"global_latitude0",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("global_latitude0"); /* Oxford */ else if((rcd=nco_inq_varid_flg(in_id,"latitude0",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("latitude0"); /* Oxford NB: Must search for global_* first */ else if((rcd=nco_inq_varid_flg(in_id,"CO_Latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("CO_Latitude"); /* MLS */ else if((rcd=nco_inq_varid_flg(in_id,"S1_Latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("S1_Latitude"); /* GPM */ else if((rcd=nco_inq_varid_flg(in_id,"yc",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("yc"); /* RTM */ else if((rcd=nco_inq_varid_flg(in_id,"gridlat_0",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("gridlat_0"); /* NWS HRRR */ } /* !lat_ctr_id */ if(lon_ctr_id == NC_MIN_INT){ if(rgr->lon_nm_in && (rcd=nco_inq_varid_flg(in_id,rgr->lon_nm_in,&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup(rgr->lon_nm_in); else if((rcd=nco_inq_varid_flg(in_id,"longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("longitude"); else if((rcd=nco_inq_varid_flg(in_id,"Longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("Longitude"); /* AMSR, TRMM */ else if((rcd=nco_inq_varid_flg(in_id,"lon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("lon"); /* CAM */ else if((rcd=nco_inq_varid_flg(in_id,"lon_d",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("lon"); /* EAM dynamics grid */ else if((rcd=nco_inq_varid_flg(in_id,"Lon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("Lon"); else if((rcd=nco_inq_varid_flg(in_id,"XLONG",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("XLONG"); /* WRF */ else if((rcd=nco_inq_varid_flg(in_id,"XLONG_M",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("XLONG_M"); /* Unknown */ else if((rcd=nco_inq_varid_flg(in_id,"LON",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("LON"); /* MAR/RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"TLON",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("TLON"); /* CICE */ else if((rcd=nco_inq_varid_flg(in_id,"TLONG",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("TLONG"); /* POP */ else if((rcd=nco_inq_varid_flg(in_id,"ULON",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("ULON"); /* CICE */ else if((rcd=nco_inq_varid_flg(in_id,"ULONG",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("ULONG"); /* POP */ else if((rcd=nco_inq_varid_flg(in_id,"lonCell",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("lonCell"); /* MPAS-O/I */ else if((rcd=nco_inq_varid_flg(in_id,"nav_lon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("nav_lon"); /* NEMO */ else if((rcd=nco_inq_varid_flg(in_id,"rlon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("rlon"); /* RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"global_longitude0",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("global_longitude0"); /* Oxford NB: Must search for global_* first */ else if((rcd=nco_inq_varid_flg(in_id,"longitude0",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("longitude0"); /* Oxford */ else if((rcd=nco_inq_varid_flg(in_id,"CO_Longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("CO_Longitude"); /* MLS */ else if((rcd=nco_inq_varid_flg(in_id,"S1_Longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("S1_Longitude"); /* GPM */ else if((rcd=nco_inq_varid_flg(in_id,"xc",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("xc"); /* RTM */ else if((rcd=nco_inq_varid_flg(in_id,"gridlon_0",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("gridlon_0"); /* NWS HRRR */ } /* !lon_ctr_id */ if(!lat_nm_in || !lon_nm_in){ (void)fprintf(stdout,"%s: ERROR %s unable to identify latitude and/or longitude variable.\nHINT: Potential causes and workarounds for this include: 1. Coordinate variables must be in the root directory (not in a group). If this might be the problem, try to \"flatten\" the input file before regridding it (see http://nco.sf.net/nco.html#flatten). 2. Horizontal dimensions with \"unusual\" names are hard to identify unless the user designates them somehow. ncremap will search for horizontal dimensions named in the \"coordinates\" attribute in a template variable specified with the \"-V rgr_var\" option. 3. NCO will also search its own internal database for likely names of horizontal coordinate variables (lat, latitude, LAT, XLAT, etc.). Contact the NCO project to have your idiosyncratic coordinate names added to the internal database.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !lat_nm_in */ /* Rank of coordinates determines whether grid is curvilinear */ rcd+=nco_inq_varndims(in_id,lat_ctr_id,&lat_rnk); rcd+=nco_inq_varndims(in_id,lon_ctr_id,&lon_rnk); /* If lat_ctr and lon_ctr share same and only dimension then grid is unstructured */ if(lat_rnk*lon_rnk == 1){ rcd+=nco_inq_vardimid(in_id,lat_ctr_id,&dmn_id_lat); rcd+=nco_inq_vardimid(in_id,lon_ctr_id,&dmn_id_lon); if(dmn_id_lat == dmn_id_lon){ dmn_id_col=dmn_id_lat; dmn_id_lat=NC_MIN_INT; dmn_id_lon=NC_MIN_INT; rcd+=nco_inq_dimname(in_id,dmn_id_col,dmn_nm); col_dmn_nm=(char *)strdup(dmn_nm); flg_grd_1D=True; } /* !unstructured */ } /* lat_rnk == lon_rnk == 1 */ if(lat_rnk*lon_rnk == 1 && dmn_id_lat != NC_MIN_INT && dmn_id_lon != NC_MIN_INT){ flg_grd_crv=False; flg_grd_2D=True; } /* !lat_rnk */ if(lat_rnk == dmn_nbr_2D || lon_rnk == dmn_nbr_2D){ flg_grd_crv=True; flg_grd_2D=False; } /* !lat_rnk */ if(lat_rnk > dmn_nbr_2D || lon_rnk > dmn_nbr_2D){ (void)fprintf(stdout,"%s: ERROR %s reports an identified grid variable (%s with rank %d and/or %s with rank %d) has rank greater than two---grid variables currently must have rank 1 or 2.\nHINT: If grid variables do not vary in time, then temporally average them (with, e.g., ncwa -a time in.nc out.nc) prior to inferring grid\n",nco_prg_nm_get(),fnc_nm,lat_nm_in,lat_rnk,lon_nm_in,lon_rnk); nco_exit(EXIT_FAILURE); } /* !3D */ if(lat_rnk*lon_rnk != 1 && lat_rnk*lon_rnk != 4) assert(False); /* Scrutinize coordinates for their dimensions NB: Unstructured already known */ if(flg_grd_2D){ rcd+=nco_inq_dimname(in_id,dmn_id_lat,dmn_nm); lat_dmn_nm=(char *)strdup(dmn_nm); rcd+=nco_inq_dimname(in_id,dmn_id_lon,dmn_nm); lon_dmn_nm=(char *)strdup(dmn_nm); } /* !flg_grd_2D */ if(flg_grd_crv){ rcd+=nco_inq_vardimid(in_id,lat_ctr_id,dmn_ids); /* fxm: use cf struct and match with units name, if any? normally curvilinear grid dimensions are just pixel dimensions that are not aligned north-south or east-west */ dmn_id_lat=dmn_ids[0]; dmn_id_lon=dmn_ids[1]; rcd+=nco_inq_dimname(in_id,dmn_id_lat,dmn_nm); lat_dmn_nm=(char *)strdup(dmn_nm); rcd+=nco_inq_dimname(in_id,dmn_id_lon,dmn_nm); lon_dmn_nm=(char *)strdup(dmn_nm); } /* !flg_grd_crv */ if(!(lat_dmn_nm && lon_dmn_nm) && !col_dmn_nm){ (void)fprintf(stdout,"%s: ERROR %s unable to identify latitude and/or longitude dimension and/or column dimension.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !col_dmn_nm !lat_dmn_nm !lon_dmn_nm */ /* Locate spatial dimensions that may be present NB: bounds dimensions may present a special problem CAM-FV and CAM-SE use nbnd for temporal bounds and have no spatial bounds dimension CAM3 uses tbnd for temporal bounds and has no spatial bounds dimension CICE and POP use d2 for temporal bounds, and CICE uses nvertices for spatial bounds while POP uses nothing Hence search for nvertices before nbnd to ensure spatial bound is found first */ if((rcd=nco_inq_dimid_flg(in_id,"nv",&dmn_id_bnd)) == NC_NOERR) bnd_dmn_nm=strdup("nv"); /* fxm */ else if((rcd=nco_inq_dimid_flg(in_id,"nvertices",&dmn_id_bnd)) == NC_NOERR) bnd_dmn_nm=strdup("nvertices"); /* CICE */ else if((rcd=nco_inq_dimid_flg(in_id,"maxEdges",&dmn_id_bnd)) == NC_NOERR) bnd_dmn_nm=strdup("maxEdges"); /* MPAS */ if((rcd=nco_inq_dimid_flg(in_id,"nVertices",&dmn_id_vrt)) == NC_NOERR) vrt_dmn_nm=strdup("nVertices"); /* MPAS */ /* Use dimension IDs to get dimension sizes and grid size */ if(flg_grd_1D){ rcd+=nco_inq_dimlen(in_id,dmn_id_col,&col_nbr); lat_nbr=lon_nbr=col_nbr; }else{ rcd+=nco_inq_dimlen(in_id,dmn_id_lat,&lat_nbr); rcd+=nco_inq_dimlen(in_id,dmn_id_lon,&lon_nbr); col_nbr=NC_MIN_INT; } /* !flg_grd_1D */ if(dmn_id_bnd != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_bnd,&grd_crn_nbr); if(dmn_id_bnd != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_bnd,&bnd_nbr); if(dmn_id_vrt != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_vrt,&vrt_nbr); if(flg_grd_1D){ /* Unstructured grid (e.g., CAM-SE) */ grd_rnk_nbr=dmn_nbr_1D; grd_typ=nco_grd_2D_unk; lat_typ=nco_grd_lat_unk; lon_typ=nco_grd_lon_unk; /* 1D grids without their own boundaries are at the mercy of the weight generator */ if(dmn_id_bnd == NC_MIN_INT){ (void)fprintf(stdout,"%s: WARNING %s reports an unstructured grid without spatial boundary information. NCO can copy but not infer spatial boundaries from unstructured grids. Thus NCO will not write spatial bounds to the gridfile inferred from this input file. Instead, the weight generator that ingests this gridfile must generate weights for gridcells with unknown spatial extent. This is feasible for grids and mappings where weights masquerade as areas and are determined by underlying grid and interpolation type (e.g., bilinear remapping of spectral element grid). Unfortunately, the ESMF_RegridWeightGen (ERWG) program requires cell interfaces in both grid files, so ERWG will break on this gridfile. Other weight generators such as TempestRemap may be more successful with this SCRIP file.\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT Re-run the regridder, this time adding the \"-s src_grd\" option to specify the source grid file in SCRIP format. That SCRIP file will have the spatial bounds information required by the ESMF_RegridWeightGen (ERWG) program, so that the regridder will circumvent inferring the underlying grid through its black but fragile magic.\n",nco_prg_nm_get()); flg_wrt_crn=False; /* Input could actually be from grid with no polygonal definition, e.g., CAM-SE Corner number is non-deterministic since, e.g., CAM-SE dual grid can be fit to quadrilaterals, pentagons, chevrons, etc. Bounds will not be diagnosed so safe to set grd_crn_nbr to harmless (though weird) value like 4 However, ERWG requires presence of valid corner dimension "grid_corners" and arrays in input SCRIP file So ERWG will break when reading this SCRIP file regardless of whether it contains arrays (with bogus values) By default do not write grid corner values */ grd_crn_nbr=4; } /* !dmn_id_bnd */ if(bnd_nbr == 2){ /* Unstructured grids with bounds information (e.g., OCO2) may use a pseudo-rectangular convention of archiving latitude and longitude bounds as 2xN (rather than 4XN) arrays even though cell have four corners. "convention" is that two latitudes and two longitudes can specify rectangular boundary cell In this case, bnd_nbr=grd_crn_nbr=2=sizeof(nv)=sizeof(nvertices) currently Set number of corners to rectangular and leave bnd_nbr as is */ grd_crn_nbr=4; flg_1D_psd_rct_bnd=True; } /* !bnd_nbr */ if(!strcmp(bnd_dmn_nm,"maxEdges")){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Unstructured grid has dimension \"%s\" which indicates an MPAS grid. Will attempt to locate other MPAS information (dimension nVertices and variables verticesOnCell, lonVertex, and latVertex) to construct SCRIP-compliant bounds variables...\n",nco_prg_nm_get(),bnd_dmn_nm); if((rcd=nco_inq_varid_flg(in_id,"verticesOnCell",&vrt_cll_id)) == NC_NOERR) vrt_cll_nm=strdup("verticesOnCell"); if((rcd=nco_inq_varid_flg(in_id,"lonVertex",&vrt_lon_id)) == NC_NOERR) vrt_lon_nm=strdup("lonVertex"); if((rcd=nco_inq_varid_flg(in_id,"latVertex",&vrt_lat_id)) == NC_NOERR) vrt_lat_nm=strdup("latVertex"); if(dmn_id_vrt != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_vrt,&vrt_nbr); if(vrt_dmn_nm && vrt_cll_nm && vrt_lon_nm && vrt_lat_nm){ flg_1D_mpas_bnd=True; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Found all MPAS information needed to construct SCRIP-compliant bounds variables.\n",nco_prg_nm_get()); }else{ (void)fprintf(stdout,"%s: INFO Unable to find all MPAS information needed to construct SCRIP-compliant bounds variables. Will not write bounds coordinates. This will degrade usefulness of SCRIP file for regridding schemes (e.g., conservative) that require cell boundaries.\n",nco_prg_nm_get()); (void)fprintf(stdout,"%s: HINT Often MPAS restart files contain the required bounds variables (verticesOnCell, lonVertex, latVertex) that normal MPAS data files lack. Try inferring the SCRIP grid from a restart file not a normal time-varying output dataset.\n",nco_prg_nm_get()); flg_wrt_crn=False; } /* !vrt_cll_nm */ } /* !bnd_dmn_nm */ }else if(flg_grd_2D){ /* !flg_grd_1D */ /* Assume 2D grid of uninitialized type */ grd_rnk_nbr=dmn_nbr_2D; grd_typ=nco_grd_2D_nil; lat_typ=nco_grd_lat_nil; lon_typ=nco_grd_lon_nil; /* Assume rectangular grids that do not specify otherwise use quadrilaterals */ if(dmn_id_bnd == NC_MIN_INT) grd_crn_nbr=4; /* Sometimes we infer from a 2D grid, like those produced by nco_grd_mk(), that has bounds with nv=2 This signals rectangular gridcell bounds are interfaces not vertices (to save half the space) These rectangles really have four corners so we change grd_crn_nbr (not bnd_nbr) accordingly */ if(grd_crn_nbr == 2) grd_crn_nbr=4; /* Convention is to archive only two bounds for rectangular grids (since sides are identical) Non-quadrilateral rectangular grids are untested */ if(grd_crn_nbr == 4) bnd_nbr=2; }else if(flg_grd_crv){ /* !flg_grd_2D */ /* Assume curvilinear grid (e.g., WRF) */ flg_grd_2D=False; grd_rnk_nbr=dmn_nbr_2D; grd_typ=nco_grd_2D_unk; lat_typ=nco_grd_lat_unk; lon_typ=nco_grd_lon_unk; /* Assume curvilinear grids that do not specify otherwise use quadrilaterals */ if(dmn_id_bnd == NC_MIN_INT) grd_crn_nbr=4; /* Assume quadrilaterals are, well, quadrilaterals (e.g., rhomboids) not necessarily rectangles Non-quadrilateral curvilinear grids are untested */ if(grd_crn_nbr == 4) bnd_nbr=4; else assert(False); } /* !flg_grd_crv */ /* Allocate space for output data */ if(flg_grd_1D) grd_sz_nbr=col_nbr; else grd_sz_nbr=lat_nbr*lon_nbr; dmn_sz_int=(int *)nco_malloc(grd_rnk_nbr*nco_typ_lng((nc_type)NC_INT)); area=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); msk=(int *)nco_malloc(grd_sz_nbr*nco_typ_lng((nc_type)NC_INT)); if(flg_grd_1D){ if(bnd_nbr != NC_MIN_INT) lat_bnd=(double *)nco_malloc(grd_sz_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); if(bnd_nbr != NC_MIN_INT) lon_bnd=(double *)nco_malloc(grd_sz_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); }else if(flg_grd_2D){ /* !flg_grd_1D */ lat_bnd=(double *)nco_malloc(lat_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(lat_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lon_bnd=(double *)nco_malloc(lon_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(lon_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(lon_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); }else if(flg_grd_crv){ /* !flg_grd_2D */ lat_bnd=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lon_bnd=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); } /* !flg_grd_crv */ grd_ctr_lat=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_ctr_lon=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lat=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lon=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); /* Locate fields that may be present in input file */ if((rcd=nco_inq_varid_flg(in_id,"lat_bnds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("lat_bnds"); else if((rcd=nco_inq_varid_flg(in_id,"latt_bounds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("latt_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"latu_bounds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("latu_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"lat_ntf",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("lat_ntf"); else if((rcd=nco_inq_varid_flg(in_id,"lat_vertices",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("lat_vertices"); else if((rcd=nco_inq_varid_flg(in_id,"latitude_bnds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("latitude_bnds"); /* OCO2 */ else if((rcd=nco_inq_varid_flg(in_id,"LatitudeCornerpoints",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("LatitudeCornerpoints"); /* OMI */ if((rcd=nco_inq_varid_flg(in_id,"lon_bnds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lon_bnds"); else if((rcd=nco_inq_varid_flg(in_id,"lont_bounds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lont_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"lonu_bounds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lonu_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"lon_ntf",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lon_ntf"); else if((rcd=nco_inq_varid_flg(in_id,"lon_vertices",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lon_vertices"); else if((rcd=nco_inq_varid_flg(in_id,"longitude_bnds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("longitude_bnds"); /* OCO2 */ else if((rcd=nco_inq_varid_flg(in_id,"LongitudeCornerpoints",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("LongitudeCornerpoints"); /* OMI */ if((rcd=nco_inq_varid_flg(in_id,"area",&area_id)) == NC_NOERR) area_nm_in=strdup("area"); else if((rcd=nco_inq_varid_flg(in_id,"Area",&area_id)) == NC_NOERR) area_nm_in=strdup("Area"); else if((rcd=nco_inq_varid_flg(in_id,"areaCell",&area_id)) == NC_NOERR) area_nm_in=strdup("areaCell"); /* MPAS-O/I */ else if((rcd=nco_inq_varid_flg(in_id,"grid_area",&area_id)) == NC_NOERR) area_nm_in=strdup("grid_area"); else if((rcd=nco_inq_varid_flg(in_id,"area_d",&area_id)) == NC_NOERR) area_nm_in=strdup("area_d"); /* EAM dynamics grid */ else if((rcd=nco_inq_varid_flg(in_id,"area_p",&area_id)) == NC_NOERR) area_nm_in=strdup("area_p"); /* EAM physics grid */ // else if((rcd=nco_inq_varid_flg(in_id,"aice",&area_id)) == NC_NOERR) area_nm_in=strdup("aice"); /* CICE time-dependent ice area (3D), not total gridcell area */ else if((rcd=nco_inq_varid_flg(in_id,"tarea",&area_id)) == NC_NOERR) area_nm_in=strdup("tarea"); /* CICE time-invariant state-variable gridcell area (2D) */ else if((rcd=nco_inq_varid_flg(in_id,"uarea",&area_id)) == NC_NOERR) area_nm_in=strdup("uarea"); /* CICE time-invariant dynamics variables (2D) */ msk_nm_in=rgr->msk_var; if(msk_nm_in){ if(!strcasecmp(msk_nm_in,"none")){ /* 20170814: Some variables named "*mask*" are, e.g., quality control masks not regridding masks per se */ msk_nm_in=(char *)nco_free(msk_nm_in); }else{ /* User-supplied name overrides database */ rcd=nco_inq_varid(in_id,msk_nm_in,&msk_id); } /* !msk_nm_in */ }else{ /* Otherwise search database */ if((rcd=nco_inq_varid_flg(in_id,"mask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("mask"); else if((rcd=nco_inq_varid_flg(in_id,"Mask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("Mask"); else if((rcd=nco_inq_varid_flg(in_id,"grid_imask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("grid_imask"); else if((rcd=nco_inq_varid_flg(in_id,"landmask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("landmask"); /* ALM/CLM */ else if((rcd=nco_inq_varid_flg(in_id,"tmask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("tmask"); /* CICE */ } /* !msk_nm_in */ /* Mask field requires special handling for non-conformant models */ if(msk_id != NC_MIN_INT){ /* 20151201: All models tested define mask as NC_INT except CICE which uses NC_FLOAT 20160111: Few observations tested define mask. Exceptions include AMSR and GHRSST. AMSR uses NC_SHORT to store bitmasks. Bitmask is 1 for missing data, and up to 128 for various quality levels of valid data. Hence, almost better to ignore AMSR mask variable. GHRSST uses NC_BYTE for its 3D "mask" bit-mask of surface-type values 1,2,4,8,16. */ rcd=nco_inq_varndims(in_id,msk_id,&msk_rnk_nbr); if(msk_rnk_nbr != grd_rnk_nbr && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports input mask variable \"%s\" is rank %d while grid is rank %ld so will use first timestep/layer to determine output mask\n",nco_prg_nm_get(),fnc_nm,msk_nm_in,msk_rnk_nbr,grd_rnk_nbr); rcd=nco_inq_vartype(in_id,msk_id,&msk_typ); msk_unn.vp=(void *)nco_malloc(grd_sz_nbr*nco_typ_lng(msk_typ)); } /* !msk */ /* All grids: Some real-world datasets violate convention that coordinates ought never have missing values CICE lists missing value for lat/lon_ctr arrays (TLAT, TLONG) and re-uses that for bounds arrays (latt_bounds, lont_bounds) that do not bother to have their own missing value attributes Without counter-example, assume has_mss_val_bnd=has_mss_val_ctr and mss_val_bnd_dbl=mss_val_ctr_dbl */ has_mss_val_bnd=has_mss_val_ctr=nco_mss_val_get_dbl(in_id,lat_ctr_id,&mss_val_ctr_dbl); char *att_val; char *area_unt=NULL; /* [sng] Dimensional units used in area */ char *ngl_unt=NULL; /* [sng] Angular units used in coordinates */ long att_sz; nc_type att_typ; nco_bool flg_area_sr=True; /* [flg] Input area is in sterradians not something weird like km2 */ nco_bool flg_crd_rdn=False; /* [flg] Input coordinates are in radians not degrees */ if(flg_grd_1D){ /* Obtain fields that must be present in unstructured input file */ dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; rcd=nco_get_vara(in_id,lat_ctr_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); rcd=nco_get_vara(in_id,lon_ctr_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); /* Obtain fields that may be present in unstructured input file */ if(area_id != NC_MIN_INT) rcd=nco_get_vara(in_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); if(msk_id != NC_MIN_INT){ if(msk_rnk_nbr > grd_rnk_nbr){ /* Retrieve mask elements only from first horizontal grid, e.g., first timestep, first layer... */ for(dmn_idx=0;dmn_idx<msk_rnk_nbr-grd_rnk_nbr;dmn_idx++){ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=1L; } /* !dmn_idx */ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=col_nbr; } /* !msk_rnk_nbr */ rcd=nco_get_vara(in_id,msk_id,dmn_srt,dmn_cnt,msk_unn.vp,msk_typ); } /* !msk_id */ dmn_srt[0]=dmn_srt[1]=0L; if(flg_1D_psd_rct_bnd){ dmn_cnt[0]=col_nbr; dmn_cnt[1]=bnd_nbr; if(lat_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); if(lon_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); }else if(flg_1D_mpas_bnd){ const long grd_crn_nbrm1=grd_crn_nbr-1L; /* [nbr] Number of corners in gridcell minus one */ vrt_cll=(int *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng((nc_type)NC_INT)); vrt_lat=(double *)nco_malloc(vrt_nbr*nco_typ_lng(crd_typ)); vrt_lon=(double *)nco_malloc(vrt_nbr*nco_typ_lng(crd_typ)); dmn_cnt[0]=col_nbr; dmn_cnt[1]=grd_crn_nbr; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports dimension sizes bnd_nbr=%ld, col_nbr=%ld, grd_crn_nbr=%ld, vrt_nbr=%ld\n",nco_prg_nm_get(),fnc_nm,bnd_nbr,col_nbr,grd_crn_nbr,vrt_nbr); if(vrt_cll_id != NC_MIN_INT) rcd=nco_get_vara(in_id,vrt_cll_id,dmn_srt,dmn_cnt,vrt_cll,(nc_type)NC_INT); dmn_cnt[0]=vrt_nbr; if(vrt_lat_id != NC_MIN_INT) rcd=nco_get_vara(in_id,vrt_lat_id,dmn_srt,dmn_cnt,vrt_lat,crd_typ); if(vrt_lon_id != NC_MIN_INT) rcd=nco_get_vara(in_id,vrt_lon_id,dmn_srt,dmn_cnt,vrt_lon,crd_typ); rcd=nco_inq_att_flg(in_id,vrt_lat_id,unt_sng,&att_typ,&att_sz); if(rcd == NC_NOERR && att_typ == NC_CHAR){ att_val=(char *)nco_malloc((att_sz+1L)*nco_typ_lng(att_typ)); rcd+=nco_get_att(in_id,vrt_lat_id,unt_sng,att_val,att_typ); /* NUL-terminate attribute before using strstr() */ att_val[att_sz]='\0'; /* Match "radian" and "radians" */ if(strstr(att_val,"radian")) flg_crd_rdn=True; if(att_val) ngl_unt=(char *)strdup(att_val); if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ for(col_idx=0;col_idx<col_nbr;col_idx++){ idx=col_idx*grd_crn_nbr; for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ ttl_idx=idx+crn_idx; vrt_idx=vrt_cll[ttl_idx]; assert(vrt_idx >= 0); //if(vrt_idx >= vrt_nbr) (void)fprintf(stdout,"%s: WARNING %s input gridcell %ld corner %ld has extreme MPAS input verticesOnCell value %ld (maximum valid vertex = vrt_nbr-1 = %ld-1 = %ld)\n",nco_prg_nm_get(),fnc_nm,col_idx,crn_idx,vrt_idx,vrt_nbr,vrt_nbr-1); if(vrt_idx == 0){ /* 20201220: Convert values of zero to neighboring valid vertex index */ for(idx_fst=1;idx_fst<grd_crn_nbr;idx_fst++){ idx_tmp=crn_idx+idx_fst; /* Wrap to initial corner of this cell when candidate corner would be in next cell */ if(idx_tmp > grd_crn_nbrm1) idx_tmp-=grd_crn_nbr; ttl_idx=idx+idx_tmp; vrt_idx=vrt_cll[ttl_idx]; if(vrt_idx != 0) break; } /* !idx_fst */ assert(idx_fst < grd_crn_nbr); } /* !vrt_idx */ /* 20201220: Stored vertex indices use Fortran-based convention---subtract one for C */ vrt_idx--; lat_crn[ttl_idx]=vrt_lat[vrt_idx]; lon_crn[ttl_idx]=vrt_lon[vrt_idx]; //(void)fprintf(stdout,"%s: DEBUG %s reports col_idx = %ld, crn_idx = %ld, ttl_idx = %ld, vrt_idx = %ld, vrt_lat = %g, vrt_lon = %g\n",nco_prg_nm_get(),fnc_nm,col_idx,crn_idx,ttl_idx,vrt_idx,vrt_lat[vrt_idx],vrt_lon[vrt_idx]); } /* !crn_idx */ } /* !col_idx */ }else{ /* !flg_1D_mpas_bnd */ dmn_cnt[0]=col_nbr; dmn_cnt[1]=grd_crn_nbr; if(lat_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_crn,crd_typ); if(lon_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_crn,crd_typ); } /* !flg_1D_psd_rct_bnd */ } /* !flg_grd_1D */ if(flg_grd_crv){ /* Obtain fields that must be present in curvilinear input file */ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; rcd=nco_get_vara(in_id,lat_ctr_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); rcd=nco_get_vara(in_id,lon_ctr_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); /* 20150923: Also input, if present in curvilinear file, corners, area, and mask area and mask are same size as lat and lon */ if(area_id != NC_MIN_INT) rcd=nco_get_vara(in_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); if(msk_id != NC_MIN_INT){ if(msk_rnk_nbr > grd_rnk_nbr){ /* Retrieve mask elements only from first horizontal grid, e.g., first timestep, first layer... */ for(dmn_idx=0;dmn_idx<msk_rnk_nbr-grd_rnk_nbr;dmn_idx++){ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=1L; } /* !dmn_idx */ dmn_srt[dmn_idx]=dmn_srt[dmn_idx+1]=0L; dmn_cnt[dmn_idx]=lat_nbr; dmn_cnt[dmn_idx+1]=lon_nbr; } /* !msk_rnk_nbr */ rcd=nco_get_vara(in_id,msk_id,dmn_srt,dmn_cnt,msk_unn.vp,msk_typ); } /* !msk_id */ /* Corners are on curvilinear corner grid Rectangular boundaries (i.e., lat_bnd=[lat_nbr,2]) DNE for curvilinear grids Read-in *_crn arrays in curvilinear grids, and *_bnd arrays for rectilinear grids Rank-ordering of corner arrays is usually lat_nbr,lon_nbr,grd_crn_nbr as produced/expected by SCRIP However some datasets, e.g., OMI DOMINO use grd_crn_nbr,lat_nbr,lon_nbr Sigh... */ dmn_srt[0]=dmn_srt[1]=dmn_srt[2]=0L; if(lat_bnd_id != NC_MIN_INT && lon_bnd_id != NC_MIN_INT){ rcd=nco_inq_vardimid(in_id,lat_bnd_id,dmn_ids); if((dmn_ids[0] == dmn_id_lat && dmn_ids[1] == dmn_id_lon) || (dmn_ids[0] == dmn_id_lon && dmn_ids[1] == dmn_id_lat)){ dmn_id_bnd=dmn_ids[2]; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; dmn_cnt[2]=grd_crn_nbr; }else if((dmn_ids[1] == dmn_id_lat && dmn_ids[2] == dmn_id_lon) || (dmn_ids[1] == dmn_id_lon && dmn_ids[2] == dmn_id_lat)){ dmn_id_bnd=dmn_ids[0]; dmn_cnt[0]=grd_crn_nbr; dmn_cnt[1]=lat_nbr; dmn_cnt[2]=lon_nbr; flg_crn_grd_lat_lon=True; }else{ (void)fprintf(stdout,"%s: WARNING %s confused by dimension-ordering of latitude bounds variable \"%s\". Will ignore this bounds variable and attempt to extrapolate vertices from centers internally...\n",nco_prg_nm_get(),fnc_nm,lat_nm_in); lat_bnd_id=NC_MIN_INT; lon_bnd_id=NC_MIN_INT; } /* !dmn_ids */ rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_crn,crd_typ); rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_crn,crd_typ); if(flg_crn_grd_lat_lon){ /* Permute corner arrays from non-canonical (grd_nbr,lat_nbr,lon_nbr) to canonical (lat_nbr,lon_nbr,grd_nbr) order */ double *lat_crn_tmp=NULL; double *lon_crn_tmp=NULL; lat_crn_tmp=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_crn_tmp=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); memcpy(lat_crn_tmp,lat_crn,grd_sz_nbr*grd_crn_nbr*sizeof(double)); memcpy(lon_crn_tmp,lon_crn,grd_sz_nbr*grd_crn_nbr*sizeof(double)); for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ for(idx=0;idx<grd_sz_nbr;idx++){ lat_idx=idx/lon_nbr; lon_idx=idx%lon_nbr; /* NB: Variables differ (lat vs. lon) but indexes are identical in next two lines */ lat_crn[lat_idx*lon_nbr*grd_crn_nbr+lon_idx*grd_crn_nbr+crn_idx]=lat_crn_tmp[crn_idx*grd_sz_nbr+idx]; lon_crn[lat_idx*lon_nbr*grd_crn_nbr+lon_idx*grd_crn_nbr+crn_idx]=lon_crn_tmp[crn_idx*grd_sz_nbr+idx]; } /* !idx */ } /* !crn_idx */ if(lat_crn_tmp) lat_crn_tmp=(double *)nco_free(lat_crn_tmp); if(lon_crn_tmp) lon_crn_tmp=(double *)nco_free(lon_crn_tmp); /* In this code branch, thought to be executed only for OMI DOMINO grids, re-compute grid center arrays (known to contain missing values) as centroids of supplied grid corners */ for(idx=0;idx<grd_sz_nbr;idx++){ lat_idx=idx/lon_nbr; lon_idx=idx%lon_nbr; lat_ctr[idx]=0.25*(lat_crn[idx*grd_crn_nbr+0L]+lat_crn[idx*grd_crn_nbr+1L]+lat_crn[idx*grd_crn_nbr+2L]+lat_crn[idx*grd_crn_nbr+3L]); lon_ctr[idx]=nco_lon_crn_avg_brnch(lon_crn[idx*grd_crn_nbr+0L],lon_crn[idx*grd_crn_nbr+1L],lon_crn[idx*grd_crn_nbr+2L],lon_crn[idx*grd_crn_nbr+3L]); } /* !idx */ } /* !flg_crd_grd_lat_lon */ } /* !lat_bnd_id */ } /* !flg_grd_crv */ if(flg_grd_2D){ int lon_psn_in=1L; /* [idx] Ordinal position of longitude dimension in rectangular grid variables like area */ int lat_psn_in=0L; /* [idx] Ordinal position of latitude dimension in rectangular grid variables like area */ int tpl_id=NC_MIN_INT; /* [id] ID of template field */ /* Obtain fields that must be present in input file */ dmn_srt[0L]=0L; dmn_cnt[0L]=lat_nbr; rcd=nco_get_vara(in_id,lat_ctr_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); dmn_srt[0L]=0L; dmn_cnt[0L]=lon_nbr; rcd=nco_get_vara(in_id,lon_ctr_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); if(lat_ctr[1L] < lat_ctr[0L]) flg_s2n=False; /* Use fields that may be present in input file to override, if necessary, default lon/lat order area and mask are both suitable templates for determining input lat/lon ordering NB: Algorithm assumes area is same rank as grid, and falls-back to mask if that has same rank as grid */ if(area_id != NC_MIN_INT) tpl_id=area_id; else if(msk_id != NC_MIN_INT && msk_rnk_nbr == grd_rnk_nbr) tpl_id=msk_id; if(tpl_id != NC_MIN_INT){ int tpl_rnk_nbr; var_id=tpl_id; /* NB: Template variable rank may exceed two with --msk_[src/dst] (e.g., SST(time,lat,lon)) */ rcd=nco_inq_varndims(in_id,var_id,&tpl_rnk_nbr); rcd=nco_inq_vardimid(in_id,var_id,dmn_ids); /* fxm: Optimize discovery of lat/lon ordering */ for(dmn_idx=0;dmn_idx<grd_rnk_nbr;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_ids[dmn_idx],dmn_nm); rcd+=nco_inq_dimlen(in_id,dmn_ids[dmn_idx],&dmn_sz); if(!strcmp(dmn_nm,lat_dmn_nm)){ assert(dmn_sz == lat_nbr); assert(dmn_idx == 0); lat_psn_in=dmn_idx; } /* !lat */ if(!strcmp(dmn_nm,lon_dmn_nm)){ assert(dmn_sz == lon_nbr); assert(dmn_idx == 1); lon_psn_in=dmn_idx; } /* !lon */ } /* !dmn_idx */ } /* !tpl */ /* Obtain fields that may be present in input file */ if(area_id != NC_MIN_INT){ var_id=area_id; rcd=nco_inq_vardimid(in_id,var_id,dmn_ids); dmn_srt[lat_psn_in]=0L; dmn_cnt[lat_psn_in]=lat_nbr; dmn_srt[lon_psn_in]=0L; dmn_cnt[lon_psn_in]=lon_nbr; rcd=nco_get_vara(in_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); } /* !area */ if(msk_id != NC_MIN_INT){ var_id=msk_id; rcd=nco_inq_vardimid(in_id,var_id,dmn_ids); dmn_srt[lat_psn_in]=0L; dmn_cnt[lat_psn_in]=lat_nbr; dmn_srt[lon_psn_in]=0L; dmn_cnt[lon_psn_in]=lon_nbr; if(msk_rnk_nbr != grd_rnk_nbr){ /* Retrieve mask elements only from first horizontal grid, e.g., first timestep, first layer... */ for(dmn_idx=0;dmn_idx<msk_rnk_nbr-grd_rnk_nbr;dmn_idx++){ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=1L; } /* !dmn_idx */ dmn_srt[dmn_idx]=dmn_srt[dmn_idx+1]=0L; dmn_cnt[dmn_idx+lat_psn_in]=lat_nbr; dmn_cnt[dmn_idx+lon_psn_in]=lon_nbr; } /* !msk_rnk_nbr */ rcd=nco_get_vara(in_id,msk_id,dmn_srt,dmn_cnt,msk_unn.vp,msk_typ); } /* !msk */ /* Rectangular boundaries are often on "abbreviated" bounds grid (two bounds per center) Read-in *_crn arrays for 1D and curvilinear grids, and *_bnd arrays for rectilinear grids */ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=bnd_nbr; if(lat_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lon_nbr; dmn_cnt[1]=bnd_nbr; if(lon_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); } /* !flg_grd_2D */ /* Obtain units, if any, of input area */ if(area_id != NC_MIN_INT){ rcd=nco_inq_att_flg(in_id,area_id,unt_sng,&att_typ,&att_sz); if(rcd == NC_NOERR && att_typ == NC_CHAR){ att_val=(char *)nco_malloc((att_sz+1L)*nco_typ_lng(att_typ)); rcd+=nco_get_att(in_id,area_id,unt_sng,att_val,att_typ); /* NUL-terminate attribute before using strstr() */ att_val[att_sz]='\0'; if(!strcasestr(att_val,"radian")) flg_area_sr=False; if(att_val) area_unt=(char *)strdup(att_val); if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ } /* !area_id */ /* Additional information that may be required for any input grid */ if(area_id != NC_MIN_INT) has_mss_val_area=nco_mss_val_get_dbl(in_id,area_id,&mss_val_area_dbl); if(msk_id != NC_MIN_INT) has_mss_val_msk=nco_mss_val_get_dbl(in_id,msk_id,&mss_val_msk_dbl); /* 20160115: AMSR coordinates are packed as NC_SHORT with scale_value=0.01f. What to do? Is it worth unpacking everything? */ int flg_pck; /* [flg] Variable is packed on disk */ rcd=nco_inq_var_packing(in_id,lat_ctr_id,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports lat_ctr variable \"%s\" is packed so results unpredictable. HINT: If grid-generation causes problems, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,lat_nm_in); rcd=nco_inq_var_packing(in_id,lon_ctr_id,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports lon_ctr variable \"%s\" is packed so results unpredictable. HINT: If grid-generation causes problems, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,lon_nm_in); /* Close input netCDF file */ nco_close(in_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); /* Above this line, fl_in and in_id refer to input file to be regridded Below this line, fl_out and out_id refer to grid-file to be output */ dfl_lvl=rgr->dfl_lvl; fl_out=rgr->fl_grd; fl_out_fmt=rgr->fl_out_fmt; if(!fl_out){ (void)fprintf(stdout,"%s: ERROR %s filename for inferred SCRIP grid-file is uninitialized, supply it with \"ncks --rgr grid=filename.nc\" or \"ncremap -R '--rgr grid=filename.nc'\"\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT ncremap supplies an automatically generated default name for any output SCRIP grid-file. Users of the standalone regridder (ncks) must explicitly specify a name for the inferred SCRIP grid-file.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* !fl_out */ /* Define output variable values */ int lon_psn; /* [idx] Ordinal position of longitude dimension in rectangular grid dimension-size array */ int lat_psn; /* [idx] Ordinal position of latitude dimension in rectangular grid dimension-size array */ if(grd_rnk_nbr == dmn_nbr_1D){ dmn_sz_int[0]=col_nbr; }else if(grd_rnk_nbr == dmn_nbr_2D){ /* !dmn_nbr_1D */ /* SCRIP introduced [lon,lat] convention because more natural for Fortran NB: This [lon,lat] convention applies ONLY to grid_dims variable Write all other SCRIP variables as [lat,lon] Nonsensical? Yes, but backwards compatibility is priceless */ lon_psn=0; lat_psn=1; dmn_sz_int[lon_psn]=lon_nbr; dmn_sz_int[lat_psn]=lat_nbr; } /* !dmn_nbr_2D */ if(flg_grd_crv){ /* For curvilinear grids first, if necessary, infer corner boundaries Then perform sanity check using same code on inferred and copied grids */ if(False && has_mss_val_bnd && grd_crn_nbr == 4 && !strcmp(lat_bnd_nm,"latt_bounds") && !strcmp(lon_bnd_nm,"lont_bounds") && lat_bnd_id != NC_MIN_INT && lon_bnd_id != NC_MIN_INT){ /* Only CESM CICE is known to fit these constraints Cell center locations are (misleadingly) reported in a regular, rectangular, regional grid Cell corners/boundaries are regular only in SH, curvilinear in NH, i.e., displaced or tripole grid Grid is from southernmost Antarctic Ocean latitude and longitude near 79S,320E to North Pole Nominal centers do not agree with true centers computed from corners CICE may run in decomposed/unstructured mode, each column writes separately to output buffer? This could explain missing coordinates in non-ocean gridcells However, land points are completely masked (grid centers and corners are missing) Oversight? Why not write coordinates for land-masked cells? Regridder needs corners so we fill-in missing boundaries with derived grid Gave up on inferring 20170521 once tri-pole grid complexity became apparent */ const long idx_dbg=rgr->idx_dbg; double lat_ctr_drv; /* [dgr] Latitude center, derived */ double lon_ctr_drv; /* [dgr] Longitude center, derived */ double lat_crn_drv; /* [dgr] Latitude corner, derived */ double lon_crn_drv; /* [dgr] Longitude corner, derived */ long idx_ctr_sth; /* [idx] Index of southern neighbor */ long idx_ctr_nrt; /* [idx] Index of northern neighbor */ long idx_crn_sth; /* [idx] Index of southern neighbor */ long idx_crn_nrt; /* [idx] Index of northern neighbor */ long lon_idx_crr; /* [idx] Current longitude index */ long lon_vld_frs; /* [idx] First valid longitude in latitude row */ long *lon_vld_prv=NULL; /* [idx] Previous valid longitude in latitude row */ long *lon_vld_nxt=NULL; /* [idx] Next valid longitude in latitude row */ lon_vld_prv=(long *)nco_malloc(lon_nbr*sizeof(long)); lon_vld_nxt=(long *)nco_malloc(lon_nbr*sizeof(long)); /* First valid gridcell sets west and south bounds of entire grid */ for(idx_ctr=0;idx_ctr<grd_sz_nbr;idx_ctr++){ if(lat_ctr[idx_ctr] != mss_val_ctr_dbl) break; } /* !grd_sz_nbr */ assert(idx_ctr != grd_sz_nbr); idx_crn=idx_ctr*grd_crn_nbr; lat_sth=lat_crn[idx_crn]; lat_ncr=lat_crn[idx_crn+3]-lat_crn[idx_crn]; /* ul-ll */ lon_wst=lon_crn[idx_crn]; lon_ncr=lon_crn[idx_crn+1]-lon_crn[idx_crn]; /* lr-ll */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s will assume grid is regional CICE in curvilinear format with masked land. Will diagnose missing cell boundaries and centers from present boundaries and centers in grid of size lat_nbr=%ld, lon_nbr=%ld.\n",nco_prg_nm_get(),fnc_nm,lat_nbr,lon_nbr); for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ idx_ctr=lat_idx*lon_nbr; /* Find first valid longitude at this latitude */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++) if(lat_ctr[idx_ctr+lon_idx] != mss_val_ctr_dbl) break; lon_vld_frs=lon_idx; /* 20170519: Verified all tri-pole grid latitudes have at least one valid point */ if(lon_vld_frs == -1L) abort(); for(lon_idx_crr=0;lon_idx_crr<lon_nbr;lon_idx++){ /* Find previous and next valid longitude for all longitudes at this latitude Cells can be their own previous/next valid longitude */ lon_vld_prv[lon_idx_crr]=-1L; lon_vld_nxt[lon_idx_crr]=-1L; /* Start from current longitude and move left (west)... */ for(lon_idx=lon_idx_crr;lon_idx>=0;lon_idx--) if(lat_ctr[idx_ctr+lon_idx] != mss_val_ctr_dbl) break; if(lon_idx >= 0) lon_vld_prv[lon_idx_crr]=lon_idx; /* Start from current longitude and move right (east)... */ for(lon_idx=lon_idx_crr;lon_idx<lon_nbr;lon_idx++) if(lat_ctr[idx_ctr+lon_idx] != mss_val_ctr_dbl) break; if(lon_idx < lon_nbr) lon_vld_nxt[lon_idx_crr]=lon_idx; /* Wrap west if previous valid cell not found */ lon_vld_prv[lon_idx_crr]=lon_vld_prv[lon_nbr-1L]; /* Wrap east if next valid cell not found */ lon_vld_nxt[lon_idx_crr]=lon_vld_nxt[0]; } /* !lon_idx_crr */ /* Derive centers and corners for each missing point */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx_ctr=lat_idx*lon_nbr+lon_idx; idx_crn=idx_ctr*grd_crn_nbr; if(lat_ctr[idx_ctr] != mss_val_ctr_dbl){ lat_sth=lat_crn[idx_crn]; lat_ncr=lat_crn[idx_crn+3]-lat_crn[idx_crn]; /* ul-ll */ lat_ctr_drv=lat_sth+0.5*lat_ncr; lat_crn_drv=lat_sth; lon_wst=lon_crn[idx_crn]; lon_ncr=lon_crn[idx_crn+1]-lon_crn[idx_crn]; /* lr-ll */ lon_ctr_drv=lon_wst+lon_ncr*(lon_idx+0.5); if(nco_dbg_lvl_get() >= nco_dbg_std && idx_ctr == idx_dbg) (void)fprintf(stdout,"%s: DEBUG %s idx=%ld lat_idx=%ld, lon_idx=%ld, lat_sth=%g, lat_ncr=%g, lon_wst=%g, lon_ncr=%g\n",nco_prg_nm_get(),fnc_nm,idx_ctr,lat_idx,lon_idx,lat_sth,lat_ncr,lon_wst,lon_ncr); } /* !idx_ctr */ if(lat_ctr[idx_ctr] == mss_val_ctr_dbl){ if(lat_idx != 0L){ /* Not bottom row */ idx_ctr_sth=idx_ctr-lon_nbr; if(lat_ctr[idx_ctr_sth] != mss_val_ctr_dbl){ /* Copy southern corners from northern corners of southern neighbor */ idx_crn_sth=idx_ctr_sth*grd_crn_nbr; lat_crn[idx_crn+0L]=lat_crn[idx_crn_sth+3L]; lat_crn[idx_crn+1L]=lat_crn[idx_crn_sth+2L]; lon_crn[idx_crn+0L]=lon_crn[idx_crn_sth+3L]; lon_crn[idx_crn+1L]=lon_crn[idx_crn_sth+2L]; } /* !mss_val */ } /* !lat_idx */ if(lat_idx != lat_nbr-1L){ /* Not top row */ idx_ctr_nrt=idx_ctr+lon_nbr; if(lat_ctr[idx_ctr_nrt] != mss_val_ctr_dbl){ /* Copy northern corners from southern corners of northern neighbor */ idx_crn_nrt=idx_ctr_nrt*grd_crn_nbr; lat_crn[idx_crn+2L]=lat_crn[idx_crn_nrt+1L]; lat_crn[idx_crn+3L]=lat_crn[idx_crn_nrt+0L]; lon_crn[idx_crn+2L]=lon_crn[idx_crn_nrt+1L]; lon_crn[idx_crn+3L]=lon_crn[idx_crn_nrt+0L]; } /* !mss_val */ } /* !lat_idx */ /* Got to here before giving up Idea was to interpolate missing cell corners between previous and next valid cell */ /* Algorithm assumes lon_wst never changes (too simple for displaced/tri_pole) */ lon_ctr_drv=lon_wst+lon_ncr*(lon_idx+0.5); lon_crn_drv=lon_wst+lon_ncr*lon_idx; if(lon_ctr_drv >= 360.0) lon_ctr_drv-=360.0; lat_ctr[idx_ctr]=lat_ctr_drv; lon_ctr[idx_ctr]=lon_ctr_drv; lat_crn[idx_crn+0L]=lat_crn[idx_crn+1L]=lat_crn_drv; lat_crn[idx_crn+2L]=lat_crn[idx_crn+3L]=lat_crn_drv+lat_ncr; lon_crn[idx_crn+0L]=lon_crn[idx_crn+3L]=lon_crn_drv; lon_crn[idx_crn+1L]=lon_crn[idx_crn+2L]=lon_crn_drv+lon_ncr; /* Branch-cut rule */ if(lon_crn_drv+lon_ncr >= 360.0){ lon_crn[idx_crn+0L]=lon_crn[idx_crn+3L]=lon_crn_drv-360.0; lon_crn[idx_crn+1L]=lon_crn[idx_crn+2L]=lon_crn_drv+lon_ncr-360.0; } /* !brnch */ } /* !mss_val */ } /* !lon_idx */ } /* !lat_idx */ if(lon_vld_nxt) lon_vld_nxt=(long *)nco_free(lon_vld_nxt); if(lon_vld_prv) lon_vld_prv=(long *)nco_free(lon_vld_prv); } /* !CICE */ if(lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT){ /* Interfaces (ntf) and boundaries (bnd) for curvilinear grids are ill-defined since sides need not follow latitudes nor meridians Simplest representation that contains equivalent information to interfaces/boundaries is grid corners array Diagnose grid corners from midpoints Most curvilinear data (e.g., WRF) is dimensioned lat x lon unlike SCRIP which uses lon x lat Hence we keep lat_ctr, lon_ctr, lat_crn, lon_crn with same order (likely lat x lon) as data file from which we infer grid Always use input order to write skeleton file Change that order, if necessary, to write SCRIP grid file In the interior of a curvilinear grid, nine points contribute to the four corners of a quadrilateral surrounding each center point These are the three points above the point, the three points at the same latitude, and the three points beneath the point In other words, a nine-point stencil is required to define the four corners inferred around each gridcell center It is cleanest to use this stencil only once for all cells in the "real"-grid, including those on the edges, not the interior For this to work cleanly we define an enlarged "fake"-grid where we pre-copy the values that lead to the desired extrapolation on "real"-grid edges Inspired by array-based solutions to integration of PDEs on meshes in Juri Toomre's class NB: implementation is not robust to missing value points in interior of grid. Hopefully grids have no missing values in coordinate variables, although they may have missing values in non-grid fields (e.g., mask, temperature) */ double *lat_ctr_fk; /* [dgr] Latitude grid with extrapolated boundaries necessary for 9-point template to find four grid corners for each real center */ double *lon_ctr_fk; /* [dgr] Longitude grid with extrapolated boundaries necessary for 9-point template to find four grid corners for each real center */ lat_ctr_fk=(double *)nco_malloc((lat_nbr+2)*(lon_nbr+2)*sizeof(double)); lon_ctr_fk=(double *)nco_malloc((lat_nbr+2)*(lon_nbr+2)*sizeof(double)); long int idx_rl; /* [idx] Index into real unrolled array */ long int idx_fk; /* [idx] Index into fake unrolled array */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ /* lat idx on real grid */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ /* lon idx on real grid */ idx_rl=lat_idx*lon_nbr+lon_idx; idx_fk=(lat_idx+1)*(lon_nbr+2)+lon_idx+1; /* Copy real grid to interior of fake grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]; lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]; } /* !lon */ } /* !lat */ /* Formulae to extrapolate sides and corners of fake grid are written as a starting lat/lon plus or minus adjustment Adjustment is positive-definite if grid monotonically increases in latitude and longitude from LL to UR 20160111: Use macros/functions to determine longitude adjustments that are always less than 180 This ensures all longitudes contributing to extrapolated longitude are from same branch cut */ /* Bottom row */ lat_idx=0; /* lat idx of extrapolated point on fake grid */ for(lon_idx=1;lon_idx<lon_nbr+1;lon_idx++){ /* lon idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on bottom row of fake grid */ idx_rl=lat_idx*lon_nbr+lon_idx-1; /* 1D-offset of neighboring point on bottom row of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]-(lat_ctr[idx_rl+lon_nbr]-lat_ctr[idx_rl]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]-nco_lon_dff_brnch_dgr(lon_ctr[idx_rl+lon_nbr],lon_ctr[idx_rl]); } /* !lon */ /* Top row */ lat_idx=lat_nbr+1; /* lat idx of extrapolated point on fake grid */ for(lon_idx=1;lon_idx<lon_nbr+1;lon_idx++){ /* lon idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on top row of fake grid */ idx_rl=(lat_nbr-1)*lon_nbr+lon_idx-1; /* 1D-offset of neighboring point on top row of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]+(lat_ctr[idx_rl]-lat_ctr[idx_rl-lon_nbr]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]+nco_lon_dff_brnch_dgr(lon_ctr[idx_rl],lon_ctr[idx_rl-lon_nbr]); } /* !lon */ /* Left side */ lon_idx=0; /* lon idx of extrapolated point on fake grid */ for(lat_idx=1;lat_idx<lat_nbr+1;lat_idx++){ /* lat idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on left side of fake grid */ idx_rl=(lat_idx-1)*lon_nbr+lon_idx; /* 1D-offset of neighboring point on left side of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]-(lat_ctr[idx_rl+1]-lat_ctr[idx_rl]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]-nco_lon_dff_brnch_dgr(lon_ctr[idx_rl+1],lon_ctr[idx_rl]); } /* !lat */ /* Right side */ lon_idx=lon_nbr+1; /* lon idx of extrapolated point on fake grid */ for(lat_idx=1;lat_idx<lat_nbr+1;lat_idx++){ /* lat idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on right side of fake grid */ idx_rl=(lat_idx-1)*lon_nbr+lon_idx-2; /* 1D-offset of neighboring point on right side of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]+(lat_ctr[idx_rl]-lat_ctr[idx_rl-1]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]+nco_lon_dff_brnch_dgr(lon_ctr[idx_rl],lon_ctr[idx_rl-1]); } /* !lat */ /* LL */ lat_ctr_fk[0]=lat_ctr_fk[lon_nbr+2]-(lat_ctr_fk[2*(lon_nbr+2)]-lat_ctr_fk[lon_nbr+2]); lon_ctr_fk[0]=lon_ctr_fk[1]-nco_lon_dff_brnch_dgr(lon_ctr_fk[2],lon_ctr_fk[1]); /* LR */ lat_ctr_fk[lon_nbr+1]=lat_ctr_fk[2*(lon_nbr+2)-1]-(lat_ctr_fk[3*(lon_nbr+2)-1]-lat_ctr_fk[2*(lon_nbr+2)-1]); lon_ctr_fk[lon_nbr+1]=lon_ctr_fk[lon_nbr]+nco_lon_dff_brnch_dgr(lon_ctr_fk[lon_nbr],lon_ctr_fk[lon_nbr-1]); /* UR */ lat_ctr_fk[(lat_nbr+2)*(lon_nbr+2)-1]=lat_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-1]+(lat_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-1]-lat_ctr_fk[lat_nbr*(lon_nbr+2)-1]); lon_ctr_fk[(lat_nbr+2)*(lon_nbr+2)-1]=lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-2]+nco_lon_dff_brnch_dgr(lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-2],lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-3]); /* UL */ lat_ctr_fk[(lat_nbr+1)*(lon_nbr+2)]=lat_ctr_fk[lat_nbr*(lon_nbr+2)]+(lat_ctr_fk[lat_nbr*(lon_nbr+2)]-lat_ctr_fk[(lat_nbr-1)*(lon_nbr+2)]); lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)]=lon_ctr_fk[lat_nbr*(lon_nbr+2)+1]-nco_lon_dff_brnch_dgr(lon_ctr_fk[lat_nbr*(lon_nbr+2)+2],lon_ctr_fk[lat_nbr*(lon_nbr+2)+1]); if(nco_dbg_lvl_get() >= nco_dbg_std){ long idx_dbg; idx_dbg=rgr->idx_dbg; (void)fprintf(stderr,"%s: INFO %s idx_dbg = %li, Fake Center [lat,lon]=[%g,%g]\n",nco_prg_nm_get(),fnc_nm,idx_dbg,lat_ctr_fk[idx_dbg],lon_ctr_fk[idx_dbg]); } /* !dbg */ long int lat_idx_fk; /* [idx] Index into fake (extrapolated) latitude array */ long int lon_idx_fk; /* [idx] Index into fake (extrapolated) longitude array */ long int idx_fk_crn_ll_ctr_ll; long int idx_fk_crn_ll_ctr_lr; long int idx_fk_crn_ll_ctr_ur; long int idx_fk_crn_ll_ctr_ul; long int idx_fk_crn_lr_ctr_ll; long int idx_fk_crn_lr_ctr_lr; long int idx_fk_crn_lr_ctr_ur; long int idx_fk_crn_lr_ctr_ul; long int idx_fk_crn_ur_ctr_ll; long int idx_fk_crn_ur_ctr_lr; long int idx_fk_crn_ur_ctr_ur; long int idx_fk_crn_ur_ctr_ul; long int idx_fk_crn_ul_ctr_ll; long int idx_fk_crn_ul_ctr_lr; long int idx_fk_crn_ul_ctr_ur; long int idx_fk_crn_ul_ctr_ul; double *crn_lat; double *crn_lon; crn_lat=(double *)nco_malloc(grd_crn_nbr*sizeof(double)); crn_lon=(double *)nco_malloc(grd_crn_nbr*sizeof(double)); size_t wrn_nbr_max=20; size_t wrn_nbr=0; for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ /* 9-point template valid at all interior (non-edge) points in real grid, and at all points (including edges) in fake grid Read variables idx_crn_ll_ctr_ul as "index of upper left gridcell center that contributes to lower-left gridcell corner" Algorithms execute in counter-clockwise (CCW) direction: lower-left, lower-right, upper-right, upper-left lat_idx and lon_idx are true indices and are used to write into grd_crn_lat/lon arrays lat_idx_fk and lon_idx_fk are indices into fake arrays with extrapolated boundaries and are used to read data from fake arrays */ lon_idx_fk=lon_idx+1; lat_idx_fk=lat_idx+1; idx_rl=lat_idx*lon_nbr+lon_idx; idx_fk=lat_idx_fk*(lon_nbr+2)+lon_idx_fk; /* Determine index into fake array (valid everywhere it is applied) Comments after each equation are formula for real index (valid only at interior gridcells) */ idx_fk_crn_ll_ctr_ll=idx_fk-(lon_nbr+2)-1; // (lat_idx-1)*lon_nbr+lon_idx-1 idx_fk_crn_ll_ctr_lr=idx_fk-(lon_nbr+2); // (lat_idx-1)*lon_nbr+lon_idx idx_fk_crn_ll_ctr_ur=idx_fk; // lat_idx*lon_nbr+lon_idx idx_fk_crn_ll_ctr_ul=idx_fk-1; // lat_idx*lon_nbr+lon_idx-1; idx_fk_crn_lr_ctr_ll=idx_fk-(lon_nbr+2); // (lat_idx-1)*lon_nbr+lon_idx idx_fk_crn_lr_ctr_lr=idx_fk-(lon_nbr+2)+1; // (lat_idx-1)*lon_nbr+lon_idx+1 idx_fk_crn_lr_ctr_ur=idx_fk+1; // lat_idx*lon_nbr+lon_idx+1 idx_fk_crn_lr_ctr_ul=idx_fk; // lat_idx*lon_nbr+lon_idx; idx_fk_crn_ur_ctr_ll=idx_fk; // lat_idx*lon_nbr+lon_idx idx_fk_crn_ur_ctr_lr=idx_fk+1; // lat_idx*lon_nbr+lon_idx+1 idx_fk_crn_ur_ctr_ur=idx_fk+(lon_nbr+2)+1; // (lat_idx+1)*lon_nbr+lon_idx+1 idx_fk_crn_ur_ctr_ul=idx_fk+(lon_nbr+2); // (lat_idx+1)*lon_nbr+lon_idx; idx_fk_crn_ul_ctr_ll=idx_fk-1; // lat_idx*lon_nbr+lon_idx-1 idx_fk_crn_ul_ctr_lr=idx_fk; // lat_idx*lon_nbr+lon_idx idx_fk_crn_ul_ctr_ur=idx_fk+(lon_nbr+2); // (lat_idx+1)*lon_nbr+lon_idx idx_fk_crn_ul_ctr_ul=idx_fk+(lon_nbr+2)-1; // (lat_idx+1)*lon_nbr+lon_idx-1; /* 20160111: Algorithm requires that all longitudes in template be on same "branch cut" If, say, LL longitude is 179.0 and LR longitude is -179.0 then their sum and average are zero, not 180.0 or -180.0 as desired Routines labeled "*_brnch" in the following ensure that branch-cut rules are followed */ idx_crn_ll=grd_crn_nbr*idx_rl+0; lat_crn[idx_crn_ll]=0.25*(lat_ctr_fk[idx_fk_crn_ll_ctr_ll]+lat_ctr_fk[idx_fk_crn_ll_ctr_lr]+lat_ctr_fk[idx_fk_crn_ll_ctr_ur]+lat_ctr_fk[idx_fk_crn_ll_ctr_ul]); lon_crn[idx_crn_ll]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_ll_ctr_ll],lon_ctr_fk[idx_fk_crn_ll_ctr_lr],lon_ctr_fk[idx_fk_crn_ll_ctr_ur],lon_ctr_fk[idx_fk_crn_ll_ctr_ul]); idx_crn_lr=grd_crn_nbr*idx_rl+1; lat_crn[idx_crn_lr]=0.25*(lat_ctr_fk[idx_fk_crn_lr_ctr_ll]+lat_ctr_fk[idx_fk_crn_lr_ctr_lr]+lat_ctr_fk[idx_fk_crn_lr_ctr_ur]+lat_ctr_fk[idx_fk_crn_lr_ctr_ul]); lon_crn[idx_crn_lr]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_lr_ctr_ll],lon_ctr_fk[idx_fk_crn_lr_ctr_lr],lon_ctr_fk[idx_fk_crn_lr_ctr_ur],lon_ctr_fk[idx_fk_crn_lr_ctr_ul]); idx_crn_ur=grd_crn_nbr*idx_rl+2; lat_crn[idx_crn_ur]=0.25*(lat_ctr_fk[idx_fk_crn_ur_ctr_ll]+lat_ctr_fk[idx_fk_crn_ur_ctr_lr]+lat_ctr_fk[idx_fk_crn_ur_ctr_ur]+lat_ctr_fk[idx_fk_crn_ur_ctr_ul]); lon_crn[idx_crn_ur]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_ur_ctr_ll],lon_ctr_fk[idx_fk_crn_ur_ctr_lr],lon_ctr_fk[idx_fk_crn_ur_ctr_ur],lon_ctr_fk[idx_fk_crn_ur_ctr_ul]); idx_crn_ul=grd_crn_nbr*idx_rl+3; lat_crn[idx_crn_ul]=0.25*(lat_ctr_fk[idx_fk_crn_ul_ctr_ll]+lat_ctr_fk[idx_fk_crn_ul_ctr_lr]+lat_ctr_fk[idx_fk_crn_ul_ctr_ur]+lat_ctr_fk[idx_fk_crn_ul_ctr_ul]); lon_crn[idx_crn_ul]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_ul_ctr_ll],lon_ctr_fk[idx_fk_crn_ul_ctr_lr],lon_ctr_fk[idx_fk_crn_ul_ctr_ur],lon_ctr_fk[idx_fk_crn_ul_ctr_ul]); crn_lat[0]=lat_crn[idx_crn_ll]; crn_lat[1]=lat_crn[idx_crn_lr]; crn_lat[2]=lat_crn[idx_crn_ur]; crn_lat[3]=lat_crn[idx_crn_ul]; crn_lon[0]=lon_crn[idx_crn_ll]; crn_lon[1]=lon_crn[idx_crn_lr]; crn_lon[2]=lon_crn[idx_crn_ur]; crn_lon[3]=lon_crn[idx_crn_ul]; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,grd_crn_nbr,idx_ccw,rcr_lvl); if(!flg_ccw && wrn_nbr < wrn_nbr_max){ (void)fprintf(stdout,"%s: %s WARNING reports non-CCW gridcell at idx=%li, (lat,lon)_idx=(%li,%li), (lat,lon) = (%g, %g)\n",nco_prg_nm_get(),fnc_nm,idx_rl,lat_idx,lon_idx,lat_ctr[lat_idx],lon_ctr[lon_idx]); wrn_nbr++; if(wrn_nbr == wrn_nbr_max) (void)fprintf(stdout,"%s: %s INFO Number of non-CCW errors reached maximum = %li, not printing anymore\n",nco_prg_nm_get(),fnc_nm,wrn_nbr_max); } /* endif */ lat_crn[idx_crn_ll]=crn_lat[0]; lat_crn[idx_crn_lr]=crn_lat[1]; lat_crn[idx_crn_ur]=crn_lat[2]; lat_crn[idx_crn_ul]=crn_lat[3]; lon_crn[idx_crn_ll]=crn_lon[0]; lon_crn[idx_crn_lr]=crn_lon[1]; lon_crn[idx_crn_ur]=crn_lon[2]; lon_crn[idx_crn_ul]=crn_lon[3]; } /* !lon */ } /* !lat */ if(lat_ctr_fk) lat_ctr_fk=(double *)nco_free(lat_ctr_fk); if(lon_ctr_fk) lon_ctr_fk=(double *)nco_free(lon_ctr_fk); if(crn_lon) crn_lon=(double *)nco_free(crn_lon); if(crn_lat) crn_lat=(double *)nco_free(crn_lat); } /* !(lat_bnd_id && lon_bnd_id) */ } /* !flg_grd_crv */ if(flg_1D_psd_rct_bnd){ double lon_brnch_min; double lon_brnch_max; double lon_dff; assert(grd_crn_nbr == 4); /* Make boundaries that were provided as pseudo-rectangular branch-cut-compliant */ for(col_idx=0;col_idx<col_nbr;col_idx++){ lon_brnch_min=(lon_bnd[2*col_idx] <= lon_bnd[2*col_idx+1]) ? lon_bnd[2*col_idx] : lon_bnd[2*col_idx+1]; lon_brnch_max=(lon_bnd[2*col_idx] >= lon_bnd[2*col_idx+1]) ? lon_bnd[2*col_idx] : lon_bnd[2*col_idx+1]; lon_dff=lon_brnch_max-lon_brnch_min; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports 1D pseudo-rectangular bounds branch-cut straddle at col_idx=%ld lon_brnch_max, lon_brnch_min, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,col_idx,lon_brnch_max,lon_brnch_min,lon_dff); lon_brnch_max-=360.0; }else if(lon_dff <= -180.0){ lon_brnch_max+=360.0; } /* !lon_dff */ /* Extra condition to convert CW bounds to CCW bounds (necessary for OCO2) */ if(lon_brnch_min <= lon_brnch_max){ lon_bnd[2*col_idx]=lon_brnch_min; lon_bnd[2*col_idx+1]=lon_brnch_max; }else{ lon_bnd[2*col_idx]=lon_brnch_max; lon_bnd[2*col_idx+1]=lon_brnch_min; } /* end else */ } /* !col_idx */ /* Convert boundaries that were provided as pseudo-rectangular to corners */ for(col_idx=0;col_idx<col_nbr;col_idx++){ idx=grd_crn_nbr*col_idx; /* fxm: OCO2 provides boundaries in CW not CCW orientation */ lon_crn[idx]=lon_bnd[2*col_idx]; /* LL */ lon_crn[idx+1]=lon_bnd[2*col_idx+1]; /* LR */ lon_crn[idx+2]=lon_bnd[2*col_idx+1]; /* UR */ lon_crn[idx+3]=lon_bnd[2*col_idx]; /* UL */ lat_crn[idx]=lat_bnd[2*col_idx]; /* LL */ lat_crn[idx+1]=lat_bnd[2*col_idx]; /* LR */ lat_crn[idx+2]=lat_bnd[2*col_idx+1]; /* UR */ lat_crn[idx+3]=lat_bnd[2*col_idx+1]; /* UL */ /* fxm: OCO2 provides boundaries in CW not CCW orientation */ } /* !col_idx */ } /* flg_1D_psd_rct_bnd */ if(flg_grd_crv || flg_1D_psd_rct_bnd){ /* As of 20160308, use same sanity check for 1D pseudo-rectangular grids as for curvilinear grids Pseudo-rectangular grids rely on user-produced boundaries that may be psychotic (CW, non-branch-cut) Starting 20151205, use same sanity check for both inferred and copied curvilinear grids 20151129: Curvilinear extrapolation technique above yields corners outside [-90.0,90.0], [-180.0,360.0] Also, it may assume input is ascending swath and fail for descending swaths Complications not fully addressed: Swaths may (verify this) turn from ascending to descending, or visa-versa, when satellite crosses latitude extrema Swaths may cross the date-line (and back!) */ /* Determine numeric bounds of input coordinate system */ double lon_min_min; double lon_max_max; nco_bool NCO_LON_0_TO_360=True; if(has_mss_val_ctr){ for(idx=0;idx<grd_sz_nbr;idx++) if(lon_ctr[idx] != mss_val_ctr_dbl && lon_ctr[idx] < 0.0) break; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(lon_ctr[idx] < 0.0) break; } /* !has_mss_val_ctr */ if(idx != grd_sz_nbr) NCO_LON_0_TO_360=False; if(NCO_LON_0_TO_360){ lon_min_min=0.0; lon_max_max=360.0; }else{ lon_min_min=-180.0; lon_max_max=180.0; } /* !NCO_LON_0_TO_360 */ /* Correct for extrapolation outside boundaries */ for(idx=0;idx<grd_sz_nbr*grd_crn_nbr;idx++){ idx_ctr=idx/grd_crn_nbr; if(has_mss_val_ctr) if(lat_ctr[idx_ctr] == mss_val_ctr_dbl) continue; if(lat_crn[idx] < -90.0 || lat_crn[idx] > 90.0 || lon_crn[idx] < lon_min_min || lon_crn[idx] > lon_max_max){ idx_crn_ll=grd_crn_nbr*idx_ctr+0; idx_crn_lr=grd_crn_nbr*idx_ctr+1; idx_crn_ur=grd_crn_nbr*idx_ctr+2; idx_crn_ul=grd_crn_nbr*idx_ctr+3; if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stderr,"%s: INFO %s reports %s corner outside canonical bounds at idx = %li, Center [lat,lon]=[%g,%g]; Corners LL [%g,%g] LR [%g,%g] UR [%g,%g] UL [%g,%g]\n",nco_prg_nm_get(),fnc_nm,(lat_bnd_id == NC_MIN_INT) ? "inferred" : "copied",idx_ctr,lat_ctr[idx_ctr],lon_ctr[idx_ctr],lat_crn[idx_crn_ll],lon_crn[idx_crn_ll],lat_crn[idx_crn_lr],lon_crn[idx_crn_lr],lat_crn[idx_crn_ur],lon_crn[idx_crn_ur],lat_crn[idx_crn_ul],lon_crn[idx_crn_ul]); /* Restrict grid to real latitudes and to the 360-degree range detected from input cell-centers */ if(lat_crn[idx] < -90.0) lat_crn[idx]=-90.0; if(lat_crn[idx] > 90.0) lat_crn[idx]=90.0; if(lon_crn[idx] < lon_min_min) lon_crn[idx]+=360.0; if(lon_crn[idx] > lon_max_max) lon_crn[idx]-=360.0; } /* !sanity */ } /* !idx */ /* Vertices (for valid points) are now within 360 degrees (either [0,360] or [-180,180]) implied by input coordinate system Curvilinear inferred grid are, by construction, branch-cut compliant fxm: Curvilinear and 1D pseudo-rectangular grids prescribed by (i.e., read-in from) input may not be branch-cut compliant */ if(nco_dbg_lvl_get() >= nco_dbg_std){ long idx_dbg; idx_dbg=rgr->idx_dbg; idx_crn_ll=grd_crn_nbr*idx_dbg+0; idx_crn_lr=grd_crn_nbr*idx_dbg+1; idx_crn_ur=grd_crn_nbr*idx_dbg+2; idx_crn_ul=grd_crn_nbr*idx_dbg+3; (void)fprintf(stderr,"%s: INFO %s idx_dbg = %li, Center [lat,lon]=[%g,%g]; Corners LL [%g,%g] LR [%g,%g] UR [%g,%g] UL [%g,%g]\n",nco_prg_nm_get(),fnc_nm,idx_dbg,lat_ctr[idx_dbg],lon_ctr[idx_dbg],lat_crn[idx_crn_ll],lon_crn[idx_crn_ll],lat_crn[idx_crn_lr],lon_crn[idx_crn_lr],lat_crn[idx_crn_ur],lon_crn[idx_crn_ur],lat_crn[idx_crn_ul],lon_crn[idx_crn_ul]); } /* !dbg */ } /* !flg_grd_crv || flg_1D_psd_rct_bnd */ if(flg_grd_crv){ /* Copy centers into empty output array */ for(idx=0;idx<grd_sz_nbr;idx++){ grd_ctr_lat[idx]=lat_ctr[idx]; grd_ctr_lon[idx]=lon_ctr[idx]; } /* !idx */ /* Copy inferred or copied (from input) sanity-checked corners into empty output array */ for(idx=0;idx<grd_sz_nbr*grd_crn_nbr;idx++){ grd_crn_lat[idx]=lat_crn[idx]; grd_crn_lon[idx]=lon_crn[idx]; } /* !idx */ } /* !flg_grd_crv */ /* 20150512 Many 2D datasets have bad bounds Primary example is Gaussian grids archived by CESM models that use midpoint rule rather than iterate to compute interfaces from quadrature points Such files have correct gw arrays and incorrect cell bounds flg_dgn_bnd allows nco_grd_nfr() to override faulty boundaries in file with correct bounds */ const nco_bool flg_dgn_bnd=rgr->flg_dgn_bnd; /* [flg] Diagnose rather than copy inferred bounds */ const long lat_nbr_hlf=lat_nbr/2L; // [nbr] Half number of latitudes (e.g., lat_nbr_hlf=32 for lat_nbr=64 and 65) if(flg_grd_2D){ if(flg_dgn_bnd || (lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT)){ if(nco_dbg_lvl_get() >= nco_dbg_std && flg_dgn_bnd) (void)fprintf(stdout,"%s: INFO %s will diagnose cell boundaries from cell centers...\n",nco_prg_nm_get(),fnc_nm); /* Derive interfaces (ntf) and bounds (bnd) from midpoints approximation applied to center data NB: Simplistically derived interfaces (ntf) only valid on some rectangular grids (not on Gaussian grids) These inferred-from-midpoint interfaces/bounds are overwritten in next block once lat grid is known */ if(flg_s2n) lat_ntf[0L]=lat_ctr[0L]-0.5*(lat_ctr[1L]-lat_ctr[0L]); else lat_ntf[0L]=lat_ctr[0L]+0.5*(lat_ctr[0L]-lat_ctr[1L]); if(lat_ntf[0L] < -90.0) lat_ntf[0L]=-90.0; /* NB: lat_ntf[0] can be same as lat_ctr[0] for cap grid */ if(lat_ntf[0L] > 90.0) lat_ntf[0L]=90.0; for(lat_idx=0L;lat_idx<lat_nbr-1L;lat_idx++) lat_ntf[lat_idx+1L]=0.5*(lat_ctr[lat_idx]+lat_ctr[lat_idx+1L]); if(flg_s2n) lat_ntf[lat_nbr]=lat_ctr[lat_nbr-1L]+0.5*(lat_ctr[lat_nbr-1L]-lat_ctr[lat_nbr-2L]); else lat_ntf[lat_nbr]=lat_ctr[lat_nbr-1L]-0.5*(lat_ctr[lat_nbr-2L]-lat_ctr[lat_nbr-1L]); if(lat_ntf[lat_nbr] > 90.0) lat_ntf[lat_nbr]=90.0; /* NB: lat_ntf[lat_nbr] can be same as lat_ctr[lat_nbr-1] for cap grid */ if(lat_ntf[lat_nbr] < -90.0) lat_ntf[lat_nbr]=-90.0; /* NB: lat_ntf[lat_nbr] can be same as lat_ctr[lat_nbr-1] for cap grid */ if(flg_s2n) lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); /* fabs() ensures positive-definite span for N->S grids */ lon_ntf[0L]=lon_ctr[0L]-0.5*(lon_ctr[1L]-lon_ctr[0L]); for(lon_idx=0;lon_idx<lon_nbr-1L;lon_idx++) lon_ntf[lon_idx+1L]=0.5*(lon_ctr[lon_idx]+lon_ctr[lon_idx+1L]); lon_ntf[lon_nbr]=lon_ctr[lon_nbr-1L]+0.5*(lon_ctr[lon_nbr-1L]-lon_ctr[lon_nbr-2L]); lon_spn=lon_ntf[lon_nbr]-lon_ntf[0L]; for(idx=0;idx<lon_nbr;idx++){ lon_bnd[2L*idx]=lon_ntf[idx]; lon_bnd[2L*idx+1L]=lon_ntf[idx+1L]; } /* !idx */ for(idx=0;idx<lat_nbr;idx++){ lat_bnd[2L*idx]=lat_ntf[idx]; lat_bnd[2L*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ }else{ /* !(lat_bnd_id && lon_bnd_id) */ /* Derive interfaces (ntf) from bounds (bnd) data on disk */ for(idx=0;idx<lon_nbr;idx++) lon_ntf[idx]=lon_bnd[2L*idx]; lon_ntf[lon_nbr]=lon_bnd[2L*lon_nbr-1L]; for(idx=0;idx<lat_nbr;idx++) lat_ntf[idx]=lat_bnd[2L*idx]; lat_ntf[lat_nbr]=lat_bnd[2L*lat_nbr-1L]; lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); /* fabs() ensures positive-definite span for N->S grids */ lon_spn=lon_ntf[lon_nbr]-lon_ntf[0L]; } /* !(lat_bnd_id && lon_bnd_id) */ } /* !flg_grd_2D */ if(flg_grd_2D){ /* Diagnose type of two-dimensional input grid by testing second latitude center against formulae */ double lat_ctr_tst_eqa; double lat_ctr_tst_fv; if(flg_s2n) lat_ctr_tst_eqa=lat_ntf[0L]+lat_spn*1.5/lat_nbr; else lat_ctr_tst_eqa=lat_ntf[0L]-lat_spn*1.5/lat_nbr; if(flg_s2n) lat_ctr_tst_fv=lat_ntf[0L]+lat_spn/(lat_nbr-1L); else lat_ctr_tst_fv=lat_ntf[0L]-lat_spn/(lat_nbr-1L); double lat_ctr_tst_gss; /* In diagnosing grids, agreement with input to single-precision is "good enough for government work" Hence some comparisons cast from double to float before comparison 20150526: T42 grid from SCRIP and related maps are only accurate to ~eight digits 20150611: map_ne120np4_to_fv801x1600_bilin.150418.nc has yc_b[1600]=-89.775000006 not expected exact value lat_ctr[1]=-89.775000000000006 20170521: T62 grid from NCEP-NCAR Reanalysis 1 worse than single precision, has yc_[192]=-86.6531 not expected exact value lat_ctr[1]=-86.6531671712612, relative difference is 7.86021e-07 20191008: T62 grid from NCEP-NCAR Reanalysis 2 worse than single precision, has yc_[92]=-86.6531 not expected exact value lat_ctr[1]=-86.6531671712612, relative difference is 7.86021e-07 */ if(nco_dbg_lvl_get() >= nco_dbg_scl && !flg_s2n) (void)fprintf(stderr,"%s: INFO %s reports that grid inferral has detected a 2D grid that runs from north-to-south, not south-to-north. Support for creating/inferring 2D N-to-S grids was added in NCO 4.7.7 (September, 2018) and should work fine.\nHINT: If present command fails, report problem to developers and then re-try inferring grid after reversing input dataset's latitude coordinate (with, e.g., ncpdq -a time,-lat,lon in.nc out.nc)\n",nco_prg_nm_get(),fnc_nm); if((float)lat_ctr[1L] == (float)lat_ctr_tst_eqa) lat_typ=nco_grd_lat_eqa; if((float)lat_ctr[1L] == (float)lat_ctr_tst_fv) lat_typ=nco_grd_lat_fv; double *lat_sin=NULL_CEWI; // [frc] Sine of Gaussian latitudes double precision double *wgt_Gss=NULL; // [frc] Gaussian weights double precision if(lat_typ == nco_grd_lat_nil){ /* Check for Gaussian grid */ lat_sin=(double *)nco_malloc(lat_nbr*sizeof(double)); wgt_Gss=(double *)nco_malloc(lat_nbr*sizeof(double)); (void)nco_lat_wgt_gss(lat_nbr,flg_s2n,lat_sin,wgt_Gss); lat_ctr_tst_gss=rdn2dgr*asin(lat_sin[1L]); /* Gaussian weights on output grid will be double-precision accurate Grid itself is kept as user-specified so area diagnosed by ESMF_RegridWeightGen may be slightly inconsistent with weights */ const double eps_rlt_cnv_gss=1.0e-6; // Convergence criterion (1.0e-7 fails for NCEP NCAR Reanalysis 1!) if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: DEBUG %s reports lat_ctr[1]=%g, lat_ctr_tst_gss=%g, fabs(1.0-fabs(lat_ctr[1]/lat_ctr_tst_gss))=%g\n",nco_prg_nm_get(),fnc_nm,lat_ctr[1],lat_ctr_tst_gss,fabs(1.0-fabs(lat_ctr[1]/lat_ctr_tst_gss))); if(fabs(1.0-fabs(lat_ctr[1]/lat_ctr_tst_gss)) < eps_rlt_cnv_gss) lat_typ=nco_grd_lat_gss; } /* !Gaussian */ if(lat_typ == nco_grd_lat_nil){ /* If still of unknown type, this 2D grid may be weird This occurs, e.g., with POP3 destination grid Change gridtype from nil (which means not-yet-set) to unknown (which means none of the others matched) */ lat_typ=nco_grd_lat_unk; } /* !nil */ /* Currently grd_lat_typ and grd_2D_typ are equivalent, though that may be relaxed in future */ if(lat_typ == nco_grd_lat_unk) grd_typ=nco_grd_2D_unk; else if(lat_typ == nco_grd_lat_gss) grd_typ=nco_grd_2D_gss; else if(lat_typ == nco_grd_lat_fv) grd_typ=nco_grd_2D_fv; else if(lat_typ == nco_grd_lat_eqa) grd_typ=nco_grd_2D_eqa; else assert(False); /* Diagnose latitude interfaces from gridcell centers (if boundaries not provided) */ if(flg_dgn_bnd || (lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT)){ //if(flg_s2n) lat_nrt=lat_ntf[lat_nbr]; else lat_nrt=lat_ntf[0L]; lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); switch(lat_typ){ case nco_grd_lat_fv: lat_ncr=lat_spn/(lat_nbr-1L); if(flg_s2n) lat_ntf[1L]=lat_ntf[0L]+0.5*lat_ncr; else lat_ntf[1L]=lat_ntf[0L]-0.5*lat_ncr; for(lat_idx=2;lat_idx<lat_nbr;lat_idx++) if(flg_s2n) lat_ntf[lat_idx]=lat_ntf[1L]+(lat_idx-1L)*lat_ncr; else lat_ntf[lat_idx]=lat_ntf[1L]-(lat_idx-1L)*lat_ncr; break; case nco_grd_lat_eqa: lat_ncr=lat_spn/lat_nbr; for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) if(flg_s2n) lat_ntf[lat_idx]=lat_ntf[0L]+lat_idx*lat_ncr; else lat_ntf[lat_idx]=lat_ntf[0L]-lat_idx*lat_ncr; break; case nco_grd_lat_gss: for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=rdn2dgr*asin(lat_sin[lat_idx]); /* First guess for lat_ntf is midway between Gaussian abscissae */ for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=0.5*(lat_ctr[lat_idx-1L]+lat_ctr[lat_idx]); /* Iterate guess until area between interfaces matches Gaussian weight */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++){ double fofx_at_x0; /* [frc] Function to iterate evaluated at current guess */ double dfdx_at_x0; /* [frc] Derivative of equation evaluated at current guess */ // 20190531: Wuyin Lin reports this convergence criterion fails on ECMWF F640 grid // Probably because latitude iterations assume s2n grid and ECMWF is n2s // Possibly also because latitude coordinates are stored in single precision // Implement precision-dependent convergence criterion, e.g., 1.0e-15 and 1.0e-7 for double- and single-precision, respectively? const double eps_rlt_cnv=1.0e-15; // Convergence criterion (1.0e-16 pushes double precision to the brink) itr_cnt=0; lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; while(fabs(fofx_at_x0) > eps_rlt_cnv){ /* Newton-Raphson iteration: Let x=lat_ntf[lat_idx], y0=lat_ntf[lat_idx-1], gw = Gaussian weight (exact solution) f(x)=sin(dgr2rdn*x)-sin(dgr2rdn*y0)-gw=0 # s2n grid f(x)=sin(dgr2rdn*y0)-sin(dgr2rdn*x)-gw=0 # n2s grid dfdx(x)= dgr2rdn*cos(dgr2rdn*x) # s2n grid dfdx(x)=-dgr2rdn*cos(dgr2rdn*x) # n2s grid x_better=x0-f(x0)/f'(x0) */ dfdx_at_x0=dgr2rdn*cos(dgr2rdn*lat_ntf[lat_idx]); if(!flg_s2n) dfdx_at_x0=-dfdx_at_x0; lat_ntf[lat_idx]+=fofx_at_x0/dfdx_at_x0; /* NB: not sure why this is minus not plus but it works :) */ lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; if(++itr_cnt > itr_nbr_max){ (void)fprintf(stdout,"%s: ERROR %s reports convergence only %g after %d iterations for lat_idx = %ld\n",nco_prg_nm_get(),fnc_nm,fabs(fofx_at_x0),itr_nbr_max,lat_idx); nco_exit(EXIT_FAILURE); } /* endif */ } /* !while */ } /* !lat_idx */ /* Use Gaussian grid symmetry to obtain same interfaces in both hemispheres (avoids cumulative rounding errors) */ if(lat_nbr%2){ /* lat_nbr is odd */ for(lat_idx=1L;lat_idx<=lat_nbr_hlf+1L;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx+1L]; }else{ /* lat_nbr is even */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx]; } /* !flg_lat_evn */ if(lat_sin) lat_sin=(double *)nco_free(lat_sin); break; case nco_grd_lat_unk: /* No generic formula exists so use interfaces already read or diagnosed as midpoints between centers */ break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ if(lat_typ == nco_grd_lat_gss){ /* 20170510: First approximation above to exterior interfaces for Gaussian grid are ~ +/-89 degrees Loops below recompute interior interfaces only Southern- and northern-most interfaces must be explicitly assigned Inferral test for Gaussian grid _assumes_ global grid Hence WLOG can assign [-90.0, 90.0] to Gaussian grid exterior boundaries */ if(flg_s2n) lat_ntf[0L]=-90.0; else lat_ntf[0L]=90.0; if(flg_s2n) lat_ntf[lat_nbr]=90.0; else lat_ntf[lat_nbr]=-90.0; } /* !nco_grd_lat_gss */ /* Now that final latitude interfaces are known for all grid-types, assign to boundaries, overwriting provisional values stored there earlier */ for(idx=0;idx<lat_nbr;idx++){ lat_bnd[2L*idx]=lat_ntf[idx]; lat_bnd[2L*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ } /* !(lat_bnd_id && lon_bnd_id) */ /* Use centers and boundaries to diagnose latitude weights */ switch(lat_typ){ case nco_grd_lat_eqa: case nco_grd_lat_fv: for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=fabs(sin(dgr2rdn*lat_ntf[lat_idx+1L])-sin(dgr2rdn*lat_ntf[lat_idx])); break; case nco_grd_lat_gss: for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=wgt_Gss[lat_idx]; break; case nco_grd_lat_unk: for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=fabs(sin(dgr2rdn*lat_ntf[lat_idx+1L])-sin(dgr2rdn*lat_ntf[lat_idx])); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: WARNING %s reports unknown input latitude grid-type. Guessing that weights for grid of rectangles is OK.\n",nco_prg_nm_get(),fnc_nm); break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ /* Diagnose type of longitude grid by testing second longitude center against formulae */ lon_spn=lon_ntf[lon_nbr]-lon_ntf[0L]; lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); if((float)lon_spn == 360.0f && (float)lat_spn == 180.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; if(lon_typ == nco_grd_lon_nil){ if( (float)lon_ctr[0L] == 0.0f && (float)lon_ctr[1L] == (float)(lon_ctr[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_Grn_ctr; else if((float)lon_ctr[0L] == -180.0f && (float)lon_ctr[1L] == (float)(lon_ctr[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_180_ctr; else if((float)lon_ntf[0L] == 0.0f && (float)lon_ntf[1L] == (float)(lon_ntf[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_Grn_wst; else if((float)lon_ntf[0L] == -180.0f && (float)lon_ntf[1L] == (float)(lon_ntf[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_180_wst; else if((float)lon_ctr[1L] == (float)(lon_ctr[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_bb; else lon_typ=nco_grd_lon_unk; } /* !lon_typ */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input 2D grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_2D_sng(grd_typ)); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input latitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lat_sng(lat_typ)); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input longitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lon_sng(lon_typ)); } /* !flg_grd_2D */ if(flg_grd_2D){ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0;idx<lat_nbr;idx++){ (void)fprintf(stdout,"lat[%li] = %g, vertices = ",idx,lat_ctr[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lat_bnd[bnd_nbr*idx+bnd_idx],bnd_idx == bnd_nbr-1 ? "]\n" : ", "); } /* end loop over lat */ for(idx=0;idx<lon_nbr;idx++){ (void)fprintf(stdout,"lon[%li] = %g, vertices = ",idx,lon_ctr[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lon_bnd[bnd_nbr*idx+bnd_idx],bnd_idx == bnd_nbr-1 ? "]\n" : ", "); } /* end loop over lon */ } /* endif dbg */ /* Fuzzy test of latitude weight normalization */ //const double eps_rlt_max=1.0e-14; /* [frc] Round-off error tolerance: Used 1.0e-14 until 20180904 */ const double eps_rlt_max=1.0e-12; /* [frc] Round-off error tolerance: Used 1.0e-12 since 20180904 */ double lat_wgt_ttl_xpc; /* [frc] Expected sum of latitude weights */ lat_wgt_ttl=0.0; for(idx=0;idx<lat_nbr;idx++) lat_wgt_ttl+=lat_wgt[idx]; lat_wgt_ttl_xpc=fabs(sin(dgr2rdn*lat_bnd[2*(lat_nbr-1)+1L])-sin(dgr2rdn*lat_bnd[0L])); if(grd_typ != nco_grd_2D_unk && 1.0-lat_wgt_ttl/lat_wgt_ttl_xpc > eps_rlt_max){ (void)fprintf(stdout,"%s: ERROR %s reports grid normalization does not meet precision tolerance eps_rlt_max = %20.15f\nlat_wgt_ttl = %20.15f, lat_wgt_ttl_xpc = %20.15f, lat_wgt_frc = %20.15f, eps_rlt = %20.15f\n",nco_prg_nm_get(),fnc_nm,eps_rlt_max,lat_wgt_ttl,lat_wgt_ttl_xpc,lat_wgt_ttl/lat_wgt_ttl_xpc,1.0-lat_wgt_ttl/lat_wgt_ttl_xpc); nco_exit(EXIT_FAILURE); } /* !imprecise */ } /* !flg_grd_2D */ if(flg_grd_2D){ assert(grd_crn_nbr == 4); if(flg_dgn_bnd || (lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT)){ /* If interfaces were diagnosed from centers, copy corners from interfaces */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx=grd_crn_nbr*lon_idx; lon_crn[idx]=lon_ntf[lon_idx]; /* LL */ lon_crn[idx+1L]=lon_ntf[lon_idx+1L]; /* LR */ lon_crn[idx+2L]=lon_ntf[lon_idx+1L]; /* UR */ lon_crn[idx+3L]=lon_ntf[lon_idx]; /* UL */ } /* !lon_idx */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ idx=grd_crn_nbr*lat_idx; lat_crn[idx]=lat_ntf[lat_idx]; /* LL */ lat_crn[idx+1L]=lat_ntf[lat_idx]; /* LR */ lat_crn[idx+2L]=lat_ntf[lat_idx+1L]; /* UR */ lat_crn[idx+3L]=lat_ntf[lat_idx+1L]; /* UL */ } /* !lat_idx */ }else{ /* !lat_bnd_id */ /* If boundaries were provided in input dataset, copy corners from boundaries */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx=grd_crn_nbr*lon_idx; lon_crn[idx]=lon_bnd[2*lon_idx]; /* LL */ lon_crn[idx+1L]=lon_bnd[2*lon_idx+1L]; /* LR */ lon_crn[idx+2L]=lon_bnd[2*lon_idx+1L]; /* UR */ lon_crn[idx+3L]=lon_bnd[2*lon_idx]; /* UL */ } /* !lon_idx */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ idx=grd_crn_nbr*lat_idx; lat_crn[idx]=lat_bnd[2*lat_idx]; /* LL */ lat_crn[idx+1L]=lat_bnd[2*lat_idx]; /* LR */ lat_crn[idx+2L]=lat_bnd[2*lat_idx+1L]; /* UR */ lat_crn[idx+3L]=lat_bnd[2*lat_idx+1L]; /* UL */ } /* !lat_idx */ } /* !lat_bnd_id */ } /* !flg_grd_2D */ /* lat/lon_crn will not change anymore so stuff rectangular arrays into unrolled arrays */ if(flg_grd_1D){ for(idx=0;idx<grd_sz_nbr;idx++){ grd_ctr_lat[idx]=lat_ctr[idx]; grd_ctr_lon[idx]=lon_ctr[idx]; if(flg_wrt_crn){ for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; grd_crn_lat[idx2]=lat_crn[idx2]; grd_crn_lon[idx2]=lon_crn[idx2]; } /* !crn */ }else{ /* !flg_wrt_crn */ /* Defaults for ERWG when corners are unknown */ for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; grd_crn_lat[idx2]=0.0; grd_crn_lon[idx2]=0.0; } /* !crn */ } /* !flg_wrt_crn */ } /* !col */ } /* !flg_grd_1D */ if(flg_grd_2D){ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx=lat_idx*lon_nbr+lon_idx; grd_ctr_lat[idx]=lat_ctr[lat_idx]; grd_ctr_lon[idx]=lon_ctr[lon_idx]; for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; lat_idx2=lat_idx*grd_crn_nbr+crn_idx; lon_idx2=lon_idx*grd_crn_nbr+crn_idx; grd_crn_lat[idx2]=lat_crn[lat_idx2]; grd_crn_lon[idx2]=lon_crn[lon_idx2]; } /* !crn */ } /* !lon */ } /* !lat */ /* 20190613: Convert CW quadrilaterals to CCW quadrilaterals so TempestRemap accepts grids Default construction/inferral method orders corners CCW and CW for s2n and n2s grids, respectively */ if(!flg_s2n){ for(idx=0L;idx<grd_sz_nbr;idx++){ idx2=grd_crn_nbr*idx; flg_ccw=nco_ccw_chk(grd_crn_lat+idx2,grd_crn_lon+idx2,grd_crn_nbr,idx_ccw,rcr_lvl); } /* !idx */ } /* !flg_s2n */ } /* !flg_grd_2D */ /* Find span of all grids */ double lat_max; /* [dgr] Maximum latitude */ double lat_min; /* [dgr] Minimum latitude */ double lon_max; /* [dgr] Maximum longitude */ double lon_min; /* [dgr] Minimum longitude */ idx_ctr=0; if(has_mss_val_ctr){ /* Find first non-missing value center and thus corners */ for(idx_ctr=0;idx_ctr<grd_sz_nbr;idx_ctr++){ if(grd_ctr_lat[idx_ctr] != mss_val_ctr_dbl) break; } /* !grd_sz_nbr */ assert(idx_ctr != grd_sz_nbr); } /* !has_mss_val_ctr */ if(flg_wrt_crn){ /* Grids with corner boundaries supplied or inferred */ lon_max=grd_crn_lon[idx_ctr*grd_crn_nbr]; lat_max=grd_crn_lat[idx_ctr*grd_crn_nbr]; lon_min=grd_crn_lon[idx_ctr*grd_crn_nbr]; lat_min=grd_crn_lat[idx_ctr*grd_crn_nbr]; for(idx=1;idx<grd_sz_nbr*grd_crn_nbr;idx++){ idx_ctr=idx/grd_crn_nbr; if(has_mss_val_ctr) if(grd_ctr_lat[idx_ctr] == mss_val_ctr_dbl) continue; lat_max=(grd_crn_lat[idx] > lat_max) ? grd_crn_lat[idx] : lat_max; lon_max=(grd_crn_lon[idx] > lon_max) ? grd_crn_lon[idx] : lon_max; lat_min=(grd_crn_lat[idx] < lat_min) ? grd_crn_lat[idx] : lat_min; lon_min=(grd_crn_lon[idx] < lon_min) ? grd_crn_lon[idx] : lon_min; } /* !idx */ }else{ /* !flg_wrt_crn */ /* 20170424: Diagnose grid-extent when corners were not provided or inferred This is usually (always?) for 1d unstructured grids with only centers provided */ lon_max=grd_ctr_lon[idx_ctr]; lat_max=grd_ctr_lat[idx_ctr]; lon_min=grd_ctr_lon[idx_ctr]; lat_min=grd_ctr_lat[idx_ctr]; for(idx_ctr=1;idx_ctr<grd_sz_nbr;idx_ctr++){ if(has_mss_val_ctr) if(grd_ctr_lat[idx_ctr] == mss_val_ctr_dbl) continue; lat_max=(grd_ctr_lat[idx_ctr] > lat_max) ? grd_ctr_lat[idx_ctr] : lat_max; lon_max=(grd_ctr_lon[idx_ctr] > lon_max) ? grd_ctr_lon[idx_ctr] : lon_max; lat_min=(grd_ctr_lat[idx_ctr] < lat_min) ? grd_ctr_lat[idx_ctr] : lat_min; lon_min=(grd_ctr_lon[idx_ctr] < lon_min) ? grd_ctr_lon[idx_ctr] : lon_min; } /* !idx_ctr */ } /* flg_wrt_crn */ lat_spn=lat_max-lat_min; lon_spn=lon_max-lon_min; /* Use strict rules for rectangular grids, looser for spans that are inferred, or center-to-center not corner-to-corner */ if(flg_grd_2D){ if((float)lon_spn == 360.0f && (float)lat_spn == 180.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; }else{ /* !flg_grd_2D */ if((float)lon_spn >= 340.0f && (float)lat_spn >= 170.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; } /* flg_wrt_crn */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s reports grid resolution %li x %li, spans %g x %g degrees: [%g <= lat <= %g], [%g <= lon <= %g]\n",nco_prg_nm_get(),fnc_nm,lat_nbr,lon_nbr,lat_spn,lon_spn,lat_min,lat_max,lon_min,lon_max); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input grid-extent: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_xtn_sng(nco_grd_xtn)); /* Write ERWG hints if filenames provided and grid is regional */ char *fl_hnt=NULL; char *fl_hnt_dst=NULL; char *fl_hnt_src=NULL; if(rgr->fl_hnt_dst) fl_hnt=fl_hnt_dst=rgr->fl_hnt_dst; if(rgr->fl_hnt_src) fl_hnt=fl_hnt_src=rgr->fl_hnt_src; if(nco_grd_xtn == nco_grd_xtn_rgn && fl_hnt){ const char *fl_mode="w"; FILE *fp_hnt; /* [fl] Hint file (for ERWG switches) file handle */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s writing ERWG weight-generation regional hint to file %s\n",nco_prg_nm_get(),fnc_nm,fl_hnt); /* Open output file */ if((fp_hnt=fopen(fl_hnt,fl_mode)) == NULL){ (void)fprintf(stderr,"%s: ERROR unable to open hint output file %s\n",nco_prg_nm_get(),fl_hnt); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: Opened hint file %s\n",nco_prg_nm_get(),fl_hnt); if(fl_hnt_src) (void)fprintf(fp_hnt,"--src_regional"); if(fl_hnt_dst) (void)fprintf(fp_hnt,"--dst_regional"); rcd=fclose(fp_hnt); if(rcd != 0){ (void)fprintf(stderr,"%s: ERROR unable to close hint output file %s\n",nco_prg_nm_get(),fl_hnt); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: Closed hint file %s\n",nco_prg_nm_get(),fl_hnt); } /* !nco_grd_xtn */ /* Diagnose area if necessary 20170510: ALM/CLM "area" is _FillValue=1.0e36f over ocean and total gridcell area in km2 (not multiplied by landfrac) elsewhere Writing this ALM/CLM "area" variable to gridfile, then using with ERWG --user_areas could be disastrous (depending on mask array and interpolation type) On the other hand CAM "area" variable is exactly what we want for gridfile Input areas are considered "untrustworthy" iff they have _and use_ missing value attribute Re-diagnose areas considered untrustworthy so output area array does not contain missing values */ if(flg_wrt_crn && has_mss_val_area){ const double mss_val_dbl=mss_val_area_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(area[idx] == mss_val_dbl) break; if(idx < grd_sz_nbr) use_mss_val_area=True; if(nco_dbg_lvl_get() >= nco_dbg_fl && use_mss_val_area) (void)fprintf(stdout,"%s: INFO %s reports input area field %s is considered untrustworthy because it uses missing values, will diagnose area from cell boundaries instead...\n",nco_prg_nm_get(),fnc_nm,area_nm_in); } /* !has_mss_val_area */ /* 20170511: There remain a handful of cases when input area should be diagnosed not copied These include using ncremap in SGS mode when inferred grids must use sensible area units Otherwise an inferred grid with area [km2] from ALM/CLM might be combined with area [sr] from NCO This would bias ERWG --user_areas produced values by ~10^10 Setting flg_dgn_area ensures inferred area uses [sr] */ const nco_bool flg_dgn_area=rgr->flg_dgn_area; /* [flg] Diagnose rather than copy inferred area */ if(flg_wrt_crn && /* If bounds are available to compute area and ... */ (area_id == NC_MIN_INT || /* Area is not in input file ... */ use_mss_val_area || /* Area is untrustworthy */ flg_dgn_area)){ /* User/application explicitly requests diagnostic area */ /* Not absolutely necessary to diagnose area because ERWG will diagnose and output area itself _unless_ --user_areas option is given */ if(nco_dbg_lvl_get() >= nco_dbg_std && flg_dgn_area) (void)fprintf(stdout,"%s: INFO %s reports diagnosing area from cell boundaries...\n",nco_prg_nm_get(),fnc_nm); if(flg_grd_crv || flg_grd_1D){ /* Area of arbitrary unstructured or curvilinear grids requires spherical trigonometry */ nco_sph_plg_area(rgr,grd_crn_lat,grd_crn_lon,grd_sz_nbr,grd_crn_nbr,area); }else if(flg_grd_2D){ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr;lon_idx++) area[lat_idx*lon_nbr+lon_idx]=fabs(dgr2rdn*(lon_bnd[2*lon_idx+1L]-lon_bnd[2*lon_idx])*(sin(dgr2rdn*lat_bnd[2*lat_idx+1L])-sin(dgr2rdn*lat_bnd[2*lat_idx]))); /* fabs() ensures positive area in n2s grids */ } /* !flg_grd_2D */ } /* !area_id */ /* ERWG will fail unless grid file has mask variable Use nul-mask (all points included) whenever input mask variable not supplied/detected Define nul-mask true everywhere and overwrite with false below Input mask can be any type and output mask will always be NC_INT */ for(idx=0;idx<grd_sz_nbr;idx++) msk[idx]=1; if(msk_id != NC_MIN_INT){ /* Change missing-value-masked points to 0 integer mask for SCRIP grids (SCRIP has no missing value convention) Input mask can be any type and output mask will always be NC_INT Applications: ALM/CLM mask (landmask) is NC_FLOAT and defines but does not use NC_FLOAT missing value CICE mask (tmask/umask) is NC_FLOAT and defines and uses NC_FLOAT missing value AMSR mask is NC_SHORT and has no missing value GHRSST mask is NC_BYTE and is a multi-valued surface-type flag with missing value == -1b */ if(msk_typ != NC_INT){ if(nco_dbg_lvl_get() == nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s mask variable \"%s\" has odd type = %s. Re-run with higher debugging level for more information.\n",nco_prg_nm_get(),fnc_nm,msk_nm,nco_typ_sng(msk_typ)); if(nco_dbg_lvl_get() > nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s mask variable \"%s\" has odd type = %s. Regridding weight generators require a mask variable of type NC_INT to specify points to include/exclude as sources/destinations. Points where the mask variable is zero will be excluded (ignored) in regridding, all other points will be included. When inferring gridfiles, NCO assumes the first variable with a \"mask\"-like name (\"mask\", \"Mask\", \"grid_imask\", \"landmask\", or \"tmask\"), or the variable designated by the \"--msk_[src/dst]=msk_nm\" option, is this mask. However the variable \"%s\" in this file is not type NC_INT and so may not be intended as a regridding mask, hence this pleasant informational warning. To prevent NCO from interpreting \"%s\" as a regridding mask, specify \"--msk_src=none\" and/or \"--msk_dst=none\", as appropriate. To utilize some other variable as the mask variable, specify \"--msk_src=msk_nm\" and/or \"--msk_dst=msk_nm\", as appropriate. Mask treatment is subtle, and NCO tries to \"do the right thing\". Whether it does is often easiest to discern by visual inspection of the regridded results.\n",nco_prg_nm_get(),fnc_nm,msk_nm,nco_typ_sng(msk_typ),msk_nm,msk_nm); } /* msk_typ */ switch(msk_typ){ case NC_FLOAT: if(has_mss_val_msk){ const float mss_val_flt=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.fp[idx] == mss_val_flt || msk_unn.fp[idx] == 0.0f) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.fp[idx] == 0.0f) msk[idx]=0; } /* !mss_val */ break; case NC_DOUBLE: if(has_mss_val_msk){ const double mss_val_dbl=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.dp[idx] == mss_val_dbl || msk_unn.dp[idx] == 0.0) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.dp[idx] == 0.0) msk[idx]=0; } /* !mss_val */ break; case NC_INT: if(has_mss_val_msk){ const int mss_val_int=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.ip[idx] == mss_val_int || msk_unn.ip[idx] == 0) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.ip[idx] == 0) msk[idx]=0; } /* !mss_val */ break; case NC_SHORT: /* http://stackoverflow.com/questions/208433/how-do-i-write-a-short-literal-in-c */ if(has_mss_val_msk){ const short mss_val_sht=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.sp[idx] == mss_val_sht || msk_unn.sp[idx] == ((short)0)) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.sp[idx] == ((short)0)) msk[idx]=0; /* 20160111: AMSR kludge fxm */ // for(idx=0;idx<grd_sz_nbr;idx++) if(msk[idx] == 1) msk[idx]=0; } /* !mss_val */ break; case NC_BYTE: if(has_mss_val_msk){ const nco_byte mss_val_byt=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.bp[idx] == mss_val_byt || msk_unn.bp[idx] == ((nco_byte)0)) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.bp[idx] == ((nco_byte)0)) msk[idx]=0; /* 20170811: GHRSST kludge? */ } /* !mss_val */ break; default: (void)fprintf(stderr,"%s: ERROR %s mask variable \"%s\" has unsupported type = %s\n",nco_prg_nm_get(),fnc_nm,msk_nm,nco_typ_sng(msk_typ)); nco_dfl_case_generic_err(); return NCO_ERR; break; } /* !msk_typ */ if(msk_unn.vp) msk_unn.vp=(void *)nco_free(msk_unn.vp); } /* !msk_id */ if(nco_dbg_lvl_get() >= nco_dbg_sbr){ lat_wgt_ttl=0.0; area_ttl=0.0; if(flg_grd_2D){ (void)fprintf(stderr,"%s: INFO %s reports destination rectangular latitude grid:\n",nco_prg_nm_get(),fnc_nm); for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt_ttl+=lat_wgt[lat_idx]; } /* !flg_grd_2D */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr;lon_idx++) area_ttl+=area[lat_idx*lon_nbr+lon_idx]; (void)fprintf(stdout,"lat_wgt_ttl = %20.15f, frc_lat_wgt = %20.15f, area_ttl = %20.15f, frc_area = %20.15f\n",lat_wgt_ttl,lat_wgt_ttl/2.0,area_ttl,area_ttl/(4.0*M_PI)); assert(area_ttl > 0.0); assert(area_ttl <= 4.0*M_PI); } /* endif dbg */ /* Open grid file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Define dimensions */ /* 20151230 ERWG appears to require presence of corner arrays in grid file even when they are not used (e.g., bilinear) But ERWG will break when corner values are bad. Default is do not write bad corner values. Uncomment next line to write bad corner values. */ /* flg_wrt_crn=True; */ if(flg_wrt_crn) rcd=nco_def_dim(out_id,grd_crn_nm,grd_crn_nbr,&dmn_id_grd_crn); rcd=nco_def_dim(out_id,grd_sz_nm,grd_sz_nbr,&dmn_id_grd_sz); rcd=nco_def_dim(out_id,grd_rnk_nm,grd_rnk_nbr,&dmn_id_grd_rnk); int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; /* Define variables */ (void)nco_def_var(out_id,dmn_sz_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_rnk,&dmn_sz_int_id); /* NB: Too small to deflate */ (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,msk_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_sz,&msk_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lat_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lon_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lon_id,shuffle,deflate,dfl_lvl); if(flg_wrt_crn){ dmn_ids[0]=dmn_id_grd_sz; dmn_ids[1]=dmn_id_grd_crn; (void)nco_def_var(out_id,grd_crn_lat_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_crn_lon_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lon_id,shuffle,deflate,dfl_lvl); } /* !flg_wrt_crn */ /* Define attributes */ aed_sct aed_mtd; char *att_nm; if(strstr(rgr->grd_ttl,"None given")){ const char att_fmt[]="NCO inferred this grid from input file %s"; att_val=(char *)nco_malloc((strlen(att_fmt)+strlen(rgr->fl_in)+1L)*sizeof(char)); sprintf(att_val,att_fmt,rgr->fl_in); }else{ att_val=strdup(rgr->grd_ttl); } /* !grd_ttl */ rcd=nco_char_att_put(out_id,NULL,"title",att_val); rcd=nco_char_att_put(out_id,NULL,"Conventions","SCRIP"); const char usr_cpp[]=TKN2SNG(USER); /* [sng] Hostname from C pre-processor */ rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); rcd=nco_char_att_put(out_id,NULL,"grid_generator","NCO"); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,NULL,"latitude_grid_type",nco_grd_lat_sng(lat_typ)); rcd=nco_char_att_put(out_id,NULL,"longitude_grid_type",nco_grd_lon_sng(lon_typ)); rcd=nco_char_att_put(out_id,dmn_sz_nm,"long_name","Size(s) of horizontal dimensions (in Fortran storage order for historical reasons)"); if(flg_area_sr){ rcd=nco_char_att_put(out_id,area_nm,"long_name","Solid Angle Subtended on Source Grid"); rcd=nco_char_att_put(out_id,area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm,"units","steradian"); }else{ /* !flg_area_sr */ rcd=nco_char_att_put(out_id,area_nm,"long_name","Area on Source Grid"); // rcd=nco_char_att_put(out_id,area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm,"units",area_unt); } /* !flg_area_sr */ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"standard_name","latitude"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees"); } /* !ngl_unt */ rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"standard_name","longitude"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees_east"); else rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees"); } /* !ngl_unt */ if(flg_wrt_crn){ rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"long_name","Latitude of Grid Cell Vertices"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_crn_lat_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees"); } /* !ngl_unt */ rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"long_name","Longitude of Grid Cell Vertices"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_crn_lon_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees"); } /* !ngl_unt */ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"bounds",grd_crn_lat_nm); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"bounds",grd_crn_lon_nm); } /* !flg_wrt_crn */ rcd=nco_char_att_put(out_id,msk_nm,"long_name","Binary Integer Mask for Grid"); rcd=nco_char_att_put(out_id,msk_nm,"units","none"); /* Begin data mode */ (void)nco_enddef(out_id); /* Write variables */ dmn_srt[0]=0L; dmn_cnt[0]=grd_rnk_nbr; rcd=nco_put_vara(out_id,dmn_sz_int_id,dmn_srt,dmn_cnt,dmn_sz_int,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,msk_id,dmn_srt,dmn_cnt,msk,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lat_id,dmn_srt,dmn_cnt,grd_ctr_lat,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lon_id,dmn_srt,dmn_cnt,grd_ctr_lon,crd_typ); if(flg_wrt_crn){ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lat_id,dmn_srt,dmn_cnt,grd_crn_lat,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lon_id,dmn_srt,dmn_cnt,grd_crn_lon,crd_typ); } /* !flg_wrt_crn */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); fl_out=rgr->fl_ugrid; if(fl_out){ /* Test UGRID: Documentation: https://github.com/ugrid-conventions/ugrid-conventions Procedure: Create 1x1 skeleton file, infer UGRID and SCRIP grids from it ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr skl=${HOME}/skl_180x360.nc --rgr scrip=${HOME}/grd_180x360_SCRIP.nc --rgr latlon=180,360#lat_typ=eqa#lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr infer --rgr ugrid=${HOME}/grd_ugrid.nc --rgr scrip=${HOME}/grd_scrip.nc ~/skl_180x360.nc ~/foo.nc ncks --cdl -v mesh_node_y ~/grd_ugrid.nc ncks --cdl -v mesh_face_nodes,mesh_face_x,mesh_face_y -d nFaces,0 ~/grd_ugrid.nc ncks --cdl -v mesh_edge_nodes,mesh_edge_x,mesh_edge_y -d nEdges,0 ~/grd_ugrid.nc ncks --cdl -v grid_center_lat,grid_corner_lat -d grid_size,0,,360 -d grid_corners,0,3 ~/grd_scrip.nc ncks --cdl -m -M ~/grd_ugrid.nc */ char *dgx_nm=NULL_CEWI; /* [sng] Name of edge_coordinates x variable */ char *dgy_nm=NULL_CEWI; /* [sng] Name of edge_coordinates y variable */ char *dg_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as edges */ char *dg_nd_nm=NULL_CEWI; /* [sng] Name of edge_node_connectivity variable */ char *fcx_nm=NULL_CEWI; /* [sng] Name of face_coordinates x variable */ char *fcy_nm=NULL_CEWI; /* [sng] Name of face_coordinates y variable */ char *fc_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as faces */ char *fc_nd_nm=NULL_CEWI; /* [sng] Name of face_node_connectivity variable */ char *msh_nm=NULL_CEWI; /* [sng] Name of mesh topology variable */ char *nd_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as nodes */ char *ndx_nm=NULL_CEWI; /* [sng] Name of node_coordinates x variable */ char *ndy_nm=NULL_CEWI; /* [sng] Name of node_coordinates y variable */ char *npe_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as nodes-per-edge */ char *npf_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as nodes-per-face */ double *dgx=NULL_CEWI; /* [dgr] Characteristic longitude of edges */ double *dgy=NULL_CEWI; /* [dgr] Characteristic latitude of edges */ double *fcx=NULL_CEWI; /* [dgr] Characteristic longitude of faces */ double *fcy=NULL_CEWI; /* [dgr] Characteristic latitude of faces */ double *ndx=NULL_CEWI; /* [dgr] Longitude of nodes */ double *ndy=NULL_CEWI; /* [dgr] Latitude of nodes */ int *dg_nd; /* [idx] edge_node_connectivity variable */ int *fc_nd; /* [idx] face_node_connectivity variable */ int dg_nd_id=NC_MIN_INT; /* [id] edge_node_connectivity variable ID */ int dgx_id=NC_MIN_INT; /* [id] Characteristic longitude of edges variable ID */ int dgy_id=NC_MIN_INT; /* [id] Characteristic latitude of edges variable ID */ int dmn_id_dg=NC_MIN_INT; /* [id] Dimension ID for edges */ int dmn_id_fc=NC_MIN_INT; /* [id] Dimension ID for faces */ int dmn_id_nd=NC_MIN_INT; /* [id] Dimension ID for nodes */ int dmn_id_npe=NC_MIN_INT; /* [id] Dimension ID for nodes-per-edge */ int dmn_id_npf=NC_MIN_INT; /* [id] Dimension ID for nodes-per-face */ int fc_nd_id=NC_MIN_INT; /* [id] face_node_connectivity variable ID */ int fcx_id=NC_MIN_INT; /* [id] Characteristic longitude of faces variable ID */ int fcy_id=NC_MIN_INT; /* [id] Characteristic latitude of faces variable ID */ int msh_id=NC_MIN_INT; /* [id] Mesh topology variable ID */ int msh_val=42; /* [id] Mesh topology variable value from Monty Python */ int ndx_id=NC_MIN_INT; /* [id] Longitude of mesh nodes variable ID */ int ndy_id=NC_MIN_INT; /* [id] Latitude of mesh nodes variable ID */ const long fc_nbr=grd_sz_nbr; /* [nbr] Number of faces in mesh */ const long npe_nbr=2; /* [nbr] Number of nodes per edge */ const long npf_nbr=grd_crn_nbr; /* [nbr] Number of nodes per face */ long dg_idx; /* [idx] Counting index for edges */ long dg_nbr=(long)NC_MIN_INT64; /* [nbr] Number of edges in mesh */ long fc_idx; /* [idx] Counting index for faces */ long nd_idx; /* [idx] Counting index for nodes */ long nd_nbr=(long)NC_MIN_INT64; /* [nbr] Number of nodes in mesh */ long srt_idx=0; /* [idx] start_index (C/Fortran) for edge_nodes, face_nodes */ if(!dgx_nm) dgx_nm=(char *)strdup("mesh_edge_x"); if(!dgy_nm) dgy_nm=(char *)strdup("mesh_edge_y"); if(!dg_dmn_nm) dg_dmn_nm=(char *)strdup("nEdges"); if(!fcx_nm) fcx_nm=(char *)strdup("mesh_face_x"); if(!fcy_nm) fcy_nm=(char *)strdup("mesh_face_y"); if(!fc_dmn_nm) fc_dmn_nm=(char *)strdup("nFaces"); if(!dg_nd_nm) dg_nd_nm=(char *)strdup("mesh_edge_nodes"); if(!fc_nd_nm) fc_nd_nm=(char *)strdup("mesh_face_nodes"); if(!msh_nm) msh_nm=(char *)strdup("mesh"); if(!nd_dmn_nm) nd_dmn_nm=(char *)strdup("nNodes"); if(!ndx_nm) ndx_nm=(char *)strdup("mesh_node_x"); if(!ndy_nm) ndy_nm=(char *)strdup("mesh_node_y"); if(!npe_dmn_nm) npe_dmn_nm=(char *)strdup("two"); if(!npf_dmn_nm) npf_dmn_nm=(char *)strdup("maxNodesPerFace"); if(flg_grd_1D){ (void)fprintf(stdout,"%s: ERROR %s UGRID output does not yet support 1D grids\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); }else if(flg_grd_2D){ /* Assume 2D grids are global and comprised of quadrilaterals */ switch(lat_typ){ case nco_grd_lat_fv: /* Currently all 2D grids are converted to the same UGRID representation fxm: Cap grids (e.g., FV) should eventually be written with a real cap, rather than as the "polar teeth" representation currently used. Polar teeth convention allows cap grid to be represented as rectangular on disk However, cap grids are better suited to non-rectangular UGRID meshes */ case nco_grd_lat_eqa: case nco_grd_lat_gss: /* Numbers of unique edges and nodes counted from South Pole (SP) to North Pole (NP) */ dg_nbr=lon_nbr*2+ /* SP: cells_per_lat*unique_edges_per_cell */ (lat_nbr-2)*lon_nbr*2+ /* Mid: lats*cells_per_lat*unique_edges_per_cell */ lon_nbr*1; /* NP: cells_per_lat*unique_edges_per_cell */ nd_nbr=1+lon_nbr*1+ /* SP: SP+cells_per_lat*unique_nodes_per_cell */ (lat_nbr-2)*lon_nbr*1+ /* Mid: lats*cells_per_lat*unique_nodes_per_cell */ 1; /* NP: NP */ break; case nco_grd_lat_unk: case nco_grd_lat_nil: default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ }else if(flg_grd_crv){ (void)fprintf(stdout,"%s: ERROR %s UGRID output does not yet support curvilinear grids\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !flg_grd */ dg_nd=(int *)nco_malloc(dg_nbr*npe_nbr*nco_typ_lng(NC_INT)); dgx=(double *)nco_malloc(dg_nbr*nco_typ_lng(crd_typ)); dgy=(double *)nco_malloc(dg_nbr*nco_typ_lng(crd_typ)); fc_nd=(int *)nco_malloc(fc_nbr*npf_nbr*nco_typ_lng(NC_INT)); fcx=(double *)nco_malloc(fc_nbr*nco_typ_lng(crd_typ)); fcy=(double *)nco_malloc(fc_nbr*nco_typ_lng(crd_typ)); ndx=(double *)nco_malloc(nd_nbr*nco_typ_lng(crd_typ)); ndy=(double *)nco_malloc(nd_nbr*nco_typ_lng(crd_typ)); const long int idx_fst_crn_ll=0; const long int idx_fst_crn_lr=1; const long int idx_fst_crn_ur=2; const long int idx_fst_crn_ul=3; /* Node Ordering: Each interior face requires one new node Node 0 at SP New latitude row moves next node North Add nodes to run West->East */ /* SP */ ndx[0]=lon_crn[0]; /* Longitude degenerate at SP, NP, keep same longitude as corner array */ ndy[0]=lat_crn[0]; /* Mid */ for(nd_idx=1;nd_idx<nd_nbr-1L;nd_idx++){ fc_idx=nd_idx-1L; lat_idx=fc_idx/lon_nbr; lon_idx=fc_idx%lon_nbr; ndx[nd_idx]=lon_crn[lon_idx*grd_crn_nbr+idx_fst_crn_ul]; ndy[nd_idx]=lat_crn[lat_idx*grd_crn_nbr+idx_fst_crn_ul]; } /* !nd_idx */ /* NP */ ndx[nd_nbr-1L]=lon_crn[(lon_nbr-1)*grd_crn_nbr+idx_fst_crn_ul]; ndy[nd_nbr-1L]=lat_crn[(lat_nbr-1)*grd_crn_nbr+idx_fst_crn_ul]; /* Edge Ordering: epf_nbr is number of distinct edges-per-face (incremental, for interior cells) Each additional interior rectangular gridcell requires two new edges: Edge 0 runs South->North for all cells Edge 1 runs West->East for all cells NP row requires only one new edge per face */ /* SP */ const int epf_nbr=2; /* [nbr] Number of distinct edges-per-face (incremental, for interior cells) */ for(fc_idx=0;fc_idx<lon_nbr;fc_idx++){ dg_idx=fc_idx*epf_nbr; /* Edge 0 */ dg_nd[(dg_idx+0L)*npe_nbr+0L]=srt_idx; dg_nd[(dg_idx+0L)*npe_nbr+1L]=srt_idx+fc_idx+1L; /* Edge 1 */ dg_nd[(dg_idx+1L)*npe_nbr+0L]=srt_idx+fc_idx+1L; dg_nd[(dg_idx+1L)*npe_nbr+1L]=srt_idx+fc_idx+2L; } /* !fc_idx */ /* Mid */ for(fc_idx=lon_nbr;fc_idx<(lat_nbr-1L)*lon_nbr;fc_idx++){ dg_idx=fc_idx*epf_nbr; /* Edge 0 */ dg_nd[(dg_idx+0L)*npe_nbr+0L]=srt_idx+fc_idx-lon_nbr+1L; dg_nd[(dg_idx+0L)*npe_nbr+1L]=srt_idx+fc_idx+1L; /* Edge 1 */ dg_nd[(dg_idx+1L)*npe_nbr+0L]=srt_idx+fc_idx+1L; dg_nd[(dg_idx+1L)*npe_nbr+1L]=srt_idx+fc_idx+2L; } /* !fc_idx */ /* NP */ for(fc_idx=fc_nbr-lon_nbr;fc_idx<fc_nbr;fc_idx++){ /* Only one new edge per face in last row, easiest to count backwards from last edge */ dg_idx=dg_nbr-(fc_nbr-fc_idx); /* NP faces require only only one new edge, Edge 0 */ dg_nd[(dg_idx+0L)*npe_nbr+0L]=srt_idx+fc_idx-lon_nbr+1L; dg_nd[(dg_idx+0L)*npe_nbr+1L]=srt_idx+nd_nbr-1L; } /* !fc_idx */ /* SP */ for(fc_idx=0;fc_idx<lon_nbr;fc_idx++){ fc_nd[fc_idx*npf_nbr+0L]=srt_idx+0L; fc_nd[fc_idx*npf_nbr+1L]=srt_idx+fc_idx+2L; /* NB: CCW */ fc_nd[fc_idx*npf_nbr+2L]=srt_idx+fc_idx+1L; /* NB: CCW */ fc_nd[fc_idx*npf_nbr+3L]=mss_val_int_out; } /* !fc_idx */ /* Mid */ for(fc_idx=lon_nbr;fc_idx<fc_nbr-lon_nbr;fc_idx++){ fc_nd[fc_idx*npf_nbr+idx_fst_crn_ll]=srt_idx+fc_idx-lon_nbr+1L; fc_nd[fc_idx*npf_nbr+idx_fst_crn_lr]=srt_idx+fc_idx-lon_nbr+2L; fc_nd[fc_idx*npf_nbr+idx_fst_crn_ur]=srt_idx+fc_idx+2L; fc_nd[fc_idx*npf_nbr+idx_fst_crn_ul]=srt_idx+fc_idx+1L; } /* !fc_idx */ /* NP */ for(fc_idx=fc_nbr-lon_nbr;fc_idx<fc_nbr;fc_idx++){ fc_nd[fc_idx*npf_nbr+0L]=srt_idx+nd_nbr-(fc_nbr-fc_idx)-2L; fc_nd[fc_idx*npf_nbr+1L]=srt_idx+nd_nbr-(fc_nbr-fc_idx)-1L; fc_nd[fc_idx*npf_nbr+2L]=srt_idx+nd_nbr-1L; fc_nd[fc_idx*npf_nbr+3L]=mss_val_int_out; } /* !fc_idx */ /* Characteristic coordinates */ for(dg_idx=0;dg_idx<dg_nbr-1L;dg_idx++){ idx=dg_idx*npe_nbr; dgx[dg_idx]=0.5*(ndx[dg_nd[idx+0L]]+ndx[dg_nd[idx+1L]]); dgy[dg_idx]=0.5*(ndy[dg_nd[idx+0L]]+ndy[dg_nd[idx+1L]]); } /* !dg_idx */ /* Degenerate longitude at SP, NP, causes weird characterisic longitude unless special care taken */ for(fc_idx=0;fc_idx<fc_nbr-1L;fc_idx++){ idx=fc_idx*npf_nbr; if(fc_idx < lon_nbr){ fcx[fc_idx]=0.5*(ndx[fc_nd[idx+1L]]+ndx[fc_nd[idx+2L]]); }else if(fc_idx >= fc_nbr-lon_nbr-1){ fcx[fc_idx]=0.5*(ndx[fc_nd[idx+0L]]+ndx[fc_nd[idx+1L]]); }else if(fc_nd[idx+3L] != mss_val_int_out){ /* fxm for fcx use nco_lon_crn_avg_brnch() and 3-node version too */ fcx[fc_idx]=0.25*(ndx[fc_nd[idx+0L]]+ndx[fc_nd[idx+1L]]+ndx[fc_nd[idx+2L]]+ndx[fc_nd[idx+3L]]); }else{ abort(); } /* !fc_idx */ if(fc_nd[idx+3L] != mss_val_int_out) fcy[fc_idx]=0.25*(ndy[fc_nd[idx+0L]]+ndy[fc_nd[idx+1L]]+ndy[fc_nd[idx+2L]]+ndy[fc_nd[idx+3L]]); else fcy[fc_idx]=0.33*(ndy[fc_nd[idx+0L]]+ndy[fc_nd[idx+1L]]+ndy[fc_nd[idx+2L]]); } /* !fc_idx */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); rcd=nco_def_dim(out_id,dg_dmn_nm,dg_nbr,&dmn_id_dg); rcd=nco_def_dim(out_id,fc_dmn_nm,fc_nbr,&dmn_id_fc); rcd=nco_def_dim(out_id,nd_dmn_nm,nd_nbr,&dmn_id_nd); rcd=nco_def_dim(out_id,npe_dmn_nm,npe_nbr,&dmn_id_npe); rcd=nco_def_dim(out_id,npf_dmn_nm,npf_nbr,&dmn_id_npf); dmn_ids[0]=dmn_id_dg; dmn_ids[1]=dmn_id_npe; rcd=nco_def_var(out_id,dg_nd_nm,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids,&dg_nd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,dg_nd_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_fc; dmn_ids[1]=dmn_id_npf; rcd=nco_def_var(out_id,fc_nd_nm,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids,&fc_nd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,fc_nd_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,msh_nm,(nc_type)NC_INT,dmn_nbr_0D,(int *)NULL,&msh_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msh_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,ndx_nm,crd_typ,dmn_nbr_1D,&dmn_id_nd,&ndx_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ndx_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,ndy_nm,crd_typ,dmn_nbr_1D,&dmn_id_nd,&ndy_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ndy_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,dgx_nm,crd_typ,dmn_nbr_1D,&dmn_id_dg,&dgx_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,dgx_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,dgy_nm,crd_typ,dmn_nbr_1D,&dmn_id_dg,&dgy_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,dgy_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,fcx_nm,crd_typ,dmn_nbr_1D,&dmn_id_fc,&fcx_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,fcx_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,fcy_nm,crd_typ,dmn_nbr_1D,&dmn_id_fc,&fcy_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,fcy_id,shuffle,deflate,dfl_lvl); if(strstr(rgr->grd_ttl,"None given")){ const char att_fmt[]="NCO constructed this UGRID grid from scratch"; att_val=(char *)nco_malloc((strlen(att_fmt)+strlen(rgr->fl_in)+1L)*sizeof(char)); sprintf(att_val,att_fmt); }else{ att_val=strdup(rgr->grd_ttl); } /* !grd_ttl */ rcd=nco_char_att_put(out_id,NULL,"title",att_val); rcd=nco_char_att_put(out_id,NULL,"Conventions","CF-1.6, UGRID-1.0"); rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); rcd=nco_char_att_put(out_id,NULL,"grid_generator","NCO"); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,msh_nm,"cf_role","mesh_topology"); rcd=nco_char_att_put(out_id,msh_nm,"standard_name","mesh_topology"); rcd=nco_char_att_put(out_id,msh_nm,"long_name","Topology data"); att_nm=strdup("topology_dimension"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=msh_nm; aed_mtd.id=msh_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&val_two; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,msh_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); aed_mtd.sz=strlen(ndx_nm)+strlen(ndy_nm)+1L; att_val=(char *)nco_malloc((aed_mtd.sz+1L)*nco_typ_lng(NC_CHAR)); (void)sprintf(att_val,"%s %s",ndx_nm,ndy_nm); rcd=nco_char_att_put(out_id,msh_nm,"node_coordinates",att_val); rcd=nco_char_att_put(out_id,msh_nm,"face_node_connectivity",fc_nd_nm); aed_mtd.sz=strlen(fcx_nm)+strlen(fcy_nm)+1L; att_val=(char *)nco_malloc((aed_mtd.sz+1L)*nco_typ_lng(NC_CHAR)); (void)sprintf(att_val,"%s %s",fcx_nm,fcy_nm); rcd=nco_char_att_put(out_id,msh_nm,"face_coordinates",att_val); rcd=nco_char_att_put(out_id,msh_nm,"face_dimension",fc_dmn_nm); rcd=nco_char_att_put(out_id,msh_nm,"edge_node_connectivity",dg_nd_nm); aed_mtd.sz=strlen(dgx_nm)+strlen(dgy_nm)+1L; att_val=(char *)nco_malloc((aed_mtd.sz+1L)*nco_typ_lng(NC_CHAR)); (void)sprintf(att_val,"%s %s",dgx_nm,dgy_nm); rcd=nco_char_att_put(out_id,msh_nm,"edge_coordinates",att_val); rcd=nco_char_att_put(out_id,msh_nm,"edge_dimension",dg_dmn_nm); rcd=nco_char_att_put(out_id,ndx_nm,"standard_name","longitude"); rcd=nco_char_att_put(out_id,ndx_nm,"long_name","Longitude of mesh nodes"); rcd=nco_char_att_put(out_id,ndx_nm,"units","degrees_east"); rcd=nco_char_att_put(out_id,ndy_nm,"standard_name","latitude"); rcd=nco_char_att_put(out_id,ndy_nm,"long_name","Latitude of mesh nodes"); rcd=nco_char_att_put(out_id,ndy_nm,"units","degrees_north"); rcd=nco_char_att_put(out_id,dg_nd_nm,"cf_role","edge_node_connectivity"); rcd=nco_char_att_put(out_id,dg_nd_nm,"long_name","Maps every edge to the two nodes that it connects"); att_nm=strdup("start_index"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=dg_nd_nm; aed_mtd.id=dg_nd_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&val_zero; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,dg_nd_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,fc_nd_nm,"cf_role","face_node_connectivity"); rcd=nco_char_att_put(out_id,fc_nd_nm,"long_name","Maps every face to its corner nodes"); att_nm=strdup("start_index"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=fc_nd_nm; aed_mtd.id=fc_nd_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&val_zero; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,fc_nd_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); att_nm=strdup("_FillValue"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=fc_nd_nm; aed_mtd.id=fc_nd_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&mss_val_int_out; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,fc_nd_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,dgx_nm,"standard_name","longitude"); rcd=nco_char_att_put(out_id,dgx_nm,"long_name","Characteristic longitude of 2D mesh face"); rcd=nco_char_att_put(out_id,dgx_nm,"units","degrees_east"); rcd=nco_char_att_put(out_id,dgy_nm,"standard_name","latitude"); rcd=nco_char_att_put(out_id,dgy_nm,"long_name","Characteristic latitude of 2D mesh face"); rcd=nco_char_att_put(out_id,dgy_nm,"units","degrees_north"); rcd=nco_char_att_put(out_id,fcx_nm,"standard_name","longitude"); rcd=nco_char_att_put(out_id,fcx_nm,"long_name","Characteristic longitude of 2D mesh edge"); rcd=nco_char_att_put(out_id,fcx_nm,"units","degrees_east"); rcd=nco_char_att_put(out_id,fcy_nm,"standard_name","latitude"); rcd=nco_char_att_put(out_id,fcy_nm,"long_name","Characteristic latitude of 2D mesh edge"); rcd=nco_char_att_put(out_id,fcy_nm,"units","degrees_north"); /* Begin data mode */ (void)nco_enddef(out_id); (void)nco_put_vara(out_id,msh_id,dmn_srt,dmn_cnt,&msh_val,(nc_type)NC_INT); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=dg_nbr; dmn_cnt[1]=epf_nbr; (void)nco_put_vara(out_id,dg_nd_id,dmn_srt,dmn_cnt,dg_nd,(nc_type)NC_INT); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=fc_nbr; dmn_cnt[1]=npf_nbr; (void)nco_put_vara(out_id,fc_nd_id,dmn_srt,dmn_cnt,fc_nd,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=nd_nbr; (void)nco_put_vara(out_id,ndx_id,dmn_srt,dmn_cnt,ndx,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=nd_nbr; (void)nco_put_vara(out_id,ndy_id,dmn_srt,dmn_cnt,ndy,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=dg_nbr; (void)nco_put_vara(out_id,dgx_id,dmn_srt,dmn_cnt,dgx,crd_typ); (void)nco_put_vara(out_id,dgy_id,dmn_srt,dmn_cnt,dgy,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=fc_nbr; (void)nco_put_vara(out_id,fcx_id,dmn_srt,dmn_cnt,fcx,crd_typ); (void)nco_put_vara(out_id,fcy_id,dmn_srt,dmn_cnt,fcy,crd_typ); /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); /* Free memory associated with output file */ if(dgx) dgx=(double *)nco_free(dgx); if(dgy) dgy=(double *)nco_free(dgy); if(dg_nd) dg_nd=(int *)nco_free(dg_nd); if(fcx) fcx=(double *)nco_free(fcx); if(fcy) fcy=(double *)nco_free(fcy); if(fc_nd) fc_nd=(int *)nco_free(fc_nd); if(ndx) ndx=(double *)nco_free(ndx); if(ndy) ndy=(double *)nco_free(ndy); /* Free strings */ if(dgx_nm) dgx_nm=(char *)nco_free(dgx_nm); if(dgy_nm) dgy_nm=(char *)nco_free(dgy_nm); if(dg_dmn_nm) dg_dmn_nm=(char *)nco_free(dg_dmn_nm); if(dg_nd_nm) dg_nd_nm=(char *)nco_free(dg_nd_nm); if(fcx_nm) fcx_nm=(char *)nco_free(fcx_nm); if(fcy_nm) fcy_nm=(char *)nco_free(fcy_nm); if(fc_dmn_nm) fc_dmn_nm=(char *)nco_free(fc_dmn_nm); if(fc_nd_nm) fc_nd_nm=(char *)nco_free(fc_nd_nm); if(msh_nm) msh_nm=(char *)nco_free(msh_nm); if(nd_dmn_nm) nd_dmn_nm=(char *)nco_free(nd_dmn_nm); if(ndx_nm) ndx_nm=(char *)nco_free(ndx_nm); if(ndy_nm) ndy_nm=(char *)nco_free(ndy_nm); if(npe_dmn_nm) npe_dmn_nm=(char *)nco_free(npe_dmn_nm); if(npf_dmn_nm) npf_dmn_nm=(char *)nco_free(npf_dmn_nm); } /* !fl_ugrid */ /* Free memory associated with input file */ if(dmn_sz_int) dmn_sz_int=(int *)nco_free(dmn_sz_int); if(msk) msk=(int *)nco_free(msk); if(area) area=(double *)nco_free(area); if(grd_ctr_lat) grd_ctr_lat=(double *)nco_free(grd_ctr_lat); if(grd_ctr_lon) grd_ctr_lon=(double *)nco_free(grd_ctr_lon); if(grd_crn_lat) grd_crn_lat=(double *)nco_free(grd_crn_lat); if(grd_crn_lon) grd_crn_lon=(double *)nco_free(grd_crn_lon); if(lat_bnd) lat_bnd=(double *)nco_free(lat_bnd); if(lat_crn) lat_crn=(double *)nco_free(lat_crn); if(lat_ctr) lat_ctr=(double *)nco_free(lat_ctr); if(lat_ntf) lat_ntf=(double *)nco_free(lat_ntf); if(lat_wgt) lat_wgt=(double *)nco_free(lat_wgt); if(lon_bnd) lon_bnd=(double *)nco_free(lon_bnd); if(lon_crn) lon_crn=(double *)nco_free(lon_crn); if(lon_ctr) lon_ctr=(double *)nco_free(lon_ctr); if(lon_ntf) lon_ntf=(double *)nco_free(lon_ntf); if(vrt_cll) vrt_cll=(int *)nco_free(vrt_cll); if(vrt_lat) vrt_lat=(double *)nco_free(vrt_lat); if(vrt_lon) vrt_lon=(double *)nco_free(vrt_lon); /* Free strings */ if(area_nm_in) area_nm_in=(char *)nco_free(area_nm_in); if(area_unt) area_unt=(char *)nco_free(area_unt); if(bnd_dmn_nm) bnd_dmn_nm=(char *)nco_free(bnd_dmn_nm); if(col_dmn_nm) col_dmn_nm=(char *)nco_free(col_dmn_nm); if(lat_bnd_nm) lat_bnd_nm=(char *)nco_free(lat_bnd_nm); if(lat_dmn_nm) lat_dmn_nm=(char *)nco_free(lat_dmn_nm); if(lat_nm_in) lat_nm_in=(char *)nco_free(lat_nm_in); if(lon_bnd_nm) lon_bnd_nm=(char *)nco_free(lon_bnd_nm); if(lon_dmn_nm) lon_dmn_nm=(char *)nco_free(lon_dmn_nm); if(lon_nm_in) lon_nm_in=(char *)nco_free(lon_nm_in); if(msk_nm_in) msk_nm_in=(char *)nco_free(msk_nm_in); if(ngl_unt) ngl_unt=(char *)nco_free(ngl_unt); if(vrt_cll_nm) vrt_cll_nm=(char *)nco_free(vrt_cll_nm); if(vrt_lat_nm) vrt_lat_nm=(char *)nco_free(vrt_lat_nm); if(vrt_lon_nm) vrt_lon_nm=(char *)nco_free(vrt_lon_nm); return rcd; } /* !nco_grd_nfr() */ double /* O [dgr] Longitude difference (lon_r-lon_l) */ nco_lon_dff_brnch_dgr /* [fnc] Subtract longitudes with branch-cut rules */ (double lon_r, /* I [dgr] Longitude on right of gridcell (subtractor) */ double lon_l) /* I [dgr] Longitude on left of gridcell (subtractee) */ { /* Purpose: Return difference of two longitudes in degrees Assume longitudes are within 180 degrees of eachother Default orientation is monotonically increasing longitude from left to right */ const char fnc_nm[]="nco_lon_dff_brnch_dgr()"; const double lon_dff=lon_r-lon_l; /* [dgr] Longitude difference (lon_r-lon_l) */ if(lon_dff >= 180.0){ (void)fprintf(stdout,"%s: WARNING %s reports lon_r, lon_l, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_r,lon_l,lon_dff); return lon_dff-360.0; }else if(lon_dff <= -180.0){ return lon_dff+360.0; } /* !lon_dff */ return lon_dff; } /* !nco_lon_dff_brnch_dgr() */ double /* O [rdn] Longitude difference (lon_r-lon_l) */ nco_lon_dff_brnch_rdn /* [fnc] Subtract longitudes with branch-cut rules */ (double lon_r, /* I [rdn] Longitude on right of gridcell (subtractor) */ double lon_l) /* I [rdn] Longitude on left of gridcell (subtractee) */ { /* Purpose: Return difference of two longitudes in radians Assume longitudes are within pi radians of eachother Default orientation is monotonically increasing longitude from left to right */ const char fnc_nm[]="nco_lon_dff_brnch_rdn()"; const double lon_dff=lon_r-lon_l; /* [rdn] Longitude difference (lon_r-lon_l) */ //nco_bool dbg_prn=False; /* [flg] Print warning when longitude difference is suspicious */ /* longitudes on different branch cuts are expected when computing polygon area, so warn only if requested with high debugging level */ if(lon_dff >= M_PI){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports lon_r, lon_l, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_r,lon_l,lon_dff); return lon_dff-M_PI-M_PI; }else if(lon_dff <= -M_PI){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports lon_r, lon_l, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_r,lon_l,lon_dff); return lon_dff+M_PI+M_PI; } /* !lon_dff */ return lon_dff; } /* !nco_lon_dff_brnch_rdn() */ double /* O [dgr] Longitude average */ nco_lon_crn_avg_brnch /* [fnc] Average quadrilateral longitude with branch-cut rules */ (double lon_ll, /* I [dgr] Longitude at lower left of gridcell */ double lon_lr, /* I [dgr] Longitude at lower right of gridcell */ double lon_ur, /* I [dgr] Longitude at upper right of gridcell */ double lon_ul) /* I [dgr] Longitude at upper left of gridcell */ { /* Purpose: Return average of four corner longitudes of quadrilateral Assume longitudes are within 180 degrees of eachother Default orientation is monotonically increasing longitude from left to right WLOG, adjust all longitudes to be on same branch as lon_ll */ const char fnc_nm[]="nco_lon_crn_avg_brnch()"; double lon_dff; /* [dgr] Longitude difference */ lon_dff=lon_lr-lon_ll; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports lon_lr, lon_ll, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_lr,lon_ll,lon_dff); lon_lr-=360.0; }else if(lon_dff <= -180.0){ lon_lr+=360.0; } /* !lon_dff */ lon_dff=lon_ur-lon_ll; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports lon_ur, lon_ll, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_ur,lon_ll,lon_dff); lon_ur-=360.0; }else if(lon_dff <= -180.0){ lon_ur+=360.0; } /* !lon_dff */ lon_dff=lon_ul-lon_ll; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports lon_ul, lon_ll, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_ul,lon_ll,lon_dff); lon_ul-=360.0; }else if(lon_dff <= -180.0){ lon_ul+=360.0; } /* !lon_dff */ return 0.25*(lon_ll+lon_lr+lon_ur+lon_ul); } /* !nco_lon_crn_avg_brnch() */ double /* O [dgr] Longitude average */ nco_lon_ply_avg_brnch_dgr /* [fnc] Average polygon longitude with branch-cut rules */ (double *lon_crn, /* I [dgr] Longitude of gridcell corners */ long lon_nbr) /* I [nbr] Number of vertices in polygon */ { /* Purpose: Return average longitude of polygon vertices, i.e., centroid longitude Assume longitudes are within 180 degrees of one another Default orientation is monotonically increasing longitude from left to right WLOG, adjust all longitudes to be on same branch as lon_ll */ // const char fnc_nm[]="nco_lon_ply_avg_brnch()"; double lon_dff; /* [dgr] Longitude difference */ double lon_avg; /* [dgr] Longitude average */ int lon_idx; /* [idx] Polygon vertex index */ assert(lon_nbr != 0); lon_avg=lon_crn[0]; for(lon_idx=1;lon_idx<lon_nbr;lon_idx++){ lon_avg+=lon_crn[lon_idx]; lon_dff=lon_crn[lon_idx]-lon_crn[0]; if(lon_dff >= 180.0){ lon_avg-=360.0; }else if(lon_dff <= -180.0){ lon_avg+=360.0; } /* !lon_dff */ } /* !lon_idx */ return lon_avg/lon_nbr; } /* !nco_lon_ply_avg_brnch() */ nco_bool /* O [flg] Input corners were CCW */ nco_ccw_chk /* [fnc] Convert quadrilateral gridcell corners to CCW orientation */ (double * const crn_lat, /* [dgr] Latitude corners of gridcell */ double * const crn_lon, /* [dgr] Latitude corners of gridcell */ const int crn_nbr, /* [nbr] Number of corners per gridcell */ int idx_ccw, /* [idx] Index of starting vertice for CCW check (Point A = tail side AB) */ const int rcr_lvl) /* [nbr] Recursion level */ { /* Purpose: Determine whether corner vertices are oriented CCW If not, alter order so they are returned in CCW order Function can call itself, and rcr_lvl indicates recursion level: rcr_lvl=1: Called by host code, i.e., nco_grd_nfr() rcr_lvl=2: Called by itself, i.e., nco_ccw_chk() Assumptions: Quadrilateral vertices are already corrected to obey branch-cut rules, i.e., all vertices are on "same side" of dateline or Greenwich as appropriate Algorithm: Start crn_idx=0, i.e., quadrilateral LL corner Vector A runs from crn_idx=0 to crn_idx=1, i.e., quadrilateral LL->LR Vector B runs from crn_idx=1 to crn_idx=2, i.e., quadrilateral LR->UR Compute cross-product A x B = C C is normal to plane containining A and B Dot-product of C with radial vector to head A = tail B is positive if A and B are CCW if(ABC is CCW){ if(CDA is CCW) Done else Copy D:=A (make CDA degenerate, triangularize quadrilateral) endif }else(ABC is not CCW){ Assume entire quadrilateral is CW Take mirror image of quadrilateral by switching B with D If(new ABC is CCW){ If(CDA is CCW) Done else Copy D:=A (make CDA degenerate, triangularize quadrilateral) endif }else{ Fail (return False, meaning point should be masked) } All cases return True (i.e., CCW) from rcr_lvl=1 except last Last case returns False, and calling code should mask such an aberrant point */ const char fnc_nm[]="nco_ccw_chk()"; /* MSVC compiler chokes unless array size is compile-time constant */ const int CRN_NBR_MSVC=4; double sin_lat[CRN_NBR_MSVC]; double sin_lon[CRN_NBR_MSVC]; double cos_lat[CRN_NBR_MSVC]; double cos_lon[CRN_NBR_MSVC]; double A_tail_x,A_tail_y,A_tail_z; double A_head_x,A_head_y,A_head_z; double A_x,A_y,A_z; double B_tail_x,B_tail_y,B_tail_z; double B_head_x,B_head_y,B_head_z; double B_x,B_y,B_z; double C_x,C_y,C_z; double R_x,R_y,R_z; double lat_rdn; double lon_rdn; double dot_prd; int crn_idx; /* [idx] Corner idx */ int A_tail_idx,A_head_idx; int B_tail_idx,B_head_idx; nco_bool flg_ccw; /* [flg] Input is CCW */ assert(crn_nbr == CRN_NBR_MSVC); for(crn_idx=0;crn_idx<crn_nbr;crn_idx++){ lat_rdn=crn_lat[crn_idx]*M_PI/180.0; lon_rdn=crn_lon[crn_idx]*M_PI/180.0; sin_lat[crn_idx]=sin(lat_rdn); cos_lat[crn_idx]=cos(lat_rdn); sin_lon[crn_idx]=sin(lon_rdn); cos_lon[crn_idx]=cos(lon_rdn); } /* !crn_idx */ /* Calls from host code (i.e., nco_grd_nfr()) start at lower-left of quadrilateral ABCD = Point A = vertex 0 Calls from self can start from quadrilateral Point A or C To check triangle CDA, start at upper-right of quadrilateral ABCD = Point C = vertex 2 */ A_tail_idx=idx_ccw; A_head_idx=B_tail_idx=(A_tail_idx+1)%crn_nbr; B_head_idx=(B_tail_idx+1)%crn_nbr; A_tail_x=cos_lat[A_tail_idx]*cos_lon[A_tail_idx]; A_tail_y=cos_lat[A_tail_idx]*sin_lon[A_tail_idx]; A_tail_z=sin_lat[A_tail_idx]; A_head_x=B_tail_x=R_x=cos_lat[A_head_idx]*cos_lon[A_head_idx]; A_head_y=B_tail_y=R_y=cos_lat[A_head_idx]*sin_lon[A_head_idx]; A_head_z=B_tail_z=R_z=sin_lat[A_head_idx]; B_head_x=cos_lat[B_head_idx]*cos_lon[B_head_idx]; B_head_y=cos_lat[B_head_idx]*sin_lon[B_head_idx]; B_head_z=sin_lat[B_head_idx]; A_x=A_head_x-A_tail_x; A_y=A_head_y-A_tail_y; A_z=A_head_z-A_tail_z; B_x=B_head_x-B_tail_x; B_y=B_head_y-B_tail_y; B_z=B_head_z-B_tail_z; /* Cross-Product C = A x B */ C_x=A_y*B_z-B_y*A_z; C_y=-A_x*B_z+B_x*A_z; C_z=A_x*B_y-B_x*A_y; /* Dot-Product R dot C */ dot_prd=C_x*R_x+C_y*R_y+C_z*R_z; if(dot_prd > 0.0) flg_ccw=True; else flg_ccw=False; if(flg_ccw && crn_nbr == 4 && rcr_lvl == 1){ /* Original ABC is CCW, now check CDA */ idx_ccw=2; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,crn_nbr,idx_ccw,rcr_lvl+1); if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports triangle ABC is and CDA is not CCW in quadrilateral gridcell with LL (lat,lon) = (%g, %g), dot_prd = %g. Setting D:=A to triangularize quadrilateral.\n",nco_prg_nm_get(),fnc_nm,*crn_lat+0,*crn_lon+0,dot_prd); /* Triangularize quadrilateral D:=A */ crn_lat[3]=crn_lat[0]; crn_lon[3]=crn_lon[0]; return True; }else if(!flg_ccw && crn_nbr == 4 && rcr_lvl == 1){ /* Original ABC is not CCW 20160124: Simplistic fix: reverse gridpoint order This only works for quadrilaterals without degenerate points */ double crn_tmp; if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: INFO %s reports triangle ABC is non-CCW in quadrilateral gridcell with LL (lat,lon) = (%g, %g), dot_prd = %g. Mirror-imaging...\n",nco_prg_nm_get(),fnc_nm,*crn_lat+0,*crn_lon+0,dot_prd); crn_tmp=crn_lat[1]; crn_lat[1]=crn_lat[3]; crn_lat[3]=crn_tmp; crn_tmp=crn_lon[1]; crn_lon[1]=crn_lon[3]; crn_lon[3]=crn_tmp; /* Check new triangle ABC */ idx_ccw=0; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,crn_nbr,idx_ccw,rcr_lvl+1); if(flg_ccw){ /* Inverted ABC is CCW, now check CDA */ idx_ccw=2; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,crn_nbr,idx_ccw,rcr_lvl+1); if(flg_ccw){ return True; }else{ if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: INFO %s reports triangle ABC is CCW after inversion, but triangle CDA is not at quadrilateral gridcell with LL (lat,lon) = (%g, %g), dot_prd = %g. Setting D:=A to triangularize quadrilateral.\n",nco_prg_nm_get(),fnc_nm,*crn_lat+0,*crn_lon+0,dot_prd); /* Triangularize quadrilateral D:=A */ crn_lat[3]=crn_lat[0]; crn_lon[3]=crn_lon[0]; return True; } /* flg_ccw */ }else{ /* Original and Inverted ABC are not CCW */ if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports triangle ABC remains non-CCW after first inversion\n",nco_prg_nm_get(),fnc_nm); return False; } /* !flg_ccw */ } /* flg_ccw */ return flg_ccw; } /* !nco_ccw_chk() */
tti-so8-unoptimized.c
t#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "omp.h" struct dataobj { void *restrict data; int * size; int * npsize; int * dsize; int * hsize; int * hofs; int * oofs; } ; struct profiler { double section0; double section1; double section2; } ; int ForwardTTI(struct dataobj *restrict damp_vec, struct dataobj *restrict delta_vec, const float dt, struct dataobj *restrict epsilon_vec, const float o_x, const float o_y, const float o_z, struct dataobj *restrict phi_vec, struct dataobj *restrict rec_vec, struct dataobj *restrict rec_coords_vec, struct dataobj *restrict src_vec, struct dataobj *restrict src_coords_vec, struct dataobj *restrict theta_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int p_rec_M, const int p_rec_m, const int p_src_M, const int p_src_m, const int time_M, const int time_m, struct profiler * timers, const int nthreads, const int nthreads_nonaffine) { float (*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[damp_vec->size[1]][damp_vec->size[2]]) damp_vec->data; float (*restrict delta)[delta_vec->size[1]][delta_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[delta_vec->size[1]][delta_vec->size[2]]) delta_vec->data; float (*restrict epsilon)[epsilon_vec->size[1]][epsilon_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[epsilon_vec->size[1]][epsilon_vec->size[2]]) epsilon_vec->data; float (*restrict phi)[phi_vec->size[1]][phi_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[phi_vec->size[1]][phi_vec->size[2]]) phi_vec->data; float (*restrict rec)[rec_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[rec_vec->size[1]]) rec_vec->data; float (*restrict rec_coords)[rec_coords_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[rec_coords_vec->size[1]]) rec_coords_vec->data; float (*restrict src)[src_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[src_vec->size[1]]) src_vec->data; float (*restrict src_coords)[src_coords_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[src_coords_vec->size[1]]) src_coords_vec->data; float (*restrict theta)[theta_vec->size[1]][theta_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[theta_vec->size[1]][theta_vec->size[2]]) theta_vec->data; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; float (*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]]) v_vec->data; float (*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[vp_vec->size[1]][vp_vec->size[2]]) vp_vec->data; for (int time = time_m, t0 = (time)%(3), t1 = (time + 1)%(3), t2 = (time + 2)%(3); time <= time_M; time += 1, t0 = (time)%(3), t1 = (time + 1)%(3), t2 = (time + 2)%(3)) { struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(dynamic,1) for (int x = x_m; x <= x_M; x += 1) { for (int y = y_m; y <= y_M; y += 1) { for (int z = z_m; z <= z_M; z += 1) { u[t1][x + 8][y + 8][z + 8] = 1.0F*(2.0F*pow(dt, 2)*(sqrt(2*delta[x + 8][y + 8][z + 8] + 1)*(-8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 4][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 5][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 7][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 6][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 6][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 6][y + 10][z + 8])*sin(phi[x + 6][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 6][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 6][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 6][y + 8][z + 10])*cos(theta[x + 6][y + 8][z + 8]))*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) + 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 5][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 6][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 9][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 7][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 7][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 7][y + 10][z + 8])*sin(phi[x + 7][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 7][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 7][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 7][y + 8][z + 10])*cos(theta[x + 7][y + 8][z + 8]))*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 6][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 6][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8])*cos(phi[x + 8][y + 6][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 4][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 5][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 7][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 8])*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 6][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 6][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 6][z + 10])*cos(theta[x + 8][y + 6][z + 8]))*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) + 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 7][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 7][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8])*cos(phi[x + 8][y + 7][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 5][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 6][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 9][z + 8])*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 7][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 7][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 7][z + 10])*cos(theta[x + 8][y + 7][z + 8]))*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 6] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 6] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6])*cos(phi[x + 8][y + 8][z + 6]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 6] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 6] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 6])*sin(phi[x + 8][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 4] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 5] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 7] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 8])*cos(theta[x + 8][y + 8][z + 6]))*cos(theta[x + 8][y + 8][z + 6]) + 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 7] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 7] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7])*cos(phi[x + 8][y + 8][z + 7]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 7] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 7] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 7])*sin(phi[x + 8][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 5] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 6] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 9])*cos(theta[x + 8][y + 8][z + 7]))*cos(theta[x + 8][y + 8][z + 7]) - 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 9] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 9] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9])*cos(phi[x + 8][y + 8][z + 9]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 9] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 9] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 9])*sin(phi[x + 8][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 7] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 10] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 11])*cos(theta[x + 8][y + 8][z + 9]))*cos(theta[x + 8][y + 8][z + 9]) + 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 10] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 10] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 10] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10])*cos(phi[x + 8][y + 8][z + 10]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 10] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 10] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 10] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 10])*sin(phi[x + 8][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 9] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 11] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 12])*cos(theta[x + 8][y + 8][z + 10]))*cos(theta[x + 8][y + 8][z + 10]) - 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 9][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 9][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8])*cos(phi[x + 8][y + 9][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 7][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 10][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 11][z + 8])*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 9][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 9][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 9][z + 10])*cos(theta[x + 8][y + 9][z + 8]))*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 10][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 10][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 10][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8])*cos(phi[x + 8][y + 10][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 9][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 11][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 12][z + 8])*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 10][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 10][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 10][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 10])*cos(theta[x + 8][y + 10][z + 8]))*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) - 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 7][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 10][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 11][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 9][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 9][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 9][y + 10][z + 8])*sin(phi[x + 9][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 9][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 9][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 9][y + 8][z + 10])*cos(theta[x + 9][y + 8][z + 8]))*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 9][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 11][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 12][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 10][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 10][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 10][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 10][z + 8])*sin(phi[x + 10][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 10][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 10][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 10][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 10])*cos(theta[x + 10][y + 8][z + 8]))*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8])) + (2*epsilon[x + 8][y + 8][z + 8] + 1)*(8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 4][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 5][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 7][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 6][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 6][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 6][y + 10][z + 8])*sin(phi[x + 6][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 6][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 6][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 6][y + 8][z + 10])*cos(theta[x + 6][y + 8][z + 8]))*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) - 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 5][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 6][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 9][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 7][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 7][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 7][y + 10][z + 8])*sin(phi[x + 7][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 7][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 7][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 7][y + 8][z + 10])*cos(theta[x + 7][y + 8][z + 8]))*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 6][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 6][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8])*cos(phi[x + 8][y + 6][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 4][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 5][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 7][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 8])*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 6][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 6][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 6][z + 10])*cos(theta[x + 8][y + 6][z + 8]))*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) - 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 7][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 7][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8])*cos(phi[x + 8][y + 7][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 5][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 6][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 9][z + 8])*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 7][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 7][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 7][z + 10])*cos(theta[x + 8][y + 7][z + 8]))*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 6] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 6] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6])*cos(phi[x + 8][y + 8][z + 6]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 6] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 6] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 6])*sin(phi[x + 8][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 4] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 5] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 7] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 8])*cos(theta[x + 8][y + 8][z + 6]))*cos(theta[x + 8][y + 8][z + 6]) - 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 7] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 7] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7])*cos(phi[x + 8][y + 8][z + 7]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 7] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 7] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 7])*sin(phi[x + 8][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 5] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 6] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 9])*cos(theta[x + 8][y + 8][z + 7]))*cos(theta[x + 8][y + 8][z + 7]) + 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 9] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 9] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9])*cos(phi[x + 8][y + 8][z + 9]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 9] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 9] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 9])*sin(phi[x + 8][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 7] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 10] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 11])*cos(theta[x + 8][y + 8][z + 9]))*cos(theta[x + 8][y + 8][z + 9]) - 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 10] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 10] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 10] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10])*cos(phi[x + 8][y + 8][z + 10]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 10] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 10] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 10] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 10])*sin(phi[x + 8][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 9] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 11] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 12])*cos(theta[x + 8][y + 8][z + 10]))*cos(theta[x + 8][y + 8][z + 10]) + 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 9][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 9][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8])*cos(phi[x + 8][y + 9][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 7][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 10][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 11][z + 8])*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 9][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 9][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 9][z + 10])*cos(theta[x + 8][y + 9][z + 8]))*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 10][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 10][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 10][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8])*cos(phi[x + 8][y + 10][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 9][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 11][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 12][z + 8])*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 10][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 10][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 10][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 10])*cos(theta[x + 8][y + 10][z + 8]))*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) + 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 7][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 10][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 11][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 9][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 9][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 9][y + 10][z + 8])*sin(phi[x + 9][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 9][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 9][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 9][y + 8][z + 10])*cos(theta[x + 9][y + 8][z + 8]))*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 9][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 11][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 12][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 10][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 10][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 10][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 10][z + 8])*sin(phi[x + 10][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 10][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 10][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 10][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 10])*cos(theta[x + 10][y + 8][z + 8]))*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8]) - 1.78571425e-5F*u[t0][x + 4][y + 8][z + 8] + 2.53968248e-4F*u[t0][x + 5][y + 8][z + 8] - 1.99999996e-3F*u[t0][x + 6][y + 8][z + 8] + 1.59999996e-2F*u[t0][x + 7][y + 8][z + 8] - 1.78571425e-5F*u[t0][x + 8][y + 4][z + 8] + 2.53968248e-4F*u[t0][x + 8][y + 5][z + 8] - 1.99999996e-3F*u[t0][x + 8][y + 6][z + 8] + 1.59999996e-2F*u[t0][x + 8][y + 7][z + 8] - 1.78571425e-5F*u[t0][x + 8][y + 8][z + 4] + 2.53968248e-4F*u[t0][x + 8][y + 8][z + 5] - 1.99999996e-3F*u[t0][x + 8][y + 8][z + 6] + 1.59999996e-2F*u[t0][x + 8][y + 8][z + 7] - 8.54166647e-2F*u[t0][x + 8][y + 8][z + 8] + 1.59999996e-2F*u[t0][x + 8][y + 8][z + 9] - 1.99999996e-3F*u[t0][x + 8][y + 8][z + 10] + 2.53968248e-4F*u[t0][x + 8][y + 8][z + 11] - 1.78571425e-5F*u[t0][x + 8][y + 8][z + 12] + 1.59999996e-2F*u[t0][x + 8][y + 9][z + 8] - 1.99999996e-3F*u[t0][x + 8][y + 10][z + 8] + 2.53968248e-4F*u[t0][x + 8][y + 11][z + 8] - 1.78571425e-5F*u[t0][x + 8][y + 12][z + 8] + 1.59999996e-2F*u[t0][x + 9][y + 8][z + 8] - 1.99999996e-3F*u[t0][x + 10][y + 8][z + 8] + 2.53968248e-4F*u[t0][x + 11][y + 8][z + 8] - 1.78571425e-5F*u[t0][x + 12][y + 8][z + 8])) + (dt*damp[x + 1][y + 1][z + 1] - 2.0F/pow(vp[x + 8][y + 8][z + 8], 2))*u[t2][x + 8][y + 8][z + 8] + 4.0F*u[t0][x + 8][y + 8][z + 8]/pow(vp[x + 8][y + 8][z + 8], 2))/(dt*damp[x + 1][y + 1][z + 1] + 2.0F/pow(vp[x + 8][y + 8][z + 8], 2)); v[t1][x + 8][y + 8][z + 8] = 1.0F*(2.0F*pow(dt, 2)*(sqrt(2*delta[x + 8][y + 8][z + 8] + 1)*(8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 4][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 5][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 7][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 6][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 6][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 6][y + 10][z + 8])*sin(phi[x + 6][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 6][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 6][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 6][y + 8][z + 10])*cos(theta[x + 6][y + 8][z + 8]))*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) - 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 5][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 6][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 9][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 7][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 7][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 7][y + 10][z + 8])*sin(phi[x + 7][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 7][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 7][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 7][y + 8][z + 10])*cos(theta[x + 7][y + 8][z + 8]))*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 6][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 6][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8])*cos(phi[x + 8][y + 6][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 4][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 5][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 7][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 8])*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 6][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 6][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 6][z + 10])*cos(theta[x + 8][y + 6][z + 8]))*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) - 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 7][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 7][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8])*cos(phi[x + 8][y + 7][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 5][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 6][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 9][z + 8])*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 7][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 7][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 7][z + 10])*cos(theta[x + 8][y + 7][z + 8]))*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 6] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 6] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6])*cos(phi[x + 8][y + 8][z + 6]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 6] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 6] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 6])*sin(phi[x + 8][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 4] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 5] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 7] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 8])*cos(theta[x + 8][y + 8][z + 6]))*cos(theta[x + 8][y + 8][z + 6]) - 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 7] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 7] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7])*cos(phi[x + 8][y + 8][z + 7]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 7] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 7] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 7])*sin(phi[x + 8][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 5] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 6] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 9])*cos(theta[x + 8][y + 8][z + 7]))*cos(theta[x + 8][y + 8][z + 7]) + 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 9] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 9] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9])*cos(phi[x + 8][y + 8][z + 9]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 9] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 9] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 9])*sin(phi[x + 8][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 7] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 10] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 11])*cos(theta[x + 8][y + 8][z + 9]))*cos(theta[x + 8][y + 8][z + 9]) - 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 8][z + 10] - 6.66666677e-2F*u[t0][x + 7][y + 8][z + 10] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 10] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10])*cos(phi[x + 8][y + 8][z + 10]) - (8.33333346e-3F*u[t0][x + 8][y + 6][z + 10] - 6.66666677e-2F*u[t0][x + 8][y + 7][z + 10] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 10] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 10])*sin(phi[x + 8][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 9] + 6.66666677e-2F*u[t0][x + 8][y + 8][z + 11] - 8.33333346e-3F*u[t0][x + 8][y + 8][z + 12])*cos(theta[x + 8][y + 8][z + 10]))*cos(theta[x + 8][y + 8][z + 10]) + 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 6][y + 9][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 9][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8])*cos(phi[x + 8][y + 9][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 7][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 10][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 11][z + 8])*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 9][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 9][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 9][z + 10])*cos(theta[x + 8][y + 9][z + 8]))*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 6][y + 10][z + 8] - 6.66666677e-2F*u[t0][x + 7][y + 10][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 10][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8])*cos(phi[x + 8][y + 10][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 9][z + 8] + 6.66666677e-2F*u[t0][x + 8][y + 11][z + 8] - 8.33333346e-3F*u[t0][x + 8][y + 12][z + 8])*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) - (8.33333346e-3F*u[t0][x + 8][y + 10][z + 6] - 6.66666677e-2F*u[t0][x + 8][y + 10][z + 7] + 6.66666677e-2F*u[t0][x + 8][y + 10][z + 9] - 8.33333346e-3F*u[t0][x + 8][y + 10][z + 10])*cos(theta[x + 8][y + 10][z + 8]))*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) + 6.66666677e-2F*(-(8.33333346e-3F*u[t0][x + 7][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 10][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 11][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 9][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 9][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 9][y + 10][z + 8])*sin(phi[x + 9][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 9][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 9][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 9][y + 8][z + 10])*cos(theta[x + 9][y + 8][z + 8]))*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*u[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*u[t0][x + 9][y + 8][z + 8] + 6.66666677e-2F*u[t0][x + 11][y + 8][z + 8] - 8.33333346e-3F*u[t0][x + 12][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 10][y + 6][z + 8] - 6.66666677e-2F*u[t0][x + 10][y + 7][z + 8] + 6.66666677e-2F*u[t0][x + 10][y + 9][z + 8] - 8.33333346e-3F*u[t0][x + 10][y + 10][z + 8])*sin(phi[x + 10][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8]) - (8.33333346e-3F*u[t0][x + 10][y + 8][z + 6] - 6.66666677e-2F*u[t0][x + 10][y + 8][z + 7] + 6.66666677e-2F*u[t0][x + 10][y + 8][z + 9] - 8.33333346e-3F*u[t0][x + 10][y + 8][z + 10])*cos(theta[x + 10][y + 8][z + 8]))*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8]) - 1.78571425e-5F*u[t0][x + 4][y + 8][z + 8] + 2.53968248e-4F*u[t0][x + 5][y + 8][z + 8] - 1.99999996e-3F*u[t0][x + 6][y + 8][z + 8] + 1.59999996e-2F*u[t0][x + 7][y + 8][z + 8] - 1.78571425e-5F*u[t0][x + 8][y + 4][z + 8] + 2.53968248e-4F*u[t0][x + 8][y + 5][z + 8] - 1.99999996e-3F*u[t0][x + 8][y + 6][z + 8] + 1.59999996e-2F*u[t0][x + 8][y + 7][z + 8] - 1.78571425e-5F*u[t0][x + 8][y + 8][z + 4] + 2.53968248e-4F*u[t0][x + 8][y + 8][z + 5] - 1.99999996e-3F*u[t0][x + 8][y + 8][z + 6] + 1.59999996e-2F*u[t0][x + 8][y + 8][z + 7] - 8.54166647e-2F*u[t0][x + 8][y + 8][z + 8] + 1.59999996e-2F*u[t0][x + 8][y + 8][z + 9] - 1.99999996e-3F*u[t0][x + 8][y + 8][z + 10] + 2.53968248e-4F*u[t0][x + 8][y + 8][z + 11] - 1.78571425e-5F*u[t0][x + 8][y + 8][z + 12] + 1.59999996e-2F*u[t0][x + 8][y + 9][z + 8] - 1.99999996e-3F*u[t0][x + 8][y + 10][z + 8] + 2.53968248e-4F*u[t0][x + 8][y + 11][z + 8] - 1.78571425e-5F*u[t0][x + 8][y + 12][z + 8] + 1.59999996e-2F*u[t0][x + 9][y + 8][z + 8] - 1.99999996e-3F*u[t0][x + 10][y + 8][z + 8] + 2.53968248e-4F*u[t0][x + 11][y + 8][z + 8] - 1.78571425e-5F*u[t0][x + 12][y + 8][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 4][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 5][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 7][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 6][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 6][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 6][y + 10][z + 8])*sin(phi[x + 6][y + 8][z + 8])*sin(theta[x + 6][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 6][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 6][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 6][y + 8][z + 10])*cos(theta[x + 6][y + 8][z + 8]))*sin(theta[x + 6][y + 8][z + 8])*cos(phi[x + 6][y + 8][z + 8]) + 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 5][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 6][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 9][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 7][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 7][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 7][y + 10][z + 8])*sin(phi[x + 7][y + 8][z + 8])*sin(theta[x + 7][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 7][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 7][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 7][y + 8][z + 10])*cos(theta[x + 7][y + 8][z + 8]))*sin(theta[x + 7][y + 8][z + 8])*cos(phi[x + 7][y + 8][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 6][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 6][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8])*cos(phi[x + 8][y + 6][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 4][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 5][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 7][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 8])*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 6][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 6][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 6][z + 10])*cos(theta[x + 8][y + 6][z + 8]))*sin(phi[x + 8][y + 6][z + 8])*sin(theta[x + 8][y + 6][z + 8]) + 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 7][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 7][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8])*cos(phi[x + 8][y + 7][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 5][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 6][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 9][z + 8])*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 7][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 7][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 7][z + 10])*cos(theta[x + 8][y + 7][z + 8]))*sin(phi[x + 8][y + 7][z + 8])*sin(theta[x + 8][y + 7][z + 8]) - 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 6] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 6] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6])*cos(phi[x + 8][y + 8][z + 6]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 6] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 6] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 6])*sin(phi[x + 8][y + 8][z + 6])*sin(theta[x + 8][y + 8][z + 6]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 4] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 5] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 7] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 8])*cos(theta[x + 8][y + 8][z + 6]))*cos(theta[x + 8][y + 8][z + 6]) + 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 7] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 7] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7])*cos(phi[x + 8][y + 8][z + 7]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 7] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 7] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 7])*sin(phi[x + 8][y + 8][z + 7])*sin(theta[x + 8][y + 8][z + 7]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 5] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 6] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 9])*cos(theta[x + 8][y + 8][z + 7]))*cos(theta[x + 8][y + 8][z + 7]) - 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 9] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 9] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9])*cos(phi[x + 8][y + 8][z + 9]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 9] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 9] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 9])*sin(phi[x + 8][y + 8][z + 9])*sin(theta[x + 8][y + 8][z + 9]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 7] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 10] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 11])*cos(theta[x + 8][y + 8][z + 9]))*cos(theta[x + 8][y + 8][z + 9]) + 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 8][z + 10] - 6.66666677e-2F*v[t0][x + 7][y + 8][z + 10] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 10] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10])*cos(phi[x + 8][y + 8][z + 10]) - (8.33333346e-3F*v[t0][x + 8][y + 6][z + 10] - 6.66666677e-2F*v[t0][x + 8][y + 7][z + 10] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 10] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 10])*sin(phi[x + 8][y + 8][z + 10])*sin(theta[x + 8][y + 8][z + 10]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 9] + 6.66666677e-2F*v[t0][x + 8][y + 8][z + 11] - 8.33333346e-3F*v[t0][x + 8][y + 8][z + 12])*cos(theta[x + 8][y + 8][z + 10]))*cos(theta[x + 8][y + 8][z + 10]) - 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 6][y + 9][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 9][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8])*cos(phi[x + 8][y + 9][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 7][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 10][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 11][z + 8])*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 9][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 9][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 9][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 9][z + 10])*cos(theta[x + 8][y + 9][z + 8]))*sin(phi[x + 8][y + 9][z + 8])*sin(theta[x + 8][y + 9][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 6][y + 10][z + 8] - 6.66666677e-2F*v[t0][x + 7][y + 10][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 10][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8])*cos(phi[x + 8][y + 10][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 9][z + 8] + 6.66666677e-2F*v[t0][x + 8][y + 11][z + 8] - 8.33333346e-3F*v[t0][x + 8][y + 12][z + 8])*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) - (8.33333346e-3F*v[t0][x + 8][y + 10][z + 6] - 6.66666677e-2F*v[t0][x + 8][y + 10][z + 7] + 6.66666677e-2F*v[t0][x + 8][y + 10][z + 9] - 8.33333346e-3F*v[t0][x + 8][y + 10][z + 10])*cos(theta[x + 8][y + 10][z + 8]))*sin(phi[x + 8][y + 10][z + 8])*sin(theta[x + 8][y + 10][z + 8]) - 6.66666677e-2F*(-(8.33333346e-3F*v[t0][x + 7][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 8][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 10][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 11][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 9][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 9][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 9][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 9][y + 10][z + 8])*sin(phi[x + 9][y + 8][z + 8])*sin(theta[x + 9][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 9][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 9][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 9][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 9][y + 8][z + 10])*cos(theta[x + 9][y + 8][z + 8]))*sin(theta[x + 9][y + 8][z + 8])*cos(phi[x + 9][y + 8][z + 8]) + 8.33333346e-3F*(-(8.33333346e-3F*v[t0][x + 8][y + 8][z + 8] - 6.66666677e-2F*v[t0][x + 9][y + 8][z + 8] + 6.66666677e-2F*v[t0][x + 11][y + 8][z + 8] - 8.33333346e-3F*v[t0][x + 12][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 10][y + 6][z + 8] - 6.66666677e-2F*v[t0][x + 10][y + 7][z + 8] + 6.66666677e-2F*v[t0][x + 10][y + 9][z + 8] - 8.33333346e-3F*v[t0][x + 10][y + 10][z + 8])*sin(phi[x + 10][y + 8][z + 8])*sin(theta[x + 10][y + 8][z + 8]) - (8.33333346e-3F*v[t0][x + 10][y + 8][z + 6] - 6.66666677e-2F*v[t0][x + 10][y + 8][z + 7] + 6.66666677e-2F*v[t0][x + 10][y + 8][z + 9] - 8.33333346e-3F*v[t0][x + 10][y + 8][z + 10])*cos(theta[x + 10][y + 8][z + 8]))*sin(theta[x + 10][y + 8][z + 8])*cos(phi[x + 10][y + 8][z + 8])) + (dt*damp[x + 1][y + 1][z + 1] - 2.0F/pow(vp[x + 8][y + 8][z + 8], 2))*v[t2][x + 8][y + 8][z + 8] + 4.0F*v[t0][x + 8][y + 8][z + 8]/pow(vp[x + 8][y + 8][z + 8], 2))/(dt*damp[x + 1][y + 1][z + 1] + 2.0F/pow(vp[x + 8][y + 8][z + 8], 2)); } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec-start_section0.tv_sec)+(double)(end_section0.tv_usec-start_section0.tv_usec)/1000000; struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ #pragma omp parallel num_threads(nthreads_nonaffine) { int chunk_size = (int)(fmax(1, (1.0F/3.0F)*(p_src_M - p_src_m + 1)/nthreads_nonaffine)); #pragma omp for collapse(1) schedule(dynamic,chunk_size) for (int p_src = p_src_m; p_src <= p_src_M; p_src += 1) { int ii_src_0 = (int)(floor(-1.0e-1*o_x + 1.0e-1*src_coords[p_src][0])); int ii_src_1 = (int)(floor(-1.0e-1*o_y + 1.0e-1*src_coords[p_src][1])); int ii_src_2 = (int)(floor(-1.0e-1*o_z + 1.0e-1*src_coords[p_src][2])); int ii_src_3 = (int)(floor(-1.0e-1*o_z + 1.0e-1*src_coords[p_src][2])) + 1; int ii_src_4 = (int)(floor(-1.0e-1*o_y + 1.0e-1*src_coords[p_src][1])) + 1; int ii_src_5 = (int)(floor(-1.0e-1*o_x + 1.0e-1*src_coords[p_src][0])) + 1; float px = (float)(-o_x - 1.0e+1F*(int)(floor(-1.0e-1F*o_x + 1.0e-1F*src_coords[p_src][0])) + src_coords[p_src][0]); float py = (float)(-o_y - 1.0e+1F*(int)(floor(-1.0e-1F*o_y + 1.0e-1F*src_coords[p_src][1])) + src_coords[p_src][1]); float pz = (float)(-o_z - 1.0e+1F*(int)(floor(-1.0e-1F*o_z + 1.0e-1F*src_coords[p_src][2])) + src_coords[p_src][2]); if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1) { u[t1][ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*px*py + 1.0e-2F*px*pz - 1.0e-1F*px + 1.0e-2F*py*pz - 1.0e-1F*py - 1.0e-1F*pz + 1)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8], 2); } if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1) { u[t1][ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] += pow(dt, 2)*(1.0e-3F*px*py*pz - 1.0e-2F*px*pz - 1.0e-2F*py*pz + 1.0e-1F*pz)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8], 2); } if (ii_src_0 >= x_m - 1 && ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1) { u[t1][ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] += pow(dt, 2)*(1.0e-3F*px*py*pz - 1.0e-2F*px*py - 1.0e-2F*py*pz + 1.0e-1F*py)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8], 2); } if (ii_src_0 >= x_m - 1 && ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1) { u[t1][ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*py*pz)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8], 2); } if (ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1 && ii_src_5 <= x_M + 1) { u[t1][ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] += pow(dt, 2)*(1.0e-3F*px*py*pz - 1.0e-2F*px*py - 1.0e-2F*px*pz + 1.0e-1F*px)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8], 2); } if (ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1 && ii_src_5 <= x_M + 1) { u[t1][ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*px*pz)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8], 2); } if (ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { u[t1][ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*px*py)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8], 2); } if (ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { u[t1][ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] += 1.0e-3F*px*py*pz*pow(dt, 2)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8], 2); } ii_src_0 = (int)(floor(-1.0e-1*o_x + 1.0e-1*src_coords[p_src][0])); ii_src_1 = (int)(floor(-1.0e-1*o_y + 1.0e-1*src_coords[p_src][1])); ii_src_2 = (int)(floor(-1.0e-1*o_z + 1.0e-1*src_coords[p_src][2])); ii_src_3 = (int)(floor(-1.0e-1*o_z + 1.0e-1*src_coords[p_src][2])) + 1; ii_src_4 = (int)(floor(-1.0e-1*o_y + 1.0e-1*src_coords[p_src][1])) + 1; ii_src_5 = (int)(floor(-1.0e-1*o_x + 1.0e-1*src_coords[p_src][0])) + 1; px = (float)(-o_x - 1.0e+1F*(int)(floor(-1.0e-1F*o_x + 1.0e-1F*src_coords[p_src][0])) + src_coords[p_src][0]); py = (float)(-o_y - 1.0e+1F*(int)(floor(-1.0e-1F*o_y + 1.0e-1F*src_coords[p_src][1])) + src_coords[p_src][1]); pz = (float)(-o_z - 1.0e+1F*(int)(floor(-1.0e-1F*o_z + 1.0e-1F*src_coords[p_src][2])) + src_coords[p_src][2]); if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1) { v[t1][ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*px*py + 1.0e-2F*px*pz - 1.0e-1F*px + 1.0e-2F*py*pz - 1.0e-1F*py - 1.0e-1F*pz + 1)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8], 2); } if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1) { v[t1][ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] += pow(dt, 2)*(1.0e-3F*px*py*pz - 1.0e-2F*px*pz - 1.0e-2F*py*pz + 1.0e-1F*pz)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8], 2); } if (ii_src_0 >= x_m - 1 && ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1) { v[t1][ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] += pow(dt, 2)*(1.0e-3F*px*py*pz - 1.0e-2F*px*py - 1.0e-2F*py*pz + 1.0e-1F*py)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8], 2); } if (ii_src_0 >= x_m - 1 && ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1) { v[t1][ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*py*pz)*src[time][p_src]*pow(vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8], 2); } if (ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1 && ii_src_5 <= x_M + 1) { v[t1][ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] += pow(dt, 2)*(1.0e-3F*px*py*pz - 1.0e-2F*px*py - 1.0e-2F*px*pz + 1.0e-1F*px)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8], 2); } if (ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1 && ii_src_5 <= x_M + 1) { v[t1][ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*px*pz)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8], 2); } if (ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { v[t1][ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] += pow(dt, 2)*(-1.0e-3F*px*py*pz + 1.0e-2F*px*py)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8], 2); } if (ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { v[t1][ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] += 1.0e-3F*px*py*pz*pow(dt, 2)*src[time][p_src]*pow(vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8], 2); } } } /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec-start_section1.tv_sec)+(double)(end_section1.tv_usec-start_section1.tv_usec)/1000000; struct timeval start_section2, end_section2; gettimeofday(&start_section2, NULL); /* Begin section2 */ #pragma omp parallel num_threads(nthreads_nonaffine) { int chunk_size = (int)(fmax(1, (1.0F/3.0F)*(p_rec_M - p_rec_m + 1)/nthreads_nonaffine)); #pragma omp for collapse(1) schedule(dynamic,chunk_size) for (int p_rec = p_rec_m; p_rec <= p_rec_M; p_rec += 1) { int ii_rec_0 = (int)(floor(-1.0e-1*o_x + 1.0e-1*rec_coords[p_rec][0])); int ii_rec_1 = (int)(floor(-1.0e-1*o_y + 1.0e-1*rec_coords[p_rec][1])); int ii_rec_2 = (int)(floor(-1.0e-1*o_z + 1.0e-1*rec_coords[p_rec][2])); int ii_rec_3 = (int)(floor(-1.0e-1*o_z + 1.0e-1*rec_coords[p_rec][2])) + 1; int ii_rec_4 = (int)(floor(-1.0e-1*o_y + 1.0e-1*rec_coords[p_rec][1])) + 1; int ii_rec_5 = (int)(floor(-1.0e-1*o_x + 1.0e-1*rec_coords[p_rec][0])) + 1; float px = (float)(-o_x - 1.0e+1F*(int)(floor(-1.0e-1F*o_x + 1.0e-1F*rec_coords[p_rec][0])) + rec_coords[p_rec][0]); float py = (float)(-o_y - 1.0e+1F*(int)(floor(-1.0e-1F*o_y + 1.0e-1F*rec_coords[p_rec][1])) + rec_coords[p_rec][1]); float pz = (float)(-o_z - 1.0e+1F*(int)(floor(-1.0e-1F*o_z + 1.0e-1F*rec_coords[p_rec][2])) + rec_coords[p_rec][2]); float sum = 0.0F; if (ii_rec_0 >= x_m - 1 && ii_rec_1 >= y_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_1 <= y_M + 1 && ii_rec_2 <= z_M + 1) { sum += (u[t0][ii_rec_0 + 8][ii_rec_1 + 8][ii_rec_2 + 8] + v[t0][ii_rec_0 + 8][ii_rec_1 + 8][ii_rec_2 + 8])*(-1.0e-3F*px*py*pz + 1.0e-2F*px*py + 1.0e-2F*px*pz - 1.0e-1F*px + 1.0e-2F*py*pz - 1.0e-1F*py - 1.0e-1F*pz + 1); } if (ii_rec_0 >= x_m - 1 && ii_rec_1 >= y_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_1 <= y_M + 1 && ii_rec_3 <= z_M + 1) { sum += (u[t0][ii_rec_0 + 8][ii_rec_1 + 8][ii_rec_3 + 8] + v[t0][ii_rec_0 + 8][ii_rec_1 + 8][ii_rec_3 + 8])*(1.0e-3F*px*py*pz - 1.0e-2F*px*pz - 1.0e-2F*py*pz + 1.0e-1F*pz); } if (ii_rec_0 >= x_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_2 <= z_M + 1 && ii_rec_4 <= y_M + 1) { sum += (u[t0][ii_rec_0 + 8][ii_rec_4 + 8][ii_rec_2 + 8] + v[t0][ii_rec_0 + 8][ii_rec_4 + 8][ii_rec_2 + 8])*(1.0e-3F*px*py*pz - 1.0e-2F*px*py - 1.0e-2F*py*pz + 1.0e-1F*py); } if (ii_rec_0 >= x_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_3 <= z_M + 1 && ii_rec_4 <= y_M + 1) { sum += (-1.0e-3F*px*py*pz + 1.0e-2F*py*pz)*(u[t0][ii_rec_0 + 8][ii_rec_4 + 8][ii_rec_3 + 8] + v[t0][ii_rec_0 + 8][ii_rec_4 + 8][ii_rec_3 + 8]); } if (ii_rec_1 >= y_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_1 <= y_M + 1 && ii_rec_2 <= z_M + 1 && ii_rec_5 <= x_M + 1) { sum += (u[t0][ii_rec_5 + 8][ii_rec_1 + 8][ii_rec_2 + 8] + v[t0][ii_rec_5 + 8][ii_rec_1 + 8][ii_rec_2 + 8])*(1.0e-3F*px*py*pz - 1.0e-2F*px*py - 1.0e-2F*px*pz + 1.0e-1F*px); } if (ii_rec_1 >= y_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_1 <= y_M + 1 && ii_rec_3 <= z_M + 1 && ii_rec_5 <= x_M + 1) { sum += (-1.0e-3F*px*py*pz + 1.0e-2F*px*pz)*(u[t0][ii_rec_5 + 8][ii_rec_1 + 8][ii_rec_3 + 8] + v[t0][ii_rec_5 + 8][ii_rec_1 + 8][ii_rec_3 + 8]); } if (ii_rec_2 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_2 <= z_M + 1 && ii_rec_4 <= y_M + 1 && ii_rec_5 <= x_M + 1) { sum += (-1.0e-3F*px*py*pz + 1.0e-2F*px*py)*(u[t0][ii_rec_5 + 8][ii_rec_4 + 8][ii_rec_2 + 8] + v[t0][ii_rec_5 + 8][ii_rec_4 + 8][ii_rec_2 + 8]); } if (ii_rec_3 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_3 <= z_M + 1 && ii_rec_4 <= y_M + 1 && ii_rec_5 <= x_M + 1) { sum += 1.0e-3F*px*py*pz*(u[t0][ii_rec_5 + 8][ii_rec_4 + 8][ii_rec_3 + 8] + v[t0][ii_rec_5 + 8][ii_rec_4 + 8][ii_rec_3 + 8]); } rec[time][p_rec] = sum; } } /* End section2 */ gettimeofday(&end_section2, NULL); timers->section2 += (double)(end_section2.tv_sec-start_section2.tv_sec)+(double)(end_section2.tv_usec-start_section2.tv_usec)/1000000; } return 0; }
yuv_to_rgb.c
/* * YUV to RGB convert * * Copyright (C) 2019 Hiroshi Kuwagata <kgt9221@gamil.com> */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #ifdef ENABLE_NEON #if defined(__ARM_NEON) || defined(__ARM_NEON__) #include <arm_neon.h> #else /* defined(__ARM_NEON) || defined(__ARM_NEON__) */ #error "ARM NEON instruction is not supported." #endif /* defined(__ARM_NEON) || defined(__ARM_NEON__) */ #endif /* defined(ENABLE_NEON) */ #ifdef ENABLE_SSE2 #if defined(__SSE2__) #if defined(_MSC_VER) #include <intrin.h> #elif defined(__GNUC__) #include <x86intrin.h> #endif /* defined(*) */ #else /* defined(__SSE2__) */ #error "SSE2 instruction is not supported." #endif /* defined(__SSE2__) */ #endif /* defined(ENABLE_SSE2) */ #define SATURATE8(x) (uint8_t)(((x) < 0)? 0:(((x) > 255)? 255:(x))) #ifdef ENABLE_NEON void i420_to_rgb(uint8_t* _y, uint8_t* _u, uint8_t* _v, int wd, int ht, uint8_t* _d) { /* * 2x2ピクセルを1ユニットとして処理する。 * ピクセルに対するレジスタのレーン配置は以下の通り。 * * 0 1 * 2 3 * * YUVからRGBへの変換式は以下の通り * * R = (1.164f * (y - 16)) + (1.596f * (v - 128)) * G = (1.164f * (y - 16)) - (0.813f * (v - 128)) - (0.391f * (u - 128)) * B = (1.164f * (y - 16)) + (2.018f * (u - 128)) * * 上記を、整数演算化による高速化を狙って以下の様に実装する。 * * R = ((1192 * (y - 16)) + (1634 * (v - 128))) >> 10 * G = ((1192 * (y - 16)) - ( 833 * (v - 128)) - (400 * (u - 128))) >> 10 * B = ((1192 * (y - 16)) + (2066 * (u - 128))) >> 10 * */ int i; int j; int32x4_t c16; int32x4_t min; int32x4_t max; c16 = vmovq_n_s32(16); min = vmovq_n_s32(0); max = vmovq_n_s32(255); #pragma omp parallel for private(j) shared(c16,min,max) for (i = 0; i < ht; i += 2) { uint8_t* y1; uint8_t* y2; uint8_t* u; uint8_t* v; uint8_t* d1; uint8_t* d2; int32x4_t tl; // as "temporary for load" int32x4_t vy; int32x4_t vr; int32x4_t vg; int32x4_t vb; y1 = _y + (i * wd); y2 = y1 + wd; u = _u + ((i / 2) * (wd / 2)); v = _v + ((i / 2) * (wd / 2)); d1 = _d + (i * (wd * 3)); d2 = d1 + (wd * 3); for (j = 0; j < wd; j += 2) { /* * Y */ tl = vsetq_lane_s32(y1[0], tl, 0); tl = vsetq_lane_s32(y1[1], tl, 1); tl = vsetq_lane_s32(y2[0], tl, 2); tl = vsetq_lane_s32(y2[1], tl, 3); tl = vsubq_s32(tl, c16); vy = vmulq_n_s32(tl, 1192); /* * U */ tl = vmovq_n_s32(u[0] - 128); vg = vmlsq_n_s32(vy, tl, 400); vb = vmlaq_n_s32(vy, tl, 2066); /* * V */ tl = vmovq_n_s32(v[0] - 128); vr = vmlaq_n_s32(vy, tl, 1634); vg = vmlsq_n_s32(vg, tl, 833); /* * スケールの戻しと飽和処理 */ vr = vshrq_n_s32(vr, 10); vr = vmaxq_s32(vr, min); vr = vminq_s32(vr, max); vg = vshrq_n_s32(vg, 10); vg = vmaxq_s32(vg, min); vg = vminq_s32(vg, max); vb = vshrq_n_s32(vb, 10); vb = vmaxq_s32(vb, min); vb = vminq_s32(vb, max); /* * output RGB pixels */ d1[0] = vgetq_lane_s32(vr, 0); d1[1] = vgetq_lane_s32(vg, 0); d1[2] = vgetq_lane_s32(vb, 0); d1[3] = vgetq_lane_s32(vr, 1); d1[4] = vgetq_lane_s32(vg, 1); d1[5] = vgetq_lane_s32(vb, 1); d2[0] = vgetq_lane_s32(vr, 2); d2[1] = vgetq_lane_s32(vg, 2); d2[2] = vgetq_lane_s32(vb, 2); d2[3] = vgetq_lane_s32(vr, 3); d2[4] = vgetq_lane_s32(vg, 3); d2[5] = vgetq_lane_s32(vb, 3); /* * increase pointers */ y1 += 2; y2 += 2; u += 1; v += 1; d1 += 6; d2 += 6; } } } #else /* defined(__ARM_NEON) || defined(__ARM_NEON__) */ void i420_to_rgb(uint8_t* _y, uint8_t* _u, uint8_t* _v, int wd, int ht, uint8_t* _d) { /* * 2x2ピクセルを1ユニットとして処理する。 * ピクセルに対するレジスタのレーン配置は以下の通り。 * * 0 1 * 2 3 * * YUVからRGBへの変換式は以下の通り * * R = (1.164f * (y - 16)) + (1.596f * (v - 128)) * G = (1.164f * (y - 16)) - (0.813f * (v - 128)) - (0.391f * (u - 128)) * B = (1.164f * (y - 16)) + (2.018f * (u - 128)) * * 上記を、整数演算化による高速化を狙って以下の様に実装する。 * * R = ((1192 * (y - 16)) + (1634 * (v - 128))) >> 10 * G = ((1192 * (y - 16)) - ( 833 * (v - 128)) - (400 * (u - 128))) >> 10 * B = ((1192 * (y - 16)) + (2066 * (u - 128))) >> 10 */ int i; int j; #pragma omp parallel for private(j) for (i = 0; i < ht; i += 2) { uint8_t* y1; uint8_t* y2; uint8_t* u; uint8_t* v; uint8_t* d1; uint8_t* d2; int c; int d; int e; int r0; int g0; int b0; int r; int g; int b; y1 = _y + (i * wd); y2 = y1 + wd; u = _u + ((i / 2) * (wd / 2)); v = _v + ((i / 2) * (wd / 2)); d1 = _d + (i * (wd * 3)); d2 = d1 + (wd * 3); for (j = 0; j < wd; j += 2) { d = ((int)u[0]) - 128; e = ((int)v[0]) - 128; r0 = (e * 1634); g0 = (d * 400) + (e * 833); b0 = (d * 2066); /* * 0,0 */ c = (((int)y1[0]) - 16) * 1192; r = (c + r0) >> 10; g = (c - g0) >> 10; b = (c + b0) >> 10; d1[0] = SATURATE8(r); d1[1] = SATURATE8(g); d1[2] = SATURATE8(b); /* * 0,1 */ c = (((int)y1[1]) - 16) * 1192; r = (c + r0) >> 10; g = (c - g0) >> 10; b = (c + b0) >> 10; d1[3] = SATURATE8(r); d1[4] = SATURATE8(g); d1[5] = SATURATE8(b); /* * 1,0 */ c = (((int)y2[0]) - 16) * 1192; r = (c + r0) >> 10; g = (c - g0) >> 10; b = (c + b0) >> 10; d2[0] = SATURATE8(r); d2[1] = SATURATE8(g); d2[2] = SATURATE8(b); /* * 1,1 */ c = (((int)y2[1]) - 16) * 1192; r = (c + r0) >> 10; g = (c - g0) >> 10; b = (c + b0) >> 10; d2[3] = SATURATE8(r); d2[4] = SATURATE8(g); d2[5] = SATURATE8(b); /* * increase pointers */ y1 += 2; y2 += 2; u += 1; v += 1; d1 += 6; d2 += 6; } } } #endif /* defined(__ARM_NEON) || defined(__ARM_NEON__) */
for_loop.c
// RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s // REQUIRES: ompt // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8 #include "callback.h" #include <omp.h> int main() { int y[] = {0,1,2,3}; #pragma omp parallel num_threads(2) { //implicit barrier at end of for loop int i; #pragma omp for for (i = 0; i < 4; i++) { y[i]++; } print_current_address(); } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_sync_region' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_sync_region_wait' // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // master thread implicit barrier at loop end // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // master thread implicit barrier at parallel end // CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // worker thread explicit barrier // CHECK: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: ompt_event_wait_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: ompt_event_wait_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // worker thread implicit barrier after parallel // CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: ompt_event_wait_barrier_begin: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}} // CHECK: {{^}}[[THREAD_ID]]: ompt_event_wait_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra=[[NULL]] // CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: parallel_id={{[0-9]+}}, task_id={{[0-9]+}}, codeptr_ra=[[NULL]] return 0; }
gemm.c
#include "gemm.h" #include "utils.h" #include "cuda.h" #include <stdlib.h> #include <stdio.h> #include <math.h> void gemm_bin(int M, int N, int K, float ALPHA, char *A, int lda, float *B, int ldb, float *C, int ldc) { int i,j,k; for(i = 0; i < M; ++i){ for(k = 0; k < K; ++k){ char A_PART = A[i*lda+k]; if(A_PART){ for(j = 0; j < N; ++j){ C[i*ldc+j] += B[k*ldb+j]; } } else { for(j = 0; j < N; ++j){ C[i*ldc+j] -= B[k*ldb+j]; } } } } } float *random_matrix(int rows, int cols) { int i; float *m = calloc(rows*cols, sizeof(float)); for(i = 0; i < rows*cols; ++i){ m[i] = (float)rand()/RAND_MAX; } return m; } void time_random_matrix(int TA, int TB, int m, int k, int n) { float *a; if(!TA) a = random_matrix(m,k); else a = random_matrix(k,m); int lda = (!TA)?k:m; float *b; if(!TB) b = random_matrix(k,n); else b = random_matrix(n,k); int ldb = (!TB)?n:k; float *c = random_matrix(m,n); int i; clock_t start = clock(), end; for(i = 0; i<10; ++i){ gemm_cpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n); } end = clock(); printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf ms\n",m,k,k,n, TA, TB, (float)(end-start)/CLOCKS_PER_SEC); free(a); free(b); free(c); } void gemm(int TA, int TB, int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float BETA, float *C, int ldc) { gemm_cpu( TA, TB, M, N, K, ALPHA,A,lda, B, ldb,BETA,C,ldc); } void gemm_nn(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i,j,k; for(i = 0; i < M; ++i){ for(k = 0; k < K; ++k){ register float A_PART = ALPHA*A[i*lda+k]; for(j = 0; j < N; ++j){ C[i*ldc+j] += A_PART*B[k*ldb+j]; } } } } void gemm_nt(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i,j,k; for(i = 0; i < M; ++i){ for(j = 0; j < N; ++j){ register float sum = 0; for(k = 0; k < K; ++k){ sum += ALPHA*A[i*lda+k]*B[j*ldb + k]; } C[i*ldc+j] += sum; } } } void gemm_tn(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i,j,k; for(i = 0; i < M; ++i){ for(k = 0; k < K; ++k){ register float A_PART = ALPHA*A[k*lda+i]; for(j = 0; j < N; ++j){ C[i*ldc+j] += A_PART*B[k*ldb+j]; } } } } void gemm_tt(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i,j,k; for(i = 0; i < M; ++i){ for(j = 0; j < N; ++j){ register float sum = 0; for(k = 0; k < K; ++k){ sum += ALPHA*A[i+k*lda]*B[k+j*ldb]; } C[i*ldc+j] += sum; } } } void gemm_cpu(int TA, int TB, int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float BETA, float *C, int ldc) { //printf("cpu: %d %d %d %d %d %f %d %d %f %d\n",TA, TB, M, N, K, ALPHA, lda, ldb, BETA, ldc); int i, j; for(i = 0; i < M; ++i){ for(j = 0; j < N; ++j){ C[i*ldc + j] *= BETA; } } int t; #pragma omp parallel for for (t = 0; t < M; ++t) { if (!TA && !TB) gemm_nn(1, N, K, ALPHA, A + t*lda, lda, B, ldb, C + t*ldc, ldc); else if (TA && !TB) gemm_tn(1, N, K, ALPHA, A + t, lda, B, ldb, C + t*ldc, ldc); else if (!TA && TB) gemm_nt(1, N, K, ALPHA, A + t*lda, lda, B, ldb, C + t*ldc, ldc); else gemm_tt(1, N, K, ALPHA, A + t, lda, B, ldb, C + t*ldc, ldc); } } #ifdef GPU #include <math.h> void gemm_ongpu(int TA, int TB, int M, int N, int K, float ALPHA, float *A_gpu, int lda, float *B_gpu, int ldb, float BETA, float *C_gpu, int ldc) { cublasHandle_t handle = blas_handle(); cudaError_t stream_status = cublasSetStream(handle, get_cuda_stream()); cudaError_t status = cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N), (TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb, A_gpu, lda, &BETA, C_gpu, ldc); check_error(status); } void gemm_gpu(int TA, int TB, int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float BETA, float *C, int ldc) { float *A_gpu = cuda_make_array(A, (TA ? lda*K:lda*M)); float *B_gpu = cuda_make_array(B, (TB ? ldb*N : ldb*K)); float *C_gpu = cuda_make_array(C, ldc*M); gemm_ongpu(TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc); cuda_pull_array(C_gpu, C, ldc*M); cuda_free(A_gpu); cuda_free(B_gpu); cuda_free(C_gpu); } #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> void time_gpu_random_matrix(int TA, int TB, int m, int k, int n) { float *a; if(!TA) a = random_matrix(m,k); else a = random_matrix(k,m); int lda = (!TA)?k:m; float *b; if(!TB) b = random_matrix(k,n); else b = random_matrix(n,k); int ldb = (!TB)?n:k; float *c = random_matrix(m,n); int i; clock_t start = clock(), end; for(i = 0; i<32; ++i){ gemm_gpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n); } end = clock(); printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s\n",m,k,k,n, TA, TB, (float)(end-start)/CLOCKS_PER_SEC); free(a); free(b); free(c); } void time_ongpu(int TA, int TB, int m, int k, int n) { int iter = 10; float *a = random_matrix(m,k); float *b = random_matrix(k,n); int lda = (!TA)?k:m; int ldb = (!TB)?n:k; float *c = random_matrix(m,n); float *a_cl = cuda_make_array(a, m*k); float *b_cl = cuda_make_array(b, k*n); float *c_cl = cuda_make_array(c, m*n); int i; clock_t start = clock(), end; for(i = 0; i<iter; ++i){ gemm_ongpu(TA,TB,m,n,k,1,a_cl,lda,b_cl,ldb,1,c_cl,n); cudaThreadSynchronize(); } double flop = ((double)m)*n*(2.*k + 2.)*iter; double gflop = flop/pow(10., 9); end = clock(); double seconds = sec(end-start); printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s, %lf GFLOPS\n",m,k,k,n, TA, TB, seconds, gflop/seconds); cuda_free(a_cl); cuda_free(b_cl); cuda_free(c_cl); free(a); free(b); free(c); } void test_gpu_accuracy(int TA, int TB, int m, int k, int n) { srand(0); float *a; if(!TA) a = random_matrix(m,k); else a = random_matrix(k,m); int lda = (!TA)?k:m; float *b; if(!TB) b = random_matrix(k,n); else b = random_matrix(n,k); int ldb = (!TB)?n:k; float *c = random_matrix(m,n); float *c_gpu = random_matrix(m,n); memset(c, 0, m*n*sizeof(float)); memset(c_gpu, 0, m*n*sizeof(float)); int i; //pm(m,k,b); gemm_gpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c_gpu,n); //printf("GPU\n"); //pm(m, n, c_gpu); gemm_cpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n); //printf("\n\nCPU\n"); //pm(m, n, c); double sse = 0; for(i = 0; i < m*n; ++i) { //printf("%f %f\n", c[i], c_gpu[i]); sse += pow(c[i]-c_gpu[i], 2); } printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %g SSE\n",m,k,k,n, TA, TB, sse/(m*n)); free(a); free(b); free(c); free(c_gpu); } int test_gpu_blas() { /* test_gpu_accuracy(0,0,10,576,75); test_gpu_accuracy(0,0,17,10,10); test_gpu_accuracy(1,0,17,10,10); test_gpu_accuracy(0,1,17,10,10); test_gpu_accuracy(1,1,17,10,10); test_gpu_accuracy(0,0,1000,10,100); test_gpu_accuracy(1,0,1000,10,100); test_gpu_accuracy(0,1,1000,10,100); test_gpu_accuracy(1,1,1000,10,100); test_gpu_accuracy(0,0,10,10,10); time_ongpu(0,0,64,2916,363); time_ongpu(0,0,64,2916,363); time_ongpu(0,0,64,2916,363); time_ongpu(0,0,192,729,1600); time_ongpu(0,0,384,196,1728); time_ongpu(0,0,256,196,3456); time_ongpu(0,0,256,196,2304); time_ongpu(0,0,128,4096,12544); time_ongpu(0,0,128,4096,4096); */ time_ongpu(0,0,64,75,12544); time_ongpu(0,0,64,75,12544); time_ongpu(0,0,64,75,12544); time_ongpu(0,0,64,576,12544); time_ongpu(0,0,256,2304,784); time_ongpu(1,1,2304,256,784); time_ongpu(0,0,512,4608,196); time_ongpu(1,1,4608,512,196); return 0; } #endif
pbvh.c
/* * $Id: pbvh.c 40539 2011-09-25 12:33:51Z ender79 $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/blenlib/intern/pbvh.c * \ingroup bli */ #include "DNA_meshdata_types.h" #include "MEM_guardedalloc.h" #include "BLI_math.h" #include "BLI_utildefines.h" #include "BLI_ghash.h" #include "BLI_pbvh.h" #include "BKE_DerivedMesh.h" #include "BKE_mesh.h" /* for mesh_calc_normals */ #include "BKE_global.h" /* for mesh_calc_normals */ #include "GPU_buffers.h" #define LEAF_LIMIT 10000 //#define PERFCNTRS /* Bitmap */ typedef char* BLI_bitmap; static BLI_bitmap BLI_bitmap_new(int tot) { return MEM_callocN((tot >> 3) + 1, "BLI bitmap"); } static int BLI_bitmap_get(BLI_bitmap b, int index) { return b[index >> 3] & (1 << (index & 7)); } static void BLI_bitmap_set(BLI_bitmap b, int index) { b[index >> 3] |= (1 << (index & 7)); } #if 0 /* UNUSED */ static void BLI_bitmap_clear(BLI_bitmap b, int index) { b[index >> 3] &= ~(1 << (index & 7)); } #endif /* Axis-aligned bounding box */ typedef struct { float bmin[3], bmax[3]; } BB; /* Axis-aligned bounding box with centroid */ typedef struct { float bmin[3], bmax[3], bcentroid[3]; } BBC; struct PBVHNode { /* Opaque handle for drawing code */ void *draw_buffers; /* Voxel bounds */ BB vb; BB orig_vb; /* For internal nodes, the offset of the children in the PBVH 'nodes' array. */ int children_offset; /* Pointer into the PBVH prim_indices array and the number of primitives used by this leaf node. Used for leaf nodes in both mesh- and multires-based PBVHs. */ int *prim_indices; unsigned int totprim; /* Array of indices into the mesh's MVert array. Contains the indices of all vertices used by faces that are within this node's bounding box. Note that a vertex might be used by a multiple faces, and these faces might be in different leaf nodes. Such a vertex will appear in the vert_indices array of each of those leaf nodes. In order to support cases where you want access to multiple nodes' vertices without duplication, the vert_indices array is ordered such that the first part of the array, up to index 'uniq_verts', contains "unique" vertex indices. These vertices might not be truly unique to this node, but if they appear in another node's vert_indices array, they will be above that node's 'uniq_verts' value. Used for leaf nodes in a mesh-based PBVH (not multires.) */ int *vert_indices; unsigned int uniq_verts, face_verts; /* An array mapping face corners into the vert_indices array. The array is sized to match 'totprim', and each of the face's corners gets an index into the vert_indices array, in the same order as the corners in the original MFace. The fourth value should not be used if the original face is a triangle. Used for leaf nodes in a mesh-based PBVH (not multires.) */ int (*face_vert_indices)[4]; /* Indicates whether this node is a leaf or not; also used for marking various updates that need to be applied. */ PBVHNodeFlags flag : 8; /* Used for raycasting: how close bb is to the ray point. */ float tmin; int proxy_count; PBVHProxyNode* proxies; }; struct PBVH { PBVHNode *nodes; int node_mem_count, totnode; int *prim_indices; int totprim; int totvert; int leaf_limit; /* Mesh data */ MVert *verts; MFace *faces; /* Grid Data */ DMGridData **grids; DMGridAdjacency *gridadj; void **gridfaces; int totgrid; int gridsize; /* Only used during BVH build and update, don't need to remain valid after */ BLI_bitmap vert_bitmap; #ifdef PERFCNTRS int perf_modified; #endif /* flag are verts/faces deformed */ int deformed; }; #define STACK_FIXED_DEPTH 100 typedef struct PBVHStack { PBVHNode *node; int revisiting; } PBVHStack; typedef struct PBVHIter { PBVH *bvh; BLI_pbvh_SearchCallback scb; void *search_data; PBVHStack *stack; int stacksize; PBVHStack stackfixed[STACK_FIXED_DEPTH]; int stackspace; } PBVHIter; static void BB_reset(BB *bb) { bb->bmin[0] = bb->bmin[1] = bb->bmin[2] = FLT_MAX; bb->bmax[0] = bb->bmax[1] = bb->bmax[2] = -FLT_MAX; } /* Expand the bounding box to include a new coordinate */ static void BB_expand(BB *bb, float co[3]) { int i; for(i = 0; i < 3; ++i) { bb->bmin[i] = MIN2(bb->bmin[i], co[i]); bb->bmax[i] = MAX2(bb->bmax[i], co[i]); } } /* Expand the bounding box to include another bounding box */ static void BB_expand_with_bb(BB *bb, BB *bb2) { int i; for(i = 0; i < 3; ++i) { bb->bmin[i] = MIN2(bb->bmin[i], bb2->bmin[i]); bb->bmax[i] = MAX2(bb->bmax[i], bb2->bmax[i]); } } /* Return 0, 1, or 2 to indicate the widest axis of the bounding box */ static int BB_widest_axis(BB *bb) { float dim[3]; int i; for(i = 0; i < 3; ++i) dim[i] = bb->bmax[i] - bb->bmin[i]; if(dim[0] > dim[1]) { if(dim[0] > dim[2]) return 0; else return 2; } else { if(dim[1] > dim[2]) return 1; else return 2; } } static void BBC_update_centroid(BBC *bbc) { int i; for(i = 0; i < 3; ++i) bbc->bcentroid[i] = (bbc->bmin[i] + bbc->bmax[i]) * 0.5f; } /* Not recursive */ static void update_node_vb(PBVH *bvh, PBVHNode *node) { BB vb; BB_reset(&vb); if(node->flag & PBVH_Leaf) { PBVHVertexIter vd; BLI_pbvh_vertex_iter_begin(bvh, node, vd, PBVH_ITER_ALL) { BB_expand(&vb, vd.co); } BLI_pbvh_vertex_iter_end; } else { BB_expand_with_bb(&vb, &bvh->nodes[node->children_offset].vb); BB_expand_with_bb(&vb, &bvh->nodes[node->children_offset + 1].vb); } node->vb= vb; } //void BLI_pbvh_node_BB_reset(PBVHNode* node) //{ // BB_reset(&node->vb); //} // //void BLI_pbvh_node_BB_expand(PBVHNode* node, float co[3]) //{ // BB_expand(&node->vb, co); //} /* Adapted from BLI_kdopbvh.c */ /* Returns the index of the first element on the right of the partition */ static int partition_indices(int *prim_indices, int lo, int hi, int axis, float mid, BBC *prim_bbc) { int i=lo, j=hi; for(;;) { for(; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++); for(; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--); if(!(i < j)) return i; SWAP(int, prim_indices[i], prim_indices[j]); i++; } } static void check_partitioning(int *prim_indices, int lo, int hi, int axis, float mid, BBC *prim_bbc, int index_of_2nd_partition) { int i; for(i = lo; i <= hi; ++i) { const float c = prim_bbc[prim_indices[i]].bcentroid[axis]; if((i < index_of_2nd_partition && c > mid) || (i > index_of_2nd_partition && c < mid)) { printf("fail\n"); } } } static void grow_nodes(PBVH *bvh, int totnode) { if(totnode > bvh->node_mem_count) { PBVHNode *prev = bvh->nodes; bvh->node_mem_count *= 1.33; if(bvh->node_mem_count < totnode) bvh->node_mem_count = totnode; bvh->nodes = MEM_callocN(sizeof(PBVHNode) * bvh->node_mem_count, "bvh nodes"); memcpy(bvh->nodes, prev, bvh->totnode * sizeof(PBVHNode)); MEM_freeN(prev); } bvh->totnode = totnode; } /* Add a vertex to the map, with a positive value for unique vertices and a negative value for additional vertices */ static int map_insert_vert(PBVH *bvh, GHash *map, unsigned int *face_verts, unsigned int *uniq_verts, int vertex) { void *value, *key = SET_INT_IN_POINTER(vertex); if(!BLI_ghash_haskey(map, key)) { if(BLI_bitmap_get(bvh->vert_bitmap, vertex)) { value = SET_INT_IN_POINTER(~(*face_verts)); ++(*face_verts); } else { BLI_bitmap_set(bvh->vert_bitmap, vertex); value = SET_INT_IN_POINTER(*uniq_verts); ++(*uniq_verts); } BLI_ghash_insert(map, key, value); return GET_INT_FROM_POINTER(value); } else return GET_INT_FROM_POINTER(BLI_ghash_lookup(map, key)); } /* Find vertices used by the faces in this node and update the draw buffers */ static void build_mesh_leaf_node(PBVH *bvh, PBVHNode *node) { GHashIterator *iter; GHash *map; int i, j, totface; map = BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "build_mesh_leaf_node gh"); node->uniq_verts = node->face_verts = 0; totface= node->totprim; node->face_vert_indices = MEM_callocN(sizeof(int) * 4*totface, "bvh node face vert indices"); for(i = 0; i < totface; ++i) { MFace *f = bvh->faces + node->prim_indices[i]; int sides = f->v4 ? 4 : 3; for(j = 0; j < sides; ++j) { node->face_vert_indices[i][j]= map_insert_vert(bvh, map, &node->face_verts, &node->uniq_verts, (&f->v1)[j]); } } node->vert_indices = MEM_callocN(sizeof(int) * (node->uniq_verts + node->face_verts), "bvh node vert indices"); /* Build the vertex list, unique verts first */ for(iter = BLI_ghashIterator_new(map), i = 0; !BLI_ghashIterator_isDone(iter); BLI_ghashIterator_step(iter), ++i) { void *value = BLI_ghashIterator_getValue(iter); int ndx = GET_INT_FROM_POINTER(value); if(ndx < 0) ndx = -ndx + node->uniq_verts - 1; node->vert_indices[ndx] = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(iter)); } BLI_ghashIterator_free(iter); for(i = 0; i < totface; ++i) { MFace *f = bvh->faces + node->prim_indices[i]; int sides = f->v4 ? 4 : 3; for(j = 0; j < sides; ++j) { if(node->face_vert_indices[i][j] < 0) node->face_vert_indices[i][j]= -node->face_vert_indices[i][j] + node->uniq_verts - 1; } } if(!G.background) { node->draw_buffers = GPU_build_mesh_buffers(map, bvh->verts, bvh->faces, node->prim_indices, node->totprim, node->vert_indices, node->uniq_verts, node->uniq_verts + node->face_verts); } node->flag |= PBVH_UpdateDrawBuffers; BLI_ghash_free(map, NULL, NULL); } static void build_grids_leaf_node(PBVH *bvh, PBVHNode *node) { if(!G.background) { node->draw_buffers = GPU_build_grid_buffers(bvh->grids, node->prim_indices, node->totprim, bvh->gridsize); } node->flag |= PBVH_UpdateDrawBuffers; } /* Recursively build a node in the tree vb is the voxel box around all of the primitives contained in this node. cb is the bounding box around all the centroids of the primitives contained in this node offset and start indicate a range in the array of primitive indices */ static void build_sub(PBVH *bvh, int node_index, BB *cb, BBC *prim_bbc, int offset, int count) { int i, axis, end; BB cb_backing; /* Decide whether this is a leaf or not */ // XXX adapt leaf limit for grids if(count <= bvh->leaf_limit) { bvh->nodes[node_index].flag |= PBVH_Leaf; bvh->nodes[node_index].prim_indices = bvh->prim_indices + offset; bvh->nodes[node_index].totprim = count; /* Still need vb for searches */ BB_reset(&bvh->nodes[node_index].vb); for(i = offset + count - 1; i >= offset; --i) { BB_expand_with_bb(&bvh->nodes[node_index].vb, (BB*)(prim_bbc + bvh->prim_indices[i])); } if(bvh->faces) build_mesh_leaf_node(bvh, bvh->nodes + node_index); else build_grids_leaf_node(bvh, bvh->nodes + node_index); bvh->nodes[node_index].orig_vb= bvh->nodes[node_index].vb; /* Done with this subtree */ return; } else { BB_reset(&bvh->nodes[node_index].vb); bvh->nodes[node_index].children_offset = bvh->totnode; grow_nodes(bvh, bvh->totnode + 2); if(!cb) { cb = &cb_backing; BB_reset(cb); for(i = offset + count - 1; i >= offset; --i) BB_expand(cb, prim_bbc[bvh->prim_indices[i]].bcentroid); } } axis = BB_widest_axis(cb); for(i = offset + count - 1; i >= offset; --i) { BB_expand_with_bb(&bvh->nodes[node_index].vb, (BB*)(prim_bbc + bvh->prim_indices[i])); } bvh->nodes[node_index].orig_vb= bvh->nodes[node_index].vb; end = partition_indices(bvh->prim_indices, offset, offset + count - 1, axis, (cb->bmax[axis] + cb->bmin[axis]) * 0.5f, prim_bbc); check_partitioning(bvh->prim_indices, offset, offset + count - 1, axis, (cb->bmax[axis] + cb->bmin[axis]) * 0.5f, prim_bbc, end); build_sub(bvh, bvh->nodes[node_index].children_offset, NULL, prim_bbc, offset, end - offset); build_sub(bvh, bvh->nodes[node_index].children_offset + 1, NULL, prim_bbc, end, offset + count - end); } static void pbvh_build(PBVH *bvh, BB *cb, BBC *prim_bbc, int totprim) { int i; if(totprim != bvh->totprim) { bvh->totprim = totprim; if(bvh->nodes) MEM_freeN(bvh->nodes); if(bvh->prim_indices) MEM_freeN(bvh->prim_indices); bvh->prim_indices = MEM_callocN(sizeof(int) * totprim, "bvh prim indices"); for(i = 0; i < totprim; ++i) bvh->prim_indices[i] = i; bvh->totnode = 0; if(bvh->node_mem_count < 100) { bvh->node_mem_count = 100; bvh->nodes = MEM_callocN(sizeof(PBVHNode) * bvh->node_mem_count, "bvh initial nodes"); } } bvh->totnode = 1; build_sub(bvh, 0, cb, prim_bbc, 0, totprim); } /* Do a full rebuild with on Mesh data structure */ void BLI_pbvh_build_mesh(PBVH *bvh, MFace *faces, MVert *verts, int totface, int totvert) { BBC *prim_bbc = NULL; BB cb; int i, j; bvh->faces = faces; bvh->verts = verts; bvh->vert_bitmap = BLI_bitmap_new(totvert); bvh->totvert = totvert; bvh->leaf_limit = LEAF_LIMIT; BB_reset(&cb); /* For each face, store the AABB and the AABB centroid */ prim_bbc = MEM_mallocN(sizeof(BBC) * totface, "prim_bbc"); for(i = 0; i < totface; ++i) { MFace *f = faces + i; const int sides = f->v4 ? 4 : 3; BBC *bbc = prim_bbc + i; BB_reset((BB*)bbc); for(j = 0; j < sides; ++j) BB_expand((BB*)bbc, verts[(&f->v1)[j]].co); BBC_update_centroid(bbc); BB_expand(&cb, bbc->bcentroid); } if(totface) pbvh_build(bvh, &cb, prim_bbc, totface); MEM_freeN(prim_bbc); MEM_freeN(bvh->vert_bitmap); } /* Do a full rebuild with on Grids data structure */ void BLI_pbvh_build_grids(PBVH *bvh, DMGridData **grids, DMGridAdjacency *gridadj, int totgrid, int gridsize, void **gridfaces) { BBC *prim_bbc = NULL; BB cb; int i, j; bvh->grids= grids; bvh->gridadj= gridadj; bvh->gridfaces= gridfaces; bvh->totgrid= totgrid; bvh->gridsize= gridsize; bvh->leaf_limit = MAX2(LEAF_LIMIT/((gridsize-1)*(gridsize-1)), 1); BB_reset(&cb); /* For each grid, store the AABB and the AABB centroid */ prim_bbc = MEM_mallocN(sizeof(BBC) * totgrid, "prim_bbc"); for(i = 0; i < totgrid; ++i) { DMGridData *grid= grids[i]; BBC *bbc = prim_bbc + i; BB_reset((BB*)bbc); for(j = 0; j < gridsize*gridsize; ++j) BB_expand((BB*)bbc, grid[j].co); BBC_update_centroid(bbc); BB_expand(&cb, bbc->bcentroid); } if(totgrid) pbvh_build(bvh, &cb, prim_bbc, totgrid); MEM_freeN(prim_bbc); } PBVH *BLI_pbvh_new(void) { PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh"); return bvh; } void BLI_pbvh_free(PBVH *bvh) { PBVHNode *node; int i; for(i = 0; i < bvh->totnode; ++i) { node= &bvh->nodes[i]; if(node->flag & PBVH_Leaf) { if(node->draw_buffers) GPU_free_buffers(node->draw_buffers); if(node->vert_indices) MEM_freeN(node->vert_indices); if(node->face_vert_indices) MEM_freeN(node->face_vert_indices); } } if (bvh->deformed) { if (bvh->verts) { /* if pbvh was deformed, new memory was allocated for verts/faces -- free it */ MEM_freeN(bvh->verts); MEM_freeN(bvh->faces); } } MEM_freeN(bvh->nodes); MEM_freeN(bvh->prim_indices); MEM_freeN(bvh); } static void pbvh_iter_begin(PBVHIter *iter, PBVH *bvh, BLI_pbvh_SearchCallback scb, void *search_data) { iter->bvh= bvh; iter->scb= scb; iter->search_data= search_data; iter->stack= iter->stackfixed; iter->stackspace= STACK_FIXED_DEPTH; iter->stack[0].node= bvh->nodes; iter->stack[0].revisiting= 0; iter->stacksize= 1; } static void pbvh_iter_end(PBVHIter *iter) { if(iter->stackspace > STACK_FIXED_DEPTH) MEM_freeN(iter->stack); } static void pbvh_stack_push(PBVHIter *iter, PBVHNode *node, int revisiting) { if(iter->stacksize == iter->stackspace) { PBVHStack *newstack; iter->stackspace *= 2; newstack= MEM_callocN(sizeof(PBVHStack)*iter->stackspace, "PBVHStack"); memcpy(newstack, iter->stack, sizeof(PBVHStack)*iter->stacksize); if(iter->stackspace > STACK_FIXED_DEPTH) MEM_freeN(iter->stack); iter->stack= newstack; } iter->stack[iter->stacksize].node= node; iter->stack[iter->stacksize].revisiting= revisiting; iter->stacksize++; } static PBVHNode *pbvh_iter_next(PBVHIter *iter) { PBVHNode *node; int revisiting; /* purpose here is to traverse tree, visiting child nodes before their parents, this order is necessary for e.g. computing bounding boxes */ while(iter->stacksize) { /* pop node */ iter->stacksize--; node= iter->stack[iter->stacksize].node; /* on a mesh with no faces this can happen * can remove this check if we know meshes have at least 1 face */ if(node==NULL) return NULL; revisiting= iter->stack[iter->stacksize].revisiting; /* revisiting node already checked */ if(revisiting) return node; if(iter->scb && !iter->scb(node, iter->search_data)) continue; /* don't traverse, outside of search zone */ if(node->flag & PBVH_Leaf) { /* immediately hit leaf node */ return node; } else { /* come back later when children are done */ pbvh_stack_push(iter, node, 1); /* push two child nodes on the stack */ pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset+1, 0); pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset, 0); } } return NULL; } static PBVHNode *pbvh_iter_next_occluded(PBVHIter *iter) { PBVHNode *node; while(iter->stacksize) { /* pop node */ iter->stacksize--; node= iter->stack[iter->stacksize].node; /* on a mesh with no faces this can happen * can remove this check if we know meshes have at least 1 face */ if(node==NULL) return NULL; if(iter->scb && !iter->scb(node, iter->search_data)) continue; /* don't traverse, outside of search zone */ if(node->flag & PBVH_Leaf) { /* immediately hit leaf node */ return node; } else { pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset+1, 0); pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset, 0); } } return NULL; } void BLI_pbvh_search_gather(PBVH *bvh, BLI_pbvh_SearchCallback scb, void *search_data, PBVHNode ***r_array, int *r_tot) { PBVHIter iter; PBVHNode **array= NULL, **newarray, *node; int tot= 0, space= 0; pbvh_iter_begin(&iter, bvh, scb, search_data); while((node=pbvh_iter_next(&iter))) { if(node->flag & PBVH_Leaf) { if(tot == space) { /* resize array if needed */ space= (tot == 0)? 32: space*2; newarray= MEM_callocN(sizeof(PBVHNode)*space, "PBVHNodeSearch"); if(array) { memcpy(newarray, array, sizeof(PBVHNode)*tot); MEM_freeN(array); } array= newarray; } array[tot]= node; tot++; } } pbvh_iter_end(&iter); if(tot == 0 && array) { MEM_freeN(array); array= NULL; } *r_array= array; *r_tot= tot; } void BLI_pbvh_search_callback(PBVH *bvh, BLI_pbvh_SearchCallback scb, void *search_data, BLI_pbvh_HitCallback hcb, void *hit_data) { PBVHIter iter; PBVHNode *node; pbvh_iter_begin(&iter, bvh, scb, search_data); while((node=pbvh_iter_next(&iter))) if (node->flag & PBVH_Leaf) hcb(node, hit_data); pbvh_iter_end(&iter); } typedef struct node_tree { PBVHNode* data; struct node_tree* left; struct node_tree* right; } node_tree; static void node_tree_insert(node_tree* tree, node_tree* new_node) { if (new_node->data->tmin < tree->data->tmin) { if (tree->left) { node_tree_insert(tree->left, new_node); } else { tree->left = new_node; } } else { if (tree->right) { node_tree_insert(tree->right, new_node); } else { tree->right = new_node; } } } static void traverse_tree(node_tree* tree, BLI_pbvh_HitOccludedCallback hcb, void* hit_data, float* tmin) { if (tree->left) traverse_tree(tree->left, hcb, hit_data, tmin); hcb(tree->data, hit_data, tmin); if (tree->right) traverse_tree(tree->right, hcb, hit_data, tmin); } static void free_tree(node_tree* tree) { if (tree->left) { free_tree(tree->left); tree->left = 0; } if (tree->right) { free_tree(tree->right); tree->right = 0; } free(tree); } float BLI_pbvh_node_get_tmin(PBVHNode* node) { return node->tmin; } static void BLI_pbvh_search_callback_occluded(PBVH *bvh, BLI_pbvh_SearchCallback scb, void *search_data, BLI_pbvh_HitOccludedCallback hcb, void *hit_data) { PBVHIter iter; PBVHNode *node; node_tree *tree = 0; pbvh_iter_begin(&iter, bvh, scb, search_data); while((node=pbvh_iter_next_occluded(&iter))) { if(node->flag & PBVH_Leaf) { node_tree* new_node = malloc(sizeof(node_tree)); new_node->data = node; new_node->left = NULL; new_node->right = NULL; if (tree) { node_tree_insert(tree, new_node); } else { tree = new_node; } } } pbvh_iter_end(&iter); if (tree) { float tmin = FLT_MAX; traverse_tree(tree, hcb, hit_data, &tmin); free_tree(tree); } } static int update_search_cb(PBVHNode *node, void *data_v) { int flag= GET_INT_FROM_POINTER(data_v); if(node->flag & PBVH_Leaf) return (node->flag & flag); return 1; } static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes, int totnode, float (*face_nors)[3]) { float (*vnor)[3]; int n; if(bvh->grids) return; /* could be per node to save some memory, but also means we have to store for each vertex which node it is in */ vnor= MEM_callocN(sizeof(float)*3*bvh->totvert, "bvh temp vnors"); /* subtle assumptions: - We know that for all edited vertices, the nodes with faces adjacent to these vertices have been marked with PBVH_UpdateNormals. This is true because if the vertex is inside the brush radius, the bounding box of it's adjacent faces will be as well. - However this is only true for the vertices that have actually been edited, not for all vertices in the nodes marked for update, so we can only update vertices marked with ME_VERT_PBVH_UPDATE. */ #pragma omp parallel for private(n) schedule(static) for(n = 0; n < totnode; n++) { PBVHNode *node= nodes[n]; if((node->flag & PBVH_UpdateNormals)) { int i, j, totface, *faces; faces= node->prim_indices; totface= node->totprim; for(i = 0; i < totface; ++i) { MFace *f= bvh->faces + faces[i]; float fn[3]; unsigned int *fv = &f->v1; int sides= (f->v4)? 4: 3; if(f->v4) normal_quad_v3(fn, bvh->verts[f->v1].co, bvh->verts[f->v2].co, bvh->verts[f->v3].co, bvh->verts[f->v4].co); else normal_tri_v3(fn, bvh->verts[f->v1].co, bvh->verts[f->v2].co, bvh->verts[f->v3].co); for(j = 0; j < sides; ++j) { int v= fv[j]; if(bvh->verts[v].flag & ME_VERT_PBVH_UPDATE) { /* this seems like it could be very slow but profile does not show this, so just leave it for now? */ #pragma omp atomic vnor[v][0] += fn[0]; #pragma omp atomic vnor[v][1] += fn[1]; #pragma omp atomic vnor[v][2] += fn[2]; } } if(face_nors) copy_v3_v3(face_nors[faces[i]], fn); } } } #pragma omp parallel for private(n) schedule(static) for(n = 0; n < totnode; n++) { PBVHNode *node= nodes[n]; if(node->flag & PBVH_UpdateNormals) { int i, *verts, totvert; verts= node->vert_indices; totvert= node->uniq_verts; for(i = 0; i < totvert; ++i) { const int v = verts[i]; MVert *mvert= &bvh->verts[v]; if(mvert->flag & ME_VERT_PBVH_UPDATE) { float no[3]; copy_v3_v3(no, vnor[v]); normalize_v3(no); mvert->no[0] = (short)(no[0]*32767.0f); mvert->no[1] = (short)(no[1]*32767.0f); mvert->no[2] = (short)(no[2]*32767.0f); mvert->flag &= ~ME_VERT_PBVH_UPDATE; } } node->flag &= ~PBVH_UpdateNormals; } } MEM_freeN(vnor); } static void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag) { int n; /* update BB, redraw flag */ #pragma omp parallel for private(n) schedule(static) for(n = 0; n < totnode; n++) { PBVHNode *node= nodes[n]; if((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB)) /* don't clear flag yet, leave it for flushing later */ update_node_vb(bvh, node); if((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB)) node->orig_vb= node->vb; if((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw)) node->flag &= ~PBVH_UpdateRedraw; } } static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode, int smooth) { PBVHNode *node; int n; /* can't be done in parallel with OpenGL */ for(n = 0; n < totnode; n++) { node= nodes[n]; if(node->flag & PBVH_UpdateDrawBuffers) { if(bvh->grids) { GPU_update_grid_buffers(node->draw_buffers, bvh->grids, node->prim_indices, node->totprim, bvh->gridsize, smooth); } else { GPU_update_mesh_buffers(node->draw_buffers, bvh->verts, node->vert_indices, node->uniq_verts + node->face_verts); } node->flag &= ~PBVH_UpdateDrawBuffers; } } } static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag) { int update= 0; /* difficult to multithread well, we just do single threaded recursive */ if(node->flag & PBVH_Leaf) { if(flag & PBVH_UpdateBB) { update |= (node->flag & PBVH_UpdateBB); node->flag &= ~PBVH_UpdateBB; } if(flag & PBVH_UpdateOriginalBB) { update |= (node->flag & PBVH_UpdateOriginalBB); node->flag &= ~PBVH_UpdateOriginalBB; } return update; } else { update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset, flag); update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset + 1, flag); if(update & PBVH_UpdateBB) update_node_vb(bvh, node); if(update & PBVH_UpdateOriginalBB) node->orig_vb= node->vb; } return update; } void BLI_pbvh_update(PBVH *bvh, int flag, float (*face_nors)[3]) { PBVHNode **nodes; int totnode; BLI_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(flag), &nodes, &totnode); if(flag & PBVH_UpdateNormals) pbvh_update_normals(bvh, nodes, totnode, face_nors); if(flag & (PBVH_UpdateBB|PBVH_UpdateOriginalBB|PBVH_UpdateRedraw)) pbvh_update_BB_redraw(bvh, nodes, totnode, flag); if(flag & (PBVH_UpdateBB|PBVH_UpdateOriginalBB)) pbvh_flush_bb(bvh, bvh->nodes, flag); if(nodes) MEM_freeN(nodes); } void BLI_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3]) { PBVHIter iter; PBVHNode *node; BB bb; BB_reset(&bb); pbvh_iter_begin(&iter, bvh, NULL, NULL); while((node=pbvh_iter_next(&iter))) if(node->flag & PBVH_UpdateRedraw) BB_expand_with_bb(&bb, &node->vb); pbvh_iter_end(&iter); copy_v3_v3(bb_min, bb.bmin); copy_v3_v3(bb_max, bb.bmax); } void BLI_pbvh_get_grid_updates(PBVH *bvh, int clear, void ***gridfaces, int *totface) { PBVHIter iter; PBVHNode *node; GHashIterator *hiter; GHash *map; void *face, **faces; unsigned i; int tot; map = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "pbvh_get_grid_updates gh"); pbvh_iter_begin(&iter, bvh, NULL, NULL); while((node=pbvh_iter_next(&iter))) { if(node->flag & PBVH_UpdateNormals) { for(i = 0; i < node->totprim; ++i) { face= bvh->gridfaces[node->prim_indices[i]]; if(!BLI_ghash_lookup(map, face)) BLI_ghash_insert(map, face, face); } if(clear) node->flag &= ~PBVH_UpdateNormals; } } pbvh_iter_end(&iter); tot= BLI_ghash_size(map); if(tot == 0) { *totface= 0; *gridfaces= NULL; BLI_ghash_free(map, NULL, NULL); return; } faces= MEM_callocN(sizeof(void*)*tot, "PBVH Grid Faces"); for(hiter = BLI_ghashIterator_new(map), i = 0; !BLI_ghashIterator_isDone(hiter); BLI_ghashIterator_step(hiter), ++i) faces[i]= BLI_ghashIterator_getKey(hiter); BLI_ghashIterator_free(hiter); BLI_ghash_free(map, NULL, NULL); *totface= tot; *gridfaces= faces; } /***************************** Node Access ***********************************/ void BLI_pbvh_node_mark_update(PBVHNode *node) { node->flag |= PBVH_UpdateNormals|PBVH_UpdateBB|PBVH_UpdateOriginalBB|PBVH_UpdateDrawBuffers|PBVH_UpdateRedraw; } void BLI_pbvh_node_get_verts(PBVH *bvh, PBVHNode *node, int **vert_indices, MVert **verts) { if(vert_indices) *vert_indices= node->vert_indices; if(verts) *verts= bvh->verts; } void BLI_pbvh_node_num_verts(PBVH *bvh, PBVHNode *node, int *uniquevert, int *totvert) { if(bvh->grids) { const int tot= node->totprim*bvh->gridsize*bvh->gridsize; if(totvert) *totvert= tot; if(uniquevert) *uniquevert= tot; } else { if(totvert) *totvert= node->uniq_verts + node->face_verts; if(uniquevert) *uniquevert= node->uniq_verts; } } void BLI_pbvh_node_get_grids(PBVH *bvh, PBVHNode *node, int **grid_indices, int *totgrid, int *maxgrid, int *gridsize, DMGridData ***griddata, DMGridAdjacency **gridadj) { if(bvh->grids) { if(grid_indices) *grid_indices= node->prim_indices; if(totgrid) *totgrid= node->totprim; if(maxgrid) *maxgrid= bvh->totgrid; if(gridsize) *gridsize= bvh->gridsize; if(griddata) *griddata= bvh->grids; if(gridadj) *gridadj= bvh->gridadj; } else { if(grid_indices) *grid_indices= NULL; if(totgrid) *totgrid= 0; if(maxgrid) *maxgrid= 0; if(gridsize) *gridsize= 0; if(griddata) *griddata= NULL; if(gridadj) *gridadj= NULL; } } void BLI_pbvh_node_get_BB(PBVHNode *node, float bb_min[3], float bb_max[3]) { copy_v3_v3(bb_min, node->vb.bmin); copy_v3_v3(bb_max, node->vb.bmax); } void BLI_pbvh_node_get_original_BB(PBVHNode *node, float bb_min[3], float bb_max[3]) { copy_v3_v3(bb_min, node->orig_vb.bmin); copy_v3_v3(bb_max, node->orig_vb.bmax); } void BLI_pbvh_node_get_proxies(PBVHNode* node, PBVHProxyNode** proxies, int* proxy_count) { if (node->proxy_count > 0) { if (proxies) *proxies = node->proxies; if (proxy_count) *proxy_count = node->proxy_count; } else { if (proxies) *proxies = 0; if (proxy_count) *proxy_count = 0; } } /********************************* Raycast ***********************************/ typedef struct { /* Ray */ float start[3]; int sign[3]; float inv_dir[3]; int original; } RaycastData; /* Adapted from here: http://www.gamedev.net/community/forums/topic.asp?topic_id=459973 */ static int ray_aabb_intersect(PBVHNode *node, void *data_v) { RaycastData *ray = data_v; float bbox[2][3]; float tmin, tmax, tymin, tymax, tzmin, tzmax; if(ray->original) BLI_pbvh_node_get_original_BB(node, bbox[0], bbox[1]); else BLI_pbvh_node_get_BB(node, bbox[0], bbox[1]); tmin = (bbox[ray->sign[0]][0] - ray->start[0]) * ray->inv_dir[0]; tmax = (bbox[1-ray->sign[0]][0] - ray->start[0]) * ray->inv_dir[0]; tymin = (bbox[ray->sign[1]][1] - ray->start[1]) * ray->inv_dir[1]; tymax = (bbox[1-ray->sign[1]][1] - ray->start[1]) * ray->inv_dir[1]; if((tmin > tymax) || (tymin > tmax)) return 0; if(tymin > tmin) tmin = tymin; if(tymax < tmax) tmax = tymax; tzmin = (bbox[ray->sign[2]][2] - ray->start[2]) * ray->inv_dir[2]; tzmax = (bbox[1-ray->sign[2]][2] - ray->start[2]) * ray->inv_dir[2]; if((tmin > tzmax) || (tzmin > tmax)) return 0; if(tzmin > tmin) tmin = tzmin; // XXX jwilkins: tmax does not need to be updated since we don't use it // keeping this here for future reference //if(tzmax < tmax) tmax = tzmax; node->tmin = tmin; return 1; } void BLI_pbvh_raycast(PBVH *bvh, BLI_pbvh_HitOccludedCallback cb, void *data, float ray_start[3], float ray_normal[3], int original) { RaycastData rcd; copy_v3_v3(rcd.start, ray_start); rcd.inv_dir[0] = 1.0f / ray_normal[0]; rcd.inv_dir[1] = 1.0f / ray_normal[1]; rcd.inv_dir[2] = 1.0f / ray_normal[2]; rcd.sign[0] = rcd.inv_dir[0] < 0; rcd.sign[1] = rcd.inv_dir[1] < 0; rcd.sign[2] = rcd.inv_dir[2] < 0; rcd.original = original; BLI_pbvh_search_callback_occluded(bvh, ray_aabb_intersect, &rcd, cb, data); } static int ray_face_intersection(float ray_start[3], float ray_normal[3], float *t0, float *t1, float *t2, float *t3, float *fdist) { float dist; if ((isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t1, t2, &dist, NULL, 0.1f) && dist < *fdist) || (t3 && isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t2, t3, &dist, NULL, 0.1f) && dist < *fdist)) { *fdist = dist; return 1; } else { return 0; } } int BLI_pbvh_node_raycast(PBVH *bvh, PBVHNode *node, float (*origco)[3], float ray_start[3], float ray_normal[3], float *dist) { int hit= 0; if(bvh->faces) { MVert *vert = bvh->verts; int *faces= node->prim_indices; int totface= node->totprim; int i; for(i = 0; i < totface; ++i) { MFace *f = bvh->faces + faces[i]; int *face_verts = node->face_vert_indices[i]; if(origco) { /* intersect with backuped original coordinates */ hit |= ray_face_intersection(ray_start, ray_normal, origco[face_verts[0]], origco[face_verts[1]], origco[face_verts[2]], f->v4? origco[face_verts[3]]: NULL, dist); } else { /* intersect with current coordinates */ hit |= ray_face_intersection(ray_start, ray_normal, vert[f->v1].co, vert[f->v2].co, vert[f->v3].co, f->v4 ? vert[f->v4].co : NULL, dist); } } } else { int totgrid= node->totprim; int gridsize= bvh->gridsize; int i, x, y; for(i = 0; i < totgrid; ++i) { DMGridData *grid= bvh->grids[node->prim_indices[i]]; if (!grid) continue; for(y = 0; y < gridsize-1; ++y) { for(x = 0; x < gridsize-1; ++x) { if(origco) { hit |= ray_face_intersection(ray_start, ray_normal, origco[y*gridsize + x], origco[y*gridsize + x+1], origco[(y+1)*gridsize + x+1], origco[(y+1)*gridsize + x], dist); } else { hit |= ray_face_intersection(ray_start, ray_normal, grid[y*gridsize + x].co, grid[y*gridsize + x+1].co, grid[(y+1)*gridsize + x+1].co, grid[(y+1)*gridsize + x].co, dist); } } } if(origco) origco += gridsize*gridsize; } } return hit; } //#include <GL/glew.h> void BLI_pbvh_node_draw(PBVHNode *node, void *UNUSED(data)) { #if 0 /* XXX: Just some quick code to show leaf nodes in different colors */ float col[3]; int i; if(0) { //is_partial) { col[0] = (rand() / (float)RAND_MAX); col[1] = col[2] = 0.6; } else { srand((long long)node); for(i = 0; i < 3; ++i) col[i] = (rand() / (float)RAND_MAX) * 0.3 + 0.7; } glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, col); glColor3f(1, 0, 0); #endif GPU_draw_buffers(node->draw_buffers); } /* Adapted from: http://www.gamedev.net/community/forums/topic.asp?topic_id=512123 Returns true if the AABB is at least partially within the frustum (ok, not a real frustum), false otherwise. */ int BLI_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data) { float (*planes)[4] = data; int i, axis; float vmin[3] /*, vmax[3]*/, bb_min[3], bb_max[3]; BLI_pbvh_node_get_BB(node, bb_min, bb_max); for(i = 0; i < 4; ++i) { for(axis = 0; axis < 3; ++axis) { if(planes[i][axis] > 0) { vmin[axis] = bb_min[axis]; /*vmax[axis] = bb_max[axis];*/ /*UNUSED*/ } else { vmin[axis] = bb_max[axis]; /*vmax[axis] = bb_min[axis];*/ /*UNUSED*/ } } if(dot_v3v3(planes[i], vmin) + planes[i][3] > 0) return 0; } return 1; } void BLI_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*face_nors)[3], int smooth) { PBVHNode **nodes; int totnode; BLI_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(PBVH_UpdateNormals|PBVH_UpdateDrawBuffers), &nodes, &totnode); pbvh_update_normals(bvh, nodes, totnode, face_nors); pbvh_update_draw_buffers(bvh, nodes, totnode, smooth); if(nodes) MEM_freeN(nodes); if(planes) { BLI_pbvh_search_callback(bvh, BLI_pbvh_node_planes_contain_AABB, planes, BLI_pbvh_node_draw, NULL); } else { BLI_pbvh_search_callback(bvh, NULL, NULL, BLI_pbvh_node_draw, NULL); } } void BLI_pbvh_grids_update(PBVH *bvh, DMGridData **grids, DMGridAdjacency *gridadj, void **gridfaces) { bvh->grids= grids; bvh->gridadj= gridadj; bvh->gridfaces= gridfaces; } float (*BLI_pbvh_get_vertCos(PBVH *pbvh))[3] { int a; float (*vertCos)[3]= NULL; if (pbvh->verts) { float *co; MVert *mvert= pbvh->verts; vertCos= MEM_callocN(3*pbvh->totvert*sizeof(float), "BLI_pbvh_get_vertCoords"); co= (float*)vertCos; for (a= 0; a<pbvh->totvert; a++, mvert++, co+= 3) { copy_v3_v3(co, mvert->co); } } return vertCos; } void BLI_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3]) { int a; if (!pbvh->deformed) { if (pbvh->verts) { /* if pbvh is not already deformed, verts/faces points to the */ /* original data and applying new coords to this arrays would lead to */ /* unneeded deformation -- duplicate verts/faces to avoid this */ pbvh->verts= MEM_dupallocN(pbvh->verts); pbvh->faces= MEM_dupallocN(pbvh->faces); pbvh->deformed= 1; } } if (pbvh->verts) { MVert *mvert= pbvh->verts; /* copy new verts coords */ for (a= 0; a < pbvh->totvert; ++a, ++mvert) { copy_v3_v3(mvert->co, vertCos[a]); mvert->flag |= ME_VERT_PBVH_UPDATE; } /* coordinates are new -- normals should also be updated */ mesh_calc_normals(pbvh->verts, pbvh->totvert, pbvh->faces, pbvh->totprim, NULL); for (a= 0; a < pbvh->totnode; ++a) BLI_pbvh_node_mark_update(&pbvh->nodes[a]); BLI_pbvh_update(pbvh, PBVH_UpdateBB, NULL); BLI_pbvh_update(pbvh, PBVH_UpdateOriginalBB, NULL); } } int BLI_pbvh_isDeformed(PBVH *pbvh) { return pbvh->deformed; } /* Proxies */ PBVHProxyNode* BLI_pbvh_node_add_proxy(PBVH* bvh, PBVHNode* node) { int index, totverts; #pragma omp critical { index = node->proxy_count; node->proxy_count++; if (node->proxies) node->proxies= MEM_reallocN(node->proxies, node->proxy_count*sizeof(PBVHProxyNode)); else node->proxies= MEM_mallocN(sizeof(PBVHProxyNode), "PBVHNodeProxy"); if (bvh->grids) totverts = node->totprim*bvh->gridsize*bvh->gridsize; else totverts = node->uniq_verts; node->proxies[index].co= MEM_callocN(sizeof(float[3])*totverts, "PBVHNodeProxy.co"); } return node->proxies + index; } void BLI_pbvh_node_free_proxies(PBVHNode* node) { #pragma omp critical { int p; for (p= 0; p < node->proxy_count; p++) { MEM_freeN(node->proxies[p].co); node->proxies[p].co= 0; } MEM_freeN(node->proxies); node->proxies = 0; node->proxy_count= 0; } } void BLI_pbvh_gather_proxies(PBVH* pbvh, PBVHNode*** r_array, int* r_tot) { PBVHNode **array= NULL, **newarray, *node; int tot= 0, space= 0; int n; for (n= 0; n < pbvh->totnode; n++) { node = pbvh->nodes + n; if(node->proxy_count > 0) { if(tot == space) { /* resize array if needed */ space= (tot == 0)? 32: space*2; newarray= MEM_callocN(sizeof(PBVHNode)*space, "BLI_pbvh_gather_proxies"); if (array) { memcpy(newarray, array, sizeof(PBVHNode)*tot); MEM_freeN(array); } array= newarray; } array[tot]= node; tot++; } } if(tot == 0 && array) { MEM_freeN(array); array= NULL; } *r_array= array; *r_tot= tot; }
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // Copyright (C) 2018 SenseNets Technology Ltd. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*9 + q*9; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i+1 < outh; i+=2) { int remain = outw; for (; remain>0; remain--) { float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain>0; remain--) { float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } } static void conv3x3s1_winograd23_transform_kernel_sse(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(4*4, inch, outch); // G const float ktm[4][3] = { { 1.0f, 0.0f, 0.0f}, { 1.0f/2, 1.0f/2, 1.0f/2}, { 1.0f/2, -1.0f/2, 1.0f/2}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[4][3]; for (int i=0; i<4; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j=0; j<4; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<4; i++) { kernel_tm0[j*4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd23_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 2n+2, winograd F(2,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 1) / 2 * 2; outh = (outh + 1) / 2 * 2; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt.workspace_allocator, opt.num_threads); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; const int tiles = nColBlocks * nRowBlocks; bottom_blob_tm.create(4*4, tiles, inch, 4u, opt.workspace_allocator); // BT // const float itm[4][4] = { // {1.0f, 0.0f, -1.0f, 0.0f}, // {0.0f, 1.0f, 1.00f, 0.0f}, // {0.0f, -1.0f, 1.00f, 0.0f}, // {0.0f, -1.0f, 0.00f, 1.0f} // }; #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const float* img = bottom_blob_bordered.channel(q); float* out_tm0 = bottom_blob_tm.channel(q); for (int j = 0; j < nColBlocks; j++) { const float* r0 = img + w * j * 2; const float* r1 = r0 + w; const float* r2 = r1 + w; const float* r3 = r2 + w; for (int i = 0; i < nRowBlocks; i++) { float d0[4],d1[4],d2[4],d3[4]; float w0[4],w1[4],w2[4],w3[4]; float t0[4],t1[4],t2[4],t3[4]; // load for (int n = 0; n < 4; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; } // w = B_t * d for (int n = 0; n < 4; n++) { w0[n] = d0[n] - d2[n]; w1[n] = d1[n] + d2[n]; w2[n] = d2[n] - d1[n]; w3[n] = d3[n] - d1[n]; } // transpose d to d_t { t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; } // d = B_t * d_t for (int n = 0; n < 4; n++) { d0[n] = t0[n] - t2[n]; d1[n] = t1[n] + t2[n]; d2[n] = t2[n] - t1[n]; d3[n] = t3[n] - t1[n]; } // save to out_tm for (int n = 0; n < 4; n++) { out_tm0[n ] = d0[n]; out_tm0[n+ 4] = d1[n]; out_tm0[n+ 8] = d2[n]; out_tm0[n+12] = d3[n]; } r0 += 2; r1 += 2; r2 += 2; r3 += 2; out_tm0 += 16; } } } } bottom_blob_bordered = Mat(); // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; const int tiles = nColBlocks * nRowBlocks; top_blob_tm.create(16, tiles, outch, 4u, opt.workspace_allocator); int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); Mat out2_tm = top_blob_tm.channel(p+2); Mat out3_tm = top_blob_tm.channel(p+3); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); const Mat kernel2_tm = kernel_tm.channel(p+2); const Mat kernel3_tm = kernel_tm.channel(p+3); for (int i=0; i<tiles; i++) { float* output0_tm = out0_tm.row(i); float* output1_tm = out1_tm.row(i); float* output2_tm = out2_tm.row(i); float* output3_tm = out3_tm.row(i); float sum0[16] = {0.0f}; float sum1[16] = {0.0f}; float sum2[16] = {0.0f}; float sum3[16] = {0.0f}; int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* r1 = bottom_blob_tm.channel(q+1).row(i); const float* r2 = bottom_blob_tm.channel(q+2).row(i); const float* r3 = bottom_blob_tm.channel(q+3).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; k0 += 16; sum0[n] += r1[n] * k0[n]; k0 += 16; sum0[n] += r2[n] * k0[n]; k0 += 16; sum0[n] += r3[n] * k0[n]; k0 -= 16 * 3; sum1[n] += r0[n] * k1[n]; k1 += 16; sum1[n] += r1[n] * k1[n]; k1 += 16; sum1[n] += r2[n] * k1[n]; k1 += 16; sum1[n] += r3[n] * k1[n]; k1 -= 16 * 3; sum2[n] += r0[n] * k2[n]; k2 += 16; sum2[n] += r1[n] * k2[n]; k2 += 16; sum2[n] += r2[n] * k2[n]; k2 += 16; sum2[n] += r3[n] * k2[n]; k2 -= 16 * 3; sum3[n] += r0[n] * k3[n]; k3 += 16; sum3[n] += r1[n] * k3[n]; k3 += 16; sum3[n] += r2[n] * k3[n]; k3 += 16; sum3[n] += r3[n] * k3[n]; k3 -= 16 * 3; } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; sum1[n] += r0[n] * k1[n]; sum2[n] += r0[n] * k2[n]; sum3[n] += r0[n] * k3[n]; } } for (int n=0; n<16; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int i=0; i<tiles; i++) { float* output0_tm = out0_tm.row(i); float sum0[16] = {0.0f}; int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* r1 = bottom_blob_tm.channel(q+1).row(i); const float* r2 = bottom_blob_tm.channel(q+2).row(i); const float* r3 = bottom_blob_tm.channel(q+3).row(i); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); const float* k2 = kernel0_tm.row(q+2); const float* k3 = kernel0_tm.row(q+3); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; sum0[n] += r1[n] * k1[n]; sum0[n] += r2[n] * k2[n]; sum0[n] += r3[n] * k3[n]; } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* k0 = kernel0_tm.row(q); for (int n=0; n<16; n++) { sum0[n] += r0[n] * k0[n]; } } for (int n=0; n<16; n++) { output0_tm[n] = sum0[n]; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); { // AT // const float itm[2][4] = { // {1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 1.0f} // }; int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; int nColBlocks = h_tm/4; // may be the block num in Feathercnn int nRowBlocks = w_tm/4; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out_tm = top_blob_tm.channel(p); Mat out = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; for (int j=0; j<nColBlocks; j++) { float* outRow0 = out.row(j*2); float* outRow1 = out.row(j*2+1); for(int i=0; i<nRowBlocks; i++) { float* out_tile = out_tm.row(j*nRowBlocks + i); float s0[4],s1[4],s2[4],s3[4]; float w0[4],w1[4]; float d0[2],d1[2],d2[2],d3[2]; float o0[2],o1[2]; // load for (int n = 0; n < 4; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n+ 4]; s2[n] = out_tile[n+ 8]; s3[n] = out_tile[n+12]; } // w = A_T * W for (int n = 0; n < 4; n++) { w0[n] = s0[n] + s1[n] + s2[n]; w1[n] = s1[n] - s2[n] + s3[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d1[0] = w0[1]; d1[1] = w1[1]; d2[0] = w0[2]; d2[1] = w1[2]; d3[0] = w0[3]; d3[1] = w1[3]; } // Y = A_T * w_t for (int n = 0; n < 2; n++) { o0[n] = d0[n] + d1[n] + d2[n] + bias0; o1[n] = d1[n] - d2[n] + d3[n] + bias0; } // save to top blob tm outRow0[0] = o0[0]; outRow0[1] = o0[1]; outRow1[0] = o1[0]; outRow1[1] = o1[1]; outRow0 += 2; outRow1 += 2; } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt.blob_allocator, opt.num_threads); } static void conv3x3s1_winograd43_transform_kernel_sse(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(6*6, inch, outch); // G const float ktm[6][3] = { { 1.0f/4, 0.0f, 0.0f}, { -1.0f/6, -1.0f/6, -1.0f/6}, { -1.0f/6, 1.0f/6, -1.0f/6}, { 1.0f/24, 1.0f/12, 1.0f/6}, { 1.0f/24, -1.0f/12, 1.0f/6}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3]; for (int i=0; i<6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j=0; j<6; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<6; i++) { kernel_tm0[j*6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd43_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2, winograd F(4,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt.workspace_allocator, opt.num_threads); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; const int tiles = nColBlocks * nRowBlocks; bottom_blob_tm.create(6*6, tiles, inch, 4u, opt.workspace_allocator); // BT // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r03 + r04 // 2 = 4 * (r01 - r02) - r03 + r04 // 3 = -2 * r01 - r02 + 2 * r03 + r04 // 4 = 2 * r01 - r02 - 2 * r03 + r04 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const float* img = bottom_blob_bordered.channel(q); float* out_tm0 = bottom_blob_tm.channel(q); for (int j = 0; j < nColBlocks; j++) { const float* r0 = img + w * j * 4; const float* r1 = r0 + w; const float* r2 = r1 + w; const float* r3 = r2 + w; const float* r4 = r3 + w; const float* r5 = r4 + w; for (int i = 0; i < nRowBlocks; i++) { float d0[6],d1[6],d2[6],d3[6],d4[6],d5[6]; float w0[6],w1[6],w2[6],w3[6],w4[6],w5[6]; float t0[6],t1[6],t2[6],t3[6],t4[6],t5[6]; // load for (int n = 0; n < 6; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; d4[n] = r4[n]; d5[n] = r5[n]; } // w = B_t * d for (int n = 0; n < 6; n++) { w0[n] = 4*d0[n] - 5*d2[n] + d4[n]; w1[n] = -4*d1[n] - 4*d2[n] + d3[n] + d4[n]; w2[n] = 4*d1[n] - 4*d2[n] - d3[n] + d4[n]; w3[n] = -2*d1[n] - d2[n] + 2*d3[n] + d4[n]; w4[n] = 2*d1[n] - d2[n] - 2*d3[n] + d4[n]; w5[n] = 4*d1[n] - 5*d3[n] + d5[n]; } // transpose d to d_t { t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t4[0]=w0[4]; t5[0]=w0[5]; t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t4[1]=w1[4]; t5[1]=w1[5]; t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t4[2]=w2[4]; t5[2]=w2[5]; t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; t4[3]=w3[4]; t5[3]=w3[5]; t0[4]=w4[0]; t1[4]=w4[1]; t2[4]=w4[2]; t3[4]=w4[3]; t4[4]=w4[4]; t5[4]=w4[5]; t0[5]=w5[0]; t1[5]=w5[1]; t2[5]=w5[2]; t3[5]=w5[3]; t4[5]=w5[4]; t5[5]=w5[5]; } // d = B_t * d_t for (int n = 0; n < 6; n++) { d0[n] = 4*t0[n] - 5*t2[n] + t4[n]; d1[n] = - 4*t1[n] - 4*t2[n] + t3[n] + t4[n]; d2[n] = 4*t1[n] - 4*t2[n] - t3[n] + t4[n]; d3[n] = - 2*t1[n] - t2[n] + 2*t3[n] + t4[n]; d4[n] = 2*t1[n] - t2[n] - 2*t3[n] + t4[n]; d5[n] = 4*t1[n] - 5*t3[n] + t5[n]; } // save to out_tm for (int n = 0; n < 6; n++) { out_tm0[n ] = d0[n]; out_tm0[n+ 6] = d1[n]; out_tm0[n+12] = d2[n]; out_tm0[n+18] = d3[n]; out_tm0[n+24] = d4[n]; out_tm0[n+30] = d5[n]; } r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; out_tm0 += 36; } } } } bottom_blob_bordered = Mat(); // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; const int tiles = nColBlocks * nRowBlocks; top_blob_tm.create(36, tiles, outch, 4u, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int i=0; i<tiles; i++) { float* output0_tm = out0_tm.row(i); float sum0[36] = {0.0f}; for (int q=0; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q).row(i); const float* k0 = kernel0_tm.row(q); for (int n=0; n<36; n++) { sum0[n] += r0[n] * k0[n]; } } for (int n=0; n<36; n++) { output0_tm[n] = sum0[n]; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); { // AT // const float itm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + r01 + r02 + r03 + r04 // 1 = r01 - r02 + 2 * (r03 - r04) // 2 = r01 + r02 + 4 * (r03 + r04) // 3 = r01 - r02 + 8 * (r03 - r04) + r05 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; int nColBlocks = h_tm/6; // may be the block num in Feathercnn int nRowBlocks = w_tm/6; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out_tm = top_blob_tm.channel(p); Mat out = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; for (int j=0; j<nColBlocks; j++) { float* outRow0 = out.row(j*4); float* outRow1 = out.row(j*4+1); float* outRow2 = out.row(j*4+2); float* outRow3 = out.row(j*4+3); for(int i=0; i<nRowBlocks; i++) { float* out_tile = out_tm.row(j*nRowBlocks + i); float s0[6],s1[6],s2[6],s3[6],s4[6],s5[6]; float w0[6],w1[6],w2[6],w3[6]; float d0[4],d1[4],d2[4],d3[4],d4[4],d5[4]; float o0[4],o1[4],o2[4],o3[4]; // load for (int n = 0; n < 6; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n+ 6]; s2[n] = out_tile[n+12]; s3[n] = out_tile[n+18]; s4[n] = out_tile[n+24]; s5[n] = out_tile[n+30]; } // w = A_T * W for (int n = 0; n < 6; n++) { w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n]; w1[n] = s1[n] - s2[n] + 2*s3[n] - 2*s4[n]; w2[n] = s1[n] + s2[n] + 4*s3[n] + 4*s4[n]; w3[n] = s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + s5[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0]; d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1]; d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2]; d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3]; d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4]; d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5]; } // Y = A_T * w_t for (int n = 0; n < 4; n++) { o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n] + bias0; o1[n] = d1[n] - d2[n] + 2*d3[n] - 2*d4[n] + bias0; o2[n] = d1[n] + d2[n] + 4*d3[n] + 4*d4[n] + bias0; o3[n] = d1[n] - d2[n] + 8*d3[n] - 8*d4[n] + d5[n] + bias0; } // save to top blob tm for (int n = 0; n < 4; n++) { outRow0[n] = o0[n]; outRow1[n] = o1[n]; outRow2[n] = o2[n]; outRow3[n] = o3[n]; } outRow0 += 4; outRow1 += 4; outRow2 += 4; outRow3 += 4; } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt.blob_allocator, opt.num_threads); } static void conv3x3s2_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q = 0; q < inch; q++) { float *outptr = out; const float *img = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*9 + q*9; const float *r0 = img; const float *r1 = img + w; const float *r2 = img + w * 2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; for (int i = 0; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } }
3d7pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 4; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(8*t2-Nz,4)),t1);t3<=min(min(min(floord(Nt+Ny-4,4),floord(4*t1+Ny+5,4)),floord(8*t2+Ny+4,4)),floord(8*t1-8*t2+Nz+Ny+3,4));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(8*t2-Nz-60,64)),ceild(4*t3-Ny-60,64));t4<=min(min(min(min(floord(4*t3+Nx,64),floord(Nt+Nx-4,64)),floord(4*t1+Nx+5,64)),floord(8*t2+Nx+4,64)),floord(8*t1-8*t2+Nz+Nx+3,64));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),4*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),4*t3+2),64*t4+62),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(4*t3,t5+1);t7<=min(4*t3+3,t5+Ny-2);t7++) { lbv=max(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
jacobi-2d-imper.par2d.c
#include <math.h> #include <omp.h> #define ceild(n, d) ceil(((double)(n)) / ((double)(d))) #define floord(n, d) floor(((double)(n)) / ((double)(d))) #define max(x, y) ((x) > (y) ? (x) : (y)) #define min(x, y) ((x) < (y) ? (x) : (y)) int t1, t2, t3, t4, t5, t6; register int lb, ub, lb1, ub1, lb2, ub2; register int lbv, ubv; omp_set_nested(1); omp_set_num_threads(2); /* Generated from PLUTO-produced CLooG file by CLooG v0.14.1 64 bits in 0.27s. */ if ((T >= 1) && (N >= 4)) { for (t1 = -2; t1 <= floord(5 * T + 2 * N - 7, 32); t1++) { lb1 = max(max(max(0, ceild(64 * t1 - 2 * N - 83, 160)), ceild(32 * t1 - 3 * T - N + 4, 32)), ceild(32 * t1 - T - N - 26, 64)); ub1 = min(min(min(floord(64 * t1 + 3 * N + 115, 160), floord(32 * t1 + N + 58, 64)), floord(8 * t1 + 15, 8)), floord(2 * T + N - 3, 32)); #pragma omp parallel for shared(t1, lb1, ub1) private(lb2, ub2, t2, t3, t4, \ t5, t6) for (t2 = lb1; t2 <= ub1; t2++) { lb2 = max(max(max(max(ceild(32 * t1 - 32 * t2 - T + 1, 32), 0), ceild(32 * t2 - N - 27, 32)), ceild(64 * t1 - 64 * t2 - 29, 96)), ceild(64 * t1 - 96 * t2 - 29, 64)); ub2 = min(min(min(min(floord(32 * t1 - 32 * t2 + 31, 32), floord(64 * t1 - 96 * t2 + N + 61, 64)), floord(2 * T + N - 3, 32)), floord(32 * t2 + N + 27, 32)), floord(64 * t1 - 64 * t2 + N + 61, 96)); #pragma omp parallel for shared(t1, t2, lb1, ub1, lb2, ub2) private(t3, t4, \ t5, t6) for (t3 = lb2; t3 <= ub2; t3++) { if ((t1 <= floord(64 * t2 + 96 * t3 - N + 1, 64)) && (t2 <= t3) && (t3 >= ceild(N - 1, 32))) { if ((-N + 1) % 2 == 0) { for (t5 = max(32 * t3 - N + 4, 32 * t2); t5 <= min(32 * t3, 32 * t2 + 31); t5++) { if ((-N + 1) % 2 == 0) { a[-32 * t3 + t5 + N - 2][N - 2] = b[-32 * t3 + t5 + N - 2][N - 2]; ; } } } } if ((t1 <= floord(96 * t2 + 64 * t3 - N + 1, 64)) && (t2 >= max(ceild(N - 1, 32), ceild(32 * t3 + 1, 32)))) { if ((-N + 1) % 2 == 0) { for (t6 = max(32 * t2 - N + 4, 32 * t3); t6 <= min(32 * t2, 32 * t3 + 31); t6++) { if ((-N + 1) % 2 == 0) { a[N - 2][-32 * t2 + t6 + N - 2] = b[N - 2][-32 * t2 + t6 + N - 2]; ; } } } } if (N == 4) { for (t4 = max(max(max(0, 16 * t2 - 1), 16 * t3 - 1), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(T - 1, 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t3 + 14), 16 * t2 + 14); t4++) { b[2][2] = 0.2 * (a[2][2] + a[2][2 - 1] + a[2][1 + 2] + a[1 + 2][2] + a[2 - 1][2]); ; a[2][2] = b[2][2]; ; } } for (t4 = max(max(max(0, ceild(32 * t2 - N + 2, 2)), ceild(32 * t3 - N + 2, 2)), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(min(min(16 * t2 - 2, 16 * t3 - 2), floord(32 * t3 - N + 32, 2)), T - 1), 32 * t1 - 32 * t2 - 32 * t3 + 31), floord(32 * t2 - N + 32, 2)); t4++) { for (t5 = 32 * t2; t5 <= 2 * t4 + N - 2; t5++) { for (t6 = 32 * t3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } for (t6 = 32 * t3; t6 <= 2 * t4 + N - 1; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } for (t4 = max(max(max(16 * t2 - 1, 0), ceild(32 * t3 - N + 2, 2)), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(16 * t3 - 2, T - 1), 32 * t1 - 32 * t2 - 32 * t3 + 31), floord(32 * t2 - N + 32, 2)); t4++) { for (t6 = 32 * t3; t6 <= 2 * t4 + N - 2; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 2 * t4 + N - 2; t5++) { for (t6 = 32 * t3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } for (t6 = 32 * t3; t6 <= 2 * t4 + N - 1; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } for (t4 = max(max(max(16 * t3 - 1, 0), ceild(32 * t2 - N + 2, 2)), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(16 * t2 - 2, floord(32 * t3 - N + 32, 2)), T - 1), 32 * t1 - 32 * t2 - 32 * t3 + 31); t4++) { for (t5 = 32 * t2; t5 <= 2 * t4 + N - 2; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } for (t6 = 2 * t4 + 3; t6 <= 2 * t4 + N - 1; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } for (t4 = max(max(max(0, ceild(32 * t3 - N + 2, 2)), 32 * t1 - 32 * t2 - 32 * t3), ceild(32 * t2 - N + 33, 2)); t4 <= min(min(min(T - 1, 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t2 - 2), floord(32 * t3 - N + 32, 2)); t4++) { for (t5 = 32 * t2; t5 <= 32 * t2 + 31; t5++) { for (t6 = 32 * t3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } } for (t4 = max(max(max(ceild(32 * t3 - N + 33, 2), 32 * t1 - 32 * t2 - 32 * t3), 0), ceild(32 * t2 - N + 2, 2)); t4 <= min(min(min(16 * t3 - 2, T - 1), 32 * t1 - 32 * t2 - 32 * t3 + 31), floord(32 * t2 - N + 32, 2)); t4++) { for (t5 = 32 * t2; t5 <= 2 * t4 + N - 2; t5++) { for (t6 = 32 * t3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } for (t6 = 32 * t3; t6 <= 32 * t3 + 31; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } if (N >= 5) { for (t4 = max(max(max(16 * t2 - 1, 16 * t3 - 1), 0), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(floord(32 * t3 - N + 32, 2), T - 1), 32 * t1 - 32 * t2 - 32 * t3 + 31), floord(32 * t2 - N + 32, 2)); t4++) { for (t6 = 2 * t4 + 2; t6 <= 2 * t4 + N - 2; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 2 * t4 + N - 2; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } for (t6 = 2 * t4 + 3; t6 <= 2 * t4 + N - 1; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } } for (t4 = max(max(max(max(16 * t2 - 1, 0), ceild(32 * t3 - N + 2, 2)), 32 * t1 - 32 * t2 - 32 * t3), ceild(32 * t2 - N + 33, 2)); t4 <= min(min(min(min(T - 1, 16 * t3 - 2), 16 * t2 + 14), 32 * t1 - 32 * t2 - 32 * t3 + 31), floord(32 * t3 - N + 32, 2)); t4++) { for (t6 = 32 * t3; t6 <= 2 * t4 + N - 2; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 32 * t2 + 31; t5++) { for (t6 = 32 * t3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } } for (t4 = max(max(max(max(ceild(32 * t3 - N + 33, 2), 16 * t3 - 1), 0), ceild(32 * t2 - N + 2, 2)), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(min(16 * t2 - 2, T - 1), 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t3 + 14), floord(32 * t2 - N + 32, 2)); t4++) { for (t5 = 32 * t2; t5 <= 2 * t4 + N - 2; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } for (t6 = 2 * t4 + 3; t6 <= 32 * t3 + 31; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } for (t4 = max(max(max(0, 32 * t1 - 32 * t2 - 32 * t3), ceild(32 * t3 - N + 33, 2)), ceild(32 * t2 - N + 33, 2)); t4 <= min(min(min(T - 1, 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t2 - 2), 16 * t3 - 2); t4++) { for (t5 = 32 * t2; t5 <= 32 * t2 + 31; t5++) { for (t6 = 32 * t3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } } for (t4 = max(max(max(0, 32 * t1 - 32 * t2 - 32 * t3), 16 * t3 - 1), ceild(32 * t2 - N + 33, 2)); t4 <= min(min(min(T - 1, 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t2 + 14), floord(32 * t3 - N + 32, 2)); t4++) { for (t6 = 2 * t4 + 2; t6 <= 2 * t4 + N - 2; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 32 * t2 + 31; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 2 * t4 + N - 2; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } a[-2 * t4 + t5 - 1][N - 2] = b[-2 * t4 + t5 - 1][N - 2]; ; } } for (t4 = max(max(max(16 * t2 - 1, 0), ceild(32 * t3 - N + 33, 2)), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(T - 1, 16 * t3 - 2), 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t2 + 14); t4++) { for (t6 = 32 * t3; t6 <= 32 * t3 + 31; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 32 * t2 + 31; t5++) { for (t6 = 32 * t3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } } for (t4 = max(max(max(16 * t2 - 1, ceild(32 * t3 - N + 33, 2)), 0), 32 * t1 - 32 * t2 - 32 * t3); t4 <= min(min(min(T - 1, 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t3 + 14), floord(32 * t2 - N + 32, 2)); t4++) { for (t6 = 2 * t4 + 2; t6 <= 32 * t3 + 31; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 2 * t4 + N - 2; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } for (t6 = 2 * t4 + 3; t6 <= 32 * t3 + 31; t6++) { a[N - 2][-2 * t4 + t6 - 1] = b[N - 2][-2 * t4 + t6 - 1]; ; } } for (t4 = max(max(max(0, 32 * t1 - 32 * t2 - 32 * t3), 16 * t3 - 1), ceild(32 * t2 - N + 33, 2)); t4 <= min(min(min(T - 1, 16 * t3 + 14), 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t2 - 2); t4++) { for (t5 = 32 * t2; t5 <= 32 * t2 + 31; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } } for (t4 = max( max(max(max(max(16 * t2 - 1, 0), 32 * t1 - 32 * t2 - 32 * t3), ceild(32 * t3 - N + 33, 2)), 16 * t3 - 1), ceild(32 * t2 - N + 33, 2)); t4 <= min(min(min(T - 1, 16 * t3 + 14), 32 * t1 - 32 * t2 - 32 * t3 + 31), 16 * t2 + 14); t4++) { for (t6 = 2 * t4 + 2; t6 <= 32 * t3 + 31; t6++) { b[2][-2 * t4 + t6] = 0.2 * (a[2][-2 * t4 + t6] + a[2][-2 * t4 + t6 - 1] + a[2][1 + -2 * t4 + t6] + a[1 + 2][-2 * t4 + t6] + a[2 - 1][-2 * t4 + t6]); ; } for (t5 = 2 * t4 + 3; t5 <= 32 * t2 + 31; t5++) { b[-2 * t4 + t5][2] = 0.2 * (a[-2 * t4 + t5][2] + a[-2 * t4 + t5][2 - 1] + a[-2 * t4 + t5][1 + 2] + a[1 + -2 * t4 + t5][2] + a[-2 * t4 + t5 - 1][2]); ; for (t6 = 2 * t4 + 3; t6 <= 32 * t3 + 31; t6++) { b[-2 * t4 + t5][-2 * t4 + t6] = 0.2 * (a[-2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5][-2 * t4 + t6 - 1] + a[-2 * t4 + t5][1 + -2 * t4 + t6] + a[1 + -2 * t4 + t5][-2 * t4 + t6] + a[-2 * t4 + t5 - 1][-2 * t4 + t6]); ; a[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1] = b[-2 * t4 + t5 - 1][-2 * t4 + t6 - 1]; ; } } } } } } } /* End of CLooG code */
pngquant.c
/* pngquant.c - quantize the colors in an alphamap down to a specified number ** ** Copyright (C) 1989, 1991 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. ** ** - - - - ** ** © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. ** © 2009-2015 by Kornel Lesiński. ** ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdbool.h> #include <getopt.h> #include <unistd.h> #include "pngquant.h" extern char *optarg; extern int optind, opterr; #if defined(WIN32) || defined(__WIN32__) # include <fcntl.h> /* O_BINARY */ # include <io.h> /* setmode() */ #endif #ifdef _OPENMP #include <omp.h> #else #define omp_get_max_threads() 1 #define omp_get_thread_num() 0 #endif static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, png8_image *output_image); static void set_palette(liq_result *result, png8_image *output_image); static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool verbose); static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options); static char *add_filename_extension(const char *filename, const char *newext); static bool file_exists(const char *outname); static void verbose_printf(struct pngquant_options *context, const char *fmt, ...) { if (context->log_callback) { va_list va; va_start(va, fmt); int required_space = vsnprintf(NULL, 0, fmt, va)+1; // +\0 va_end(va); char buf[required_space]; va_start(va, fmt); vsnprintf(buf, required_space, fmt, va); va_end(va); context->log_callback(context->liq, buf, context->log_callback_user_info); } } static void log_callback(const liq_attr *attr, const char *msg, void* user_info) { fprintf(stderr, "%s\n", msg); } #ifdef _OPENMP #define LOG_BUFFER_SIZE 1300 struct buffered_log { int buf_used; char buf[LOG_BUFFER_SIZE]; }; static void log_callback_buferred_flush(const liq_attr *attr, void *context) { struct buffered_log *log = context; if (log->buf_used) { fwrite(log->buf, 1, log->buf_used, stderr); fflush(stderr); log->buf_used = 0; } } static void log_callback_buferred(const liq_attr *attr, const char *msg, void* context) { struct buffered_log *log = context; int len = strlen(msg); if (len > LOG_BUFFER_SIZE-2) len = LOG_BUFFER_SIZE-2; if (len > LOG_BUFFER_SIZE - log->buf_used - 2) log_callback_buferred_flush(attr, log); memcpy(&log->buf[log->buf_used], msg, len); log->buf_used += len+1; log->buf[log->buf_used-1] = '\n'; log->buf[log->buf_used] = '\0'; } #endif enum {arg_floyd=1, arg_ordered, arg_ext, arg_no_force, arg_iebug, arg_transbug, arg_map, arg_posterize, arg_skip_larger}; static const struct option long_options[] = { {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"force", no_argument, NULL, 'f'}, {"no-force", no_argument, NULL, arg_no_force}, {"floyd", optional_argument, NULL, arg_floyd}, {"ordered", no_argument, NULL, arg_ordered}, {"nofs", no_argument, NULL, arg_ordered}, {"iebug", no_argument, NULL, arg_iebug}, {"transbug", no_argument, NULL, arg_transbug}, {"ext", required_argument, NULL, arg_ext}, {"skip-if-larger", no_argument, NULL, arg_skip_larger}, {"output", required_argument, NULL, 'o'}, {"speed", required_argument, NULL, 's'}, {"quality", required_argument, NULL, 'Q'}, {"posterize", required_argument, NULL, arg_posterize}, {"map", required_argument, NULL, arg_map}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0}, }; pngquant_error pngquant_file(const char *filename, const char *outname, struct pngquant_options *options) { pngquant_error retval = SUCCESS; verbose_printf(options, "%s:", filename); liq_image *input_image = NULL; png24_image input_image_rwpng = {}; bool keep_input_pixels = options->skip_if_larger || (options->using_stdout && options->min_quality_limit); // original may need to be if (SUCCESS == retval) { retval = read_image(options->liq, filename, options->using_stdin, &input_image_rwpng, &input_image, keep_input_pixels, options->verbose); } int quality_percent = 90; // quality on 0-100 scale, updated upon successful remap png8_image output_image = {}; if (SUCCESS == retval) { verbose_printf(options, " read %luKB file", (input_image_rwpng.file_size+1023UL)/1024UL); #if USE_LCMS if (input_image_rwpng.lcms_status == ICCP) { verbose_printf(options, " used embedded ICC profile to transform image to sRGB colorspace"); } else if (input_image_rwpng.lcms_status == GAMA_CHRM) { verbose_printf(options, " used gAMA and cHRM chunks to transform image to sRGB colorspace"); } else if (input_image_rwpng.lcms_status == ICCP_WARN_GRAY) { verbose_printf(options, " warning: ignored ICC profile in GRAY colorspace"); } #endif if (input_image_rwpng.gamma != 0.45455) { verbose_printf(options, " corrected image from gamma %2.1f to sRGB gamma", 1.0/input_image_rwpng.gamma); } // when using image as source of a fixed palette the palette is extracted using regular quantization liq_result *remap; liq_error remap_error = liq_image_quantize(options->fixed_palette_image ? options->fixed_palette_image : input_image, options->liq, &remap); if (LIQ_OK == remap_error) { liq_set_output_gamma(remap, 0.45455); // fixed gamma ~2.2 for the web. PNG can't store exact 1/2.2 liq_set_dithering_level(remap, options->floyd); retval = prepare_output_image(remap, input_image, &output_image); if (SUCCESS == retval) { if (LIQ_OK != liq_write_remapped_image_rows(remap, input_image, output_image.row_pointers)) { retval = OUT_OF_MEMORY_ERROR; } set_palette(remap, &output_image); double palette_error = liq_get_quantization_error(remap); if (palette_error >= 0) { quality_percent = liq_get_quantization_quality(remap); verbose_printf(options, " mapped image to new colors...MSE=%.3f (Q=%d)", palette_error, quality_percent); } } liq_result_destroy(remap); } else if (LIQ_QUALITY_TOO_LOW == remap_error) { retval = TOO_LOW_QUALITY; } else { retval = INVALID_ARGUMENT; // dunno } } if (SUCCESS == retval) { if (options->skip_if_larger) { // this is very rough approximation, but generally avoid losing more quality than is gained in file size. // Quality is squared, because even greater savings are needed to justify big quality loss. double quality = quality_percent/100.0; output_image.maximum_file_size = (input_image_rwpng.file_size-1) * quality*quality; } output_image.fast_compression = options->fast_compression; output_image.chunks = input_image_rwpng.chunks; input_image_rwpng.chunks = NULL; retval = write_image(&output_image, NULL, outname, options); if (TOO_LARGE_FILE == retval) { verbose_printf(options, " file exceeded expected size of %luKB", (unsigned long)output_image.maximum_file_size/1024UL); } } if (options->using_stdout && keep_input_pixels && (TOO_LARGE_FILE == retval || TOO_LOW_QUALITY == retval)) { // when outputting to stdout it'd be nasty to create 0-byte file // so if quality is too low, output 24-bit original pngquant_error write_retval = write_image(NULL, &input_image_rwpng, outname, options); if (write_retval) { retval = write_retval; } } if (input_image) liq_image_destroy(input_image); rwpng_free_image24(&input_image_rwpng); rwpng_free_image8(&output_image); return retval; } static void set_palette(liq_result *result, png8_image *output_image) { const liq_palette *palette = liq_get_palette(result); output_image->num_palette = palette->count; for(unsigned int i=0; i < palette->count; i++) { liq_color px = palette->entries[i]; output_image->palette[i] = (rwpng_rgba){.r=px.r, .g=px.g, .b=px.b, .a=px.a}; } } static bool file_exists(const char *outname) { FILE *outfile = fopen(outname, "rb"); if ((outfile ) != NULL) { fclose(outfile); return true; } return false; } /* build the output filename from the input name by inserting "-fs8" or * "-or8" before the ".png" extension (or by appending that plus ".png" if * there isn't any extension), then make sure it doesn't exist already */ static char *add_filename_extension(const char *filename, const char *newext) { size_t x = strlen(filename); char* outname = malloc(x+4+strlen(newext)+1); if (!outname) return NULL; strncpy(outname, filename, x); if (strncmp(outname+x-4, ".png", 4) == 0 || strncmp(outname+x-4, ".PNG", 4) == 0) { strcpy(outname+x-4, newext); } else { strcpy(outname+x, newext); } return outname; } static char *temp_filename(const char *basename) { size_t x = strlen(basename); char *outname = malloc(x+1+4); if (!outname) return NULL; strcpy(outname, basename); strcpy(outname+x, ".tmp"); return outname; } static void set_binary_mode(FILE *fp) { #if defined(WIN32) || defined(__WIN32__) setmode(fp == stdout ? 1 : 0, O_BINARY); #endif } static const char *filename_part(const char *path) { const char *outfilename = strrchr(path, '/'); if (outfilename) { return outfilename+1; } else { return path; } } static bool replace_file(const char *from, const char *to, const bool force) { #if defined(WIN32) || defined(__WIN32__) if (force) { // On Windows rename doesn't replace unlink(to); } #endif return (0 == rename(from, to)); } static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options) { FILE *outfile; char *tempname = NULL; if (options->using_stdout) { set_binary_mode(stdout); outfile = stdout; if (output_image) { verbose_printf(options, " writing %d-color image to stdout", output_image->num_palette); } else { verbose_printf(options, " writing truecolor image to stdout"); } } else { tempname = temp_filename(outname); if (!tempname) return OUT_OF_MEMORY_ERROR; if ((outfile = fopen(tempname, "wb")) == NULL) { fprintf(stderr, " error: cannot open '%s' for writing\n", tempname); free(tempname); return CANT_WRITE_ERROR; } if (output_image) { verbose_printf(options, " writing %d-color image as %s", output_image->num_palette, filename_part(outname)); } else { verbose_printf(options, " writing truecolor image as %s", filename_part(outname)); } } pngquant_error retval; #pragma omp critical (libpng) { if (output_image) { retval = rwpng_write_image8(outfile, output_image); } else { retval = rwpng_write_image24(outfile, output_image24); } } if (!options->using_stdout) { fclose(outfile); if (SUCCESS == retval) { // Image has been written to a temporary file and then moved over destination. // This makes replacement atomic and avoids damaging destination file on write error. if (!replace_file(tempname, outname, options->force)) { retval = CANT_WRITE_ERROR; } } if (retval) { unlink(tempname); } } free(tempname); if (retval && retval != TOO_LARGE_FILE) { fprintf(stderr, " error: failed writing image to %s\n", outname); } return retval; } static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool verbose) { FILE *infile; if (using_stdin) { set_binary_mode(stdin); infile = stdin; } else if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, " error: cannot open %s for reading\n", filename); return READ_ERROR; } pngquant_error retval; #pragma omp critical (libpng) { retval = rwpng_read_image24(infile, input_image_p, false, verbose); } if (!using_stdin) { fclose(infile); } if (retval) { fprintf(stderr, " error: cannot decode image %s\n", using_stdin ? "from stdin" : filename_part(filename)); return retval; } *liq_image_p = liq_image_create_rgba_rows(options, (void**)input_image_p->row_pointers, input_image_p->width, input_image_p->height, input_image_p->gamma); if (!*liq_image_p) { return OUT_OF_MEMORY_ERROR; } if (!keep_input_pixels) { if (LIQ_OK != liq_image_set_memory_ownership(*liq_image_p, LIQ_OWN_ROWS | LIQ_OWN_PIXELS)) { return OUT_OF_MEMORY_ERROR; } input_image_p->row_pointers = NULL; input_image_p->rgba_data = NULL; } return SUCCESS; } static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, png8_image *output_image) { output_image->width = liq_image_get_width(input_image); output_image->height = liq_image_get_height(input_image); output_image->gamma = liq_get_output_gamma(result); /* ** Step 3.7 [GRR]: allocate memory for the entire indexed image */ output_image->indexed_data = malloc(output_image->height * output_image->width); output_image->row_pointers = malloc(output_image->height * sizeof(output_image->row_pointers[0])); if (!output_image->indexed_data || !output_image->row_pointers) { return OUT_OF_MEMORY_ERROR; } for(size_t row = 0; row < output_image->height; row++) { output_image->row_pointers[row] = output_image->indexed_data + row * output_image->width; } const liq_palette *palette = liq_get_palette(result); // tRNS, etc. output_image->num_palette = palette->count; return SUCCESS; }
pi_block.c
/* This program will numerically compute the integral of 4/(1+x*x) from 0 to 1. The value of this integral is pi -- which is great since it gives us an easy way to check the answer. The is the original sequential program. It uses the timer from the OpenMP runtime library History: Written by Tim Mattson, 11/99. edited by Tan Chengsong, parallel program with padding 7/2017 */ #include <stdio.h> #include <omp.h> #define NUM_THREADS 4 #define PADDING 8 static long num_steps = 100000000; double step; int main () { double pi = 0; double start_time, run_time; step = 1.0/(double) num_steps; start_time = omp_get_wtime(); int block_len = num_steps/NUM_THREADS; double sum[NUM_THREADS][PADDING]; #pragma omp parallel num_threads(NUM_THREADS) { int i; int ID = omp_get_thread_num(); sum[ID][0] = 0.0; int start = ID * block_len; int end = start + block_len; double x; for (i = start + 1; i <= end; i++){ x = (i-0.5)*step; sum[ID][0] = sum[ID][0] + 4.0/(1.0+x*x); } } int j; for(j = 0; j < NUM_THREADS; j++) pi += step * sum[j][0]; //pi = step * sum; run_time = omp_get_wtime() - start_time; printf("\n pi with %ld steps is %lf in %lf seconds\n ",num_steps,pi,run_time); }
GB_unop__abs_int64_int64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__abs_int64_int64) // op(A') function: GB (_unop_tran__abs_int64_int64) // C type: int64_t // A type: int64_t // cast: int64_t cij = aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ int64_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IABS (x) ; // casting #define GB_CAST(z, aij) \ int64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = aij ; \ Cx [pC] = GB_IABS (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__abs_int64_int64) ( int64_t *Cx, // Cx and Ax may be aliased const int64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t aij = Ax [p] ; int64_t z = aij ; Cx [p] = GB_IABS (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int64_t aij = Ax [p] ; int64_t z = aij ; Cx [p] = GB_IABS (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__abs_int64_int64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
main.c
#include <stdio.h> #include <math.h> #include <omp.h> #define mm 15 #define npart 4*mm*mm*mm /* * Function declarations */ void dfill(int,double,double[],int); void domove(int,double[],double[],double[],double); void dscal(int,double,double[],int); void fcc(double[],int,int,double); void forces(int,double[],double[],double,double); double mkekin(int,double[],double[],double,double); void mxwell(double[],int,double,double); void prnout(int,double,double,double,double,double,double,int,double); double velavg(int,double[],double,double); double secnds(void); /* * Variable declarations */ double epot; double vir; double count; /* * Main program : Molecular Dynamics simulation. */ int main(){ int move; double x[npart*3], vh[npart*3], f[npart*3]; double ekin; double vel; double sc; double start, time; /* * Parameter definitions */ double den = 0.83134; double side = pow((double)npart/den,0.3333333); double tref = 0.722; double rcoff = (double)mm/4.0; double h = 0.064; int irep = 10; int istop = 20; int iprint = 5; int movemx = 20; double a = side/(double)mm; double hsq = h*h; double hsq2 = hsq*0.5; double tscale = 16.0/((double)npart-1.0); double vaver = 1.13*sqrt(tref/24.0); /* * Initial output */ printf(" Molecular Dynamics Simulation example program\n"); printf(" ---------------------------------------------\n"); printf(" number of particles is ............ %6d\n",npart); printf(" side length of the box is ......... %13.6f\n",side); printf(" cut off is ........................ %13.6f\n",rcoff); printf(" reduced temperature is ............ %13.6f\n",tref); printf(" basic timestep is ................. %13.6f\n",h); printf(" temperature scale interval ........ %6d\n",irep); printf(" stop scaling at move .............. %6d\n",istop); printf(" print interval .................... %6d\n",iprint); printf(" total no. of steps ................ %6d\n",movemx); /* * Generate fcc lattice for atoms inside box */ fcc(x, npart, mm, a); /* * Initialise velocities and forces (which are zero in fcc positions) */ mxwell(vh, 3*npart, h, tref); dfill(3*npart, 0.0, f, 1); /* * Start of md */ printf("\n i ke pe e temp " " pres vel rp\n ----- ---------- ----------" " ---------- -------- -------- -------- ----\n"); start = secnds(); #pragma omp parallel default(shared) private(move) { for (move=1; move<=movemx; move++) { /* * Move the particles and partially update velocities */ #pragma omp single { domove(3*npart, x, vh, f, side); } /* * Compute forces in the new positions and accumulate the virial * and potential energy. */ forces(npart, x, f, side, rcoff); /* * Scale forces, complete update of velocities and compute k.e. */ #pragma omp single { ekin=mkekin(npart, f, vh, hsq2, hsq); /* * Average the velocity and temperature scale if desired */ vel=velavg(npart, vh, vaver, h); if (move<istop && fmod(move, irep)==0) { sc=sqrt(tref/(tscale*ekin)); dscal(3*npart, sc, vh, 1); ekin=tref/tscale; } /* * Sum to get full potential energy and virial */ if (fmod(move, iprint)==0) prnout(move, ekin, epot, tscale, vir, vel, count, npart, den); } } } time = secnds() - start; printf("Time = %f\n",(float) time); } double secnds() { return omp_get_wtime(); }
GB_binop__iseq_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__iseq_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__iseq_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__iseq_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__iseq_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_uint8) // A*D function (colscale): GB (_AxD__iseq_uint8) // D*A function (rowscale): GB (_DxB__iseq_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__iseq_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__iseq_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_uint8) // C=scalar+B GB (_bind1st__iseq_uint8) // C=scalar+B' GB (_bind1st_tran__iseq_uint8) // C=A+scalar GB (_bind2nd__iseq_uint8) // C=A'+scalar GB (_bind2nd_tran__iseq_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISEQ || GxB_NO_UINT8 || GxB_NO_ISEQ_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__iseq_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__iseq_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__iseq_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__iseq_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__iseq_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__iseq_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__iseq_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__iseq_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
locks_example.c
//===-- locks_example.c - Example for lock usage ------------------*- C -*-===// // // Part of the LOMP Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <stdio.h> #include <omp.h> int main(void) { double d = 42.0; float f = 21.42; int x = 21; omp_lock_t lock; omp_init_lock(&lock); printf("Before parallel region\n"); printf("=======================================\n"); #pragma omp parallel shared(x, d, f) shared(lock) { omp_set_lock(&lock); printf("Hello World: "); printf("my secret is %lf ", d + f); printf("and %d\n", x); omp_unset_lock(&lock); } printf("=======================================\n"); printf("After parallel region\n"); omp_destroy_lock(&lock); return 0; }
level.c
//------------------------------------------------------------------------------------------------------------------------------ // 1. support of non-even distribution ? // // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <math.h> //------------------------------------------------------------------------------------------------------------------------------ // #ifdef USE_MPI // #include <mpi.h> // #endif #ifdef _OPENMP #include <omp.h> #endif //------------------------------------------------------------------------------------------------------------------------------ #include "level.h" #include "operators.h" //------------------------------------------------------------------------------------------------------------------------------ #define BOX_ALIGN_1ST_CELL 4096 // Align to TLB page... //------------------------------------------------------------------------------------------------------------------------------ #ifdef USE_UPCXX extern hclib::upcxx::shared_array< hclib::upcxx::global_ptr<double>, 1 > upc_buf_info; extern hclib::upcxx::shared_array< hclib::upcxx::global_ptr<box_type>, 1> upc_box_info; extern hclib::upcxx::shared_array< int, 1> upc_int_info; #endif //------------------------------------------------------------------------------------------------------------------------------ void print_communicator(int printSendRecv, int rank, int level, communicator_type *comm){ int i; printf("rank=%2d level=%d ",rank,level); if(printSendRecv & 0x1){ printf("num_sends=%2d ",comm->num_sends); printf("send_ranks=[ ");for(i=0;i<comm->num_sends;i++)printf("%2d ",comm->send_ranks[i]);printf("] "); printf("send_sizes=[ ");for(i=0;i<comm->num_sends;i++)printf("%2d ",comm->send_sizes[i]);printf("] "); printf("send_buffers=[ ");for(i=0;i<comm->num_sends;i++)printf("%08lx ",(uint64_t)comm->send_buffers[i]);printf("] "); for(i=0;i<comm->num_blocks[0];i++)printf("[ %dx%dx%d from %d %d %d %d %d to %d %d %d %d %d ] ",comm->blocks[0][i].dim.i,comm->blocks[0][i].dim.j,comm->blocks[0][i].dim.k,comm->blocks[0][i].read.i,comm->blocks[0][i].read.j,comm->blocks[0][i].read.k,comm->blocks[0][i].read.jStride,comm->blocks[0][i].read.kStride,comm->blocks[0][i].write.i,comm->blocks[0][i].write.j,comm->blocks[0][i].write.k,comm->blocks[0][i].write.jStride,comm->blocks[0][i].write.kStride); printf("\n"); } if(printSendRecv & 0x2){ for(i=0;i<comm->num_blocks[1];i++)printf("[ %dx%dx%d from %d %d %d %d %d to %d %d %d %d %d ] ",comm->blocks[1][i].dim.i,comm->blocks[1][i].dim.j,comm->blocks[1][i].dim.k,comm->blocks[1][i].read.i,comm->blocks[1][i].read.j,comm->blocks[1][i].read.k,comm->blocks[1][i].read.jStride,comm->blocks[1][i].read.kStride,comm->blocks[1][i].write.i,comm->blocks[1][i].write.j,comm->blocks[1][i].write.k,comm->blocks[1][i].write.jStride,comm->blocks[1][i].write.kStride); printf("\n"); } if(printSendRecv & 0x4){ printf("num_recvs=%2d ",comm->num_recvs); printf("recv_ranks=[ ");for(i=0;i<comm->num_recvs;i++)printf("%2d ",comm->recv_ranks[i]);printf("] "); printf("recv_sizes=[ ");for(i=0;i<comm->num_recvs;i++)printf("%2d ",comm->recv_sizes[i]);printf("] "); printf("recv_buffers=[ ");for(i=0;i<comm->num_recvs;i++)printf("%08lx ",(uint64_t)comm->recv_buffers[i]);printf("] "); for(i=0;i<comm->num_blocks[2];i++)printf("[ %dx%dx%d from %d %d %d %d %d to %d %d %d %d %d ] ",comm->blocks[2][i].dim.i,comm->blocks[2][i].dim.j,comm->blocks[2][i].dim.k,comm->blocks[2][i].read.i,comm->blocks[2][i].read.j,comm->blocks[2][i].read.k,comm->blocks[2][i].read.jStride,comm->blocks[2][i].read.kStride,comm->blocks[2][i].write.i,comm->blocks[2][i].write.j,comm->blocks[2][i].write.k,comm->blocks[2][i].write.jStride,comm->blocks[2][i].write.kStride); // for(i=0;i<comm->num_blocks[2];i++)printf("[ %dx%dx%d pos %d from %d for %d]\n", comm->blocks[2][i].dim.i,comm->blocks[2][i].dim.j,comm->blocks[2][i].dim.k, i, comm->blocks[2][i].read.box, MYTHREAD); printf("\n"); } fflush(stdout); } //------------------------------------------------------------------------------------------------------------------------------ typedef struct { int sendRank; int sendBoxID; int sendBox; int sendDir; int recvRank; int recvBoxID; int recvBox; } GZ_type; int qsortGZ(const void *a, const void*b){ GZ_type *gza = (GZ_type*)a; GZ_type *gzb = (GZ_type*)b; // by convention, MPI buffers are first sorted by sendRank if(gza->sendRank < gzb->sendRank)return(-1); if(gza->sendRank > gzb->sendRank)return( 1); // then by sendBoxID if(gza->sendBoxID < gzb->sendBoxID)return(-1); if(gza->sendBoxID > gzb->sendBoxID)return( 1); // and finally by the direction sent if(gza->sendDir < gzb->sendDir)return(-1); if(gza->sendDir > gzb->sendDir)return( 1); return(0); } int qsortInt(const void *a, const void *b){ int *ia = (int*)a; int *ib = (int*)b; if(*ia < *ib)return(-1); if(*ia > *ib)return( 1); return( 0); } //------------------------------------------------------------------------------------------------------------------------------ int create_box(box_type *box, int numVectors, int dim, int ghosts){ uint64_t memory_allocated = 0; box->numVectors = numVectors; box->dim = dim; box->ghosts = ghosts; #ifndef BOX_SIMD_ALIGNMENT #define BOX_SIMD_ALIGNMENT 1 // allignment requirement for j+/-1 #endif box->jStride = (dim+2*ghosts);while(box->jStride % BOX_SIMD_ALIGNMENT)box->jStride++; // pencil #ifndef BOX_PLANE_PADDING #define BOX_PLANE_PADDING 8 // scratch space to avoid unrolled loop cleanup #endif box->kStride = box->jStride*(dim+2*ghosts); // plane if(box->jStride<BOX_PLANE_PADDING)box->kStride += (BOX_PLANE_PADDING-box->jStride); // allow the ghost zone to be clobbered... while(box->kStride % BOX_SIMD_ALIGNMENT)box->kStride++; #if 0 // pad each plane such that // 1. it is greater than a multiple of the maximum unrolling (or vector length) // 2. it carries the same alignement as the plane above/below. i.e. if ijk is aligned, ijkk+/-plane is aligned //int MaxUnrolling = 8; // 2-way SIMD x unroll by 4 = 8/thread int MaxUnrolling = 16; // 4-way SIMD x unroll by 4 = 16/thread //int MaxUnrolling = 32; // 8-way SIMD x unroll by 4 = 32/thread int paddingToAvoidStencilCleanup = 0; if(box->jStride < (MaxUnrolling-1)){paddingToAvoidStencilCleanup = (MaxUnrolling-1)-(box->jStride);} // allows partial clobbering of ghost zone //box->kStride =( ((dim+2*ghosts)*box->jStride)+paddingToAvoidStencilCleanup+0xF) & ~0xF; // multiple of 128 bytes box->kStride =( ((dim+2*ghosts)*box->jStride)+paddingToAvoidStencilCleanup+0x7) & ~0x7; // multiple of 64 bytes (required for MIC) //box->kStride =( ((dim+2*ghosts)*box->jStride)+paddingToAvoidStencilCleanup+0x3) & ~0x3; // multiple of 32 bytes (required for AVX/QPX) //box->kStride =( ((dim+2*ghosts)*box->jStride)+paddingToAvoidStencilCleanup+0x1) & ~0x1; // multiple of 16 bytes (required for SSE) #endif box->volume = (dim+2*ghosts)*box->kStride; #ifdef USE_UPCXX box->vectors = hclib::upcxx::allocate<hclib::upcxx::global_ptr<double> >(MYTHREAD, box->numVectors); memory_allocated += box->numVectors*sizeof(hclib::upcxx::global_ptr<double>); if((box->numVectors>0)&&(box->vectors==NULL)){fprintf(stderr,"malloc failed - create_box/box->vectors\n");exit(0);} uint64_t malloc_size = box->volume*box->numVectors + BOX_ALIGN_1ST_CELL/sizeof(double); box->vectors_base = hclib::upcxx::allocate<double>(MYTHREAD, malloc_size); memory_allocated += malloc_size; if((box->numVectors>0)&&(box->vectors_base==NULL)){fprintf(stderr,"malloc failed - create_box/box->vectors_base\n");exit(0);} double * tmpbuf = (double *)box->vectors_base; int num = 0; memset(tmpbuf,0,malloc_size*sizeof(double)); // zero to avoid 0.0*NaN or 0.0*Inf while( (uint64_t)(tmpbuf+box->ghosts*(1+box->jStride+box->kStride)) & (BOX_ALIGN_1ST_CELL-1) ){tmpbuf++; num++;} // allign first *non-ghost* zone element of first component to page boundary... int c; for(c=0;c<box->numVectors;c++){ box->vectors[c] = box->vectors_base + c*box->volume + num; } #else // allocate an array of pointers to vectors... box->vectors = (double **)malloc(box->numVectors*sizeof(double*)); memory_allocated += box->numVectors*sizeof(double*); if((box->numVectors>0)&&(box->vectors==NULL)){fprintf(stderr,"malloc failed - create_box/box->vectors\n");exit(0);} // allocate one aligned, double-precision array and divide it among vectors... uint64_t malloc_size = box->volume*box->numVectors*sizeof(double) + BOX_ALIGN_1ST_CELL; // shift pointer by up to 1 TLB page... box->vectors_base = (double*)malloc(malloc_size); memory_allocated += malloc_size; if((box->numVectors>0)&&(box->vectors_base==NULL)){fprintf(stderr,"malloc failed - create_box/box->vectors_base\n");exit(0);} double * tmpbuf = box->vectors_base; while( (uint64_t)(tmpbuf+box->ghosts*(1+box->jStride+box->kStride)) & (BOX_ALIGN_1ST_CELL-1) ){tmpbuf++;} // allign first *non-ghost* zone element of first component to page boundary... memset(tmpbuf,0,box->volume*box->numVectors*sizeof(double)); // zero to avoid 0.0*NaN or 0.0*Inf int c;for(c=0;c<box->numVectors;c++){box->vectors[c] = tmpbuf + c*box->volume;} #endif // USE_UPCXX // done... return the total amount of memory allocated... return(memory_allocated); } //------------------------------------------------------------------------------------------------------------------------------ #ifdef USE_UPCXX void add_vectors_to_box(box_type *box, int numAdditionalVectors){ if(numAdditionalVectors<=0)return; // nothing to do hclib::upcxx::global_ptr<double> old_bp = box->vectors_base; hclib::upcxx::global_ptr<double> old_v0 = box->vectors[0]; hclib::upcxx::global_ptr<hclib::upcxx::global_ptr<double> > old_v = box->vectors; box->numVectors+=numAdditionalVectors; // box->vectors = hclib::upcxx::allocate<hclib::upcxx::global_ptr<double> >(MYTHREAD, box->numVectors); if((box->numVectors>0)&&(box->vectors==NULL)){fprintf(stderr,"malloc failed - add_vectors_to_box/box->vectors\n");exit(0);} // NOTE !!! realloc() cannot guarantee the same alignment... malloc, allign, copy... uint64_t malloc_size = box->volume*box->numVectors + BOX_ALIGN_1ST_CELL/sizeof(double); // shift pointer by up to 1 TLB page... box->vectors_base = hclib::upcxx::allocate<double>(MYTHREAD, malloc_size); if((box->numVectors>0)&&(box->vectors_base==NULL)){fprintf(stderr,"malloc failed - add_vectors_to_box/box->vectors_base\n");exit(0);} double * tmpbuf = (double *)box->vectors_base; memset(tmpbuf,0,malloc_size*sizeof(double)); // zero to avoid 0.0*NaN or 0.0*Inf int num = 0; while( (uint64_t)(tmpbuf+box->ghosts*(1+box->jStride+box->kStride)) & (BOX_ALIGN_1ST_CELL-1) ){tmpbuf++; num++;} // allign first *non-ghost* zone element of first component to page boundary... memcpy(tmpbuf,(double *)old_v0,box->volume*(box->numVectors-numAdditionalVectors)*sizeof(double)); // cout << "NEW BASE " << box->vectors_base + num << " local " << tmpbuf << " num " << num << endl; int c;for(c=0;c<box->numVectors;c++){box->vectors[c] = box->vectors_base + c*box->volume + num;} // pointer arithmetic... hclib::upcxx::deallocate(old_bp); hclib::upcxx::deallocate(old_v ); } #else void add_vectors_to_box(box_type *box, int numAdditionalVectors){ if(numAdditionalVectors<=0)return; // nothing to do double * old_bp = box->vectors_base; // save a pointer to the base pointer for subsequent free... double * old_v0 = box->vectors[0]; // save a pointer to the old FP data... double ** old_v = box->vectors; // save a pointer to the old array of pointers... box->numVectors+=numAdditionalVectors; // box->vectors = (double **)malloc(box->numVectors*sizeof(double*)); // new array of pointers vectors if((box->numVectors>0)&&(box->vectors==NULL)){fprintf(stderr,"malloc failed - add_vectors_to_box/box->vectors\n");exit(0);} // NOTE !!! realloc() cannot guarantee the same alignment... malloc, allign, copy... uint64_t malloc_size = box->volume*box->numVectors*sizeof(double) + BOX_ALIGN_1ST_CELL; // shift pointer by up to 1 TLB page... box->vectors_base = (double*)malloc(malloc_size); if((box->numVectors>0)&&(box->vectors_base==NULL)){fprintf(stderr,"malloc failed - add_vectors_to_box/box->vectors_base\n");exit(0);} double * tmpbuf = box->vectors_base; while( (uint64_t)(tmpbuf+box->ghosts*(1+box->jStride+box->kStride)) & (BOX_ALIGN_1ST_CELL-1) ){tmpbuf++;} // allign first *non-ghost* zone element of first component to page boundary... memset(tmpbuf,0,box->volume*box->numVectors*sizeof(double)); // zero to avoid 0.0*NaN or 0.0*Inf memcpy(tmpbuf,old_v0,box->volume*(box->numVectors-numAdditionalVectors)*sizeof(double)); // copy any existant data over... int c;for(c=0;c<box->numVectors;c++){box->vectors[c] = tmpbuf + c*box->volume;} // pointer arithmetic... free(old_bp); // all vectors were created from one malloc + pointer arithmetic... free(old_v ); // free the list of pointers... } #endif // USE_UPCXX //------------------------------------------------------------------------------------------------------------------------------ void destroy_box(box_type *box){ hclib::upcxx::deallocate(box->vectors_base); // single allocate with pointer arithmetic... hclib::upcxx::deallocate(box->vectors); } //------------------------------------------------------------------------------------------------------------------------------ // should implement a 3D hilbert curve on non pow2 (but cubical) domain sizes //void decompose_level_hilbert(int *rank_of_box, int jStride, int kStride, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int rank_lo, int ranks){ //} //------------------------------------------------------------------------------------------------------------------------------ void decompose_level_lex(int *rank_of_box, int idim, int jdim, int kdim, int ranks){ // simple lexicographical decomposition of the domain (i-j-k ordering) int boxes = idim*jdim*kdim; int i,j,k; for(k=0;k<kdim;k++){ for(j=0;j<jdim;j++){ for(i=0;i<idim;i++){ int b = k*jdim*idim + j*idim + i; rank_of_box[b] = ((uint64_t)ranks*(uint64_t)b)/(uint64_t)boxes; // ranks*b can be as larger than ranks^2... can over flow int }}} } //--------------------------------------------------------------------------------------------------------------------------------------------------- void decompose_level_bisection_special(int *rank_of_box, int jStride, int kStride, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int rank_lo, int ranks){ // recursive bisection (or prime-section) of the domain // can lead to imbalance unless the number of processes and number of boxes per process are chosen well #define numPrimes 13 //int primes[numPrimes] = {41,37,31,29,23,19,17,13,11,7,5,3,2}; int primes[numPrimes] = {2,3,5,7,11,13,17,19,23,29,31,37,41}; int i,j,k,p,f,ff; // base case, no further recursion... if( (ranks==1)|| ((idim==1)&&(jdim==1)&&(kdim==1)) ){ for(i=ilo;i<ilo+idim;i++){ for(j=jlo;j<jlo+jdim;j++){ for(k=klo;k<klo+kdim;k++){ int b = i + j*jStride + k*kStride; rank_of_box[b] = rank_lo; }}} return; } // special cases for perfectly matched problem sizes with numbers of processes (but not powers of 2)... for(p=0;p<numPrimes;p++){ f=primes[p]; if( (kdim>=idim)&&(kdim>=jdim) ){if( (kdim%f==0) && (ranks%f==0) ){for(ff=0;ff<f;ff++)decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo,klo+ff*kdim/f,idim,jdim,kdim/f,rank_lo+ff*ranks/f,ranks/f);return;}} if( (jdim>=idim)&&(jdim>=kdim) ){if( (jdim%f==0) && (ranks%f==0) ){for(ff=0;ff<f;ff++)decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo+ff*jdim/f,klo,idim,jdim/f,kdim,rank_lo+ff*ranks/f,ranks/f);return;}} if( (idim>=jdim)&&(idim>=kdim) ){if( (idim%f==0) && (ranks%f==0) ){for(ff=0;ff<f;ff++)decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo+ff*idim/f,jlo,klo,idim/f,jdim,kdim,rank_lo+ff*ranks/f,ranks/f);return;}} } // try and bisect the domain in the i-dimension if( (idim>=jdim)&&(idim>=kdim) ){ int dim0 = (int)(0.5*(double)idim + 0.50); int dim1 = idim-dim0; int r0 = (int)( 0.5 + (double)ranks*(double)dim0/(double)idim ); int r1 = ranks-r0; decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo ,jlo,klo,dim0,jdim,kdim,rank_lo ,r0); // lo decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo+dim0,jlo,klo,dim1,jdim,kdim,rank_lo+r0,r1); // hi return; } // try and bisect the domain in the j-dimension if( (jdim>=idim)&&(jdim>=kdim) ){ int dim0 = (int)(0.5*(double)jdim + 0.50); int dim1 = jdim-dim0; int r0 = (int)( 0.5 + (double)ranks*(double)dim0/(double)jdim ); int r1 = ranks-r0; decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo ,klo,idim,dim0,kdim,rank_lo ,r0); // lo decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo+dim0,klo,idim,dim1,kdim,rank_lo+r0,r1); // hi return; } // try and bisect the domain in the k-dimension if( (kdim>=idim)&&(kdim>=jdim) ){ int dim0 = (int)(0.5*(double)kdim + 0.50); int dim1 = kdim-dim0; int r0 = (int)( 0.5 + (double)ranks*(double)dim0/(double)kdim ); int r1 = ranks-r0; decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo,klo ,idim,jdim,dim0,rank_lo ,r0); // lo decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo,klo+dim0,idim,jdim,dim1,rank_lo+r0,r1); // hi return; } fprintf(stderr,"decompose_level_bisection_special failed !!!\n");exit(0); } //--------------------------------------------------------------------------------------------------------------------------------------------------- void decompose_level_bisection(int *rank_of_box, int jStride, int kStride, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int ranks, int sfc_offset, int sfc_max_length){ // base case... if( (idim==1) && (jdim==1) && (kdim==1) ){ int b = ilo + jlo*jStride + klo*kStride; rank_of_box[b] = ((uint64_t)ranks*(uint64_t)sfc_offset)/(uint64_t)sfc_max_length; // sfc_max_length is the precomputed maximum length return; } // try and bisect the domain in the i-dimension if( (idim>=jdim)&&(idim>=kdim) ){ int dim0 = (int)(0.5*(double)idim + 0.50); int dim1 = idim-dim0; int sfc_delta = dim0*jdim*kdim; decompose_level_bisection(rank_of_box,jStride,kStride,ilo ,jlo,klo,dim0,jdim,kdim,ranks,sfc_offset ,sfc_max_length); // lo decompose_level_bisection(rank_of_box,jStride,kStride,ilo+dim0,jlo,klo,dim1,jdim,kdim,ranks,sfc_offset+sfc_delta,sfc_max_length); // hi return; } // try and bisect the domain in the j-dimension if( (jdim>=idim)&&(jdim>=kdim) ){ int dim0 = (int)(0.5*(double)jdim + 0.50); int dim1 = jdim-dim0; int sfc_delta = idim*dim0*kdim; decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo ,klo,idim,dim0,kdim,ranks,sfc_offset ,sfc_max_length); // lo decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo+dim0,klo,idim,dim1,kdim,ranks,sfc_offset+sfc_delta,sfc_max_length); // hi return; } // try and bisect the domain in the k-dimension if( (kdim>=idim)&&(kdim>=jdim) ){ int dim0 = (int)(0.5*(double)kdim + 0.50); int dim1 = kdim-dim0; int sfc_delta = idim*jdim*dim0; decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo,klo ,idim,jdim,dim0,ranks,sfc_offset ,sfc_max_length); // lo decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo,klo+dim0,idim,jdim,dim1,ranks,sfc_offset+sfc_delta,sfc_max_length); // hi return; } // failure... fprintf(stderr,"decompose_level_bisection failed !!!\n");exit(0); } //--------------------------------------------------------------------------------------------------------------------------------------------------- void print_decomposition(level_type *level){ if(level->my_rank!=0)return; printf("\n"); int i,j,k; int jStride = level->boxes_in.i; int kStride = level->boxes_in.i*level->boxes_in.j; for(k=level->boxes_in.k-1;k>=0;k--){ // (i,j,k)=(0,0,0) is bottom left corner for(j=level->boxes_in.j-1;j>=0;j--){ // (i,j)=(0,0) is bottom left corner for(i=0;i<j;i++)printf(" "); for(i=0;i<level->boxes_in.i;i++){ int b = i + j*jStride + k*kStride; printf("%4d ",level->rank_of_box[b]); }printf("\n"); }printf("\n\n"); } fflush(stdout); } //------------------------------------------------------------------------------------------------------------------------------ #ifndef BLOCK_LIST_MIN_SIZE #define BLOCK_LIST_MIN_SIZE 1000 #endif void append_block_to_list(blockCopy_type ** blocks, int *allocated_blocks, int *num_blocks, int dim_i, int dim_j, int dim_k, #ifdef USE_UPCXX hclib::upcxx::global_ptr<box_type> read_boxgp, #endif int read_box, double* read_ptr, int read_i, int read_j, int read_k, int read_jStride, int read_kStride, int read_scale, #ifdef USE_UPCXX hclib::upcxx::global_ptr<box_type> write_boxgp, #endif int write_box, double* write_ptr, int write_i, int write_j, int write_k, int write_jStride, int write_kStride, int write_scale, int blockcopy_tile_i, int blockcopy_tile_j, int blockcopy_tile_k, int subtype ){ int ii,jj,kk; // Take a dim_j x dim_k iteration space and tile it into smaller faces of size blockcopy_tile_j x blockcopy_tile_k // This increases the number of blockCopies in the ghost zone exchange and thereby increases the thread-level parallelism // FIX... move from lexicographical ordering of tiles to recursive (e.g. z-mort) // read_/write_scale are used to stride appropriately when read and write loop iterations spaces are different // ghostZone: read_scale=1, write_scale=1 // interpolation: read_scale=1, write_scale=2 // restriction: read_scale=2, write_scale=1 // FIX... dim_i,j,k -> read_dim_i,j,k, write_dim_i,j,k for(kk=0;kk<dim_k;kk+=blockcopy_tile_k){ for(jj=0;jj<dim_j;jj+=blockcopy_tile_j){ for(ii=0;ii<dim_i;ii+=blockcopy_tile_i){ int dim_k_mod = dim_k-kk;if(dim_k_mod>blockcopy_tile_k)dim_k_mod=blockcopy_tile_k; int dim_j_mod = dim_j-jj;if(dim_j_mod>blockcopy_tile_j)dim_j_mod=blockcopy_tile_j; int dim_i_mod = dim_i-ii;if(dim_i_mod>blockcopy_tile_i)dim_i_mod=blockcopy_tile_i; if(*num_blocks >= *allocated_blocks){ int oldSize = *allocated_blocks; if(*allocated_blocks == 0){*allocated_blocks=BLOCK_LIST_MIN_SIZE;*blocks=(blockCopy_type*) malloc( (*allocated_blocks)*sizeof(blockCopy_type));} else{*allocated_blocks*=2; *blocks=(blockCopy_type*)realloc((void*)(*blocks),(*allocated_blocks)*sizeof(blockCopy_type));} if(*blocks == NULL){fprintf(stderr,"realloc failed - append_block_to_list (%d -> %d)\n",oldSize,*allocated_blocks);exit(0);} } (*blocks)[*num_blocks].subtype = subtype; (*blocks)[*num_blocks].dim.i = dim_i_mod; (*blocks)[*num_blocks].dim.j = dim_j_mod; (*blocks)[*num_blocks].dim.k = dim_k_mod; #ifdef USE_UPCXX (*blocks)[*num_blocks].read.boxgp = read_boxgp; #endif (*blocks)[*num_blocks].read.box = read_box; (*blocks)[*num_blocks].read.ptr = read_ptr; (*blocks)[*num_blocks].read.i = read_i + read_scale*ii; (*blocks)[*num_blocks].read.j = read_j + read_scale*jj; (*blocks)[*num_blocks].read.k = read_k + read_scale*kk; (*blocks)[*num_blocks].read.jStride = read_jStride; (*blocks)[*num_blocks].read.kStride = read_kStride; #ifdef USE_UPCXX (*blocks)[*num_blocks].write.boxgp = write_boxgp; #endif (*blocks)[*num_blocks].write.box = write_box; (*blocks)[*num_blocks].write.ptr = write_ptr; (*blocks)[*num_blocks].write.i = write_i + write_scale*ii; (*blocks)[*num_blocks].write.j = write_j + write_scale*jj; (*blocks)[*num_blocks].write.k = write_k + write_scale*kk; (*blocks)[*num_blocks].write.jStride = write_jStride; (*blocks)[*num_blocks].write.kStride = write_kStride; (*num_blocks)++; }}} } //---------------------------------------------------------------------------------------------------------------------------------------------------- // create a mini program that traverses the domain boundary intersecting with this process's boxes // This includes faces, corners, and edges void build_boundary_conditions(level_type *level, int justFaces){ level->boundary_condition.blocks[justFaces] = NULL; // default for periodic (i.e. no BC's) level->boundary_condition.num_blocks[justFaces] = 0; // default for periodic (i.e. no BC's) level->boundary_condition.allocated_blocks[justFaces] = 0; // default for periodic (i.e. no BC's) if(level->boundary_condition.type == BC_PERIODIC)return; int faces[27] = {0,0,0,0,1,0,0,0,0, 0,1,0,1,0,1,0,1,0, 0,0,0,0,1,0,0,0,0}; int edges[27] = {0,1,0,1,0,1,0,1,0, 1,0,1,0,0,0,1,0,1, 0,1,0,1,0,1,0,1,0}; int corners[27] = {1,0,1,0,0,0,1,0,1, 0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,1,0,1}; int box, di,dj,dk; for(box=0;box<level->num_my_boxes;box++){ // traverse my list of boxes... for(dk=-1;dk<=1;dk++){ // for each box, examine its 26 neighbors... for(dj=-1;dj<=1;dj++){ for(di=-1;di<=1;di++){ int dir = 13+di+3*dj+9*dk; // determine if this region (box's di,dj,dk ghost zone) is outside of the domain int regionIsOutside=0; int normal = 13; // normal effectively defines the normal vector to the domain for this region... // this addition is necessary for linearly interpolated BC's as a box's corner is not necessarily a domain's corner box_type* lbox = (box_type *)&(level->my_boxes[box]); int myBox_i = lbox->low.i / level->box_dim; int myBox_j = lbox->low.j / level->box_dim; int myBox_k = lbox->low.k / level->box_dim; int neighborBox_i = ( myBox_i + di ); int neighborBox_j = ( myBox_j + dj ); int neighborBox_k = ( myBox_k + dk ); if( neighborBox_i < 0 ){regionIsOutside=1;normal-=1;} if( neighborBox_j < 0 ){regionIsOutside=1;normal-=3;} if( neighborBox_k < 0 ){regionIsOutside=1;normal-=9;} if( neighborBox_i >=level->boxes_in.i ){regionIsOutside=1;normal+=1;} if( neighborBox_j >=level->boxes_in.j ){regionIsOutside=1;normal+=3;} if( neighborBox_k >=level->boxes_in.k ){regionIsOutside=1;normal+=9;} // calculate ghost zone region size and coordinates relative to the first non-ghost zone element (0,0,0) int block_i=-1,block_j=-1,block_k=-1; int dim_i=-1, dim_j=-1, dim_k=-1; switch(di){ case -1:dim_i=level->box_ghosts;block_i=0-level->box_ghosts;break; case 0:dim_i=level->box_dim; block_i=0; break; case 1:dim_i=level->box_ghosts;block_i=0+level->box_dim; break; } switch(dj){ case -1:dim_j=level->box_ghosts;block_j=0-level->box_ghosts;break; case 0:dim_j=level->box_dim; block_j=0; break; case 1:dim_j=level->box_ghosts;block_j=0+level->box_dim; break; } switch(dk){ case -1:dim_k=level->box_ghosts;block_k=0-level->box_ghosts;break; case 0:dim_k=level->box_dim; block_k=0; break; case 1:dim_k=level->box_ghosts;block_k=0+level->box_dim; break; } if(justFaces && (faces[dir]==0))regionIsOutside=0; if(regionIsOutside){ append_block_to_list(&(level->boundary_condition.blocks[justFaces]),&(level->boundary_condition.allocated_blocks[justFaces]),&(level->boundary_condition.num_blocks[justFaces]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, #ifdef USE_UPCXX /* read.boxgp = */ &level->my_boxes[box], #endif /* read.box = */ box, /* read.ptr = */ NULL, /* read.i = */ block_i, /* read.j = */ block_j, /* read.k = */ block_k, /* read.jStride = */ lbox->jStride, /* read.kStride = */ lbox->kStride, /* read.scale = */ 1, #ifdef USE_UPCXX /* write.boxgp = */ &level->my_boxes[box], #endif /* write.box = */ box, /* write.ptr = */ NULL, /* write.i = */ block_i, /* write.j = */ block_j, /* write.k = */ block_k, /* write.jStride = */ lbox->jStride, /* write.kStride = */ lbox->kStride, /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I < level->box_ghosts ? level->box_ghosts : BLOCKCOPY_TILE_I, // BC's may never tile smaller than the ghost zone depth /* blockcopy_j = */ BLOCKCOPY_TILE_J < level->box_ghosts ? level->box_ghosts : BLOCKCOPY_TILE_J, // BC's may never tile smaller than the ghost zone depth /* blockcopy_k = */ BLOCKCOPY_TILE_K < level->box_ghosts ? level->box_ghosts : BLOCKCOPY_TILE_K, // BC's may never tile smaller than the ghost zone depth /* subtype = */ normal ); }}}}} } //---------------------------------------------------------------------------------------------------------------------------------------------------- // create a mini program that packs data into MPI recv buffers, exchanges local data, and unpacks the MPI send buffers // broadly speaking... // 1. traverse my list of Boxes and create a list of ghosts that must be sent // 2. create a list of neighbors to send to // 3. allocate and populate the pack list and allocate the send buffers // 4. allocate and populate the local exchange list // 5. traverse my list of Boxes and create a list of ghosts that must be received // 6. create a list of neighbors to receive from // 7. allocate and populate the unpack list and allocate the recv buffers // // thus a ghost zone exchange is // 1. prepost a Irecv for each MPI recv buffer (1 per neighbor) // 2. traverse the pack list // 3. post the Isends for each MPI send buffer (1 per neighbor) // 4. traverse the local copy list // 5. waitall // 6. traverse the unpack list // // / 24 25 26 / // / 21 22 23 / (k+1) // / 18 19 20 / // // / 15 16 17 / // / 12 13 14 / (k) // / 9 10 11 / // // / 6 7 8 / // / 3 4 5 / (k-1) // / 0 1 2 / // void build_exchange_ghosts(level_type *level, int justFaces){ int faces[27] = {0,0,0,0,1,0,0,0,0, 0,1,0,1,0,1,0,1,0, 0,0,0,0,1,0,0,0,0}; int edges[27] = {0,1,0,1,0,1,0,1,0, 1,0,1,0,0,0,1,0,1, 0,1,0,1,0,1,0,1,0}; int corners[27] = {1,0,1,0,0,0,1,0,1, 0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,1,0,1}; level->exchange_ghosts[justFaces].num_recvs = 0; level->exchange_ghosts[justFaces].num_sends = 0; level->exchange_ghosts[justFaces].blocks[0] = NULL; level->exchange_ghosts[justFaces].blocks[1] = NULL; level->exchange_ghosts[justFaces].blocks[2] = NULL; level->exchange_ghosts[justFaces].blocks[3] = NULL; level->exchange_ghosts[justFaces].num_blocks[0] = 0; level->exchange_ghosts[justFaces].num_blocks[1] = 0; level->exchange_ghosts[justFaces].num_blocks[2] = 0; level->exchange_ghosts[justFaces].num_blocks[3] = 0; level->exchange_ghosts[justFaces].allocated_blocks[0] = 0; level->exchange_ghosts[justFaces].allocated_blocks[1] = 0; level->exchange_ghosts[justFaces].allocated_blocks[2] = 0; level->exchange_ghosts[justFaces].allocated_blocks[3] = 0; int CommunicateThisDir[27]; int n;for(n=0;n<27;n++)CommunicateThisDir[n]=1;CommunicateThisDir[13]=0; if(justFaces)for(n=0;n<27;n++)CommunicateThisDir[n]=faces[n]; int sendBox,recvBox; int stage; int _rank; int ghost,numGhosts,numGhostsRemote; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // traverse my list of boxes and create a lists of neighboring boxes and neighboring ranks GZ_type *ghostsToSend = (GZ_type*)malloc(26*level->num_my_boxes*sizeof(GZ_type)); // There are at most 26 neighbors per box. int *sendRanks = ( int*)malloc(26*level->num_my_boxes*sizeof( int)); // There are at most 26 neighbors per box. if(level->num_my_boxes>0){ if(ghostsToSend == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/ghostsToSend\n");exit(0);} if(sendRanks == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/sendRanks \n");exit(0);} } numGhosts = 0; numGhostsRemote = 0; for(sendBox=0;sendBox<level->num_my_boxes;sendBox++){ int di,dj,dk; for(dk=-1;dk<=1;dk++){ for(dj=-1;dj<=1;dj++){ for(di=-1;di<=1;di++){ int dir = 13+di+3*dj+9*dk;if(CommunicateThisDir[dir]){ box_type* lbox = (box_type *)&(level->my_boxes[sendBox]); int myBoxID = lbox->global_box_id; int myBox_i = lbox->low.i / level->box_dim; int myBox_j = lbox->low.j / level->box_dim; int myBox_k = lbox->low.k / level->box_dim; int neighborBoxID = -1; if(level->boundary_condition.type == BC_PERIODIC){ int neighborBox_i = ( myBox_i + di + level->boxes_in.i) % level->boxes_in.i; int neighborBox_j = ( myBox_j + dj + level->boxes_in.j) % level->boxes_in.j; int neighborBox_k = ( myBox_k + dk + level->boxes_in.k) % level->boxes_in.k; neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; }else{ int neighborBox_i = ( myBox_i + di ); int neighborBox_j = ( myBox_j + dj ); int neighborBox_k = ( myBox_k + dk ); if( (neighborBox_i>=0) && (neighborBox_i<level->boxes_in.i) && (neighborBox_j>=0) && (neighborBox_j<level->boxes_in.j) && (neighborBox_k>=0) && (neighborBox_k<level->boxes_in.k) ){ // i.e. the neighbor is a valid box neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; } } if(neighborBoxID>=0){ if( level->rank_of_box[neighborBoxID] != -1 ){ ghostsToSend[numGhosts].sendRank = level->my_rank; ghostsToSend[numGhosts].sendBoxID = myBoxID; ghostsToSend[numGhosts].sendBox = sendBox; ghostsToSend[numGhosts].sendDir = dir; ghostsToSend[numGhosts].recvRank = level->rank_of_box[neighborBoxID]; ghostsToSend[numGhosts].recvBoxID = neighborBoxID; ghostsToSend[numGhosts].recvBox = -1; if( level->rank_of_box[neighborBoxID] != level->my_rank ){ sendRanks[numGhostsRemote++] = level->rank_of_box[neighborBoxID]; }else{ int recvBox=0;while(level->my_boxes[recvBox].get().global_box_id!=neighborBoxID)recvBox++; // search my list of boxes for the appropriate recvBox index ghostsToSend[numGhosts].recvBox = recvBox; } numGhosts++; }} }}}} } // sort boxes by sendRank(==my rank) then by sendBoxID... ensures the sends and receive buffers are always sorted by sendBoxID... qsort(ghostsToSend,numGhosts ,sizeof(GZ_type),qsortGZ ); // sort the lists of neighboring ranks and remove duplicates... qsort(sendRanks ,numGhostsRemote,sizeof( int),qsortInt); int numSendRanks=0;_rank=-1;for(ghost=0;ghost<numGhostsRemote;ghost++)if(sendRanks[ghost] != _rank){_rank=sendRanks[ghost];sendRanks[numSendRanks++]=sendRanks[ghost];} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // in a two-stage process, traverse the list of ghosts and allocate the pack/local lists as well as the MPI buffers, and then populate the pack/local lists level->exchange_ghosts[justFaces].num_sends = numSendRanks; level->exchange_ghosts[justFaces].send_ranks = (int*)malloc(numSendRanks*sizeof(int)); level->exchange_ghosts[justFaces].send_sizes = (int*)malloc(numSendRanks*sizeof(int)); level->exchange_ghosts[justFaces].send_buffers = (double**)malloc(numSendRanks*sizeof(double*)); #ifdef USE_UPCXX level->exchange_ghosts[justFaces].global_send_buffers = (hclib::upcxx::global_ptr<double> *)malloc(numSendRanks*sizeof(hclib::upcxx::global_ptr<double>)); level->exchange_ghosts[justFaces].global_match_buffers = (hclib::upcxx::global_ptr<double> *)malloc(numSendRanks*sizeof(hclib::upcxx::global_ptr<double>)); level->exchange_ghosts[justFaces].send_match_pos = (int *)malloc(numSendRanks*sizeof(int)); level->exchange_ghosts[justFaces].match_rflag = (hclib::upcxx::global_ptr<int> *)hclib::upcxx::allocate< hclib::upcxx::global_ptr<int> >(level->my_rank, numSendRanks); level->exchange_ghosts[justFaces].copy_e = new hclib::upcxx::event[numSendRanks]; level->exchange_ghosts[justFaces].data_e = new hclib::upcxx::event[numSendRanks]; #endif if(numSendRanks>0){ if(level->exchange_ghosts[justFaces].send_ranks ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_ranks\n",justFaces);exit(0);} if(level->exchange_ghosts[justFaces].send_sizes ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_sizes\n",justFaces);exit(0);} if(level->exchange_ghosts[justFaces].send_buffers==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_buffers\n",justFaces);exit(0);} #ifdef USE_UPCXX if(level->exchange_ghosts[justFaces].global_send_buffers==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].global_send_buffers\n",justFaces);exit(0);} #endif } level->exchange_ghosts[justFaces].blocks[0] = NULL; level->exchange_ghosts[justFaces].blocks[1] = NULL; level->exchange_ghosts[justFaces].blocks[3] = NULL; level->exchange_ghosts[justFaces].num_blocks[0] = 0; level->exchange_ghosts[justFaces].num_blocks[1] = 0; level->exchange_ghosts[justFaces].num_blocks[3] = 0; level->exchange_ghosts[justFaces].allocated_blocks[0] = 0; level->exchange_ghosts[justFaces].allocated_blocks[1] = 0; level->exchange_ghosts[justFaces].allocated_blocks[3] = 0; for(stage=0;stage<=1;stage++){ // stage=0... traverse the list and calculate the buffer sizes // stage=1... allocate MPI send buffers, traverse the list, and populate the unpack/local lists... int neighbor; for(neighbor=0;neighbor<numSendRanks;neighbor++){ if(stage==1){ #ifdef USE_UPCXX level->exchange_ghosts[justFaces].global_send_buffers[neighbor] = hclib::upcxx::allocate<double>(MYTHREAD,level->exchange_ghosts[justFaces].send_sizes[neighbor]); level->exchange_ghosts[justFaces].send_buffers[neighbor] = (double *)level->exchange_ghosts[justFaces].global_send_buffers[neighbor]; #else level->exchange_ghosts[justFaces].send_buffers[neighbor] = (double*)malloc(level->exchange_ghosts[justFaces].send_sizes[neighbor]*sizeof(double)); if(level->exchange_ghosts[justFaces].send_sizes[neighbor]>0) if(level->exchange_ghosts[justFaces].send_buffers[neighbor]==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_buffers[neighbor]\n",justFaces);exit(0);} #endif if (level->exchange_ghosts[justFaces].send_sizes[neighbor] > 0) memset(level->exchange_ghosts[justFaces].send_buffers[neighbor], 0,level->exchange_ghosts[justFaces].send_sizes[neighbor]*sizeof(double)); } level->exchange_ghosts[justFaces].send_ranks[neighbor]=sendRanks[neighbor]; level->exchange_ghosts[justFaces].send_sizes[neighbor]=0; } for(ghost=0;ghost<numGhosts;ghost++){ int dim_i=-1, dim_j=-1, dim_k=-1; int send_i=-1,send_j=-1,send_k=-1; int recv_i=-1,recv_j=-1,recv_k=-1; // decode ghostsToSend[ghost].sendDir (direction sent) into di/dj/dk int di = ((ghostsToSend[ghost].sendDir % 3) )-1; int dj = ((ghostsToSend[ghost].sendDir % 9)/3)-1; int dk = ((ghostsToSend[ghost].sendDir / 9) )-1; switch(di){ // direction relative to sender case -1:send_i=0; dim_i=level->box_ghosts;recv_i= level->box_dim; break; case 0:send_i=0; dim_i=level->box_dim; recv_i=0; break; case 1:send_i=level->box_dim-level->box_ghosts;dim_i=level->box_ghosts;recv_i=0-level->box_ghosts;break; } switch(dj){ // direction relative to sender case -1:send_j=0; dim_j=level->box_ghosts;recv_j= level->box_dim; break; case 0:send_j=0; dim_j=level->box_dim; recv_j=0; break; case 1:send_j=level->box_dim-level->box_ghosts;dim_j=level->box_ghosts;recv_j=0-level->box_ghosts;break; } switch(dk){ // direction relative to sender case -1:send_k=0; dim_k=level->box_ghosts;recv_k= level->box_dim; break; case 0:send_k=0; dim_k=level->box_dim; recv_k=0; break; case 1:send_k=level->box_dim-level->box_ghosts;dim_k=level->box_ghosts;recv_k=0-level->box_ghosts;break; } // determine if this ghost requires a pack or local exchange int LocalExchange; // 0 = pack list, 1 = local exchange list #ifdef USE_UPCXX if (!hclib::upcxx::is_memory_shared_with(ghostsToSend[ghost].recvRank)) { #else if(ghostsToSend[ghost].recvRank != level->my_rank){ #endif LocalExchange=0; // pack neighbor=0;while(level->exchange_ghosts[justFaces].send_ranks[neighbor] != ghostsToSend[ghost].recvRank)neighbor++; }else{ LocalExchange=1; // local neighbor=-1; } if(stage==1){ #ifdef USE_UPCXX hclib::upcxx::global_ptr<box_type> send_boxgp = level->addr_of_box[ghostsToSend[ghost].sendBoxID]; hclib::upcxx::global_ptr<box_type> recv_boxgp = level->addr_of_box[ghostsToSend[ghost].recvBoxID]; #endif if(LocalExchange) {// append to the local exchange list... #ifdef USE_UPCXX box_type *lbox = (box_type *)recv_boxgp; int jStride = lbox->jStride; int kStride = lbox->kStride; #else int jStride = level->my_boxes[ghostsToSend[ghost].recvBox].jStride; int kStride = level->my_boxes[ghostsToSend[ghost].recvBox].kStride; #endif if (level->my_rank == ghostsToSend[ghost].recvRank) { append_block_to_list(&(level->exchange_ghosts[justFaces].blocks[1]),&(level->exchange_ghosts[justFaces].allocated_blocks[1]),&(level->exchange_ghosts[justFaces].num_blocks[1]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, #ifdef USE_UPCXX /* read.boxgp = */ send_boxgp, #endif /* read.box = */ ghostsToSend[ghost].sendBoxID, /* read.ptr = */ NULL, /* read.i = */ send_i, /* read.j = */ send_j, /* read.k = */ send_k, /* read.jStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].get().jStride, /* read.kStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].get().kStride, /* read.scale = */ 1, #ifdef USE_UPCXX /* write.boxgp = */ recv_boxgp, #endif /* write.box = */ ghostsToSend[ghost].recvBoxID, /* write.ptr = */ NULL, /* write.i = */ recv_i, /* write.j = */ recv_j, /* write.k = */ recv_k, /* write.jStride = */ jStride, //level->my_boxes[ghostsToSend[ghost].recvBox].get().jStride, /* write.kStride = */ kStride, //level->my_boxes[ghostsToSend[ghost].recvBox].get().kStride, /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); } else { append_block_to_list(&(level->exchange_ghosts[justFaces].blocks[3]),&(level->exchange_ghosts[justFaces].allocated_blocks[3]),&(level->exchange_ghosts[justFaces].num_blocks[3]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, #ifdef USE_UPCXX /* read.boxgp = */ send_boxgp, #endif /* read.box = */ ghostsToSend[ghost].sendBoxID, /* read.ptr = */ NULL, /* read.i = */ send_i, /* read.j = */ send_j, /* read.k = */ send_k, /* read.jStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].get().jStride, /* read.kStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].get().kStride, /* read.scale = */ 1, #ifdef USE_UPCXX /* write.boxgp = */ recv_boxgp, #endif /* write.box = */ ghostsToSend[ghost].recvBoxID, /* write.ptr = */ NULL, /* write.i = */ recv_i, /* write.j = */ recv_j, /* write.k = */ recv_k, /* write.jStride = */ jStride, //level->my_boxes[ghostsToSend[ghost].recvBox].get().jStride, /* write.kStride = */ kStride, //level->my_boxes[ghostsToSend[ghost].recvBox].get().kStride, /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); } // if (level->my_rank = rece_rank) } else // append to the MPI pack list... append_block_to_list(&(level->exchange_ghosts[justFaces].blocks[0]),&(level->exchange_ghosts[justFaces].allocated_blocks[0]),&(level->exchange_ghosts[justFaces].num_blocks[0]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, #ifdef USE_UPCXX /* read.boxgp = */ send_boxgp, #endif /* read.box = */ ghostsToSend[ghost].sendBoxID, /* read.ptr = */ NULL, /* read.i = */ send_i, /* read.j = */ send_j, /* read.k = */ send_k, /* read.jStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].get().jStride, /* read.kStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].get().kStride, /* read.scale = */ 1, #ifdef USE_UPCXX /* write.boxgp = */ recv_boxgp, #endif /* write.box = */ -1, /* write.ptr = */ level->exchange_ghosts[justFaces].send_buffers[neighbor], // NOTE, 1. count _sizes, 2. allocate _buffers, 3. populate blocks /* write.i = */ level->exchange_ghosts[justFaces].send_sizes[neighbor], // current offset in the MPI send buffer /* write.j = */ 0, /* write.k = */ 0, /* write.jStride = */ dim_i, // contiguous block /* write.kStride = */ dim_i*dim_j, // contiguous block /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); } if(neighbor>=0)level->exchange_ghosts[justFaces].send_sizes[neighbor]+=dim_i*dim_j*dim_k; } // ghost for-loop } // stage for-loop // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // free temporary storage... free(ghostsToSend); free(sendRanks); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // traverse my list of boxes and create a lists of neighboring boxes and neighboring ranks GZ_type *ghostsToRecv = (GZ_type*)malloc(26*level->num_my_boxes*sizeof(GZ_type)); // There are at most 26 neighbors per box. int *recvRanks = ( int*)malloc(26*level->num_my_boxes*sizeof( int)); // There are at most 26 neighbors per box. if(level->num_my_boxes>0){ if(ghostsToRecv == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/ghostsToRecv\n");exit(0);} if(recvRanks == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/recvRanks \n");exit(0);} } numGhosts = 0; numGhostsRemote = 0; for(recvBox=0;recvBox<level->num_my_boxes;recvBox++){ int di,dj,dk; for(dk=-1;dk<=1;dk++){ for(dj=-1;dj<=1;dj++){ for(di=-1;di<=1;di++){ int dir = 13+di+3*dj+9*dk;if(CommunicateThisDir[dir]){ box_type* lbox = (box_type *)&(level->my_boxes[recvBox]); int myBoxID = lbox->global_box_id; int myBox_i = lbox->low.i / level->box_dim; int myBox_j = lbox->low.j / level->box_dim; int myBox_k = lbox->low.k / level->box_dim; int neighborBoxID = -1; //if(1){ if(level->boundary_condition.type == BC_PERIODIC){ int neighborBox_i = ( myBox_i + di + level->boxes_in.i) % level->boxes_in.i; int neighborBox_j = ( myBox_j + dj + level->boxes_in.j) % level->boxes_in.j; int neighborBox_k = ( myBox_k + dk + level->boxes_in.k) % level->boxes_in.k; neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; }else{ int neighborBox_i = ( myBox_i + di ); int neighborBox_j = ( myBox_j + dj ); int neighborBox_k = ( myBox_k + dk ); if( (neighborBox_i>=0) && (neighborBox_i<level->boxes_in.i) && (neighborBox_j>=0) && (neighborBox_j<level->boxes_in.j) && (neighborBox_k>=0) && (neighborBox_k<level->boxes_in.k) ){ // i.e. the neighbor is a valid box neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; } } if(neighborBoxID>=0){ if( (level->rank_of_box[neighborBoxID] != -1) && (level->rank_of_box[neighborBoxID] != level->my_rank) ){ ghostsToRecv[numGhosts].sendRank = level->rank_of_box[neighborBoxID]; ghostsToRecv[numGhosts].sendBoxID = neighborBoxID; ghostsToRecv[numGhosts].sendBox = -1; ghostsToRecv[numGhosts].sendDir = 26-dir; ghostsToRecv[numGhosts].recvRank = level->my_rank; ghostsToRecv[numGhosts].recvBoxID = myBoxID; ghostsToRecv[numGhosts].recvBox = recvBox; numGhosts++; recvRanks[numGhostsRemote++] = level->rank_of_box[neighborBoxID]; }} }}}} } // sort boxes by sendRank then by sendBoxID... ensures the recvs and receive buffers are always sorted by sendBoxID... qsort(ghostsToRecv,numGhosts ,sizeof(GZ_type),qsortGZ ); // sort the lists of neighboring ranks and remove duplicates... qsort(recvRanks ,numGhostsRemote,sizeof( int),qsortInt); int numRecvRanks=0;_rank=-1;for(ghost=0;ghost<numGhostsRemote;ghost++)if(recvRanks[ghost] != _rank){_rank=recvRanks[ghost];recvRanks[numRecvRanks++]=recvRanks[ghost];} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // in a two-stage process, traverse the list of ghosts and allocate the unpack lists as well as the MPI buffers, and then populate the unpack list level->exchange_ghosts[justFaces].num_recvs = numRecvRanks; level->exchange_ghosts[justFaces].recv_ranks = (int*)malloc(numRecvRanks*sizeof(int)); level->exchange_ghosts[justFaces].recv_sizes = (int*)malloc(numRecvRanks*sizeof(int)); level->exchange_ghosts[justFaces].recv_buffers = (double**)malloc(numRecvRanks*sizeof(double*)); #ifdef USE_UPCXX level->exchange_ghosts[justFaces].sblock2 = (int*)malloc((numRecvRanks+2)*sizeof(int)); level->exchange_ghosts[justFaces].rflag = hclib::upcxx::allocate<int>(MYTHREAD, MAX_VG); int *tmpp = (int *)level->exchange_ghosts[justFaces].rflag; memset(tmpp, 0, MAX_VG * sizeof(int)); memset((void *)level->exchange_ghosts[justFaces].sblock2, 0, sizeof(int)*(numRecvRanks+2)); level->exchange_ghosts[justFaces].global_recv_buffers = (hclib::upcxx::global_ptr<double> *) malloc(numRecvRanks*sizeof(hclib::upcxx::global_ptr<double>)); #endif if(numRecvRanks>0){ if(level->exchange_ghosts[justFaces].recv_ranks ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_ranks\n",justFaces);exit(0);} if(level->exchange_ghosts[justFaces].recv_sizes ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_sizes\n",justFaces);exit(0);} if(level->exchange_ghosts[justFaces].recv_buffers==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_buffers\n",justFaces);exit(0);} #ifdef USE_UPCXX if(level->exchange_ghosts[justFaces].global_recv_buffers==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].global_recv_buffers\n",justFaces);exit(0);} #endif } level->exchange_ghosts[justFaces].blocks[2] = NULL; level->exchange_ghosts[justFaces].num_blocks[2] = 0; level->exchange_ghosts[justFaces].allocated_blocks[2] = 0; for(stage=0;stage<=1;stage++){ // stage=0... traverse the list and calculate the buffer sizes // stage=1... allocate MPI recv buffers, traverse the list, and populate the unpack/local lists... int neighbor; for(neighbor=0;neighbor<numRecvRanks;neighbor++){ if(stage==1){ #ifdef USE_UPCXX level->exchange_ghosts[justFaces].global_recv_buffers[neighbor] = hclib::upcxx::allocate<double>(MYTHREAD, level->exchange_ghosts[justFaces].recv_sizes[neighbor]); level->exchange_ghosts[justFaces].recv_buffers[neighbor] = (double *)level->exchange_ghosts[justFaces].global_recv_buffers[neighbor]; #else level->exchange_ghosts[justFaces].recv_buffers[neighbor] = (double*)malloc(level->exchange_ghosts[justFaces].recv_sizes[neighbor]*sizeof(double)); if(level->exchange_ghosts[justFaces].recv_sizes[neighbor]>0) if(level->exchange_ghosts[justFaces].recv_buffers[neighbor]==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_buffers[neighbor]\n",justFaces);exit(0);} #endif if (level->exchange_ghosts[justFaces].recv_sizes[neighbor] > 0) memset(level->exchange_ghosts[justFaces].recv_buffers[neighbor], 0,level->exchange_ghosts[justFaces].recv_sizes[neighbor]*sizeof(double)); } level->exchange_ghosts[justFaces].recv_ranks[neighbor]=recvRanks[neighbor]; level->exchange_ghosts[justFaces].recv_sizes[neighbor]=0; } for(ghost=0;ghost<numGhosts;ghost++){ int dim_i=-1, dim_j=-1, dim_k=-1; //int send_i=-1,send_j=-1,send_k=-1; int recv_i=-1,recv_j=-1,recv_k=-1; // decode ghostsToRecv[ghost].sendDir (direction sent) into di/dj/dk int di = ((ghostsToRecv[ghost].sendDir % 3) )-1; int dj = ((ghostsToRecv[ghost].sendDir % 9)/3)-1; int dk = ((ghostsToRecv[ghost].sendDir / 9) )-1; switch(di){ // direction relative to sender case -1:dim_i=level->box_ghosts;recv_i= level->box_dim; break; case 0:dim_i=level->box_dim; recv_i=0; break; case 1:dim_i=level->box_ghosts;recv_i=0-level->box_ghosts;break; } switch(dj){ // direction relative to sender case -1:dim_j=level->box_ghosts;recv_j= level->box_dim; break; case 0:dim_j=level->box_dim; recv_j=0; break; case 1:dim_j=level->box_ghosts;recv_j=0-level->box_ghosts;break; } switch(dk){ // direction relative to sender case -1:dim_k=level->box_ghosts;recv_k= level->box_dim; break; case 0:dim_k=level->box_dim; recv_k=0; break; case 1:dim_k=level->box_ghosts;recv_k=0-level->box_ghosts;break; } // determine if this ghost requires a pack or local exchange #ifdef USE_UPCXX if (hclib::upcxx::is_memory_shared_with(ghostsToRecv[ghost].sendRank)) continue; #endif neighbor=0;while(level->exchange_ghosts[justFaces].recv_ranks[neighbor] != ghostsToRecv[ghost].sendRank)neighbor++; if(stage==1) { #ifdef USE_UPCXX hclib::upcxx::global_ptr<box_type> send_boxgp = level->addr_of_box[ghostsToRecv[ghost].sendBoxID]; hclib::upcxx::global_ptr<box_type> recv_boxgp = level->addr_of_box[ghostsToRecv[ghost].recvBoxID]; #endif append_block_to_list(&(level->exchange_ghosts[justFaces].blocks[2]),&(level->exchange_ghosts[justFaces].allocated_blocks[2]),&(level->exchange_ghosts[justFaces].num_blocks[2]), /*dim.i = */ dim_i, /*dim.j = */ dim_j, /*dim.k = */ dim_k, #ifdef USE_UPCXX /*read.boxgp = */ send_boxgp, #endif /*read.box = */ (-1)*ghostsToRecv[ghost].sendRank-1, // shan -1, /*read.ptr = */ level->exchange_ghosts[justFaces].recv_buffers[neighbor], // NOTE, 1. count _sizes, 2. allocate _buffers, 3. populate blocks /*read.i = */ level->exchange_ghosts[justFaces].recv_sizes[neighbor], // current offset in the MPI recv buffer /*read.j = */ 0, /*read.k = */ 0, /*read.jStride = */ dim_i, // contiguous block /*read.kStride = */ dim_i*dim_j, // contiguous block /*read.scale = */ 1, #ifdef USE_UPCXX /*write.box = */ recv_boxgp, #endif /*write.box = */ ghostsToRecv[ghost].recvBoxID, /*write.ptr = */ NULL, /*write.i = */ recv_i, /*write.j = */ recv_j, /*write.k = */ recv_k, /*write.jStride = */ level->my_boxes[ghostsToRecv[ghost].recvBox].get().jStride, /*write.kStride = */ level->my_boxes[ghostsToRecv[ghost].recvBox].get().kStride, /*write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); } if(neighbor>=0)level->exchange_ghosts[justFaces].recv_sizes[neighbor]+=dim_i*dim_j*dim_k; } // ghost for-loop } // stage for-loop // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // free temporary storage... free(ghostsToRecv); free(recvRanks); #ifdef USE_UPCXX hclib::upcxx::barrier(); // compute the global_match_buffers for upcxx::async_copy() int neighbor; hclib::upcxx::global_ptr<double> p, p1, p2; for (neighbor = 0; neighbor < level->exchange_ghosts[justFaces].num_recvs; neighbor++) { int nid = level->exchange_ghosts[justFaces].recv_ranks[neighbor]; upc_buf_info[MYTHREAD * THREADS + nid] = level->exchange_ghosts[justFaces].global_recv_buffers[neighbor]; upc_int_info[MYTHREAD * THREADS + nid] = neighbor; } upc_rflag_ptr[level->my_rank] = level->exchange_ghosts[justFaces].rflag; hclib::upcxx::barrier(); for (neighbor = 0; neighbor < level->exchange_ghosts[justFaces].num_sends; neighbor++) { int nid = level->exchange_ghosts[justFaces].send_ranks[neighbor]; level->exchange_ghosts[justFaces].global_match_buffers[neighbor] = upc_buf_info[THREADS*nid + MYTHREAD]; level->exchange_ghosts[justFaces].send_match_pos[neighbor] = upc_int_info[THREADS*nid + MYTHREAD]; level->exchange_ghosts[justFaces].match_rflag[neighbor] = upc_rflag_ptr[nid]; } hclib::upcxx::barrier(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // malloc MPI requests/status arrays #endif #ifdef USE_UPCXX // setup start and end position for each receiver if (level->exchange_ghosts[justFaces].num_blocks[2] > 0) { int curpos = 0; int curproc = level->exchange_ghosts[justFaces].blocks[2][0].read.box * (-1) -1; while (level->exchange_ghosts[justFaces].recv_ranks[curpos] != curproc && curpos < level->exchange_ghosts[justFaces].num_recvs) curpos++; level->exchange_ghosts[justFaces].sblock2[curpos] = 0; // already initialized to 0, just be safe for(int buffer=1;buffer<level->exchange_ghosts[justFaces].num_blocks[2];buffer++){ if (level->exchange_ghosts[justFaces].blocks[2][buffer].read.box != -1-curproc) { level->exchange_ghosts[justFaces].sblock2[++curpos] = buffer; curproc = level->exchange_ghosts[justFaces].blocks[2][buffer].read.box * (-1) -1; while (curproc != level->exchange_ghosts[justFaces].recv_ranks[curpos]) { level->exchange_ghosts[justFaces].sblock2[++curpos] = buffer; } } } for (int i = curpos+1; i <= level->exchange_ghosts[justFaces].num_recvs; i++) { level->exchange_ghosts[justFaces].sblock2[i] = level->exchange_ghosts[justFaces].num_blocks[2]; } } #endif } //--------------------------------------------------------------------------------------------------------------------------------------------------- void create_level(level_type *level, int boxes_in_i, int box_dim, int box_ghosts, int box_vectors, int domain_boundary_condition, int my_rank, int num_ranks){ int box; int TotalBoxes = boxes_in_i*boxes_in_i*boxes_in_i; if(my_rank==0){ if(domain_boundary_condition==BC_DIRICHLET)fprintf(stdout,"\nattempting to create a %d^3 level (with Dirichlet BC) using a %d^3 grid of %d^3 boxes and %d tasks...\n",box_dim*boxes_in_i,boxes_in_i,box_dim,num_ranks); if(domain_boundary_condition==BC_PERIODIC )fprintf(stdout,"\nattempting to create a %d^3 level (with Periodic BC) using a %d^3 grid of %d^3 boxes and %d tasks...\n", box_dim*boxes_in_i,boxes_in_i,box_dim,num_ranks); } // int omp_threads = 1; // int omp_nested = 0; int omp_threads = hclib::num_workers(); int omp_nested = 1; // #ifdef _OPENMP // #pragma omp parallel // { // #pragma omp master // { // omp_threads = omp_get_num_threads(); // omp_nested = omp_get_nested(); // } // } // #endif if(box_ghosts < stencil_get_radius() ){ if(my_rank==0)fprintf(stderr,"ghosts(%d) must be >= stencil_get_radius(%d)\n",box_ghosts,stencil_get_radius()); exit(0); } level->memory_allocated = 0; level->box_dim = box_dim; level->box_ghosts = box_ghosts; level->box_vectors = box_vectors; level->boxes_in.i = boxes_in_i; level->boxes_in.j = boxes_in_i; level->boxes_in.k = boxes_in_i; level->dim.i = box_dim*level->boxes_in.i; level->dim.j = box_dim*level->boxes_in.j; level->dim.k = box_dim*level->boxes_in.k; level->active = 1; level->my_rank = my_rank; level->num_ranks = num_ranks; level->boundary_condition.type = domain_boundary_condition; level->alpha_is_zero = -1; level->num_threads = omp_threads; // intra-box threading... level->threads_per_box = omp_threads; level->concurrent_boxes = 1; // inter-box threading... //level->threads_per_box = 1; //level->concurrent_boxes = omp_threads; level->my_blocks = NULL; level->num_my_blocks = 0; level->allocated_blocks = 0; level->tag = log2(level->dim.i); // allocate 3D array of integers to hold the MPI rank of the corresponding box and initialize to -1 (unassigned) level->rank_of_box = (int*)malloc(level->boxes_in.i*level->boxes_in.j*level->boxes_in.k*sizeof(int)); if(level->rank_of_box==NULL){fprintf(stderr,"malloc of level->rank_of_box failed\n");exit(0);} level->memory_allocated += (level->boxes_in.i*level->boxes_in.j*level->boxes_in.k*sizeof(int)); for(box=0;box<level->boxes_in.i*level->boxes_in.j*level->boxes_in.k;box++){level->rank_of_box[box]=-1;} // -1 denotes that there is no actual box assigned to this region // parallelize the grid (i.e. assign a process rank to each box)... #ifdef DECOMPOSE_LEX decompose_level_lex(level->rank_of_box,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,num_ranks); #elif DECOMPOSE_BISECTION_SPECIAL decompose_level_bisection_special(level->rank_of_box,level->boxes_in.i,level->boxes_in.i*level->boxes_in.j,0,0,0,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,0,num_ranks); #else decompose_level_bisection(level->rank_of_box,level->boxes_in.i,level->boxes_in.i*level->boxes_in.j,0,0,0,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,num_ranks,0,level->boxes_in.i*level->boxes_in.j*level->boxes_in.k); #endif //print_decomposition(level);// for debug purposes only // build my list of boxes... level->num_my_boxes=0; for(box=0;box<level->boxes_in.i*level->boxes_in.j*level->boxes_in.k;box++){if(level->rank_of_box[box]==level->my_rank)level->num_my_boxes++;} #ifdef USE_UPCXX level->my_boxes = hclib::upcxx::allocate<box_type>(MYTHREAD, level->num_my_boxes); level->my_local_boxes = (box_type **)malloc(level->num_my_boxes * sizeof(box_type *)); /* NOTE: add a local array to record the global address of every box, later, this array can be shrinked to neighbor boxes only */ level->addr_of_box = (hclib::upcxx::global_ptr<box_type> *)malloc(level->boxes_in.i*level->boxes_in.j*level->boxes_in.k*sizeof(hclib::upcxx::global_ptr<box_type>)); #else level->my_boxes = (box_type*)malloc(level->num_my_boxes*sizeof(box_type)); #endif if((level->num_my_boxes>0)&&(level->my_boxes==NULL)){fprintf(stderr,"malloc failed - create_level/level->my_boxes\n");exit(0);} box=0; int i,j,k; for(k=0;k<level->boxes_in.k;k++){ for(j=0;j<level->boxes_in.j;j++){ for(i=0;i<level->boxes_in.i;i++){ int jStride = level->boxes_in.i; int kStride = level->boxes_in.i*level->boxes_in.j; int b=i + j*jStride + k*kStride; if(level->rank_of_box[b]==level->my_rank){ level->memory_allocated += create_box((box_type *)&level->my_boxes[box],level->box_vectors,level->box_dim,level->box_ghosts); #ifdef USE_UPCXX upc_box_info[b] = &level->my_boxes[box]; box_type* lbox = (box_type *)&(level->my_boxes[box]); level->my_local_boxes[box] = lbox; lbox->low.i = i*level->box_dim; lbox->low.j = j*level->box_dim; lbox->low.k = k*level->box_dim; lbox->global_box_id = b; #else level->my_boxes[box].low.i = i*level->box_dim; level->my_boxes[box].low.j = j*level->box_dim; level->my_boxes[box].low.k = k*level->box_dim; level->my_boxes[box].global_box_id = b; #endif box++; }}}} #ifdef USE_UPCXX // NOTE: this may removed later hclib::upcxx::barrier(); for (i = 0; i < level->boxes_in.i*level->boxes_in.j*level->boxes_in.k; i++) level->addr_of_box[i] = upc_box_info[i]; hclib::upcxx::barrier(); #endif // Build and auxilarlly data structure that flattens boxes into blocks... for(box=0;box<level->num_my_boxes;box++){ #ifdef USE_UPCXX hclib::upcxx::global_ptr<box_type> boxgp = level->addr_of_box[level->my_boxes[box].get().global_box_id]; #endif append_block_to_list(&(level->my_blocks),&(level->allocated_blocks),&(level->num_my_blocks), /* dim.i = */ level->my_boxes[box].get().dim, /* dim.j = */ level->my_boxes[box].get().dim, /* dim.k = */ level->my_boxes[box].get().dim, #ifdef USE_UPCXX /* read.boxgp = */ boxgp, #endif /* read.box = */ box, /* read.ptr = */ NULL, /* read.i = */ 0, /* read.j = */ 0, /* read.k = */ 0, /* read.jStride = */ level->my_boxes[box].get().jStride, /* read.kStride = */ level->my_boxes[box].get().kStride, /* read.scale = */ 1, #ifdef USE_UPCXX /* write.boxgp = */ boxgp, #endif /* write.box = */ box, /* write.ptr = */ NULL, /* write.i = */ 0, /* write.j = */ 0, /* write.k = */ 0, /* write.jStride = */ level->my_boxes[box].get().jStride, /* write.kStride = */ level->my_boxes[box].get().kStride, /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); } // Tune the OpenMP style of parallelism... if(omp_nested){ #ifndef OMP_STENCILS_PER_THREAD #define OMP_STENCILS_PER_THREAD 64 #endif level->concurrent_boxes = level->num_my_boxes; if(level->concurrent_boxes > omp_threads)level->concurrent_boxes = omp_threads; if(level->concurrent_boxes < 1)level->concurrent_boxes = 1; level->threads_per_box = omp_threads / level->concurrent_boxes; if(level->threads_per_box > level->box_dim*level->box_dim) level->threads_per_box = level->box_dim*level->box_dim; // JK collapse if(level->threads_per_box > level->box_dim*level->box_dim*level->box_dim/OMP_STENCILS_PER_THREAD ) level->threads_per_box = level->box_dim*level->box_dim*level->box_dim/OMP_STENCILS_PER_THREAD; if(level->threads_per_box<1)level->threads_per_box = 1; }else{ if(level->num_my_boxes>8){level->concurrent_boxes=omp_threads;level->threads_per_box=1;} } if(my_rank==0){ if(omp_nested)fprintf(stdout," OMP_NESTED=TRUE OMP_NUM_THREADS=%d ... %d teams of %d threads\n",omp_threads,level->concurrent_boxes,level->threads_per_box); else fprintf(stdout," OMP_NESTED=FALSE OMP_NUM_THREADS=%d ... %d teams of %d threads\n",omp_threads,level->concurrent_boxes,level->threads_per_box); } // build an assists data structure which specifies which cells are within the domain (used with STENCIL_FUSE_BC) initialize_valid_region(level); // build an assist structure for Gauss Seidel Red Black that would facilitate unrolling and SIMDization... if(level->num_my_boxes){ int i,j; int kStride = level->my_boxes[0].get().kStride; int jStride = level->my_boxes[0].get().jStride; //posix_memalign((void**)&(level->RedBlack_FP[0] ),64,kStride*sizeof(double )); // even planes //posix_memalign((void**)&(level->RedBlack_FP[1] ),64,kStride*sizeof(double )); // FIX... align RedBlack_FP the same as elements within a plane (i.e. BOX_SIMD_ALIGNMENT) level->RedBlack_FP[0] = (double*)malloc(kStride*sizeof(double)); level->RedBlack_FP[1] = (double*)malloc(kStride*sizeof(double)); memset(level->RedBlack_FP[0],0,kStride*sizeof(double)); memset(level->RedBlack_FP[1],0,kStride*sizeof(double)); level->memory_allocated += kStride*sizeof(double); level->memory_allocated += kStride*sizeof(double); for(j=0-level->box_ghosts;j<level->box_dim+level->box_ghosts;j++){ for(i=0-level->box_ghosts;i<level->box_dim+level->box_ghosts;i++){ int ij = (i+level->box_ghosts) + (j+level->box_ghosts)*jStride; // if((i^j)&0x1)level->RedBlack_64bMask[ij]= ~0;else level->RedBlack_64bMask[ij]= 0; // useful for blend instructions if((i^j^1)&0x1)level->RedBlack_FP[ 0][ij]=1.0;else level->RedBlack_FP[ 0][ij]=0.0; if((i^j^1)&0x1)level->RedBlack_FP[ 1][ij]=0.0;else level->RedBlack_FP[ 1][ij]=1.0; }} } // create mini programs that affect ghost zone exchanges for(i=0;i<2;i++){ level->exchange_ghosts[i].num_recvs =0; level->exchange_ghosts[i].num_sends =0; level->exchange_ghosts[i].num_blocks[0]=0; level->exchange_ghosts[i].num_blocks[1]=0; level->exchange_ghosts[i].num_blocks[2]=0; } build_exchange_ghosts(level,0); // faces, edges, corners build_exchange_ghosts(level,1); // justFaces build_boundary_conditions(level,0); // faces, edges, corners build_boundary_conditions(level,1); // just faces // duplicate MPI_COMM_WORLD to be the communicator for each level #ifdef USE_MPI if(my_rank==0){fprintf(stdout," Duplicating MPI_COMM_WORLD...");fflush(stdout);} double time_start = hclib::MPI_Wtime(); hclib::MPI_Comm_dup(MPI_COMM_WORLD,&level->MPI_COMM_ALLREDUCE); // create upcxx barrier level->subteam = &hclib::upcxx::team_all; double time_end = hclib::MPI_Wtime(); double time_in_comm_dup = 0; double time_in_comm_dup_send = time_end-time_start; hclib::MPI_Allreduce(&time_in_comm_dup_send,&time_in_comm_dup,1,MPI_DOUBLE,MPI_MAX,MPI_COMM_WORLD); if(my_rank==0){fprintf(stdout,"done (%0.6f seconds)\n",time_in_comm_dup);fflush(stdout);} #endif // report on potential load imbalance int BoxesPerProcess = level->num_my_boxes; #ifdef USE_MPI int BoxesPerProcessSend = level->num_my_boxes; hclib::MPI_Allreduce(&BoxesPerProcessSend,&BoxesPerProcess,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD); #endif if(my_rank==0){fprintf(stdout," Calculating boxes per process... target=%0.3f, max=%d\n",(double)TotalBoxes/(double)num_ranks,BoxesPerProcess);} } //--------------------------------------------------------------------------------------------------------------------------------------------------- void reset_level_timers(level_type *level){ // cycle counters information... level->cycles.smooth = 0; level->cycles.apply_op = 0; level->cycles.residual = 0; level->cycles.blas1 = 0; level->cycles.blas3 = 0; level->cycles.boundary_conditions = 0; level->cycles.restriction_total = 0; level->cycles.restriction_pack = 0; level->cycles.restriction_local = 0; level->cycles.restriction_shm = 0; level->cycles.restriction_unpack = 0; level->cycles.restriction_recv = 0; level->cycles.restriction_send = 0; level->cycles.restriction_wait = 0; level->cycles.interpolation_total = 0; level->cycles.interpolation_pack = 0; level->cycles.interpolation_local = 0; level->cycles.interpolation_shm = 0; level->cycles.interpolation_unpack = 0; level->cycles.interpolation_recv = 0; level->cycles.interpolation_send = 0; level->cycles.interpolation_wait = 0; level->cycles.ghostZone_total = 0; level->cycles.ghostZone_pack = 0; level->cycles.ghostZone_local = 0; level->cycles.ghostZone_shm = 0; level->cycles.ghostZone_unpack = 0; level->cycles.ghostZone_recv = 0; level->cycles.ghostZone_send = 0; level->cycles.ghostZone_wait = 0; level->cycles.collectives = 0; level->cycles.Total = 0; // solver events information... level->Krylov_iterations = 0; level->CAKrylov_formations_of_G = 0; level->vcycles_from_this_level = 0; } //--------------------------------------------------------------------------------------------------------------------------------------------------- void max_level_timers(level_type *level){ uint64_t temp; #ifdef USE_MPI temp=level->cycles.smooth; hclib::MPI_Allreduce(&temp,&level->cycles.smooth ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.apply_op; hclib::MPI_Allreduce(&temp,&level->cycles.apply_op ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.residual; hclib::MPI_Allreduce(&temp,&level->cycles.residual ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.blas1; hclib::MPI_Allreduce(&temp,&level->cycles.blas1 ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.blas3; hclib::MPI_Allreduce(&temp,&level->cycles.blas3 ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.boundary_conditions; hclib::MPI_Allreduce(&temp,&level->cycles.boundary_conditions ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_total; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_total ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_pack; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_pack ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_local; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_local ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_shm ; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_shm ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_unpack; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_unpack ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_recv; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_recv ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_send; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_send ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.restriction_wait; hclib::MPI_Allreduce(&temp,&level->cycles.restriction_wait ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_total; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_total ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_pack; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_pack ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_local; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_local ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_shm; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_shm ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_unpack;hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_unpack,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_recv; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_recv ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_send; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_send ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.interpolation_wait; hclib::MPI_Allreduce(&temp,&level->cycles.interpolation_wait ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_total; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_total ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_pack; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_pack ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_local; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_local ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_shm; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_shm ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_unpack; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_unpack ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_recv; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_recv ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_send; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_send ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.ghostZone_wait; hclib::MPI_Allreduce(&temp,&level->cycles.ghostZone_wait ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.collectives; hclib::MPI_Allreduce(&temp,&level->cycles.collectives ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); temp=level->cycles.Total; hclib::MPI_Allreduce(&temp,&level->cycles.Total ,1,MPI_UINT64_T,MPI_MAX,MPI_COMM_WORLD); #endif } //--------------------------------------------------------------------------------------------------------------------------------------------------- void destroy_level(level_type *level){ int box; for(box=0;box<level->num_my_boxes;box++) destroy_box((box_type *)&level->my_boxes[box]); free(level->rank_of_box); }
diagsv_x_sky_u.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #include <memory.h> #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, ALPHA_Number *y) { int num_thread = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT r = 0; r < A->rows; r++) { alpha_mul(y[r], alpha, x[r]); } return ALPHA_SPARSE_STATUS_SUCCESS; }
repeat_base.h
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2013, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: David Weese <david.weese@fu-berlin.de> // ========================================================================== #ifndef SEQAN_HEADER_REPEAT_BASE_H #define SEQAN_HEADER_REPEAT_BASE_H #if SEQAN_ENABLE_PARALLELISM #include <seqan/parallel.h> #endif // #if SEQAN_ENABLE_PARALLELISM namespace seqan { /** .Class.Repeat ..summary:Store information about a repeat. ..cat:Index ..signature:Repeat<TPos, TPeriod> ..param.TPos:Type to use for storing positions. ...metafunction:Metafunction.Value ..param.TPeriod:Type to use for storing the repeat period. ...default:1 ...metafunction:Metafunction.Size ..include:seqan/index.h ..see:Function.findRepeats .Memvar.Repeat#beginPosition ..summary:The begin position of the repeat of type $TPos$. ..class:Class.Repeat .Memvar.Repeat#endPosition ..summary:The end position of the repeat of type $TPos$. ..class:Class.Repeat .Memvar.Repeat#period ..summary:The period of the repeat of type $TSize$. ..class:Class.Repeat */ /*! * @class Repeat * * @headerfile seqan/index.h * * @brief Store information about a repeat. * * @signature Repeat<TPos, TPeriod> * * @tparam TPeriod Type to use for storing the repeat period. Default: 1 * @tparam TPos Type to use for storing positions. * * @see findRepeats * * @var VariableType Repeat::endPosition * * @brief The end position of the repeat of type <tt>TPos</tt>. * * @var VariableType Repeat::beginPosition * * @brief The begin position of the repeat of type <tt>TPos</tt>. * * @var VariableType Repeat::period * * @brief The period of the repeat of type <tt>TSize</tt>. */ template <typename TPos, typename TPeriod> struct Repeat { TPos beginPosition; TPos endPosition; TPeriod period; }; template <typename TPos, typename TPeriod> struct Value< Repeat<TPos, TPeriod> > { typedef TPos Type; }; template <typename TPos, typename TPeriod> struct Size< Repeat<TPos, TPeriod> > { typedef TPeriod Type; }; template <typename TSize> struct RepeatFinderParams { TSize minRepeatLen; TSize maxPeriod; }; // custom TSpec for our customized wotd-Index struct TRepeatFinder; template <typename TText> struct Cargo<Index<TText, IndexWotd<TRepeatFinder> > > { typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex; typedef typename Size<TIndex>::Type TSize; typedef RepeatFinderParams<TSize> Type; }; // node predicate template <typename TText, typename TSpec> bool nodePredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it) { // return countOccurrences(it) * nodeDepth(it) >= cargo(container(it)).minRepeatLen; return countOccurrences(it) * repLength(it) >= cargo(container(it)).minRepeatLen; } // monotonic hull template <typename TText, typename TSpec> bool nodeHullPredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it) { // return nodeDepth(it) <= cargo(container(it)).maxPeriod; return repLength(it) <= cargo(container(it)).maxPeriod; } template <typename TPos> struct RepeatLess_ : public ::std::binary_function<TPos, TPos, bool> { // key less inline bool operator() (TPos const &a, TPos const &b) const { return posLess(a, b); } }; template <typename TValue> inline bool _repeatMaskValue(TValue const &) { // TODO(holtgrew): Maybe use unknownValue<TValue>() instead of specializing for all alphabets, especially since we have Rna5 now and might want Rna5Q later. return false; } template <> inline bool _repeatMaskValue(Dna5 const &val) { return val == unknownValue<Dna5>(); // 'N' } template <> inline bool _repeatMaskValue(Dna5Q const &val) { return val == unknownValue<Dna5Q>(); // 'N' } template <> inline bool _repeatMaskValue(Iupac const &val) { return val == unknownValue<Iupac>(); // 'N' } /* template <> inline bool _repeatMaskValue(AminoAcid val) { return val == 'X'; } */ /** .Function.findRepeats ..summary:Search for repeats in a text. ..cat:Index ..signature:findRepeats(repeatString, text, minRepeatLength[, maxPeriod]) ..param.repeatString:A @Class.String@ of @Class.Repeat@ objects. ..param.text:The text to search repeats in. ...type:Class.String ...type:Class.StringSet ..param.minRepeatLength:The minimum length each reported repeat must have. ..param.maxPeriod:Optionally, the maximal period that reported repeats can have. ...default:1 ..remarks:Subsequences of undefined values/$N$s will always be reported. ..example.text:The following demonstrates finding repeats of period 1. ..example.code: String<Repeat<unsigned, unsigned> > repeats; Dna5String text = "CGATAAAACTNN"; // repeat 0 AAAA // repeat 1 NN findRepeats(repeats, text, 3); // ==> length(repeats) == 2 // ==> repeats[0] == {beginPosition: 4, endPosition: 8, period: 1} // ==> repeats[1] == {beginPosition: 11, endPosition: 13, period: 1} ..see:Function.unknownValue ..include:seqan/index.h ..see:Class.Repeat */ /*! * @fn findRepeats * * @headerfile seqan/index.h * * @brief Search for repeats in a text. * * @signature findRepeats(repeatString, text, minRepeatLength[, maxPeriod]) * * @param text The text to search repeats in. Types: @link SequenceConcept @endlink * @param repeatString A @link String @endlink of @link Repeat @endlink objects. * @param maxPeriod Optionally, the maximal period that reported repeats can * have. Default: 1 * @param minRepeatLength The minimum length each reported repeat must have. * * @section Remarks * * Subsequences of undefined values/<tt>N</tt>s will always be reported. * * @section Examples * * The following demonstrates finding repeats of period 3. * * @include demos/index/find_repeats.cpp * * @code{.console} * # of repeats: 15 * i == 0, beginPosition = 3, endPosition = 7, period = 1 * i == 1, beginPosition = 46, endPosition = 53, period = 1 * i == 2, beginPosition = 101, endPosition = 105, period = 1 * i == 3, beginPosition = 105, endPosition = 109, period = 1 * i == 4, beginPosition = 164, endPosition = 169, period = 1 * i == 5, beginPosition = 291, endPosition = 297, period = 1 * i == 6, beginPosition = 319, endPosition = 327, period = 1 * i == 7, beginPosition = 400, endPosition = 404, period = 1 * i == 8, beginPosition = 442, endPosition = 446, period = 1 * i == 9, beginPosition = 468, endPosition = 473, period = 1 * i == 10, beginPosition = 476, endPosition = 480, period = 1 * i == 11, beginPosition = 507, endPosition = 513, period = 1 * i == 12, beginPosition = 561, endPosition = 566, period = 1 * i == 13, beginPosition = 623, endPosition = 627, period = 1 * i == 14, beginPosition = 655, endPosition = 659, period = 1 * @endcode * * @see AlphabetWithUnknownValueConcept#unknownValue * @see Repeat */ // TODO(holtgrew): minRepeatLength is 1-off. // period-1 optimization template <typename TRepeatStore, typename TString, typename TRepeatSize> inline void findRepeats(TRepeatStore &repString, TString const &text, TRepeatSize minRepeatLen) { typedef typename Value<TRepeatStore>::Type TRepeat; typedef typename Iterator<TString const>::Type TIterator; typedef typename Size<TString>::Type TSize; #if SEQAN_ENABLE_PARALLELISM typedef typename Value<TString>::Type TValue; if (length(text) > (TSize)(omp_get_max_threads() * 2 * minRepeatLen)) { // std::cerr << ">>> PARALLEL WABOOGIE!" << std::endl; // std::cerr << "omp_get_max_threads() == " << omp_get_max_threads() << std::endl; // Parallel case. // NOTE(holtgrew): The minimum text length check above makes it impossible that more than two chunks are // required to form an otherwise too short repeat. // TODO(holtgrew): Load balancing? Probably not worth it. String<TSize> splitters; String<TRepeatStore> threadLocalStores; // Each threads finds repeats on its chunk in parallel. #pragma omp parallel { // We have to determine the number of available threads at this point. We will use the number of thread // local stores to determin the number of available threads later on. #pragma omp master { // std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl; computeSplitters(splitters, length(text), omp_get_num_threads()); resize(threadLocalStores, omp_get_num_threads()); } // end of #pragma omp master #pragma omp barrier int const t = omp_get_thread_num(); TRepeatStore & store = threadLocalStores[t]; TRepeat rep; rep.beginPosition = 0; rep.endPosition = 0; rep.period = 1; // Flags used for force-adding repeats for the chunks that have a left/right neighbour. bool forceFirst = t > 0; bool forceLast = (t + 1) < omp_get_num_threads(); // #pragma omp critical // std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl; TIterator it = iter(text, splitters[t], Standard()); TIterator itEnd = iter(text, splitters[t + 1], Standard()); if (it != itEnd) { TValue last = *it; TSize repLeft = 0; TSize repRight = 1; for (++it; it != itEnd; ++it, ++repRight) { if (*it != last) { // #pragma omp critical // std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceFirst = " << forceFirst << std::endl; if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceFirst) { forceFirst = false; // insert repeat rep.beginPosition = splitters[t] + repLeft; rep.endPosition = splitters[t] + repRight; // #pragma omp critical // std::cerr << " t == " << t << ", append" << std::endl; appendValue(store, rep); } repLeft = repRight; last = *it; } } // #pragma omp critical // std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceLast = " << forceLast << std::endl; if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceLast) { // Insert repeat but only if it is not already in there. if (empty(store) || (back(store).beginPosition != repLeft && back(store).endPosition != repRight)) { rep.beginPosition = splitters[t] + repLeft; rep.endPosition = splitters[t] + repRight; // #pragma omp critical // std::cerr << " t == " << t << ", append" << std::endl; appendValue(store, rep); } } } } // end of #pragma omp parallel // std::cerr << ",-- REPEATS BEFORE MENDING\n"; // for (unsigned i = 0; i < length(threadLocalStores); ++i) // { // std::cerr << "| i = " << i << std::endl; // for (unsigned j = 0; j < length(threadLocalStores[i]); ++j) // std::cerr << "| threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl; // } // std::cerr << "`--" << std::endl; // Mend the splice points. // // We will copy out infixes described by fromPositions. String<Pair<TSize> > fromPositions; resize(fromPositions, length(threadLocalStores)); for (unsigned i = 0; i < length(fromPositions); ++i) { fromPositions[i].i1 = 0; fromPositions[i].i2 = length(threadLocalStores[i]); } // First, merge repeats spanning blocks. Do this iteratively until all has been merged. bool anyChange; do { anyChange = false; int lastNonEmpty = -1; for (unsigned i = 0; i < length(threadLocalStores); ++i) { if (fromPositions[i].i1 == fromPositions[i].i2) continue; // Skip empty buckets. if (lastNonEmpty != -1) { bool const adjacent = back(threadLocalStores[lastNonEmpty]).endPosition == front(threadLocalStores[i]).beginPosition; bool const charsEqual = text[back(threadLocalStores[lastNonEmpty]).beginPosition] == text[front(threadLocalStores[i]).beginPosition]; if (adjacent && charsEqual) { anyChange = true; back(threadLocalStores[lastNonEmpty]).endPosition = front(threadLocalStores[i]).endPosition; fromPositions[i].i1 += 1; } } if (fromPositions[i].i1 != fromPositions[i].i2) lastNonEmpty = i; } } while (anyChange); // Then, remove any repeats in the beginning and end of blocks that are too short. for (unsigned i = 0; i < length(threadLocalStores); ++i) { if (fromPositions[i].i1 == fromPositions[i].i2) continue; unsigned j = fromPositions[i].i1; TRepeatSize len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition; if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value. len <= minRepeatLen) fromPositions[i].i1 += 1; if (fromPositions[i].i1 == fromPositions[i].i2) continue; j = fromPositions[i].i2 - 1; len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition; if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value. len <= minRepeatLen) fromPositions[i].i2 -= 1; } // Last, build splitters for output in parallel. String<unsigned> outSplitters; appendValue(outSplitters, 0); for (unsigned i = 0; i < length(threadLocalStores); ++i) appendValue(outSplitters, back(outSplitters) + fromPositions[i].i2 - fromPositions[i].i1); // std::cerr << ",-- REPEATS AFTER MENDING\n"; // for (unsigned i = 0; i < length(threadLocalStores); ++i) // { // std::cerr << "| i = " << i << std::endl; // std::cerr << "`--, fromPositions[" << i << "] = (" << fromPositions[i].i1 << ", " << fromPositions[i].i2 << std::endl; // for (unsigned j = 0; j < length(threadLocalStores[i]); ++j) // std::cerr << " | threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl; // } // std::cerr << " `--" << std::endl; // Allocate memory. clear(repString); resize(repString, back(outSplitters)); // Copy back the repeats in parallel. unsigned nt = length(threadLocalStores); (void) nt; // Otherwise, GCC 4.6 warns, does not see it used in pragma clause below. #pragma omp parallel num_threads(nt) { int const t = omp_get_thread_num(); arrayCopy(iter(threadLocalStores[t], fromPositions[t].i1, Standard()), iter(threadLocalStores[t], fromPositions[t].i2, Standard()), iter(repString, outSplitters[t], Standard())); } // end of #pragma omp parallel } else { #endif // #if SEQAN_ENABLE_PARALLELISM // Sequential case. TRepeat rep; rep.period = 1; clear(repString); TIterator it = begin(text, Standard()); TIterator itEnd = end(text, Standard()); if (it == itEnd) return; TSize repLen = 1; for (++it; it != itEnd; ++it) { if (*it != *(it-1)) { if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen) { // insert repeat rep.endPosition = it - begin(text, Standard()); rep.beginPosition = rep.endPosition - repLen; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } repLen = 1; } else ++repLen; } if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen) { // insert repeat rep.endPosition = length(text); rep.beginPosition = rep.endPosition - repLen; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } #if SEQAN_ENABLE_PARALLELISM } #endif // #if SEQAN_ENABLE_PARALLELISM // #pragma omp critical // { // std::cerr << "thread #" << omp_get_thread_num() << " REPEATS:"; // for (unsigned i = 0; i < length(repString); ++i) { // std::cerr << " (" << repString[i].beginPosition << ", " << repString[i].endPosition << ", " << repString[i].period << ")"; // } // std::cerr << std::endl; // } } // TODO(holtgrew): Why for TString const and StringSet<> const? template <typename TRepeatStore, typename TString, typename TSpec, typename TRepeatSize> inline void findRepeats(TRepeatStore &repString, StringSet<TString, TSpec> const &text, TRepeatSize minRepeatLen) { typedef typename Value<TRepeatStore>::Type TRepeat; typedef typename Iterator<TString>::Type TIterator; typedef typename Value<TString>::Type TValue; typedef typename Size<TString>::Type TSize; TRepeat rep; rep.period = 1; clear(repString); for (unsigned i = 0; i < length(text); ++i) { TIterator it = begin(text[i], Standard()); TIterator itEnd = end(text[i], Standard()); if (it == itEnd) continue; TValue last = *it; TSize repLeft = 0; TSize repRight = 1; rep.beginPosition.i1 = i; rep.endPosition.i1 = i; for (++it; it != itEnd; ++it, ++repRight) { if (last != *it) { if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen) { // insert repeat rep.beginPosition.i2 = repLeft; rep.endPosition.i2 = repRight; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } repLeft = repRight; last = *it; } } if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen) { // insert repeat rep.beginPosition.i2 = repLeft; rep.endPosition.i2 = repRight; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; appendValue(repString, rep); } } } // main function template <typename TRepeatStore, typename TText, typename TRepeatSize, typename TPeriodSize> void findRepeats(TRepeatStore &repString, TText const &text, TRepeatSize minRepeatLen, TPeriodSize maxPeriod) { typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex; typedef typename Size<TIndex>::Type TSize; typedef typename Iterator<TIndex, TopDown<ParentLinks<> > >::Type TNodeIterator; typedef typename Fibre<TIndex, FibreSA>::Type const TSA; typedef typename Infix<TSA>::Type TOccString; typedef typename Iterator<TOccString>::Type TOccIterator; typedef typename Value<TRepeatStore>::Type TRepeat; typedef typename Value<TOccString>::Type TOcc; typedef ::std::map<TOcc,TRepeat,RepeatLess_<TOcc> > TRepeatList; if (maxPeriod < 1) return; if (maxPeriod == 1) { findRepeats(repString, text, minRepeatLen); return; } TIndex index(text); TRepeatList list; // set repeat finder parameters cargo(index).minRepeatLen = minRepeatLen; cargo(index).maxPeriod = maxPeriod; TNodeIterator nodeIt(index); TOccIterator itA, itB, itRepBegin, itEnd; TRepeat rep; for (; !atEnd(nodeIt); goNext(nodeIt)) { if (isRoot(nodeIt)) continue; // get occurrences TOccString occ = getOccurrences(nodeIt); itA = begin(occ, Standard()); itEnd = end(occ, Standard()); itRepBegin = itB = itA; TSize repLen = repLength(nodeIt); // representative length if ((TSize)minRepeatLen <= repLen) continue; TSize diff, period = 0; // period of current repeat TSize repeatLen = 0; // overall length of current repeat TSize minLen = minRepeatLen - repLen; // minimum repeat length minus length of representative for (++itB; itB != itEnd; ++itB) { diff = posSub(*itB, *itA); if (diff != period || getSeqNo(*itA) != getSeqNo(*itB)) { // is the repeat long enough? if (repeatLen >= minLen) // is the repeat self overlapping or connected? if (parentRepLength(nodeIt) < period && period <= repLen) { // insert repeat rep.beginPosition = *itRepBegin; rep.endPosition = posAdd(*itA, period); rep.period = period; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep)); } itRepBegin = itA; period = diff; repeatLen = 0; } repeatLen += period; itA = itB; } // is the last repeat long enough? if (repeatLen >= minLen) // is the repeat self overlapping or connected? if (parentRepLength(nodeIt) < period && period <= repLen) { // insert repeat rep.beginPosition = *itRepBegin; rep.endPosition = posAdd(*itA, period); rep.period = period; // ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl; list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep)); } } // copy low-complex regions to result string clear(repString); reserve(repString, list.size(), Exact()); typename TRepeatList::const_iterator lit = list.begin(); typename TRepeatList::const_iterator litEnd = list.end(); for (TSize i = 0; lit != litEnd; ++lit, ++i) appendValue(repString, (*lit).second); } } // namespace seqan #endif
GB_binop__second_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__second_uint16) // A.*B function (eWiseMult): GB (_AemultB_01__second_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__second_uint16) // A.*B function (eWiseMult): GB (_AemultB_03__second_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__second_uint16) // A*D function (colscale): GB (_AxD__second_uint16) // D*A function (rowscale): GB (_DxB__second_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__second_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__second_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_uint16) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = bij #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = y ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 1 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_SECOND || GxB_NO_UINT16 || GxB_NO_SECOND_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__second_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__second_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__second_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__second_uint16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__second_uint16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__second_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__second_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__second_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__second_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__second_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = bij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = y ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = y ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
bitonic_openmp.c
#include <stdio.h> #include <stdlib.h> #define TAM 1024 int DOWN = 1, UP = -1; void geraAleatorios(int numero[]) { srand(time(NULL)); int valor; for (int i = 0; i < TAM; i++) { valor = rand() % 1000; numero[i] = valor; } } void swap(int a[], int i, int j, int dir) { int test = (dir == DOWN && a[i] < a[j]) || (dir == UP && a[i] > a[j]); if (test) { int k = a[j]; a[j] = a[i]; a[i] = k; } } void bitonic_internal(int num[], int ini, int tam, int dir) { int passo, i, j; for (passo = tam; passo > 1; passo /= 2) { for (j = 0; j < tam / passo; j++) { for (i = passo * j; i < passo * j + passo / 2; i++) { swap(num, ini + i, ini + i + passo / 2, dir); } } } } void bitonic(int num[]) { int passo, i, dir = UP; for (passo = 2; passo <= TAM; passo *= 2) { #pragma omp parallel for shared(num) for (i = 0; i < TAM; i += passo) { if (i == 0 && passo != 2) { dir = DOWN; } bitonic_internal(num, i, passo, dir); dir *= -1; } } } int main(void) { int i, j, valores[TAM]; geraAleatorios(valores); bitonic(valores); // for (i = 0; i < TAM; i++) // { // printf("%d: %d\n", i, valores[i]); // } }
declare_variant_ast_print.c
// RUN: %clang_cc1 -verify -fopenmp -x c -std=c99 -ast-print %s -o - | FileCheck %s // RUN: %clang_cc1 -verify -fopenmp-simd -x c -std=c99 -ast-print %s -o - | FileCheck %s // expected-no-diagnostics int foo(void); #pragma omp declare variant(foo) match(xxx={}, yyy={ccc}) #pragma omp declare variant(foo) match(xxx={vvv}) #pragma omp declare variant(foo) match(implementation={vendor(ibm)}, implementation={vendor(llvm)}) #pragma omp declare variant(foo) match(implementation={vendor(unknown)}) #pragma omp declare variant(foo) match(implementation={vendor(score(5): ibm, xxx)}) int bar(void); // CHECK: int foo(); // CHECK-NEXT: #pragma omp declare variant(foo) match(implementation={vendor(score(5):ibm)}) // CHECK-NEXT: #pragma omp declare variant(foo) match(implementation={vendor(score(5):xxx)}) // CHECK-NEXT: #pragma omp declare variant(foo) match(implementation={vendor(unknown)}) // CHECK-NEXT: #pragma omp declare variant(foo) match(implementation={vendor(ibm)}) // CHECK-NEXT: #pragma omp declare variant(foo) match(implementation={vendor(llvm)}) // CHECK-NEXT: int bar();
timestep_opt3.c
#include <math.h> #include "timestep.h" #define REAL_CELL 1 double timestep(int ncells, double g, double sigma, int* celltype, double* H, double* U, double* V, double* dx, double* dy){ double mymindt = 1.0e20; #pragma omp simd reduction(min:mymindt) for (int ic=0; ic<ncells ; ic++) { if (celltype[ic] == REAL_CELL) { double wavespeed = sqrt(g*H[ic]); double xspeed = (fabs(U[ic])+wavespeed)/dx[ic]; double yspeed = (fabs(V[ic])+wavespeed)/dy[ic]; double dt=sigma/(xspeed+yspeed); if (dt < mymindt) mymindt = dt; } } return(mymindt); }
VerletClusterListsTest.h
/** * @file VerletClusterListsTest.h * @author nguyen * @date 21.10.18 */ #pragma once #include <gtest/gtest.h> #include "AutoPasTestBase.h" #include "autopas/cells/FullParticleCell.h" #include "autopas/containers/verletClusterLists/traversals/VCLC06Traversal.h" #include "autopas/particles/Particle.h" #include "autopas/utils/WrapOpenMP.h" #include "autopasTools/generators/RandomGenerator.h" #include "mocks/MockFunctor.h" #include "testingHelpers/commonTypedefs.h" class VerletClusterListsTest : public AutoPasTestBase {}; class CollectParticlePairsFunctor : public autopas::Functor<autopas::Particle, CollectParticlePairsFunctor> { public: std::vector<std::pair<Particle *, Particle *>> _pairs{}; std::array<double, 3> _min; std::array<double, 3> _max; CollectParticlePairsFunctor(double cutoff, std::array<double, 3> min, std::array<double, 3> max) : Functor(cutoff), _min(min), _max(max) {} void initTraversal() override { _pairs.clear(); } void AoSFunctor(Particle &i, Particle &j, bool newton3) override { auto dist = autopas::utils::ArrayMath::sub(i.getR(), j.getR()); if (autopas::utils::ArrayMath::dot(dist, dist) > getCutoff() * getCutoff() or not autopas::utils::inBox(i.getR(), _min, _max) or not autopas::utils::inBox(j.getR(), _min, _max)) return; #if defined(AUTOPAS_OPENMP) #pragma omp critical #endif { _pairs.emplace_back(&i, &j); if (newton3) _pairs.emplace_back(&j, &i); }; } bool isRelevantForTuning() override { return false; } bool allowsNewton3() override { return true; } bool allowsNonNewton3() override { return true; } auto getParticlePairs() { return _pairs; } }; #if defined(AUTOPAS_OPENMP) class CollectParticlesPerThreadFunctor : public autopas::Functor<autopas::Particle, CollectParticlesPerThreadFunctor> { public: int _currentColor{}; std::array<std::vector<std::set<Particle *>>, 8> _particlesPerThreadPerColor; public: CollectParticlesPerThreadFunctor() : Functor(0) {} void initTraversal() override { for (int i = 0; i < 8; i++) { _particlesPerThreadPerColor[i].resize(autopas::autopas_get_max_threads()); } } void AoSFunctor(Particle &i, Particle &j, bool newton3) override { if (i.isDummy() or j.isDummy()) { return; } auto threadNum = autopas::autopas_get_thread_num(); _particlesPerThreadPerColor[_currentColor][threadNum].insert(&i); _particlesPerThreadPerColor[_currentColor][threadNum].insert(&j); } bool isRelevantForTuning() override { return false; } bool allowsNewton3() override { return true; } bool allowsNonNewton3() override { return true; } void nextColor(int newColor) { _currentColor = newColor; } }; class ColoringTraversalWithColorChangeNotify : public autopas::VCLC06Traversal<FPCell, CollectParticlesPerThreadFunctor, autopas::DataLayoutOption::aos, true> { public: ColoringTraversalWithColorChangeNotify(CollectParticlesPerThreadFunctor *functor, size_t clusterSize, std::function<void(int)> whenColorChanges) : autopas::VCLC06Traversal<FPCell, CollectParticlesPerThreadFunctor, autopas::DataLayoutOption::aos, true>( functor, clusterSize) { _whenColorChanges = std::move(whenColorChanges); } void notifyColorChange(unsigned long newColor) override { _whenColorChanges(newColor); } private: std::function<void(int)> _whenColorChanges; }; #endif
primo_grande.c
#include <stdio.h> #include <math.h> #include <limits.h> #include <omp.h> typedef unsigned long long Entero_grande; #define ENTERO_MAS_GRANDE ULLONG_MAX int primo(Entero_grande n) { int p; Entero_grande i, s; p = (n % 2 != 0 || n == 2); if (p) { s = sqrt(n); int numberOfThreads; int offset; #ifdef _OPENMP #pragma omp parallel numberOfThreads = omp_get_num_threads(); offset = 2 * numberOfThreads; #else numberOfThreads = 1; offset = 2; #endif #pragma omp parallel private(i) { #ifdef _OPENMP int threadIndex = omp_get_thread_num(); int startIndex = (2 * threadIndex) + 3; #else int startIndex = 3; #endif for (i = startIndex; p && i <= s; i += offset) if (n % i == 0) p = 0; } } return p; } int main() { Entero_grande n; #ifdef _OPENMP double t1 = omp_get_wtime(); #endif for (n = ENTERO_MAS_GRANDE; !primo(n); n -= 2) { /* NADA */ } #ifdef _OPENMP double t2 = omp_get_wtime(); printf("looptime: %f \n", t2-t1); #endif printf("El mayor primo que cabe en %d bytes es %llu.\n", sizeof(Entero_grande), n); return 0; }
GB_unop__lnot_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__lnot_fp32_fp32) // op(A') function: GB (_unop_tran__lnot_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = !(z != 0) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__lnot_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = !(z != 0) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = !(z != 0) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__lnot_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
packed.c
/* * This file contains routines for manipulating block matrices with blocks * stored in LAPACK's packed storage scheme. */ #include <stdlib.h> #include <stdio.h> #include "declarations.h" void store_packed(A,B) struct blockmatrix A,B; { int blk,i,j,n; double *p; double *q; for (blk=1; blk<=A.nblocks; blk++) { switch (A.blocks[blk].blockcategory) { case DIAG: p=A.blocks[blk].data.vec; q=B.blocks[blk].data.vec; n=A.blocks[blk].blocksize; for (i=1; i<=n; i++) q[i]=p[i]; break; case MATRIX: p=A.blocks[blk].data.mat; q=B.blocks[blk].data.mat; n=A.blocks[blk].blocksize; #pragma omp parallel for schedule(dynamic,64) private(i,j) shared(p,q,n) for (j=1; j<=n; j++) for (i=1; i<=j; i++) q[ijtokp(i,j,n)]=p[ijtok(i,j,n)]; break; default: printf("store_packed illegal block type \n"); exit(12); }; } } void store_unpacked(A,B) struct blockmatrix A,B; { int blk,i,j,n; double *p; double *q; for (blk=1; blk<=A.nblocks; blk++) { switch (A.blocks[blk].blockcategory) { case DIAG: p=A.blocks[blk].data.vec; q=B.blocks[blk].data.vec; n=A.blocks[blk].blocksize; for (i=1; i<=n; i++) q[i]=p[i]; break; case PACKEDMATRIX: p=A.blocks[blk].data.mat; q=B.blocks[blk].data.mat; n=A.blocks[blk].blocksize; #pragma omp parallel for schedule(dynamic,64) private(i,j) shared(p,q,n) for (j=1; j<=n; j++) for (i=1; i<=j; i++) q[ijtok(i,j,n)]=p[ijtokp(i,j,n)]; for (j=1; j<n; j++) for (i=j+1; i<=n; i++) q[ijtok(i,j,n)]=q[ijtok(j,i,n)]; break; default: printf("store_unpacked block type \n"); exit(12); }; } } /* * Allocate space for a block matrix. Get strucutre info from A, and * allocate the matrix B with matching structure. */ void alloc_mat_packed(A,pB) struct blockmatrix A; struct blockmatrix *pB; { int blk,n; /* * First put up the number of blocks. */ pB->nblocks=A.nblocks; /* * Then allocate space for the block records. */ pB->blocks=(struct blockrec *)malloc(sizeof(struct blockrec)*(A.nblocks+1)); if (pB->blocks == NULL) { printf("Storage allocation failed!\n"); exit(10); }; /* * Now, fill in the info for each block. */ for (blk=1; blk <=A.nblocks; blk++) { switch (A.blocks[blk].blockcategory) { case DIAG: pB->blocks[blk].blockcategory=A.blocks[blk].blockcategory; pB->blocks[blk].blocksize=A.blocks[blk].blocksize; pB->blocks[blk].data.vec=(double *)malloc(sizeof(double)*(A.blocks[blk].blocksize+1)); if (pB->blocks[blk].data.vec == NULL) { printf("Storage allocation failed!\n"); exit(10); }; break; case MATRIX: n=A.blocks[blk].blocksize; pB->blocks[blk].blockcategory=PACKEDMATRIX; pB->blocks[blk].blocksize=n; pB->blocks[blk].data.mat=(double *)malloc(sizeof(double)*n*(n+1)/2); if (pB->blocks[blk].data.mat == NULL) { printf("Storage allocation failed!\n"); exit(10); }; break; default: printf("Illegal block type!\n"); exit(12); }; }; } void free_mat_packed(A) struct blockmatrix A; { int blk; /* * First, free the space for each block. */ for (blk=1; blk <=A.nblocks; blk++) { switch (A.blocks[blk].blockcategory) { case DIAG: free(A.blocks[blk].data.vec); break; case PACKEDMATRIX: free(A.blocks[blk].data.mat); break; default: printf("Illegal block type!\n"); exit(12); }; }; /* * Then free space for the block records. */ free(A.blocks); } void triu(A) struct blockmatrix A; { int i,j,n; int blk; for (blk=1; blk <= A.nblocks; blk++) { switch (A.blocks[blk].blockcategory) { case DIAG: break; case MATRIX: n=A.blocks[blk].blocksize; #pragma omp parallel for schedule(dynamic,64) private(i,j) shared(A,n) for (j=1; j<n; j++) for (i=j+1; i<=n; i++) A.blocks[blk].data.mat[ijtok(i,j,n)]=0.0; break; default: printf("triu illegal block type!\n"); exit(12); }; }; }
GB_unop__cos_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__cos_fp32_fp32) // op(A') function: GB (_unop_tran__cos_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = cosf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cosf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = cosf (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_COS || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cos_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = cosf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = cosf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cos_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
exact_parallel_minimum_cut.h
/****************************************************************************** * exact_parallel_minimum_cut.h * * Source of VieCut. * ****************************************************************************** * Copyright (C) 2018 Alexander Noe <alexander.noe@univie.ac.at> * * Published under the MIT license in the LICENSE file. *****************************************************************************/ #pragma once #include <algorithm> #include <cstdint> #include <cstdlib> #include <deque> #include <functional> #include <memory> #include <unordered_map> #include <vector> #include "algorithms/global_mincut/minimum_cut_helpers.h" #include "algorithms/global_mincut/noi_minimum_cut.h" #include "algorithms/global_mincut/viecut.h" #include "coarsening/test_wrapper.h" #include "common/configuration.h" #include "common/definitions.h" #include "data_structure/graph_access.h" #include "data_structure/priority_queues/fifo_node_bucket_pq.h" #include "data_structure/priority_queues/maxNodeHeap.h" #include "data_structure/priority_queues/node_bucket_pq.h" #include "tools/random_functions.h" #include "tools/timer.h" #ifdef PARALLEL #include "parallel/coarsening/contract_graph.h" #include "parallel/coarsening/contraction_tests.h" #include "parallel/coarsening/sparsify.h" #include "parallel/data_structure/union_find.h" #else #include "coarsening/contract_graph.h" #include "coarsening/contraction_tests.h" #include "coarsening/sparsify.h" #include "data_structure/union_find.h" #endif class exact_parallel_minimum_cut : public minimum_cut { public: exact_parallel_minimum_cut() { } ~exact_parallel_minimum_cut() { } static constexpr bool debug = false; static constexpr bool timing = true; EdgeWeight perform_minimum_cut(std::shared_ptr<graph_access> G) { return perform_minimum_cut(G, false); } EdgeWeight perform_minimum_cut(std::shared_ptr<graph_access> G, bool indirect) { if (!minimum_cut_helpers::graphValid(G)) return -1; std::vector<std::shared_ptr<graph_access> > graphs; timer t; EdgeWeight mincut = G->getMinDegree(); #ifdef PARALLEL viecut heuristic_mc; mincut = heuristic_mc.perform_minimum_cut(G, true); LOGC(timing) << "VieCut found cut " << mincut << " [Time: " << t.elapsed() << "s]"; #endif graphs.push_back(G); // if PARALLEL is set, NodeInCut are already set to the result of viecut // This is what we want. #ifndef PARALLEL minimum_cut_helpers::setInitialCutValues(graphs); #endif while (graphs.back()->number_of_nodes() > 2 && mincut > 0) { std::shared_ptr<graph_access> curr_g = graphs.back(); timer ts; #ifdef PARALLEL noi_minimum_cut noi; auto uf = parallel_modified_capforest(curr_g, mincut); if (uf.n() == curr_g->number_of_nodes()) { uf = noi.modified_capforest(curr_g, mincut); LOG1 << "seq capforest needed"; } #else LOG1 << "Error: Running exact_parallel_minimum_cut without PARALLEL" << " Using normal noi_minimum_cut instead!"; noi_minimum_cut noi; auto uf = noi.modified_capforest(curr_g, mincut); #endif if (uf.n() > 1) { std::vector<NodeID> mapping(curr_g->number_of_nodes()); std::vector<NodeID> part(curr_g->number_of_nodes(), UNDEFINED_NODE); std::vector<std::vector<NodeID> > reverse_mapping; NodeID current_pid = 0; for (NodeID n : curr_g->nodes()) { NodeID part_id = uf.Find(n); if (part[part_id] == UNDEFINED_NODE) { part[part_id] = current_pid++; } mapping[n] = part[part_id]; curr_g->setPartitionIndex(n, part[part_id]); } graphs.push_back( contraction::contractGraph(curr_g, mapping, current_pid, reverse_mapping)); mincut = minimum_cut_helpers::updateCut(graphs, mincut); } else { break; } } if (!indirect && configuration::getConfig()->save_cut) minimum_cut_helpers::retrieveMinimumCut(graphs); return mincut; } std::vector<NodeID> randomStartNodes(std::shared_ptr<graph_access> G) { std::vector<NodeID> start_nodes; for (int i = 0; i < omp_get_max_threads(); ++i) start_nodes.push_back( random_functions::next() % G->number_of_nodes()); return start_nodes; } std::vector<NodeID> bfsStartNodes(std::shared_ptr<graph_access> G) { NodeID starting_node = random_functions::next() % G->number_of_nodes(); std::vector<NodeID> start_nodes; start_nodes.push_back(starting_node); for (int i = 1; i < omp_get_max_threads(); ++i) { std::deque<NodeID> bfs; std::vector<bool> nodes(G->number_of_nodes(), false); size_t found = i; for (auto el : start_nodes) { bfs.push_back(el); nodes[el] = true; } while (!bfs.empty() && found < G->number_of_nodes()) { NodeID no = bfs.front(); bfs.pop_front(); for (EdgeID e : G->edges_of(no)) { NodeID tgt = G->getEdgeTarget(e); if (!nodes[tgt]) { found++; nodes[tgt] = true; bfs.push_back(tgt); if (found == G->number_of_nodes()) { start_nodes.push_back(tgt); break; } } } } } return start_nodes; } union_find parallel_modified_capforest( std::shared_ptr<graph_access> G, const EdgeWeight mincut) { union_find uf(G->number_of_nodes()); LOG << "Contract all edges with value at least " << mincut; timer t; timer timer2; std::vector<NodeID> start_nodes = randomStartNodes(G); // std::vector<bool> would be bad for thread-safety std::vector<uint8_t> visited(G->number_of_nodes(), false); std::vector<size_t> times(G->number_of_nodes(), 0); #pragma omp parallel for for (int i = 0; i < omp_get_num_threads(); ++i) { fifo_node_bucket_pq pq(G->number_of_nodes(), mincut + 1); std::vector<bool> blacklisted(G->number_of_nodes(), false); std::vector<NodeID> r_v(G->number_of_nodes(), 0); NodeID starting_node = start_nodes[i]; NodeID current_node = starting_node; pq.insert(current_node, 0); timer t; size_t elements = 0; while (!pq.empty()) { current_node = pq.deleteMax(); blacklisted[current_node] = true; if (visited[current_node]) { continue; } else { visited[current_node] = true; } elements++; for (EdgeID e : G->edges_of(current_node)) { NodeID tgt = G->getEdgeTarget(e); if (r_v[tgt] < mincut) { if ((r_v[tgt] + G->getEdgeWeight(e)) >= mincut) { if (!blacklisted[tgt]) { uf.Union(current_node, tgt); } } if (!visited[tgt]) { size_t new_rv = std::min(r_v[tgt] + G->getEdgeWeight(e), mincut); r_v[tgt] = new_rv; if (!visited[tgt] && !blacklisted[tgt]) { if (pq.contains(tgt)) { pq.increaseKey(tgt, new_rv); } else { pq.insert(tgt, new_rv); } } } } } } } return uf; } };
GB_matlab_helper.c
//------------------------------------------------------------------------------ // GB_matlab_helper.c: helper functions for MATLAB interface //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // These functions are only used by the MATLAB interface for // SuiteSparse:GraphBLAS. #include "GB_matlab_helper.h" //------------------------------------------------------------------------------ // GB_NTHREADS: determine the number of threads to use //------------------------------------------------------------------------------ #define GB_NTHREADS(work) \ int nthreads_max = GB_Global_nthreads_max_get ( ) ; \ double chunk = GB_Global_chunk_get ( ) ; \ int nthreads = GB_nthreads (work, chunk, nthreads_max) ; //------------------------------------------------------------------------------ // GB_ALLOCATE_WORK: allocate per-thread workspace //------------------------------------------------------------------------------ #define GB_ALLOCATE_WORK(work_type) \ work_type *Work = GB_MALLOC (nthreads, work_type) ; \ if (Work == NULL) return (false) ; //------------------------------------------------------------------------------ // GB_FREE_WORK: free per-thread workspace //------------------------------------------------------------------------------ #define GB_FREE_WORK(work_type) \ GB_FREE (Work) ; //------------------------------------------------------------------------------ // GB_matlab_helper1: convert 0-based indices to 1-based for gbextracttuples //------------------------------------------------------------------------------ void GB_matlab_helper1 // convert zero-based indices to one-based ( double *GB_RESTRICT I_double, // output array const GrB_Index *GB_RESTRICT I, // input array int64_t nvals // size of input and output arrays ) { GB_NTHREADS (nvals) ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < nvals ; k++) { I_double [k] = (double) (I [k] + 1) ; } } //------------------------------------------------------------------------------ // GB_matlab_helper1i: convert 0-based indices to 1-based for gbextracttuples //------------------------------------------------------------------------------ void GB_matlab_helper1i // convert zero-based indices to one-based ( int64_t *GB_RESTRICT I, // input/output array int64_t nvals // size of input/output array ) { GB_NTHREADS (nvals) ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < nvals ; k++) { I [k] ++ ; } } //------------------------------------------------------------------------------ // GB_matlab_helper2: create structure for dense matrix for gb_get_shallow //------------------------------------------------------------------------------ void GB_matlab_helper2 // fill Xp and Xi for a dense matrix ( GrB_Index *GB_RESTRICT Xp, // size ncols+1 GrB_Index *GB_RESTRICT Xi, // size nrows*ncols int64_t ncols, int64_t nrows ) { GB_NTHREADS (ncols) ; int64_t j ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (j = 0 ; j <= ncols ; j++) { Xp [j] = j * nrows ; } double work = ((double) ncols) * ((double) nrows) ; nthreads = GB_nthreads (work, chunk, nthreads_max) ; int64_t nel = nrows * ncols ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < nel ; k++) { int64_t i = k % nrows ; Xi [k] = i ; } } //------------------------------------------------------------------------------ // GB_matlab_helper3: convert 1-based indices to 0-based for gb_mxarray_to_list //------------------------------------------------------------------------------ bool GB_matlab_helper3 // return true if OK, false on error ( int64_t *GB_RESTRICT List, // size len, output array const double *GB_RESTRICT List_double, // size len, input array int64_t len, int64_t *List_max // also compute the max entry in the list ) { GB_NTHREADS (len) ; bool ok = true ; int64_t listmax = -1 ; GB_ALLOCATE_WORK (int64_t) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { bool my_ok = true ; int64_t k1, k2, my_listmax = -1 ; GB_PARTITION (k1, k2, len, tid, nthreads) ; for (int64_t k = k1 ; k < k2 ; k++) { double x = List_double [k] ; int64_t i = (int64_t) x ; my_ok = my_ok && (x == (double) i) ; my_listmax = GB_IMAX (my_listmax, i) ; List [k] = i - 1 ; } // rather than create a separate per-thread boolean workspace, just // use a sentinal value of INT64_MIN if non-integer indices appear // in List_double. Work [tid] = my_ok ? my_listmax : INT64_MIN ; } // wrapup for (tid = 0 ; tid < nthreads ; tid++) { listmax = GB_IMAX (listmax, Work [tid]) ; ok = ok && (Work [tid] != INT64_MIN) ; } GB_FREE_WORK (int64_t) ; (*List_max) = listmax ; return (ok) ; } //------------------------------------------------------------------------------ // GB_matlab_helper3i: convert 1-based indices to 0-based for gb_mxarray_to_list //------------------------------------------------------------------------------ bool GB_matlab_helper3i // return true if OK, false on error ( int64_t *GB_RESTRICT List, // size len, output array const int64_t *GB_RESTRICT List_int64, // size len, input array int64_t len, int64_t *List_max // also compute the max entry in the list ) { GB_NTHREADS (len) ; int64_t listmax = -1 ; GB_ALLOCATE_WORK (int64_t) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t k1, k2, my_listmax = -1 ; GB_PARTITION (k1, k2, len, tid, nthreads) ; for (int64_t k = k1 ; k < k2 ; k++) { int64_t i = List_int64 [k] ; my_listmax = GB_IMAX (my_listmax, i) ; List [k] = i - 1 ; } Work [tid] = my_listmax ; } // wrapup for (tid = 0 ; tid < nthreads ; tid++) { listmax = GB_IMAX (listmax, Work [tid]) ; } GB_FREE_WORK (int64_t) ; (*List_max) = listmax ; return (true) ; } //------------------------------------------------------------------------------ // GB_matlab_helper4: find the max entry in an index list for gbbuild //------------------------------------------------------------------------------ bool GB_matlab_helper4 // return true if OK, false on error ( const GrB_Index *GB_RESTRICT I, // array of size len const int64_t len, GrB_Index *List_max // find max (I) + 1 ) { GB_NTHREADS (len) ; GrB_Index listmax = 0 ; GB_ALLOCATE_WORK (GrB_Index) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t k1, k2 ; GrB_Index my_listmax = 0 ; GB_PARTITION (k1, k2, len, tid, nthreads) ; for (int64_t k = k1 ; k < k2 ; k++) { my_listmax = GB_IMAX (my_listmax, I [k]) ; } Work [tid] = my_listmax ; } // wrapup for (tid = 0 ; tid < nthreads ; tid++) { listmax = GB_IMAX (listmax, Work [tid]) ; } GB_FREE_WORK (GrB_Index) ; if (len > 0) listmax++ ; (*List_max) = listmax ; return (true) ; } //------------------------------------------------------------------------------ // GB_matlab_helper5: construct pattern of S for gblogassign //------------------------------------------------------------------------------ void GB_matlab_helper5 // construct pattern of S ( GrB_Index *GB_RESTRICT Si, // array of size anz GrB_Index *GB_RESTRICT Sj, // array of size anz const GrB_Index *GB_RESTRICT Mi, // array of size mnz const GrB_Index *GB_RESTRICT Mj, // array of size mnz GrB_Index *GB_RESTRICT Ai, // array of size anz const GrB_Index anz ) { GB_NTHREADS (anz) ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < anz ; k++) { Si [k] = Mi [Ai [k]] ; Sj [k] = Mj [Ai [k]] ; } } //------------------------------------------------------------------------------ // GB_matlab_helper6: set bool array to all true gblogextract //------------------------------------------------------------------------------ void GB_matlab_helper6 // set Gbool to all true ( bool *GB_RESTRICT Gbool, // array of size gnvals const GrB_Index gnvals ) { GB_NTHREADS (gnvals) ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < gnvals ; k++) { Gbool [k] = true ; } } //------------------------------------------------------------------------------ // GB_matlab_helper7: Kx = uint64 (0:mnz-1), for gblogextract //------------------------------------------------------------------------------ void GB_matlab_helper7 // Kx = uint64 (0:mnz-1) ( uint64_t *GB_RESTRICT Kx, // array of size mnz const GrB_Index mnz ) { GB_NTHREADS (mnz) ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < mnz ; k++) { Kx [k] = k ; } } //------------------------------------------------------------------------------ // GB_matlab_helper8: expand a scalar into an array for gbbuild //------------------------------------------------------------------------------ void GB_matlab_helper8 ( GB_void *C, // output array of size nvals * s GB_void *A, // input scalar of size s GrB_Index nvals, // size of C size_t s // size of each scalar ) { GB_NTHREADS (nvals) ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < nvals ; k++) { // C [k] = A [0] memcpy (C + k * s, A, s) ; } } //------------------------------------------------------------------------------ // GB_matlab_helper9: compute the degree of each vector //------------------------------------------------------------------------------ bool GB_matlab_helper9 // true if successful, false if out of memory ( GrB_Matrix A, // input matrix int64_t **degree, // degree of each vector, size nvec GrB_Index **list, // list of non-empty vectors GrB_Index *nvec // # of non-empty vectors ) { int64_t anvec = A->nvec ; GB_NTHREADS (anvec) ; uint64_t *List = GB_MALLOC (anvec, uint64_t) ; int64_t *Degree = GB_MALLOC (anvec, int64_t) ; if (List == NULL || Degree == NULL) { GB_FREE (List) ; GB_FREE (Degree) ; return (false) ; } int64_t *Ah = A->h ; int64_t *Ap = A->p ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < anvec ; k++) { List [k] = (Ah == NULL) ? k : Ah [k] ; Degree [k] = Ap [k+1] - Ap [k] ; } // return result (*degree) = Degree ; (*list) = List ; (*nvec) = anvec ; return (true) ; } //------------------------------------------------------------------------------ // GB_matlab_helper10: compute norm (x-y,p) of two dense FP32 or FP64 vectors //------------------------------------------------------------------------------ // p can be: // 0 or 2: 2-norm, sqrt (sum ((x-y).^2)) // 1: 1-norm, sum (abs (x-y)) // INT64_MAX inf-norm, max (abs (x-y)) // INT64_MIN (-inf)-norm, min (abs (x-y)) // other: p-norm not yet computed double GB_matlab_helper10 // norm (x-y,p), or -1 on error ( GB_void *x_arg, // float or double, depending on type parameter GB_void *y_arg, // same type as x, treat as zero if NULL GrB_Type type, // GrB_FP32 or GrB_FP64 int64_t p, // 0, 1, 2, INT64_MIN, or INT64_MAX GrB_Index n ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- if (!(type == GrB_FP32 || type == GrB_FP64)) { // type of x and y must be GrB_FP32 or GrB_FP64 return ((double) -1) ; } if (n == 0) { return ((double) 0) ; } //-------------------------------------------------------------------------- // allocate workspace and determine # of threads to use //-------------------------------------------------------------------------- GB_NTHREADS (n) ; GB_ALLOCATE_WORK (double) ; //-------------------------------------------------------------------------- // each thread computes its partial norm //-------------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t k1, k2 ; GB_PARTITION (k1, k2, n, tid, nthreads) ; if (type == GrB_FP32) { //------------------------------------------------------------------ // FP32 case //------------------------------------------------------------------ float my_s = 0 ; const float *x = (float *) x_arg ; const float *y = (float *) y_arg ; switch (p) { case 0: // Frobenius norm case 2: // 2-norm: sqrt of sum of (x-y).^2 { if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { float t = x [k] ; my_s += (t*t) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { float t = (x [k] - y [k]) ; my_s += (t*t) ; } } } break ; case 1: // 1-norm: sum (abs (x-y)) { if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { my_s += fabsf (x [k]) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { my_s += fabsf (x [k] - y [k]) ; } } } break ; case INT64_MAX: // inf-norm: max (abs (x-y)) { if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fmaxf (my_s, fabsf (x [k])) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fmaxf (my_s, fabsf (x [k] - y [k])) ; } } } break ; case INT64_MIN: // (-inf)-norm: min (abs (x-y)) { my_s = INFINITY ; if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fminf (my_s, fabsf (x [k])) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fminf (my_s, fabsf (x [k] - y [k])) ; } } } break ; default: ; // p-norm not yet supported } Work [tid] = (double) my_s ; } else { //------------------------------------------------------------------ // FP64 case //------------------------------------------------------------------ double my_s = 0 ; const double *x = (double *) x_arg ; const double *y = (double *) y_arg ; switch (p) { case 0: // Frobenius norm case 2: // 2-norm: sqrt of sum of (x-y).^2 { if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { double t = x [k] ; my_s += (t*t) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { double t = (x [k] - y [k]) ; my_s += (t*t) ; } } } break ; case 1: // 1-norm: sum (abs (x-y)) { if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { my_s += fabs (x [k]) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { my_s += fabs (x [k] - y [k]) ; } } } break ; case INT64_MAX: // inf-norm: max (abs (x-y)) { if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fmax (my_s, fabs (x [k])) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fmax (my_s, fabs (x [k] - y [k])) ; } } } break ; case INT64_MIN: // (-inf)-norm: min (abs (x-y)) { my_s = INFINITY ; if (y == NULL) { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fmin (my_s, fabs (x [k])) ; } } else { for (int64_t k = k1 ; k < k2 ; k++) { my_s = fmin (my_s, fabs (x [k] - y [k])) ; } } } break ; default: ; // p-norm not yet supported } Work [tid] = my_s ; } } //-------------------------------------------------------------------------- // combine results of each thread //-------------------------------------------------------------------------- double s = 0 ; switch (p) { case 0: // Frobenius norm case 2: // 2-norm: sqrt of sum of (x-y).^2 { for (int64_t tid = 0 ; tid < nthreads ; tid++) { s += Work [tid] ; } s = sqrt (s) ; } break ; case 1: // 1-norm: sum (abs (x-y)) { for (int64_t tid = 0 ; tid < nthreads ; tid++) { s += Work [tid] ; } } break ; case INT64_MAX: // inf-norm: max (abs (x-y)) { for (int64_t tid = 0 ; tid < nthreads ; tid++) { s = fmax (s, Work [tid]) ; } } break ; case INT64_MIN: // (-inf)-norm: min (abs (x-y)) { s = Work [0] ; for (int64_t tid = 1 ; tid < nthreads ; tid++) { s = fmin (s, Work [tid]) ; } } break ; default: // p-norm not yet supported s = -1 ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORK (double) ; return (s) ; }
shallow_base_openmp_v3.c
/* Code converted from shallow_base.f90 using F2C-ACC program. * Manually replaced: * - WRITE statements with printf * - MOD operator with % * - system_clock with wtime * Fixed several of the array references which had x dimension as 1, * instead of M_LEN. * Fixed values set using d and e notation. * (7 June 2011) *************** * 'Pure' C version developed by G.D Riley (UoM) (25 Jan 2012) * removed all ftocmacros * used sin and cos not sinf and cosf (since all data are doubles) * needed to declare arrays +1 to cope with Fortran indexing * Compile, e.g.: * gcc -O2 -fopenmp -o sb shallow_base_openmp_v3.c wtime.c -lm ** NOTE: May need to set 'ulimit -s unlimited' to run large * problems (e.g. 512x512). * Results are consistent with Fortran version of the code. * GDR: July 2013 * Applied static, chunk scheduling for load balance,as described * in Michail Pappas' MSc thesis (2012). */ #include <stdio.h> #include <stdlib.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif #define MIN(x,y) ((x)>(y)?(y):(x)) #define MAX(x,y) ((x)>(y)?(x):(y)) #define TRUE 1 #define FALSE 0 #define M 128 #define N 128 #define M_LEN M + 1 #define N_LEN N + 1 #define ITMAX 2000 #define L_OUT TRUE extern double wtime(); //=================================================== double compute_checksum(double field[M_LEN][N_LEN], int lenx, int leny) { int i, j; double sum = 0.0; for(i=0;i<lenx;i++){ for(j=0;j<leny;j++){ sum += field[i][j]; } } return sum; } //=================================================== //! Benchmark weather prediction program for comparing the //! preformance of current supercomputers. The model is //! based on the paper - The Dynamics of Finite-Difference //! Models of the Shallow-Water Equations, by Robert Sadourny //! J. Atm. Sciences, Vol 32, No 4, April 1975. //! //! Code by Paul N. Swarztrauber, National Center for //! Atmospheric Research, Boulder, Co, October 1984. //! Modified by Juliana Rew, NCAR, January 2006 //! //! In this version, shallow4.f, initial and calculated values //! of U, V, and P are written to a netCDF file //! for later use in visualizing the results. The netCDF data //! management library is freely available from //! http://www.unidata.ucar.edu/software/netcdf //! This code is still serial but has been brought up to modern //! Fortran constructs and uses portable intrinsic Fortran 90 timing routines. //! This can be compiled on the IBM SP using: //! xlf90 -qmaxmem=-1 -g -o shallow4 -qfixed=132 -qsclk=micro \ //! -I/usr/local/include shallow4.f -L/usr/local/lib32/r4i4 -l netcdf //! where the -L and -I point to local installation of netCDF //! //! Changes from shallow4.f (Annette Osprey, January 2010): //! - Converted to free-form fortran 90. //! - Some tidying up of old commented-out code. //! - Explicit type declarations. //! - Variables n, m, ITMAX and mprint read in from namelist. //! - Dynamic array allocation. //! - Only write to netcdf at mprint timesteps. //! - Don't write wrap-around points to NetCDF file. //! - Use 8-byte reals. //! //! Further changes (Annette Osprey & Graham Riley, February 2011): //! - Remove unnecessary halo updates. //! - Split loops to improve TLB access. //! - Modify timers to accumulate loop times over whole run. //! - Remove old-style indentation. //! //! Minimal serial version (26 May 2011) int main(int argc, char **argv) { // solution arrays double u[M_LEN][N_LEN],v[M_LEN][N_LEN],p[M_LEN][N_LEN]; double unew[M_LEN][N_LEN],vnew[M_LEN][N_LEN],pnew[M_LEN][N_LEN]; double uold[M_LEN][N_LEN],vold[M_LEN][N_LEN],pold[M_LEN][N_LEN]; double cu[M_LEN][N_LEN],cv[M_LEN][N_LEN],z[M_LEN][N_LEN],h[M_LEN][N_LEN],psi[M_LEN][N_LEN]; double dt,tdt,dx,dy,a,alpha,el,pi; double tpi,di,dj,pcf; double tdts8,tdtsdx,tdtsdy,fsdx,fsdy; int mnmin,ncycle; int i,j; int nthreads, chunk_size; // timer variables double t100,t200,t300; double tstart,ctime,tcyc,time; double t100i,t200i,t300i; double c1,c2; // ** Initialisations ** nthreads = 1; #ifdef _OPENMP nthreads = omp_get_max_threads(); #endif chunk_size = (int) ceil( (float)M / (float)nthreads); // Note below that two delta t (tdt) is set to dt on the first // cycle after which it is reset to dt+dt. dt = 90.; tdt = dt; dx = 100000.; dy = 100000.; fsdx = 4. / dx; fsdy = 4. / dy; a = 1000000.; alpha = .001; el = N * dx; pi = 4. * atanf(1.); tpi = pi + pi; di = tpi / M; dj = tpi / N; pcf = pi * pi * a * a / (el * el); // Initial values of the stream function and p #pragma omp parallel for default (shared) private(i,j) for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { psi[i][j] = a * sin((i + .5) * di) * sin((j + .5) * dj); p[i][j] = pcf * (cos(2. * (i) * di) + cos(2. * (j) * dj)) + 50000.; } } // Initialize velocities #pragma omp parallel for default (shared) private(i,j) for (i=0;i<M;i++) { for (j=0;j<N;j++) { u[i + 1][j] = -(psi[i + 1][j + 1] - psi[i + 1][j]) / dy; v[i][j + 1] = (psi[i + 1][j + 1] - psi[i][j + 1]) / dx; } } // Periodic continuation for (j=0;j<N;j++) { u[0][j] = u[M][j]; v[M][j + 1] = v[0][j + 1]; } for (i=0;i<M;i++) { u[i + 1][N] = u[i + 1][0]; v[i][0] = v[i][N]; } u[0][N] = u[M][0]; v[M][0] = v[0][N]; #pragma omp parallel default (shared) private(i,j) for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { uold[i][j] = u[i][j]; vold[i][j] = v[i][j]; pold[i][j] = p[i][j]; } } // Print initial values if ( L_OUT ) { printf(" number of points in the x direction %d\n", N); printf(" number of points in the y direction %d\n", M); printf(" grid spacing in the x direction %f\n", dx); printf(" grid spacing in the y direction %f\n", dy); printf(" time step %f\n", dt); printf(" time filter parameter %f\n", alpha); } // Start timer tstart = wtime(); time = 0.; t100 = 0.; t200 = 0.; t300 = 0.; // ** Start of time loop ** #pragma omp parallel default (shared) private(i,j,ncycle,tdts8,tdtsdx,tdtsdy) firstprivate(tdt) for (ncycle=1;ncycle<=ITMAX;ncycle++) { // Compute capital u, capital v, z and h #pragma omp master c1 = wtime(); #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M;i++) { for (j=0;j<N;j++) { cu[i + 1][j] = .5 * (p[i + 1][j] + p[i][j]) * u[i + 1][j]; } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M;i++) { for (j=0;j<N;j++) { cv[i][j + 1] = .5 * (p[i][j + 1] + p[i][j]) * v[i][j + 1]; } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M;i++) { for (j=0;j<N;j++) { z[i + 1][j + 1] = (fsdx * (v[i + 1][j + 1] - v[i][j + 1]) - fsdy * (u[i + 1][j + 1] - u[i + 1][j])) / (p[i][j] + p[i + 1][j] + p[i + 1][j + 1] + p[i][j + 1]); } } #pragma omp for schedule (static,chunk_size) for (i=0;i<M;i++) { for (j=0;j<N;j++) { h[i][j] = p[i][j] + .25 * (u[i + 1][j] * u[i + 1][j] + u[i][j] * u[i][j] + v[i][j + 1] * v[i][j + 1] + v[i][j] * v[i][j]); } } #pragma omp master { c2 = wtime(); t100 = t100 + (c2 - c1); } // Periodic continuation #pragma omp single { for (j=0;j<N;j++) { cu[0][j] = cu[M][j]; cv[M][j + 1] = cv[0][j + 1]; z[0][j + 1] = z[M][j + 1]; h[M][j] = h[0][j]; } cu[0][N] = cu[M][0]; cv[M][0] = cv[0][N]; z[0][0] = z[M][N]; h[M][N] = h[0][0]; } #pragma omp for schedule (static,chunk_size) for (i=0;i<M;i++) { cu[i + 1][N] = cu[i + 1][0]; cv[i][0] = cv[i][N]; z[i + 1][0] = z[i + 1][N]; h[i][N] = h[i][0]; } // Compute new values u,v and p tdts8 = tdt / 8.; tdtsdx = tdt / dx; tdtsdy = tdt / dy; #pragma omp master c1 = wtime(); #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M;i++) { for (j=0;j<N;j++) { unew[i + 1][j] = uold[i + 1][j] + tdts8 * (z[i + 1][j + 1] + z[i + 1][j]) * (cv[i + 1][j + 1] + cv[i][j + 1] + cv[i][j] + cv[i + 1][j]) - tdtsdx * (h[i + 1][j] - h[i][j]); } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M;i++) { for (j=0;j<N;j++) { vnew[i][j + 1] = vold[i][j + 1] - tdts8 * (z[i + 1][j + 1] + z[i][j + 1]) * (cu[i + 1][j + 1] + cu[i][j + 1] + cu[i][j] + cu[i + 1][j]) - tdtsdy * (h[i][j + 1] - h[i][j]); } } #pragma omp for schedule (static,chunk_size) for (i=0;i<M;i++) { for (j=0;j<N;j++) { pnew[i][j] = pold[i][j] - tdtsdx * (cu[i + 1][j] - cu[i][j]) - tdtsdy * (cv[i][j + 1] - cv[i][j]); } } #pragma omp master { c2 = wtime(); t200 = t200 + (c2 - c1); } // Periodic continuation #pragma omp single { for (j=0;j<N;j++) { unew[0][j] = unew[M][j]; vnew[M][j + 1] = vnew[0][j + 1]; pnew[M][j] = pnew[0][j]; } unew[0][N] = unew[M][0]; vnew[M][0] = vnew[0][N]; pnew[M][N] = pnew[0][0]; } #pragma omp for schedule (static,chunk_size) for (i=0;i<M;i++) { unew[i + 1][N] = unew[i + 1][0]; vnew[i][0] = vnew[i][N]; pnew[i][N] = pnew[i][0]; } #pragma omp master time = time + dt; // Time smoothing and update for next cycle if ( ncycle > 1 ) { #pragma omp master c1 = wtime(); #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { uold[i][j] = u[i][j] + alpha * (unew[i][j] - 2. * u[i][j] + uold[i][j]); } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { vold[i][j] = v[i][j] + alpha * (vnew[i][j] - 2. * v[i][j] + vold[i][j]); } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { pold[i][j] = p[i][j] + alpha * (pnew[i][j] - 2. * p[i][j] + pold[i][j]); } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { u[i][j] = unew[i][j]; } } #pragma omp for schedule (static,chunk_size) nowait for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { v[i][j] = vnew[i][j]; } } #pragma omp for schedule (static,chunk_size) for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { p[i][j] = pnew[i][j]; } } #pragma omp master { c2 = wtime(); t300 = t300 + (c2 - c1); } } else { tdt = tdt + tdt; #pragma omp for schedule (static,chunk_size) for (i=0;i<M_LEN;i++) { for (j=0;j<N_LEN;j++) { uold[i][j] = u[i][j]; vold[i][j] = v[i][j]; pold[i][j] = p[i][j]; u[i][j] = unew[i][j]; v[i][j] = vnew[i][j]; p[i][j] = pnew[i][j]; } } } } // ** End of time loop ** fprintf(stdout, "P CHECKSUM after %d steps = %15.7e\n", ITMAX, compute_checksum(pnew,M_LEN,N_LEN)); fprintf(stdout, "U CHECKSUM after %d steps = %15.7e\n", ITMAX, compute_checksum(unew,M_LEN,N_LEN)); fprintf(stdout, "V CHECKSUM after %d steps = %15.7e\n", ITMAX, compute_checksum(vnew,M_LEN,N_LEN)); // Output p, u, v fields and run times. if (L_OUT) { c2 = wtime(); ctime = c2 - tstart; tcyc = ctime / ITMAX; fprintf(stdout,"\n"); fprintf(stdout," Job run on %d threads with a chunk size of %d\n", nthreads, chunk_size); fprintf(stdout," No. of steps = %d, total time = %f, time per cycle = %f (s)\n", ITMAX, ctime, tcyc); fprintf(stdout," time for c{u,v},z,h calc = %.6f s\n", t100); fprintf(stdout," time for {u,v,p}new calc = %.6f s\n", t200); fprintf(stdout," time for time-smoothing = %.6f s\n", t300); } return(0); }
morphology.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M OOO RRRR PPPP H H OOO L OOO GGGG Y Y % % MM MM O O R R P P H H O O L O O G Y Y % % M M M O O RRRR PPPP HHHHH O O L O O G GGG Y % % M M O O R R P H H O O L O O G G Y % % M M OOO R R P H H OOO LLLLL OOO GGG Y % % % % % % MagickCore Morphology Methods % % % % Software Design % % Anthony Thyssen % % January 2010 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Morphology is the application of various kernels, of any size or shape, to an % image in various ways (typically binary, but not always). % % Convolution (weighted sum or average) is just one specific type of % morphology. Just one that is very common for image bluring and sharpening % effects. Not only 2D Gaussian blurring, but also 2-pass 1D Blurring. % % This module provides not only a general morphology function, and the ability % to apply more advanced or iterative morphologies, but also functions for the % generation of many different types of kernel arrays from user supplied % arguments. Prehaps even the generation of a kernel from a small image. */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/linked-list.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology.h" #include "MagickCore/morphology-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/prepress.h" #include "MagickCore/quantize.h" #include "MagickCore/resource_.h" #include "MagickCore/registry.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "ios_error.h" /* Other global definitions used by module. */ #define Minimize(assign,value) assign=MagickMin(assign,value) #define Maximize(assign,value) assign=MagickMax(assign,value) /* Integer Factorial Function - for a Binomial kernel */ #if 1 static inline size_t fact(size_t n) { size_t f,l; for(f=1, l=2; l <= n; f=f*l, l++); return(f); } #elif 1 /* glibc floating point alternatives */ #define fact(n) ((size_t)tgamma((double)n+1)) #else #define fact(n) ((size_t)lgamma((double)n+1)) #endif /* Currently these are only internal to this module */ static void CalcKernelMetaData(KernelInfo *), ExpandMirrorKernelInfo(KernelInfo *), ExpandRotateKernelInfo(KernelInfo *, const double), RotateKernelInfo(KernelInfo *, double); /* Quick function to find last kernel in a kernel list */ static inline KernelInfo *LastKernelInfo(KernelInfo *kernel) { while (kernel->next != (KernelInfo *) NULL) kernel=kernel->next; return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelInfo() takes the given string (generally supplied by the % user) and converts it into a Morphology/Convolution Kernel. This allows % users to specify a kernel from a number of pre-defined kernels, or to fully % specify their own kernel for a specific Convolution or Morphology % Operation. % % The kernel so generated can be any rectangular array of floating point % values (doubles) with the 'control point' or 'pixel being affected' % anywhere within that array of values. % % Previously IM was restricted to a square of odd size using the exact % center as origin, this is no longer the case, and any rectangular kernel % with any value being declared the origin. This in turn allows the use of % highly asymmetrical kernels. % % The floating point values in the kernel can also include a special value % known as 'nan' or 'not a number' to indicate that this value is not part % of the kernel array. This allows you to shaped the kernel within its % rectangular area. That is 'nan' values provide a 'mask' for the kernel % shape. However at least one non-nan value must be provided for correct % working of a kernel. % % The returned kernel should be freed using the DestroyKernelInfo() when you % are finished with it. Do not free this memory yourself. % % Input kernel defintion strings can consist of any of three types. % % "name:args[[@><]" % Select from one of the built in kernels, using the name and % geometry arguments supplied. See AcquireKernelBuiltIn() % % "WxH[+X+Y][@><]:num, num, num ..." % a kernel of size W by H, with W*H floating point numbers following. % the 'center' can be optionally be defined at +X+Y (such that +0+0 % is top left corner). If not defined the pixel in the center, for % odd sizes, or to the immediate top or left of center for even sizes % is automatically selected. % % "num, num, num, num, ..." % list of floating point numbers defining an 'old style' odd sized % square kernel. At least 9 values should be provided for a 3x3 % square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc. % Values can be space or comma separated. This is not recommended. % % You can define a 'list of kernels' which can be used by some morphology % operators A list is defined as a semi-colon separated list kernels. % % " kernel ; kernel ; kernel ; " % % Any extra ';' characters, at start, end or between kernel defintions are % simply ignored. % % The special flags will expand a single kernel, into a list of rotated % kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree % cyclic rotations, while a '>' will generate a list of 90-degree rotations. % The '<' also exands using 90-degree rotates, but giving a 180-degree % reflected kernel before the +/- 90-degree rotations, which can be important % for Thinning operations. % % Note that 'name' kernels will start with an alphabetic character while the % new kernel specification has a ':' character in its specification string. % If neither is the case, it is assumed an old style of a simple list of % numbers generating a odd-sized square kernel has been given. % % The format of the AcquireKernal method is: % % KernelInfo *AcquireKernelInfo(const char *kernel_string) % % A description of each parameter follows: % % o kernel_string: the Morphology/Convolution kernel wanted. % */ /* This was separated so that it could be used as a separate ** array input handling function, such as for -color-matrix */ static KernelInfo *ParseKernelArray(const char *kernel_string) { KernelInfo *kernel; char token[MagickPathExtent]; const char *p, *end; register ssize_t i; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ MagickStatusType flags; GeometryInfo args; kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *) NULL) return(kernel); (void) memset(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = UserDefinedKernel; kernel->next = (KernelInfo *) NULL; kernel->signature=MagickCoreSignature; if (kernel_string == (const char *) NULL) return(kernel); /* find end of this specific kernel definition string */ end = strchr(kernel_string, ';'); if ( end == (char *) NULL ) end = strchr(kernel_string, '\0'); /* clear flags - for Expanding kernel lists thorugh rotations */ flags = NoValue; /* Has a ':' in argument - New user kernel specification FUTURE: this split on ':' could be done by StringToken() */ p = strchr(kernel_string, ':'); if ( p != (char *) NULL && p < end) { /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, kernel_string, (size_t) (p-kernel_string)); token[p-kernel_string] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); /* Size handling and checks of geometry settings */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 1.0; /* then width = 1 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ kernel->width = (size_t)args.rho; kernel->height = (size_t)args.sigma; /* Offset Handling and Checks */ if ( args.xi < 0.0 || args.psi < 0.0 ) return(DestroyKernelInfo(kernel)); kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi : (ssize_t) (kernel->width-1)/2; kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi : (ssize_t) (kernel->height-1)/2; if ( kernel->x >= (ssize_t) kernel->width || kernel->y >= (ssize_t) kernel->height ) return(DestroyKernelInfo(kernel)); p++; /* advance beyond the ':' */ } else { /* ELSE - Old old specification, forming odd-square kernel */ /* count up number of values given */ p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ for (i=0; p < end; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); } /* set the size of the kernel - old sized square */ kernel->width = kernel->height= (size_t) sqrt((double) i+1.0); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ } /* Read in the kernel values from rest of input string argument */ kernel->values=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory( kernel->width,kernel->height*sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); kernel->minimum=MagickMaximumValue; kernel->maximum=(-MagickMaximumValue); kernel->negative_range = kernel->positive_range = 0.0; for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); if ( LocaleCompare("nan",token) == 0 || LocaleCompare("-",token) == 0 ) { kernel->values[i] = nan; /* this value is not part of neighbourhood */ } else { kernel->values[i] = StringToDouble(token,(char **) NULL); ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } } /* sanity check -- no more values in kernel definition */ (void) GetNextToken(p,&p,MagickPathExtent,token); if ( *token != '\0' && *token != ';' && *token != '\'' ) return(DestroyKernelInfo(kernel)); #if 0 /* this was the old method of handling a incomplete kernel */ if ( i < (ssize_t) (kernel->width*kernel->height) ) { Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); for ( ; i < (ssize_t) (kernel->width*kernel->height); i++) kernel->values[i]=0.0; } #else /* Number of values for kernel was not enough - Report Error */ if ( i < (ssize_t) (kernel->width*kernel->height) ) return(DestroyKernelInfo(kernel)); #endif /* check that we recieved at least one real (non-nan) value! */ if (kernel->minimum == MagickMaximumValue) return(DestroyKernelInfo(kernel)); if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */ ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */ else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */ else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */ return(kernel); } static KernelInfo *ParseKernelName(const char *kernel_string, ExceptionInfo *exception) { char token[MagickPathExtent]; const char *p, *end; GeometryInfo args; KernelInfo *kernel; MagickStatusType flags; ssize_t type; /* Parse special 'named' kernel */ (void) GetNextToken(kernel_string,&p,MagickPathExtent,token); type=ParseCommandOption(MagickKernelOptions,MagickFalse,token); if ( type < 0 || type == UserDefinedKernel ) return((KernelInfo *) NULL); /* not a valid named kernel */ while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';')) p++; end = strchr(p, ';'); /* end of this kernel defintion */ if ( end == (char *) NULL ) end = strchr(p, '\0'); /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, p, (size_t) (end-p)); token[end-p] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(thread_stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif /* special handling of missing values in input string */ switch( type ) { /* Shape Kernel Defaults */ case UnityKernel: if ( (flags & WidthValue) == 0 ) args.rho = 1.0; /* Default scale = 1.0, zero is valid */ break; case SquareKernel: case DiamondKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: if ( (flags & HeightValue) == 0 ) args.sigma = 1.0; /* Default scale = 1.0, zero is valid */ break; case RingKernel: if ( (flags & XValue) == 0 ) args.xi = 1.0; /* Default scale = 1.0, zero is valid */ break; case RectangleKernel: /* Rectangle - set size defaults */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 3; /* then width = 3 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ if ( (flags & XValue) == 0 ) /* center offset if not defined */ args.xi = (double)(((ssize_t)args.rho-1)/2); if ( (flags & YValue) == 0 ) args.psi = (double)(((ssize_t)args.sigma-1)/2); break; /* Distance Kernel Defaults */ case ChebyshevKernel: case ManhattanKernel: case OctagonalKernel: case EuclideanKernel: if ( (flags & HeightValue) == 0 ) /* no distance scale */ args.sigma = 100.0; /* default distance scaling */ else if ( (flags & AspectValue ) != 0 ) /* '!' flag */ args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */ else if ( (flags & PercentValue ) != 0 ) /* '%' flag */ args.sigma *= QuantumRange/100.0; /* percentage of color range */ break; default: break; } kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args, exception); if ( kernel == (KernelInfo *) NULL ) return(kernel); /* global expand to rotated kernel list - only for single kernels */ if ( kernel->next == (KernelInfo *) NULL ) { if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 45.0); else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); } return(kernel); } MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string, ExceptionInfo *exception) { KernelInfo *kernel, *new_kernel; char *kernel_cache, token[MagickPathExtent]; const char *p; if (kernel_string == (const char *) NULL) return(ParseKernelArray(kernel_string)); p=kernel_string; kernel_cache=(char *) NULL; if (*kernel_string == '@') { kernel_cache=FileToString(kernel_string+1,~0UL,exception); if (kernel_cache == (char *) NULL) return((KernelInfo *) NULL); p=(const char *) kernel_cache; } kernel=NULL; while (GetNextToken(p,(const char **) NULL,MagickPathExtent,token), *token != '\0') { /* ignore extra or multiple ';' kernel separators */ if (*token != ';') { /* tokens starting with alpha is a Named kernel */ if (isalpha((int) ((unsigned char) *token)) != 0) new_kernel=ParseKernelName(p,exception); else /* otherwise a user defined kernel array */ new_kernel=ParseKernelArray(p); /* Error handling -- this is not proper error handling! */ if (new_kernel == (KernelInfo *) NULL) { if (kernel != (KernelInfo *) NULL) kernel=DestroyKernelInfo(kernel); return((KernelInfo *) NULL); } /* initialise or append the kernel list */ if (kernel == (KernelInfo *) NULL) kernel=new_kernel; else LastKernelInfo(kernel)->next=new_kernel; } /* look for the next kernel in list */ p=strchr(p,';'); if (p == (char *) NULL) break; p++; } if (kernel_cache != (char *) NULL) kernel_cache=DestroyString(kernel_cache); return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l B u i l t I n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelBuiltIn() returned one of the 'named' built-in types of % kernels used for special purposes such as gaussian blurring, skeleton % pruning, and edge distance determination. % % They take a KernelType, and a set of geometry style arguments, which were % typically decoded from a user supplied string, or from a more complex % Morphology Method that was requested. % % The format of the AcquireKernalBuiltIn method is: % % KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, % const GeometryInfo args) % % A description of each parameter follows: % % o type: the pre-defined type of kernel wanted % % o args: arguments defining or modifying the kernel % % Convolution Kernels % % Unity % The a No-Op or Scaling single element kernel. % % Gaussian:{radius},{sigma} % Generate a two-dimensional gaussian kernel, as used by -gaussian. % The sigma for the curve is required. The resulting kernel is % normalized, % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % NOTE: that the 'radius' is optional, but if provided can limit (clip) % the final size of the resulting kernel to a square 2*radius+1 in size. % The radius should be at least 2 times that of the sigma value, or % sever clipping and aliasing may result. If not given or set to 0 the % radius will be determined so as to produce the best minimal error % result, which is usally much larger than is normally needed. % % LoG:{radius},{sigma} % "Laplacian of a Gaussian" or "Mexician Hat" Kernel. % The supposed ideal edge detection, zero-summing kernel. % % An alturnative to this kernel is to use a "DoG" with a sigma ratio of % approx 1.6 (according to wikipedia). % % DoG:{radius},{sigma1},{sigma2} % "Difference of Gaussians" Kernel. % As "Gaussian" but with a gaussian produced by 'sigma2' subtracted % from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1. % The result is a zero-summing kernel. % % Blur:{radius},{sigma}[,{angle}] % Generates a 1 dimensional or linear gaussian blur, at the angle given % (current restricted to orthogonal angles). If a 'radius' is given the % kernel is clipped to a width of 2*radius+1. Kernel can be rotated % by a 90 degree angle. % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % Note that two convolutions with two "Blur" kernels perpendicular to % each other, is equivalent to a far larger "Gaussian" kernel with the % same sigma value, However it is much faster to apply. This is how the % "-blur" operator actually works. % % Comet:{width},{sigma},{angle} % Blur in one direction only, much like how a bright object leaves % a comet like trail. The Kernel is actually half a gaussian curve, % Adding two such blurs in opposite directions produces a Blur Kernel. % Angle can be rotated in multiples of 90 degrees. % % Note that the first argument is the width of the kernel and not the % radius of the kernel. % % Binomial:[{radius}] % Generate a discrete kernel using a 2 dimentional Pascel's Triangle % of values. Used for special forma of image filters. % % # Still to be implemented... % # % # Filter2D % # Filter1D % # Set kernel values using a resize filter, and given scale (sigma) % # Cylindrical or Linear. Is this possible with an image? % # % % Named Constant Convolution Kernels % % All these are unscaled, zero-summing kernels by default. As such for % non-HDRI version of ImageMagick some form of normalization, user scaling, % and biasing the results is recommended, to prevent the resulting image % being 'clipped'. % % The 3x3 kernels (most of these) can be circularly rotated in multiples of % 45 degrees to generate the 8 angled varients of each of the kernels. % % Laplacian:{type} % Discrete Lapacian Kernels, (without normalization) % Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood) % Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood) % Type 2 : 3x3 with center:4 edge:1 corner:-2 % Type 3 : 3x3 with center:4 edge:-2 corner:1 % Type 5 : 5x5 laplacian % Type 7 : 7x7 laplacian % Type 15 : 5x5 LoG (sigma approx 1.4) % Type 19 : 9x9 LoG (sigma approx 1.4) % % Sobel:{angle} % Sobel 'Edge' convolution kernel (3x3) % | -1, 0, 1 | % | -2, 0,-2 | % | -1, 0, 1 | % % Roberts:{angle} % Roberts convolution kernel (3x3) % | 0, 0, 0 | % | -1, 1, 0 | % | 0, 0, 0 | % % Prewitt:{angle} % Prewitt Edge convolution kernel (3x3) % | -1, 0, 1 | % | -1, 0, 1 | % | -1, 0, 1 | % % Compass:{angle} % Prewitt's "Compass" convolution kernel (3x3) % | -1, 1, 1 | % | -1,-2, 1 | % | -1, 1, 1 | % % Kirsch:{angle} % Kirsch's "Compass" convolution kernel (3x3) % | -3,-3, 5 | % | -3, 0, 5 | % | -3,-3, 5 | % % FreiChen:{angle} % Frei-Chen Edge Detector is based on a kernel that is similar to % the Sobel Kernel, but is designed to be isotropic. That is it takes % into account the distance of the diagonal in the kernel. % % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | % | 1, 0, -1 | % % FreiChen:{type},{angle} % % Frei-Chen Pre-weighted kernels... % % Type 0: default un-nomalized version shown above. % % Type 1: Orthogonal Kernel (same as type 11 below) % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 2: Diagonal form of Kernel... % | 1, sqrt(2), 0 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 0, -sqrt(2) -1 | % % However this kernel is als at the heart of the FreiChen Edge Detection % Process which uses a set of 9 specially weighted kernel. These 9 % kernels not be normalized, but directly applied to the image. The % results is then added together, to produce the intensity of an edge in % a specific direction. The square root of the pixel value can then be % taken as the cosine of the edge, and at least 2 such runs at 90 degrees % from each other, both the direction and the strength of the edge can be % determined. % % Type 10: All 9 of the following pre-weighted kernels... % % Type 11: | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 12: | 1, sqrt(2), 1 | % | 0, 0, 0 | / 2*sqrt(2) % | 1, sqrt(2), 1 | % % Type 13: | sqrt(2), -1, 0 | % | -1, 0, 1 | / 2*sqrt(2) % | 0, 1, -sqrt(2) | % % Type 14: | 0, 1, -sqrt(2) | % | -1, 0, 1 | / 2*sqrt(2) % | sqrt(2), -1, 0 | % % Type 15: | 0, -1, 0 | % | 1, 0, 1 | / 2 % | 0, -1, 0 | % % Type 16: | 1, 0, -1 | % | 0, 0, 0 | / 2 % | -1, 0, 1 | % % Type 17: | 1, -2, 1 | % | -2, 4, -2 | / 6 % | -1, -2, 1 | % % Type 18: | -2, 1, -2 | % | 1, 4, 1 | / 6 % | -2, 1, -2 | % % Type 19: | 1, 1, 1 | % | 1, 1, 1 | / 3 % | 1, 1, 1 | % % The first 4 are for edge detection, the next 4 are for line detection % and the last is to add a average component to the results. % % Using a special type of '-1' will return all 9 pre-weighted kernels % as a multi-kernel list, so that you can use them directly (without % normalization) with the special "-set option:morphology:compose Plus" % setting to apply the full FreiChen Edge Detection Technique. % % If 'type' is large it will be taken to be an actual rotation angle for % the default FreiChen (type 0) kernel. As such FreiChen:45 will look % like a Sobel:45 but with 'sqrt(2)' instead of '2' values. % % WARNING: The above was layed out as per % http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf % But rotated 90 degrees so direction is from left rather than the top. % I have yet to find any secondary confirmation of the above. The only % other source found was actual source code at % http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf % Neigher paper defineds the kernels in a way that looks locical or % correct when taken as a whole. % % Boolean Kernels % % Diamond:[{radius}[,{scale}]] % Generate a diamond shaped kernel with given radius to the points. % Kernel size will again be radius*2+1 square and defaults to radius 1, % generating a 3x3 kernel that is slightly larger than a square. % % Square:[{radius}[,{scale}]] % Generate a square shaped kernel of size radius*2+1, and defaulting % to a 3x3 (radius 1). % % Octagon:[{radius}[,{scale}]] % Generate octagonal shaped kernel of given radius and constant scale. % Default radius is 3 producing a 7x7 kernel. A radius of 1 will result % in "Diamond" kernel. % % Disk:[{radius}[,{scale}]] % Generate a binary disk, thresholded at the radius given, the radius % may be a float-point value. Final Kernel size is floor(radius)*2+1 % square. A radius of 5.3 is the default. % % NOTE: That a low radii Disk kernels produce the same results as % many of the previously defined kernels, but differ greatly at larger % radii. Here is a table of equivalences... % "Disk:1" => "Diamond", "Octagon:1", or "Cross:1" % "Disk:1.5" => "Square" % "Disk:2" => "Diamond:2" % "Disk:2.5" => "Octagon" % "Disk:2.9" => "Square:2" % "Disk:3.5" => "Octagon:3" % "Disk:4.5" => "Octagon:4" % "Disk:5.4" => "Octagon:5" % "Disk:6.4" => "Octagon:6" % All other Disk shapes are unique to this kernel, but because a "Disk" % is more circular when using a larger radius, using a larger radius is % preferred over iterating the morphological operation. % % Rectangle:{geometry} % Simply generate a rectangle of 1's with the size given. You can also % specify the location of the 'control point', otherwise the closest % pixel to the center of the rectangle is selected. % % Properly centered and odd sized rectangles work the best. % % Symbol Dilation Kernels % % These kernel is not a good general morphological kernel, but is used % more for highlighting and marking any single pixels in an image using, % a "Dilate" method as appropriate. % % For the same reasons iterating these kernels does not produce the % same result as using a larger radius for the symbol. % % Plus:[{radius}[,{scale}]] % Cross:[{radius}[,{scale}]] % Generate a kernel in the shape of a 'plus' or a 'cross' with % a each arm the length of the given radius (default 2). % % NOTE: "plus:1" is equivalent to a "Diamond" kernel. % % Ring:{radius1},{radius2}[,{scale}] % A ring of the values given that falls between the two radii. % Defaults to a ring of approximataly 3 radius in a 7x7 kernel. % This is the 'edge' pixels of the default "Disk" kernel, % More specifically, "Ring" -> "Ring:2.5,3.5,1.0" % % Hit and Miss Kernels % % Peak:radius1,radius2 % Find any peak larger than the pixels the fall between the two radii. % The default ring of pixels is as per "Ring". % Edges % Find flat orthogonal edges of a binary shape % Corners % Find 90 degree corners of a binary shape % Diagonals:type % A special kernel to thin the 'outside' of diagonals % LineEnds:type % Find end points of lines (for pruning a skeletion) % Two types of lines ends (default to both) can be searched for % Type 0: All line ends % Type 1: single kernel for 4-conneected line ends % Type 2: single kernel for simple line ends % LineJunctions % Find three line junctions (within a skeletion) % Type 0: all line junctions % Type 1: Y Junction kernel % Type 2: Diagonal T Junction kernel % Type 3: Orthogonal T Junction kernel % Type 4: Diagonal X Junction kernel % Type 5: Orthogonal + Junction kernel % Ridges:type % Find single pixel ridges or thin lines % Type 1: Fine single pixel thick lines and ridges % Type 2: Find two pixel thick lines and ridges % ConvexHull % Octagonal Thickening Kernel, to generate convex hulls of 45 degrees % Skeleton:type % Traditional skeleton generating kernels. % Type 1: Tradional Skeleton kernel (4 connected skeleton) % Type 2: HIPR2 Skeleton kernel (8 connected skeleton) % Type 3: Thinning skeleton based on a ressearch paper by % Dan S. Bloomberg (Default Type) % ThinSE:type % A huge variety of Thinning Kernels designed to preserve conectivity. % many other kernel sets use these kernels as source definitions. % Type numbers are 41-49, 81-89, 481, and 482 which are based on % the super and sub notations used in the source research paper. % % Distance Measuring Kernels % % Different types of distance measuring methods, which are used with the % a 'Distance' morphology method for generating a gradient based on % distance from an edge of a binary shape, though there is a technique % for handling a anti-aliased shape. % % See the 'Distance' Morphological Method, for information of how it is % applied. % % Chebyshev:[{radius}][x{scale}[%!]] % Chebyshev Distance (also known as Tchebychev or Chessboard distance) % is a value of one to any neighbour, orthogonal or diagonal. One why % of thinking of it is the number of squares a 'King' or 'Queen' in % chess needs to traverse reach any other position on a chess board. % It results in a 'square' like distance function, but one where % diagonals are given a value that is closer than expected. % % Manhattan:[{radius}][x{scale}[%!]] % Manhattan Distance (also known as Rectilinear, City Block, or the Taxi % Cab distance metric), it is the distance needed when you can only % travel in horizontal or vertical directions only. It is the % distance a 'Rook' in chess would have to travel, and results in a % diamond like distances, where diagonals are further than expected. % % Octagonal:[{radius}][x{scale}[%!]] % An interleving of Manhatten and Chebyshev metrics producing an % increasing octagonally shaped distance. Distances matches those of % the "Octagon" shaped kernel of the same radius. The minimum radius % and default is 2, producing a 5x5 kernel. % % Euclidean:[{radius}][x{scale}[%!]] % Euclidean distance is the 'direct' or 'as the crow flys' distance. % However by default the kernel size only has a radius of 1, which % limits the distance to 'Knight' like moves, with only orthogonal and % diagonal measurements being correct. As such for the default kernel % you will get octagonal like distance function. % % However using a larger radius such as "Euclidean:4" you will get a % much smoother distance gradient from the edge of the shape. Especially % if the image is pre-processed to include any anti-aliasing pixels. % Of course a larger kernel is slower to use, and not always needed. % % The first three Distance Measuring Kernels will only generate distances % of exact multiples of {scale} in binary images. As such you can use a % scale of 1 without loosing any information. However you also need some % scaling when handling non-binary anti-aliased shapes. % % The "Euclidean" Distance Kernel however does generate a non-integer % fractional results, and as such scaling is vital even for binary shapes. % */ MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, const GeometryInfo *args,ExceptionInfo *exception) { KernelInfo *kernel; register ssize_t i; register ssize_t u, v; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ /* Generate a new empty kernel if needed */ kernel=(KernelInfo *) NULL; switch(type) { case UndefinedKernel: /* These should not call this function */ case UserDefinedKernel: assert("Should not call this function" != (char *) NULL); break; case LaplacianKernel: /* Named Descrete Convolution Kernels */ case SobelKernel: /* these are defined using other kernels */ case RobertsKernel: case PrewittKernel: case CompassKernel: case KirschKernel: case FreiChenKernel: case EdgesKernel: /* Hit and Miss kernels */ case CornersKernel: case DiagonalsKernel: case LineEndsKernel: case LineJunctionsKernel: case RidgesKernel: case ConvexHullKernel: case SkeletonKernel: case ThinSEKernel: break; /* A pre-generated kernel is not needed */ #if 0 /* set to 1 to do a compile-time check that we haven't missed anything */ case UnityKernel: case GaussianKernel: case DoGKernel: case LoGKernel: case BlurKernel: case CometKernel: case BinomialKernel: case DiamondKernel: case SquareKernel: case RectangleKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: case RingKernel: case PeaksKernel: case ChebyshevKernel: case ManhattanKernel: case OctangonalKernel: case EuclideanKernel: #else default: #endif /* Generate the base Kernel Structure */ kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *) NULL) return(kernel); (void) memset(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = type; kernel->next = (KernelInfo *) NULL; kernel->signature=MagickCoreSignature; break; } switch(type) { /* Convolution Kernels */ case UnityKernel: { kernel->height = kernel->width = (size_t) 1; kernel->x = kernel->y = (ssize_t) 0; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(1,sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); kernel->maximum = kernel->values[0] = args->rho; break; } break; case GaussianKernel: case DoGKernel: case LoGKernel: { double sigma = fabs(args->sigma), sigma2 = fabs(args->xi), A, B, R; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else if ( (type != DoGKernel) || (sigma >= sigma2) ) kernel->width = GetOptimalKernelWidth2D(args->rho,sigma); else kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2); kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* WARNING: The following generates a 'sampled gaussian' kernel. * What we really want is a 'discrete gaussian' kernel. * * How to do this is I don't know, but appears to be basied on the * Error Function 'erf()' (intergral of a gaussian) */ if ( type == GaussianKernel || type == DoGKernel ) { /* Calculate a Gaussian, OR positive half of a DoG */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } if ( type == DoGKernel ) { /* Subtract a Negative Gaussian for "Difference of Gaussian" */ if ( sigma2 > MagickEpsilon ) { sigma = sigma2; /* simplify loop expressions */ A = 1.0/(2.0*sigma*sigma); B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0; } if ( type == LoGKernel ) { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { R = ((double)(u*u+v*v))*A; kernel->values[i] = (1-R)*exp(-R)*B; } } else /* special case - generate a unity kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } /* Note the above kernels may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, and thus ** producing a very bright kernel. ** ** Normalization will still be needed. */ /* Normalize the 2D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); break; } case BlurKernel: { double sigma = fabs(args->sigma), alpha, beta; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else kernel->width = GetOptimalKernelWidth1D(args->rho,sigma); kernel->height = 1; kernel->x = (ssize_t) (kernel->width-1)/2; kernel->y = 0; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); #if 1 #define KernelRank 3 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix). ** It generates a gaussian 3 times the width, and compresses it into ** the expected range. This produces a closer normalization of the ** resulting kernel, especially for very low sigma values. ** As such while wierd it is prefered. ** ** I am told this method originally came from Photoshop. ** ** A properly normalized curve is generated (apart from edge clipping) ** even though we later normalize the result (for edge clipping) ** to allow the correct generation of a "Difference of Blurs". */ /* initialize */ v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */ (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); /* Calculate a Positive 1D Gaussian */ if ( sigma > MagickEpsilon ) { sigma *= KernelRank; /* simplify loop expressions */ alpha = 1.0/(2.0*sigma*sigma); beta= (double) (1.0/(MagickSQ2PI*sigma )); for ( u=-v; u <= v; u++) { kernel->values[(u+v)/KernelRank] += exp(-((double)(u*u))*alpha)*beta; } } else /* special case - generate a unity kernel */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; #else /* Direct calculation without curve averaging This is equivelent to a KernelRank of 1 */ /* Calculate a Positive Gaussian */ if ( sigma > MagickEpsilon ) { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ beta = 1.0/(MagickSQ2PI*sigma); for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u))*alpha)*beta; } else /* special case - generate a unity kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } #endif /* Note the above kernel may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, as a ** result of not generating a actual 'discrete' kernel, and thus ** producing a very bright 'impulse'. ** ** Becuase of these two factors Normalization is required! */ /* Normalize the 1D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); /* rotate the 1D kernel by given angle */ RotateKernelInfo(kernel, args->xi ); break; } case CometKernel: { double sigma = fabs(args->sigma), A; if ( args->rho < 1.0 ) kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1; else kernel->width = (size_t)args->rho; kernel->x = kernel->y = 0; kernel->height = 1; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* A comet blur is half a 1D gaussian curve, so that the object is ** blurred in one direction only. This may not be quite the right ** curve to use so may change in the future. The function must be ** normalised after generation, which also resolves any clipping. ** ** As we are normalizing and not subtracting gaussians, ** there is no need for a divisor in the gaussian formula ** ** It is less comples */ if ( sigma > MagickEpsilon ) { #if 1 #define KernelRank 3 v = (ssize_t) kernel->width*KernelRank; /* start/end points */ (void) memset(kernel->values,0, (size_t) kernel->width*sizeof(*kernel->values)); sigma *= KernelRank; /* simplify the loop expression */ A = 1.0/(2.0*sigma*sigma); /* B = 1.0/(MagickSQ2PI*sigma); */ for ( u=0; u < v; u++) { kernel->values[u/KernelRank] += exp(-((double)(u*u))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ } for (i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i]; #else A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */ /* B = 1.0/(MagickSQ2PI*sigma); */ for ( i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i] = exp(-((double)(i*i))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ #endif } else /* special case - generate a unity kernel */ { (void) memset(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; } kernel->minimum = 0.0; kernel->maximum = kernel->values[0]; kernel->negative_range = 0.0; ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */ RotateKernelInfo(kernel, args->xi); /* Rotate by angle */ break; } case BinomialKernel: { size_t order_f; if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; order_f = fact(kernel->width-1); kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=0; v < (ssize_t)kernel->height; v++) { size_t alpha = order_f / ( fact((size_t) v) * fact(kernel->height-v-1) ); for ( u=0; u < (ssize_t)kernel->width; u++, i++) kernel->positive_range += kernel->values[i] = (double) (alpha * order_f / ( fact((size_t) u) * fact(kernel->height-u-1) )); } kernel->minimum = 1.0; kernel->maximum = kernel->values[kernel->x+kernel->y*kernel->width]; kernel->negative_range = 0.0; break; } /* Convolution Kernels - Well Known Named Constant Kernels */ case LaplacianKernel: { switch ( (int) args->rho ) { case 0: default: /* laplacian square filter -- default */ kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1"); break; case 1: /* laplacian diamond filter */ kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0"); break; case 2: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); break; case 3: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1"); break; case 5: /* a 5x5 laplacian */ kernel=ParseKernelArray( "5: -4,-1,0,-1,-4 -1,2,3,2,-1 0,3,4,3,0 -1,2,3,2,-1 -4,-1,0,-1,-4"); break; case 7: /* a 7x7 laplacian */ kernel=ParseKernelArray( "7:-10,-5,-2,-1,-2,-5,-10 -5,0,3,4,3,0,-5 -2,3,6,7,6,3,-2 -1,4,7,8,7,4,-1 -2,3,6,7,6,3,-2 -5,0,3,4,3,0,-5 -10,-5,-2,-1,-2,-5,-10" ); break; case 15: /* a 5x5 LoG (sigma approx 1.4) */ kernel=ParseKernelArray( "5: 0,0,-1,0,0 0,-1,-2,-1,0 -1,-2,16,-2,-1 0,-1,-2,-1,0 0,0,-1,0,0"); break; case 19: /* a 9x9 LoG (sigma approx 1.4) */ /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */ kernel=ParseKernelArray( "9: 0,-1,-1,-2,-2,-2,-1,-1,0 -1,-2,-4,-5,-5,-5,-4,-2,-1 -1,-4,-5,-3,-0,-3,-5,-4,-1 -2,-5,-3,12,24,12,-3,-5,-2 -2,-5,-0,24,40,24,-0,-5,-2 -2,-5,-3,12,24,12,-3,-5,-2 -1,-4,-5,-3,-0,-3,-5,-4,-1 -1,-2,-4,-5,-5,-5,-4,-2,-1 0,-1,-1,-2,-2,-2,-1,-1,0"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; break; } case SobelKernel: { /* Simple Sobel Kernel */ kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case RobertsKernel: { kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case PrewittKernel: { kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case CompassKernel: { kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case KirschKernel: { kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case FreiChenKernel: /* Direction is set to be left to right positive */ /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */ /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */ { switch ( (int) args->rho ) { default: case 0: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +(MagickRealType) MagickSQ2; kernel->values[5] = -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ break; case 2: kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = kernel->values[3]= +(MagickRealType) MagickSQ2; kernel->values[5] = kernel->values[7]= -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 10: { kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19",exception); if (kernel == (KernelInfo *) NULL) return(kernel); break; } case 1: case 11: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +(MagickRealType) MagickSQ2; kernel->values[5] = -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 12: kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = +(MagickRealType) MagickSQ2; kernel->values[7] = +(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 13: kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[0] = +(MagickRealType) MagickSQ2; kernel->values[8] = -(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 14: kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[2] = -(MagickRealType) MagickSQ2; kernel->values[6] = +(MagickRealType) MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 15: kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 16: kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 17: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 18: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 19: kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/3.0, NoValue); break; } if ( fabs(args->sigma) >= MagickEpsilon ) /* Rotate by correctly supplied 'angle' */ RotateKernelInfo(kernel, args->sigma); else if ( args->rho > 30.0 || args->rho < -30.0 ) /* Rotate by out of bounds 'type' */ RotateKernelInfo(kernel, args->rho); break; } /* Boolean or Shaped Kernels */ case DiamondKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case SquareKernel: case RectangleKernel: { double scale; if ( type == SquareKernel ) { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = (size_t) (2*args->rho+1); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; scale = args->sigma; } else { /* NOTE: user defaults set in "AcquireKernelInfo()" */ if ( args->rho < 1.0 || args->sigma < 1.0 ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->width = (size_t)args->rho; kernel->height = (size_t)args->sigma; if ( args->xi < 0.0 || args->xi > (double)kernel->width || args->psi < 0.0 || args->psi > (double)kernel->height ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->x = (ssize_t) args->xi; kernel->y = (ssize_t) args->psi; scale = 1.0; } kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values to scale given */ u=(ssize_t) (kernel->width*kernel->height); for ( i=0; i < u; i++) kernel->values[i] = scale; kernel->minimum = kernel->maximum = scale; /* a flat shape */ kernel->positive_range = scale*u; break; } case OctagonKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= ((long)kernel->x + (long)(kernel->x/2)) ) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case DiskKernel: { ssize_t limit = (ssize_t)(args->rho*args->rho); if (args->rho < 0.4) /* default radius approx 4.3 */ kernel->width = kernel->height = 9L, limit = 18L; else kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ((u*u+v*v) <= limit) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case PlusKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } case CrossKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == v || u == -v) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } /* HitAndMiss Kernels */ case RingKernel: case PeaksKernel: { ssize_t limit1, limit2, scale; if (args->rho < args->sigma) { kernel->width = ((size_t)args->sigma)*2+1; limit1 = (ssize_t)(args->rho*args->rho); limit2 = (ssize_t)(args->sigma*args->sigma); } else { kernel->width = ((size_t)args->rho)*2+1; limit1 = (ssize_t)(args->sigma*args->sigma); limit2 = (ssize_t)(args->rho*args->rho); } if ( limit2 <= 0 ) kernel->width = 7L, limit1 = 7L, limit2 = 11L; kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */ scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi); for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { ssize_t radius=u*u+v*v; if (limit1 < radius && radius <= limit2) kernel->positive_range += kernel->values[i] = (double) scale; else kernel->values[i] = nan; } kernel->minimum = kernel->maximum = (double) scale; if ( type == PeaksKernel ) { /* set the central point in the middle */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; kernel->maximum = 1.0; } break; } case EdgesKernel: { kernel=AcquireKernelInfo("ThinSE:482",exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */ break; } case CornersKernel: { kernel=AcquireKernelInfo("ThinSE:87",exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */ break; } case DiagonalsKernel: { switch ( (int) args->rho ) { case 0: default: { KernelInfo *new_kernel; kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; ExpandMirrorKernelInfo(kernel); return(kernel); } case 1: kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); break; case 2: kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineEndsKernel: { /* Kernels for finding the end of thin lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all end of lines */ return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>",exception)); case 1: /* kernel for 4-connected line ends - no rotation */ kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-"); break; case 2: /* kernel to add for 8-connected lines - no rotation */ kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1"); break; case 3: /* kernel to add for orthogonal line ends - does not find corners */ kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0"); break; case 4: /* traditional line end - fails on last T end */ kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineJunctionsKernel: { /* kernels for finding the junctions of multiple lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all line junctions */ return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>",exception)); case 1: /* Y Junction */ kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-"); break; case 2: /* Diagonal T Junctions */ kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1"); break; case 3: /* Orthogonal T Junctions */ kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-"); break; case 4: /* Diagonal X Junctions */ kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1"); break; case 5: /* Orthogonal X Junctions - minimal diamond kernel */ kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case RidgesKernel: { /* Ridges - Ridge finding kernels */ KernelInfo *new_kernel; switch ( (int) args->rho ) { case 1: default: kernel=ParseKernelArray("3x1:0,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */ break; case 2: kernel=ParseKernelArray("4x1:0,1,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */ /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */ /* Unfortunatally we can not yet rotate a non-square kernel */ /* But then we can't flip a non-symetrical kernel either */ new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; break; } break; } case ConvexHullKernel: { KernelInfo *new_kernel; /* first set of 8 kernels */ kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* append the mirror versions too - no flip function yet */ new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; ExpandRotateKernelInfo(new_kernel, 90.0); LastKernelInfo(kernel)->next = new_kernel; break; } case SkeletonKernel: { switch ( (int) args->rho ) { case 1: default: /* Traditional Skeleton... ** A cyclically rotated single kernel */ kernel=AcquireKernelInfo("ThinSE:482",exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */ break; case 2: /* HIPR Variation of the cyclic skeleton ** Corners of the traditional method made more forgiving, ** but the retain the same cyclic order. */ kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;",exception); if (kernel == (KernelInfo *) NULL) return(kernel); if (kernel->next == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); kernel->type = type; kernel->next->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */ break; case 3: /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf */ kernel=AcquireKernelInfo("ThinSE:41; ThinSE:42; ThinSE:43", exception); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->next->type = type; kernel->next->next->type = type; ExpandMirrorKernelInfo(kernel); /* 12 kernels total */ break; } break; } case ThinSEKernel: { /* Special kernels for general thinning, while preserving connections ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf ** And ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html ** ** Note kernels do not specify the origin pixel, allowing them ** to be used for both thickening and thinning operations. */ switch ( (int) args->rho ) { /* SE for 4-connected thinning */ case 41: /* SE_4_1 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1"); break; case 42: /* SE_4_2 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-"); break; case 43: /* SE_4_3 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1"); break; case 44: /* SE_4_4 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-"); break; case 45: /* SE_4_5 */ kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-"); break; case 46: /* SE_4_6 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1"); break; case 47: /* SE_4_7 */ kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-"); break; case 48: /* SE_4_8 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1"); break; case 49: /* SE_4_9 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1"); break; /* SE for 8-connected thinning - negatives of the above */ case 81: /* SE_8_0 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-"); break; case 82: /* SE_8_2 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-"); break; case 83: /* SE_8_3 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-"); break; case 84: /* SE_8_4 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-"); break; case 85: /* SE_8_5 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-"); break; case 86: /* SE_8_6 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1"); break; case 87: /* SE_8_7 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-"); break; case 88: /* SE_8_8 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-"); break; case 89: /* SE_8_9 */ kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-"); break; /* Special combined SE kernels */ case 423: /* SE_4_2 , SE_4_3 Combined Kernel */ kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-"); break; case 823: /* SE_8_2 , SE_8_3 Combined Kernel */ kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-"); break; case 481: /* SE_48_1 - General Connected Corner Kernel */ kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-"); break; default: case 482: /* SE_48_2 - General Edge Kernel */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } /* Distance Measuring Kernels */ case ChebyshevKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*MagickMax(fabs((double)u),fabs((double)v)) ); kernel->maximum = kernel->values[0]; break; } case ManhattanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*(labs((long) u)+labs((long) v)) ); kernel->maximum = kernel->values[0]; break; } case OctagonalKernel: { if (args->rho < 2.0) kernel->width = kernel->height = 5; /* default/minimum radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { double r1 = MagickMax(fabs((double)u),fabs((double)v)), r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5); kernel->positive_range += kernel->values[i] = args->sigma*MagickMax(r1,r2); } kernel->maximum = kernel->values[0]; break; } case EuclideanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height* sizeof(*kernel->values))); if (kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*sqrt((double)(u*u+v*v)) ); kernel->maximum = kernel->values[0]; break; } default: { /* No-Op Kernel - Basically just a single pixel on its own */ kernel=ParseKernelArray("1:1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = UndefinedKernel; break; } break; } return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneKernelInfo() creates a new clone of the given Kernel List so that its % can be modified without effecting the original. The cloned kernel should % be destroyed using DestoryKernelInfo() when no longer needed. % % The format of the CloneKernelInfo method is: % % KernelInfo *CloneKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be cloned % */ MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel) { register ssize_t i; KernelInfo *new_kernel; assert(kernel != (KernelInfo *) NULL); new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (new_kernel == (KernelInfo *) NULL) return(new_kernel); *new_kernel=(*kernel); /* copy values in structure */ /* replace the values with a copy of the values */ new_kernel->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel->width,kernel->height*sizeof(*kernel->values))); if (new_kernel->values == (MagickRealType *) NULL) return(DestroyKernelInfo(new_kernel)); for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) new_kernel->values[i]=kernel->values[i]; /* Also clone the next kernel in the kernel list */ if ( kernel->next != (KernelInfo *) NULL ) { new_kernel->next = CloneKernelInfo(kernel->next); if ( new_kernel->next == (KernelInfo *) NULL ) return(DestroyKernelInfo(new_kernel)); } return(new_kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyKernelInfo() frees the memory used by a Convolution/Morphology % kernel. % % The format of the DestroyKernelInfo method is: % % KernelInfo *DestroyKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be destroyed % */ MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel) { assert(kernel != (KernelInfo *) NULL); if (kernel->next != (KernelInfo *) NULL) kernel->next=DestroyKernelInfo(kernel->next); kernel->values=(MagickRealType *) RelinquishAlignedMemory(kernel->values); kernel=(KernelInfo *) RelinquishMagickMemory(kernel); return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d M i r r o r K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a % sequence of 90-degree rotated kernels but providing a reflected 180 % rotatation, before the -/+ 90-degree rotations. % % This special rotation order produces a better, more symetrical thinning of % objects. % % The format of the ExpandMirrorKernelInfo method is: % % void ExpandMirrorKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ #if 0 static void FlopKernelInfo(KernelInfo *kernel) { /* Do a Flop by reversing each row. */ size_t y; register ssize_t x,r; register double *k,t; for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width) for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--) t=k[x], k[x]=k[r], k[r]=t; kernel->x = kernel->width - kernel->x - 1; angle = fmod(angle+180.0, 360.0); } #endif static void ExpandMirrorKernelInfo(KernelInfo *kernel) { KernelInfo *clone, *last; last = kernel; clone = CloneKernelInfo(last); if (clone == (KernelInfo *) NULL) return; RotateKernelInfo(clone, 180); /* flip */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); if (clone == (KernelInfo *) NULL) return; RotateKernelInfo(clone, 90); /* transpose */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); if (clone == (KernelInfo *) NULL) return; RotateKernelInfo(clone, 180); /* flop */ LastKernelInfo(last)->next = clone; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating % incrementally by the angle given, until the kernel repeats. % % WARNING: 45 degree rotations only works for 3x3 kernels. % While 90 degree roatations only works for linear and square kernels % % The format of the ExpandRotateKernelInfo method is: % % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ /* Internal Routine - Return true if two kernels are the same */ static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1, const KernelInfo *kernel2) { register size_t i; /* check size and origin location */ if ( kernel1->width != kernel2->width || kernel1->height != kernel2->height || kernel1->x != kernel2->x || kernel1->y != kernel2->y ) return MagickFalse; /* check actual kernel values */ for (i=0; i < (kernel1->width*kernel1->height); i++) { /* Test for Nan equivalence */ if ( IsNaN(kernel1->values[i]) && !IsNaN(kernel2->values[i]) ) return MagickFalse; if ( IsNaN(kernel2->values[i]) && !IsNaN(kernel1->values[i]) ) return MagickFalse; /* Test actual values are equivalent */ if ( fabs(kernel1->values[i] - kernel2->values[i]) >= MagickEpsilon ) return MagickFalse; } return MagickTrue; } static void ExpandRotateKernelInfo(KernelInfo *kernel,const double angle) { KernelInfo *clone_info, *last; clone_info=(KernelInfo *) NULL; last=kernel; DisableMSCWarning(4127) while (1) { RestoreMSCWarning clone_info=CloneKernelInfo(last); if (clone_info == (KernelInfo *) NULL) break; RotateKernelInfo(clone_info,angle); if (SameKernelInfo(kernel,clone_info) != MagickFalse) break; LastKernelInfo(last)->next=clone_info; last=clone_info; } if (clone_info != (KernelInfo *) NULL) clone_info=DestroyKernelInfo(clone_info); /* kernel repeated - junk */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a l c M e t a K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only, % using the kernel values. This should only ne used if it is not possible to % calculate that meta-data in some easier way. % % It is important that the meta-data is correct before ScaleKernelInfo() is % used to perform kernel normalization. % % The format of the CalcKernelMetaData method is: % % void CalcKernelMetaData(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % WARNING: Minimum and Maximum values are assumed to include zero, even if % zero is not part of the kernel (as in Gaussian Derived kernels). This % however is not true for flat-shaped morphological kernels. % % WARNING: Only the specific kernel pointed to is modified, not a list of % multiple kernels. % % This is an internal function and not expected to be useful outside this % module. This could change however. */ static void CalcKernelMetaData(KernelInfo *kernel) { register size_t i; kernel->minimum = kernel->maximum = 0.0; kernel->negative_range = kernel->positive_range = 0.0; for (i=0; i < (kernel->width*kernel->height); i++) { if ( fabs(kernel->values[i]) < MagickEpsilon ) kernel->values[i] = 0.0; ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y A p p l y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyApply() applies a morphological method, multiple times using % a list of multiple kernels. This is the method that should be called by % other 'operators' that internally use morphology operations as part of % their processing. % % It is basically equivalent to as MorphologyImage() (see below) but without % any user controls. This allows internel programs to use this method to % perform a specific task without possible interference by any API user % supplied settings. % % It is MorphologyImage() task to extract any such user controls, and % pass them to this function for processing. % % More specifically all given kernels should already be scaled, normalised, % and blended appropriatally before being parred to this routine. The % appropriate bias, and compose (typically 'UndefinedComposeOp') given. % % The format of the MorphologyApply method is: % % Image *MorphologyApply(const Image *image,MorphologyMethod method, % const ssize_t iterations,const KernelInfo *kernel, % const CompositeMethod compose,const double bias, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the source image % % o method: the morphology method to be applied. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o channel: the channel type. % % o kernel: An array of double representing the morphology kernel. % % o compose: How to handle or merge multi-kernel results. % If 'UndefinedCompositeOp' use default for the Morphology method. % If 'NoCompositeOp' force image to be re-iterated by each kernel. % Otherwise merge the results using the compose method given. % % o bias: Convolution Output Bias. % % o exception: return any errors or warnings in this structure. % */ static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image, const MorphologyMethod method,const KernelInfo *kernel,const double bias, ExceptionInfo *exception) { #define MorphologyTag "Morphology/Image" CacheView *image_view, *morphology_view; OffsetInfo offset; register ssize_t j, y; size_t *changes, changed, width; MagickBooleanType status; MagickOffsetType progress; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(morphology_image != (Image *) NULL); assert(morphology_image->signature == MagickCoreSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); morphology_view=AcquireAuthenticCacheView(morphology_image,exception); width=image->columns+kernel->width-1; offset.x=0; offset.y=0; switch (method) { case ConvolveMorphology: case DilateMorphology: case DilateIntensityMorphology: case IterativeDistanceMorphology: { /* Kernel needs to used with reflection about origin. */ offset.x=(ssize_t) kernel->width-kernel->x-1; offset.y=(ssize_t) kernel->height-kernel->y-1; break; } case ErodeMorphology: case ErodeIntensityMorphology: case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: { offset.x=kernel->x; offset.y=kernel->y; break; } default: { assert("Not a Primitive Morphology Method" != (char *) NULL); break; } } changed=0; changes=(size_t *) AcquireQuantumMemory(GetOpenMPMaximumThreads(), sizeof(*changes)); if (changes == (size_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++) changes[j]=0; if ((method == ConvolveMorphology) && (kernel->width == 1)) { register ssize_t x; /* Special handling (for speed) of vertical (blur) kernels. This performs its handling in columns rather than in rows. This is only done for convolve as it is the only method that generates very large 1-D vertical kernels (such as a 'BlurKernel') */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,morphology_image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t r; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,x,-offset.y,1,image->rows+ kernel->height-1,exception); q=GetCacheViewAuthenticPixels(morphology_view,x,0,1, morphology_image->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*offset.y; for (r=0; r < (ssize_t) image->rows; r++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait morphology_traits, traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels; register ssize_t v; size_t count; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); morphology_traits=GetPixelChannelTraits(morphology_image,channel); if ((traits == UndefinedPixelTrait) || (morphology_traits == UndefinedPixelTrait)) continue; if ((traits & CopyPixelTrait) != 0) { SetPixelChannel(morphology_image,channel,p[center+i],q); continue; } k=(&kernel->values[kernel->height-1]); pixels=p; pixel=bias; gamma=1.0; count=0; if (((image->alpha_trait & BlendPixelTrait) == 0) || ((morphology_traits & BlendPixelTrait) == 0)) for (v=0; v < (ssize_t) kernel->height; v++) { if (!IsNaN(*k)) { pixel+=(*k)*pixels[i]; count++; } k--; pixels+=GetPixelChannels(image); } else { gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { if (!IsNaN(*k)) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=alpha*(*k)*pixels[i]; gamma+=alpha*(*k); count++; } k--; pixels+=GetPixelChannels(image); } } if (fabs(pixel-p[center+i]) > MagickEpsilon) changes[id]++; gamma=PerceptibleReciprocal(gamma); if (count != 0) gamma*=(double) kernel->height/count; SetPixelChannel(morphology_image,channel,ClampToQuantum(gamma* pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(morphology_image); } if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MorphologyTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_image->type=image->type; morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++) changed+=changes[j]; changes=(size_t *) RelinquishMagickMemory(changes); return(status ? (ssize_t) changed : 0); } /* Normal handling of horizontal or rectangular kernels (row by row). */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,morphology_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-offset.x,y-offset.y,width, kernel->height,exception); q=GetCacheViewAuthenticPixels(morphology_view,0,y,morphology_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) (GetPixelChannels(image)*width*offset.y+ GetPixelChannels(image)*offset.x); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, intensity, maximum, minimum, pixel; PixelChannel channel; PixelTrait morphology_traits, traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels, *magick_restrict quantum_pixels; register ssize_t u; size_t count; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); morphology_traits=GetPixelChannelTraits(morphology_image,channel); if ((traits == UndefinedPixelTrait) || (morphology_traits == UndefinedPixelTrait)) continue; if ((traits & CopyPixelTrait) != 0) { SetPixelChannel(morphology_image,channel,p[center+i],q); continue; } pixels=p; quantum_pixels=(const Quantum *) NULL; maximum=0.0; minimum=(double) QuantumRange; switch (method) { case ConvolveMorphology: { pixel=bias; break; } case DilateMorphology: case ErodeIntensityMorphology: { pixel=0.0; break; } case HitAndMissMorphology: case ErodeMorphology: { pixel=QuantumRange; break; } default: { pixel=(double) p[center+i]; break; } } count=0; gamma=1.0; switch (method) { case ConvolveMorphology: { /* Weighted Average of pixels using reflected kernel For correct working of this operation for asymetrical kernels, the kernel needs to be applied in its reflected form. That is its values needs to be reversed. Correlation is actually the same as this but without reflecting the kernel, and thus 'lower-level' that Convolution. However as Convolution is the more common method used, and it does not really cost us much in terms of processing to use a reflected kernel, so it is Convolution that is implemented. Correlation will have its kernel reflected before calling this function to do a Convolve. For more details of Correlation vs Convolution see http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf */ k=(&kernel->values[kernel->width*kernel->height-1]); if (((image->alpha_trait & BlendPixelTrait) == 0) || ((morphology_traits & BlendPixelTrait) == 0)) { /* No alpha blending. */ for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { pixel+=(*k)*pixels[i]; count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } /* Alpha blending. */ gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=alpha*(*k)*pixels[i]; gamma+=alpha*(*k); count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case ErodeMorphology: { /* Minimum value within kernel neighbourhood. The kernel is not reflected for this operation. In normal Greyscale Morphology, the kernel value should be added to the real value, this is currently not done, due to the nature of the boolean kernels being used. */ k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k >= 0.5)) { if ((double) pixels[i] < pixel) pixel=(double) pixels[i]; } k++; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case DilateMorphology: { /* Maximum value within kernel neighbourhood. For correct working of this operation for asymetrical kernels, the kernel needs to be applied in its reflected form. That is its values needs to be reversed. In normal Greyscale Morphology, the kernel value should be added to the real value, this is currently not done, due to the nature of the boolean kernels being used. */ k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k > 0.5)) { if ((double) pixels[i] > pixel) pixel=(double) pixels[i]; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: { /* Minimum of foreground pixel minus maxumum of background pixels. The kernel is not reflected for this operation, and consists of both foreground and background pixel neighbourhoods, 0.0 for background, and 1.0 for foreground with either Nan or 0.5 values for don't care. This never produces a meaningless negative result. Such results cause Thinning/Thicken to not work correctly when used against a greyscale image. */ k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if (*k > 0.7) { if ((double) pixels[i] < pixel) pixel=(double) pixels[i]; } else if (*k < 0.3) { if ((double) pixels[i] > maximum) maximum=(double) pixels[i]; } count++; } k++; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } pixel-=maximum; if (pixel < 0.0) pixel=0.0; if (method == ThinningMorphology) pixel=(double) p[center+i]-pixel; else if (method == ThickenMorphology) pixel+=(double) p[center+i]+pixel; break; } case ErodeIntensityMorphology: { /* Select pixel with minimum intensity within kernel neighbourhood. The kernel is not reflected for this operation. */ k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k >= 0.5)) { intensity=(double) GetPixelIntensity(image,pixels); if (intensity < minimum) { quantum_pixels=pixels; pixel=(double) pixels[i]; minimum=intensity; } count++; } k++; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case DilateIntensityMorphology: { /* Select pixel with maximum intensity within kernel neighbourhood. The kernel is not reflected for this operation. */ k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k) && (*k >= 0.5)) { intensity=(double) GetPixelIntensity(image,pixels); if (intensity > maximum) { pixel=(double) pixels[i]; quantum_pixels=pixels; maximum=intensity; } count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case IterativeDistanceMorphology: { /* Compute th iterative distance from black edge of a white image shape. Essentially white values are decreased to the smallest 'distance from edge' it can find. It works by adding kernel values to the neighbourhood, and select the minimum value found. The kernel is rotated before use, so kernel distances match resulting distances, when a user provided asymmetric kernel is applied. This code is nearly identical to True GrayScale Morphology but not quite. GreyDilate Kernel values added, maximum value found Kernel is rotated before use. GrayErode: Kernel values subtracted and minimum value found No kernel rotation used. Note the Iterative Distance method is essentially a GrayErode, but with negative kernel values, and kernel rotation applied. */ k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); count++; } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } break; } case UndefinedMorphology: default: break; } if (fabs(pixel-p[center+i]) > MagickEpsilon) changes[id]++; if (quantum_pixels != (const Quantum *) NULL) { SetPixelChannel(morphology_image,channel,quantum_pixels[i],q); continue; } gamma=PerceptibleReciprocal(gamma); if (count != 0) gamma*=(double) kernel->height*kernel->width/count; SetPixelChannel(morphology_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(morphology_image); } if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MorphologyTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++) changed+=changes[j]; changes=(size_t *) RelinquishMagickMemory(changes); return(status ? (ssize_t) changed : -1); } /* This is almost identical to the MorphologyPrimative() function above, but applies the primitive directly to the actual image using two passes, once in each direction, with the results of the previous (and current) row being re-used. That is after each row is 'Sync'ed' into the image, the next row makes use of those values as part of the calculation of the next row. It repeats, but going in the oppisite (bottom-up) direction. Because of this 're-use of results' this function can not make use of multi- threaded, parellel processing. */ static ssize_t MorphologyPrimitiveDirect(Image *image, const MorphologyMethod method,const KernelInfo *kernel, ExceptionInfo *exception) { CacheView *morphology_view, *image_view; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; size_t width, changed; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=MagickTrue; changed=0; progress=0; switch(method) { case DistanceMorphology: case VoronoiMorphology: { /* Kernel reflected about origin. */ offset.x=(ssize_t) kernel->width-kernel->x-1; offset.y=(ssize_t) kernel->height-kernel->y-1; break; } default: { offset.x=kernel->x; offset.y=kernel->y; break; } } /* Two views into same image, do not thread. */ image_view=AcquireVirtualCacheView(image,exception); morphology_view=AcquireAuthenticCacheView(image,exception); width=image->columns+kernel->width-1; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Read virtual pixels, and authentic pixels, from the same image! We read using virtual to get virtual pixel handling, but write back into the same image. Only top half of kernel is processed as we do a single pass downward through the image iterating the distance function as we go. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-offset.x,y-offset.y,width,(size_t) offset.y+1,exception); q=GetCacheViewAuthenticPixels(morphology_view,0,y,image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; pixels=p; pixel=(double) QuantumRange; switch (method) { case DistanceMorphology: { k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v <= offset.y; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*(kernel->y+1)-1]); pixels=q-offset.x*GetPixelChannels(image); for (u=0; u < offset.x; u++) { if (!IsNaN(*k) && ((x+u-offset.x) >= 0)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } break; } case VoronoiMorphology: { k=(&kernel->values[kernel->width*kernel->height-1]); for (v=0; v < offset.y; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*(kernel->y+1)-1]); pixels=q-offset.x*GetPixelChannels(image); for (u=0; u < offset.x; u++) { if (!IsNaN(*k) && ((x+u-offset.x) >= 0)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } break; } default: break; } if (fabs(pixel-q[i]) > MagickEpsilon) changed++; q[i]=ClampToQuantum(pixel); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MorphologyTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); /* Do the reverse pass through the image. */ image_view=AcquireVirtualCacheView(image,exception); morphology_view=AcquireAuthenticCacheView(image,exception); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Read virtual pixels, and authentic pixels, from the same image. We read using virtual to get virtual pixel handling, but write back into the same image. Only the bottom half of the kernel is processed as we up the image. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-offset.x,y,width,(size_t) kernel->y+1,exception); q=GetCacheViewAuthenticPixels(morphology_view,0,y,image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } p+=(image->columns-1)*GetPixelChannels(image); q+=(image->columns-1)*GetPixelChannels(image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits; register const MagickRealType *magick_restrict k; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; pixels=p; pixel=(double) QuantumRange; switch (method) { case DistanceMorphology: { k=(&kernel->values[kernel->width*(kernel->y+1)-1]); for (v=offset.y; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*kernel->y+kernel->x-1]); pixels=q; for (u=offset.x+1; u < (ssize_t) kernel->width; u++) { pixels+=GetPixelChannels(image); if (!IsNaN(*k) && ((x+u-offset.x) < (ssize_t) image->columns)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; } break; } case VoronoiMorphology: { k=(&kernel->values[kernel->width*(kernel->y+1)-1]); for (v=offset.y; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++) { if (!IsNaN(*k)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; pixels+=GetPixelChannels(image); } pixels+=(image->columns-1)*GetPixelChannels(image); } k=(&kernel->values[kernel->width*(kernel->y+1)-1]); pixels=q; for (u=offset.x+1; u < (ssize_t) kernel->width; u++) { pixels+=GetPixelChannels(image); if (!IsNaN(*k) && ((x+u-offset.x) < (ssize_t) image->columns)) { if ((pixels[i]+(*k)) < pixel) pixel=(double) pixels[i]+(*k); } k--; } break; } default: break; } if (fabs(pixel-q[i]) > MagickEpsilon) changed++; q[i]=ClampToQuantum(pixel); } p-=GetPixelChannels(image); q-=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MorphologyTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } morphology_view=DestroyCacheView(morphology_view); image_view=DestroyCacheView(image_view); return(status ? (ssize_t) changed : -1); } /* Apply a Morphology by calling one of the above low level primitive application functions. This function handles any iteration loops, composition or re-iteration of results, and compound morphology methods that is based on multiple low-level (staged) morphology methods. Basically this provides the complex glue between the requested morphology method and raw low-level implementation (above). */ MagickPrivate Image *MorphologyApply(const Image *image, const MorphologyMethod method, const ssize_t iterations, const KernelInfo *kernel, const CompositeOperator compose,const double bias, ExceptionInfo *exception) { CompositeOperator curr_compose; Image *curr_image, /* Image we are working with or iterating */ *work_image, /* secondary image for primitive iteration */ *save_image, /* saved image - for 'edge' method only */ *rslt_image; /* resultant image - after multi-kernel handling */ KernelInfo *reflected_kernel, /* A reflected copy of the kernel (if needed) */ *norm_kernel, /* the current normal un-reflected kernel */ *rflt_kernel, /* the current reflected kernel (if needed) */ *this_kernel; /* the kernel being applied */ MorphologyMethod primitive; /* the current morphology primitive being applied */ CompositeOperator rslt_compose; /* multi-kernel compose method for results to use */ MagickBooleanType special, /* do we use a direct modify function? */ verbose; /* verbose output of results */ size_t method_loop, /* Loop 1: number of compound method iterations (norm 1) */ method_limit, /* maximum number of compound method iterations */ kernel_number, /* Loop 2: the kernel number being applied */ stage_loop, /* Loop 3: primitive loop for compound morphology */ stage_limit, /* how many primitives are in this compound */ kernel_loop, /* Loop 4: iterate the kernel over image */ kernel_limit, /* number of times to iterate kernel */ count, /* total count of primitive steps applied */ kernel_changed, /* total count of changed using iterated kernel */ method_changed; /* total count of changed over method iteration */ ssize_t changed; /* number pixels changed by last primitive operation */ char v_info[MagickPathExtent]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); count = 0; /* number of low-level morphology primitives performed */ if ( iterations == 0 ) return((Image *) NULL); /* null operation - nothing to do! */ kernel_limit = (size_t) iterations; if ( iterations < 0 ) /* negative interations = infinite (well alomst) */ kernel_limit = image->columns>image->rows ? image->columns : image->rows; verbose = IsStringTrue(GetImageArtifact(image,"debug")); /* initialise for cleanup */ curr_image = (Image *) image; curr_compose = image->compose; (void) curr_compose; work_image = save_image = rslt_image = (Image *) NULL; reflected_kernel = (KernelInfo *) NULL; /* Initialize specific methods * + which loop should use the given iteratations * + how many primitives make up the compound morphology * + multi-kernel compose method to use (by default) */ method_limit = 1; /* just do method once, unless otherwise set */ stage_limit = 1; /* assume method is not a compound */ special = MagickFalse; /* assume it is NOT a direct modify primitive */ rslt_compose = compose; /* and we are composing multi-kernels as given */ switch( method ) { case SmoothMorphology: /* 4 primitive compound morphology */ stage_limit = 4; break; case OpenMorphology: /* 2 primitive compound morphology */ case OpenIntensityMorphology: case TopHatMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case EdgeMorphology: stage_limit = 2; break; case HitAndMissMorphology: rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */ /* FALL THUR */ case ThinningMorphology: case ThickenMorphology: method_limit = kernel_limit; /* iterate the whole method */ kernel_limit = 1; /* do not do kernel iteration */ break; case DistanceMorphology: case VoronoiMorphology: special = MagickTrue; /* use special direct primative */ break; default: break; } /* Apply special methods with special requirments ** For example, single run only, or post-processing requirements */ if ( special != MagickFalse ) { rslt_image=CloneImage(image,0,0,MagickTrue,exception); if (rslt_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse) goto error_cleanup; changed=MorphologyPrimitiveDirect(rslt_image,method,kernel,exception); if (verbose != MagickFalse) (void) (void) FormatLocaleFile(thread_stderr, "%s:%.20g.%.20g #%.20g => Changed %.20g\n", CommandOptionToMnemonic(MagickMorphologyOptions, method), 1.0,0.0,1.0, (double) changed); if ( changed < 0 ) goto error_cleanup; if ( method == VoronoiMorphology ) { /* Preserve the alpha channel of input image - but turned it off */ (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel, exception); (void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp, MagickTrue,0,0,exception); (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel, exception); } goto exit_cleanup; } /* Handle user (caller) specified multi-kernel composition method */ if ( compose != UndefinedCompositeOp ) rslt_compose = compose; /* override default composition for method */ if ( rslt_compose == UndefinedCompositeOp ) rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */ /* Some methods require a reflected kernel to use with primitives. * Create the reflected kernel for those methods. */ switch ( method ) { case CorrelateMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case SmoothMorphology: reflected_kernel = CloneKernelInfo(kernel); if (reflected_kernel == (KernelInfo *) NULL) goto error_cleanup; RotateKernelInfo(reflected_kernel,180); break; default: break; } /* Loops around more primitive morpholgy methods ** erose, dilate, open, close, smooth, edge, etc... */ /* Loop 1: iterate the compound method */ method_loop = 0; method_changed = 1; while ( method_loop < method_limit && method_changed > 0 ) { method_loop++; method_changed = 0; /* Loop 2: iterate over each kernel in a multi-kernel list */ norm_kernel = (KernelInfo *) kernel; this_kernel = (KernelInfo *) kernel; rflt_kernel = reflected_kernel; kernel_number = 0; while ( norm_kernel != NULL ) { /* Loop 3: Compound Morphology Staging - Select Primative to apply */ stage_loop = 0; /* the compound morphology stage number */ while ( stage_loop < stage_limit ) { stage_loop++; /* The stage of the compound morphology */ /* Select primitive morphology for this stage of compound method */ this_kernel = norm_kernel; /* default use unreflected kernel */ primitive = method; /* Assume method is a primitive */ switch( method ) { case ErodeMorphology: /* just erode */ case EdgeInMorphology: /* erode and image difference */ primitive = ErodeMorphology; break; case DilateMorphology: /* just dilate */ case EdgeOutMorphology: /* dilate and image difference */ primitive = DilateMorphology; break; case OpenMorphology: /* erode then dialate */ case TopHatMorphology: /* open and image difference */ primitive = ErodeMorphology; if ( stage_loop == 2 ) primitive = DilateMorphology; break; case OpenIntensityMorphology: primitive = ErodeIntensityMorphology; if ( stage_loop == 2 ) primitive = DilateIntensityMorphology; break; case CloseMorphology: /* dilate, then erode */ case BottomHatMorphology: /* close and image difference */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; if ( stage_loop == 2 ) primitive = ErodeMorphology; break; case CloseIntensityMorphology: this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateIntensityMorphology; if ( stage_loop == 2 ) primitive = ErodeIntensityMorphology; break; case SmoothMorphology: /* open, close */ switch ( stage_loop ) { case 1: /* start an open method, which starts with Erode */ primitive = ErodeMorphology; break; case 2: /* now Dilate the Erode */ primitive = DilateMorphology; break; case 3: /* Reflect kernel a close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; break; case 4: /* Finish the Close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ErodeMorphology; break; } break; case EdgeMorphology: /* dilate and erode difference */ primitive = DilateMorphology; if ( stage_loop == 2 ) { save_image = curr_image; /* save the image difference */ curr_image = (Image *) image; primitive = ErodeMorphology; } break; case CorrelateMorphology: /* A Correlation is a Convolution with a reflected kernel. ** However a Convolution is a weighted sum using a reflected ** kernel. It may seem stange to convert a Correlation into a ** Convolution as the Correlation is the simplier method, but ** Convolution is much more commonly used, and it makes sense to ** implement it directly so as to avoid the need to duplicate the ** kernel when it is not required (which is typically the ** default). */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ConvolveMorphology; break; default: break; } assert( this_kernel != (KernelInfo *) NULL ); /* Extra information for debugging compound operations */ if (verbose != MagickFalse) { if ( stage_limit > 1 ) (void) FormatLocaleString(v_info,MagickPathExtent,"%s:%.20g.%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions,method),(double) method_loop,(double) stage_loop); else if ( primitive != method ) (void) FormatLocaleString(v_info, MagickPathExtent, "%s:%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions, method),(double) method_loop); else v_info[0] = '\0'; } /* Loop 4: Iterate the kernel with primitive */ kernel_loop = 0; kernel_changed = 0; changed = 1; while ( kernel_loop < kernel_limit && changed > 0 ) { kernel_loop++; /* the iteration of this kernel */ /* Create a clone as the destination image, if not yet defined */ if ( work_image == (Image *) NULL ) { work_image=CloneImage(image,0,0,MagickTrue,exception); if (work_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse) goto error_cleanup; } /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */ count++; changed = MorphologyPrimitive(curr_image, work_image, primitive, this_kernel, bias, exception); if (verbose != MagickFalse) { if ( kernel_loop > 1 ) (void) FormatLocaleFile(thread_stderr, "\n"); /* add end-of-line from previous */ (void) (void) FormatLocaleFile(thread_stderr, "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g", v_info,CommandOptionToMnemonic(MagickMorphologyOptions, primitive),(this_kernel == rflt_kernel ) ? "*" : "", (double) (method_loop+kernel_loop-1),(double) kernel_number, (double) count,(double) changed); } if ( changed < 0 ) goto error_cleanup; kernel_changed += changed; method_changed += changed; /* prepare next loop */ { Image *tmp = work_image; /* swap images for iteration */ work_image = curr_image; curr_image = tmp; } if ( work_image == image ) work_image = (Image *) NULL; /* replace input 'image' */ } /* End Loop 4: Iterate the kernel with primitive */ if (verbose != MagickFalse && kernel_changed != (size_t)changed) (void) FormatLocaleFile(thread_stderr, " Total %.20g",(double) kernel_changed); if (verbose != MagickFalse && stage_loop < stage_limit) (void) FormatLocaleFile(thread_stderr, "\n"); /* add end-of-line before looping */ #if 0 (void) FormatLocaleFile(thread_stderr, "--E-- image=0x%lx\n", (unsigned long)image); (void) FormatLocaleFile(thread_stderr, " curr =0x%lx\n", (unsigned long)curr_image); (void) FormatLocaleFile(thread_stderr, " work =0x%lx\n", (unsigned long)work_image); (void) FormatLocaleFile(thread_stderr, " save =0x%lx\n", (unsigned long)save_image); (void) FormatLocaleFile(thread_stderr, " union=0x%lx\n", (unsigned long)rslt_image); #endif } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */ /* Final Post-processing for some Compound Methods ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** Turn off SVG composition 'alpha blending'. */ switch( method ) { case EdgeOutMorphology: case EdgeInMorphology: case TopHatMorphology: case BottomHatMorphology: if (verbose != MagickFalse) (void) FormatLocaleFile(thread_stderr, "\n%s: Difference with original image",CommandOptionToMnemonic( MagickMorphologyOptions, method) ); (void) CompositeImage(curr_image,image,DifferenceCompositeOp, MagickTrue,0,0,exception); break; case EdgeMorphology: if (verbose != MagickFalse) (void) FormatLocaleFile(thread_stderr, "\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic( MagickMorphologyOptions, method) ); (void) CompositeImage(curr_image,save_image,DifferenceCompositeOp, MagickTrue,0,0,exception); save_image = DestroyImage(save_image); /* finished with save image */ break; default: break; } /* multi-kernel handling: re-iterate, or compose results */ if ( kernel->next == (KernelInfo *) NULL ) rslt_image = curr_image; /* just return the resulting image */ else if ( rslt_compose == NoCompositeOp ) { if (verbose != MagickFalse) { if ( this_kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(thread_stderr, " (re-iterate)"); else (void) FormatLocaleFile(thread_stderr, " (done)"); } rslt_image = curr_image; /* return result, and re-iterate */ } else if ( rslt_image == (Image *) NULL) { if (verbose != MagickFalse) (void) FormatLocaleFile(thread_stderr, " (save for compose)"); rslt_image = curr_image; curr_image = (Image *) image; /* continue with original image */ } else { /* Add the new 'current' result to the composition ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** IE: Turn off SVG composition 'alpha blending'. */ if (verbose != MagickFalse) (void) FormatLocaleFile(thread_stderr, " (compose \"%s\")", CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) ); (void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue, 0,0,exception); curr_image = DestroyImage(curr_image); curr_image = (Image *) image; /* continue with original image */ } if (verbose != MagickFalse) (void) FormatLocaleFile(thread_stderr, "\n"); /* loop to the next kernel in a multi-kernel list */ norm_kernel = norm_kernel->next; if ( rflt_kernel != (KernelInfo *) NULL ) rflt_kernel = rflt_kernel->next; kernel_number++; } /* End Loop 2: Loop over each kernel */ } /* End Loop 1: compound method interation */ goto exit_cleanup; /* Yes goto's are bad, but it makes cleanup lot more efficient */ error_cleanup: if ( curr_image == rslt_image ) curr_image = (Image *) NULL; if ( rslt_image != (Image *) NULL ) rslt_image = DestroyImage(rslt_image); exit_cleanup: if ( curr_image == rslt_image || curr_image == image ) curr_image = (Image *) NULL; if ( curr_image != (Image *) NULL ) curr_image = DestroyImage(curr_image); if ( work_image != (Image *) NULL ) work_image = DestroyImage(work_image); if ( save_image != (Image *) NULL ) save_image = DestroyImage(save_image); if ( reflected_kernel != (KernelInfo *) NULL ) reflected_kernel = DestroyKernelInfo(reflected_kernel); return(rslt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyImage() applies a user supplied kernel to the image according to % the given mophology method. % % This function applies any and all user defined settings before calling % the above internal function MorphologyApply(). % % User defined settings include... % * Output Bias for Convolution and correlation ("-define convolve:bias=??") % * Kernel Scale/normalize settings ("-define convolve:scale=??") % This can also includes the addition of a scaled unity kernel. % * Show Kernel being applied ("-define morphology:showKernel=1") % % Other operators that do not want user supplied options interfering, % especially "convolve:bias" and "morphology:showKernel" should use % MorphologyApply() directly. % % The format of the MorphologyImage method is: % % Image *MorphologyImage(const Image *image,MorphologyMethod method, % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the morphology method to be applied. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o kernel: An array of double representing the morphology kernel. % Warning: kernel may be normalized for the Convolve method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod method,const ssize_t iterations, const KernelInfo *kernel,ExceptionInfo *exception) { const char *artifact; CompositeOperator compose; double bias; Image *morphology_image; KernelInfo *curr_kernel; curr_kernel = (KernelInfo *) kernel; bias=0.0; compose = UndefinedCompositeOp; /* use default for method */ /* Apply Convolve/Correlate Normalization and Scaling Factors. * This is done BEFORE the ShowKernelInfo() function is called so that * users can see the results of the 'option:convolve:scale' option. */ if ( method == ConvolveMorphology || method == CorrelateMorphology ) { /* Get the bias value as it will be needed */ artifact = GetImageArtifact(image,"convolve:bias"); if ( artifact != (const char *) NULL) { if (IsGeometry(artifact) == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"InvalidSetting","'%s' '%s'", "convolve:bias",artifact); else bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0); } /* Scale kernel according to user wishes */ artifact = GetImageArtifact(image,"convolve:scale"); if ( artifact != (const char *) NULL ) { if (IsGeometry(artifact) == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"InvalidSetting","'%s' '%s'", "convolve:scale",artifact); else { if ( curr_kernel == kernel ) curr_kernel = CloneKernelInfo(kernel); if (curr_kernel == (KernelInfo *) NULL) return((Image *) NULL); ScaleGeometryKernelInfo(curr_kernel, artifact); } } } /* display the (normalized) kernel via thread_stderr */ artifact=GetImageArtifact(image,"morphology:showKernel"); if (IsStringTrue(artifact) != MagickFalse) ShowKernelInfo(curr_kernel); /* Override the default handling of multi-kernel morphology results * If 'Undefined' use the default method * If 'None' (default for 'Convolve') re-iterate previous result * Otherwise merge resulting images using compose method given. * Default for 'HitAndMiss' is 'Lighten'. */ { ssize_t parse; artifact = GetImageArtifact(image,"morphology:compose"); if ( artifact != (const char *) NULL) { parse=ParseCommandOption(MagickComposeOptions, MagickFalse,artifact); if ( parse < 0 ) (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'", "morphology:compose",artifact); else compose=(CompositeOperator)parse; } } /* Apply the Morphology */ morphology_image = MorphologyApply(image,method,iterations, curr_kernel,compose,bias,exception); /* Cleanup and Exit */ if ( curr_kernel != kernel ) curr_kernel=DestroyKernelInfo(curr_kernel); return(morphology_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotateKernelInfo() rotates the kernel by the angle given. % % Currently it is restricted to 90 degree angles, of either 1D kernels % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels. % It will ignore usless rotations for specific 'named' built-in kernels. % % The format of the RotateKernelInfo method is: % % void RotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is currently internal to this module only, but can be exported % to other modules if needed. */ static void RotateKernelInfo(KernelInfo *kernel, double angle) { /* angle the lower kernels first */ if ( kernel->next != (KernelInfo *) NULL) RotateKernelInfo(kernel->next, angle); /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical ** ** TODO: expand beyond simple 90 degree rotates, flips and flops */ /* Modulus the angle */ angle = fmod(angle, 360.0); if ( angle < 0 ) angle += 360.0; if ( 337.5 < angle || angle <= 22.5 ) return; /* Near zero angle - no change! - At least not at this time */ /* Handle special cases */ switch (kernel->type) { /* These built-in kernels are cylindrical kernels, rotating is useless */ case GaussianKernel: case DoGKernel: case LoGKernel: case DiskKernel: case PeaksKernel: case LaplacianKernel: case ChebyshevKernel: case ManhattanKernel: case EuclideanKernel: return; /* These may be rotatable at non-90 angles in the future */ /* but simply rotating them in multiples of 90 degrees is useless */ case SquareKernel: case DiamondKernel: case PlusKernel: case CrossKernel: return; /* These only allows a +/-90 degree rotation (by transpose) */ /* A 180 degree rotation is useless */ case BlurKernel: if ( 135.0 < angle && angle <= 225.0 ) return; if ( 225.0 < angle && angle <= 315.0 ) angle -= 180; break; default: break; } /* Attempt rotations by 45 degrees -- 3x3 kernels only */ if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 ) { if ( kernel->width == 3 && kernel->height == 3 ) { /* Rotate a 3x3 square by 45 degree angle */ double t = kernel->values[0]; kernel->values[0] = kernel->values[3]; kernel->values[3] = kernel->values[6]; kernel->values[6] = kernel->values[7]; kernel->values[7] = kernel->values[8]; kernel->values[8] = kernel->values[5]; kernel->values[5] = kernel->values[2]; kernel->values[2] = kernel->values[1]; kernel->values[1] = t; /* rotate non-centered origin */ if ( kernel->x != 1 || kernel->y != 1 ) { ssize_t x,y; x = (ssize_t) kernel->x-1; y = (ssize_t) kernel->y-1; if ( x == y ) x = 0; else if ( x == 0 ) x = -y; else if ( x == -y ) y = 0; else if ( y == 0 ) y = x; kernel->x = (ssize_t) x+1; kernel->y = (ssize_t) y+1; } angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */ kernel->angle = fmod(kernel->angle+45.0, 360.0); } else perror("Unable to rotate non-3x3 kernel by 45 degrees"); } if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 ) { if ( kernel->width == 1 || kernel->height == 1 ) { /* Do a transpose of a 1 dimensional kernel, ** which results in a fast 90 degree rotation of some type. */ ssize_t t; t = (ssize_t) kernel->width; kernel->width = kernel->height; kernel->height = (size_t) t; t = kernel->x; kernel->x = kernel->y; kernel->y = t; if ( kernel->width == 1 ) { angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else { angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */ kernel->angle = fmod(kernel->angle+270.0, 360.0); } } else if ( kernel->width == kernel->height ) { /* Rotate a square array of values by 90 degrees */ { register ssize_t i,j,x,y; register MagickRealType *k,t; k=kernel->values; for( i=0, x=(ssize_t) kernel->width-1; i<=x; i++, x--) for( j=0, y=(ssize_t) kernel->height-1; j<y; j++, y--) { t = k[i+j*kernel->width]; k[i+j*kernel->width] = k[j+x*kernel->width]; k[j+x*kernel->width] = k[x+y*kernel->width]; k[x+y*kernel->width] = k[y+i*kernel->width]; k[y+i*kernel->width] = t; } } /* rotate the origin - relative to center of array */ { register ssize_t x,y; x = (ssize_t) (kernel->x*2-kernel->width+1); y = (ssize_t) (kernel->y*2-kernel->height+1); kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2; kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2; } angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else perror("Unable to rotate a non-square, non-linear kernel 90 degrees"); } if ( 135.0 < angle && angle <= 225.0 ) { /* For a 180 degree rotation - also know as a reflection * This is actually a very very common operation! * Basically all that is needed is a reversal of the kernel data! * And a reflection of the origon */ MagickRealType t; register MagickRealType *k; ssize_t i, j; k=kernel->values; j=(ssize_t) (kernel->width*kernel->height-1); for (i=0; i < j; i++, j--) t=k[i], k[i]=k[j], k[j]=t; kernel->x = (ssize_t) kernel->width - kernel->x - 1; kernel->y = (ssize_t) kernel->height - kernel->y - 1; angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */ kernel->angle = fmod(kernel->angle+180.0, 360.0); } /* At this point angle should at least between -45 (315) and +45 degrees * In the future some form of non-orthogonal angled rotates could be * performed here, posibily with a linear kernel restriction. */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e G e o m e t r y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleGeometryKernelInfo() takes a geometry argument string, typically % provided as a "-set option:convolve:scale {geometry}" user setting, % and modifies the kernel according to the parsed arguments of that setting. % % The first argument (and any normalization flags) are passed to % ScaleKernelInfo() to scale/normalize the kernel. The second argument % is then passed to UnityAddKernelInfo() to add a scled unity kernel % into the scaled/normalized kernel. % % The format of the ScaleGeometryKernelInfo method is: % % void ScaleGeometryKernelInfo(KernelInfo *kernel, % const double scaling_factor,const MagickStatusType normalize_flags) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % o geometry: % The geometry string to parse, typically from the user provided % "-set option:convolve:scale {geometry}" setting. % */ MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel, const char *geometry) { MagickStatusType flags; GeometryInfo args; SetGeometryInfo(&args); flags = ParseGeometry(geometry, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(thread_stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/ args.rho *= 0.01, args.sigma *= 0.01; if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */ args.rho = 1.0; if ( (flags & SigmaValue) == 0 ) args.sigma = 0.0; /* Scale/Normalize the input kernel */ ScaleKernelInfo(kernel, args.rho, (GeometryFlags) flags); /* Add Unity Kernel, for blending with original */ if ( (flags & SigmaValue) != 0 ) UnityAddKernelInfo(kernel, args.sigma); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleKernelInfo() scales the given kernel list by the given amount, with or % without normalization of the sum of the kernel values (as per given flags). % % By default (no flags given) the values within the kernel is scaled % directly using given scaling factor without change. % % If either of the two 'normalize_flags' are given the kernel will first be % normalized and then further scaled by the scaling factor value given. % % Kernel normalization ('normalize_flags' given) is designed to ensure that % any use of the kernel scaling factor with 'Convolve' or 'Correlate' % morphology methods will fall into -1.0 to +1.0 range. Note that for % non-HDRI versions of IM this may cause images to have any negative results % clipped, unless some 'bias' is used. % % More specifically. Kernels which only contain positive values (such as a % 'Gaussian' kernel) will be scaled so that those values sum to +1.0, % ensuring a 0.0 to +1.0 output range for non-HDRI images. % % For Kernels that contain some negative values, (such as 'Sharpen' kernels) % the kernel will be scaled by the absolute of the sum of kernel values, so % that it will generally fall within the +/- 1.0 range. % % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel % will be scaled by just the sum of the postive values, so that its output % range will again fall into the +/- 1.0 range. % % For special kernels designed for locating shapes using 'Correlate', (often % only containing +1 and -1 values, representing foreground/brackground % matching) a special normalization method is provided to scale the positive % values separately to those of the negative values, so the kernel will be % forced to become a zero-sum kernel better suited to such searches. % % WARNING: Correct normalization of the kernel assumes that the '*_range' % attributes within the kernel structure have been correctly set during the % kernels creation. % % NOTE: The values used for 'normalize_flags' have been selected specifically % to match the use of geometry options, so that '!' means NormalizeValue, '^' % means CorrelateNormalizeValue. All other GeometryFlags values are ignored. % % The format of the ScaleKernelInfo method is: % % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor, % const MagickStatusType normalize_flags ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scaling_factor: % multiply all values (after normalization) by this factor if not % zero. If the kernel is normalized regardless of any flags. % % o normalize_flags: % GeometryFlags defining normalization method to use. % specifically: NormalizeValue, CorrelateNormalizeValue, % and/or PercentValue % */ MagickExport void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,const GeometryFlags normalize_flags) { register double pos_scale, neg_scale; register ssize_t i; /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags); /* Normalization of Kernel */ pos_scale = 1.0; if ( (normalize_flags&NormalizeValue) != 0 ) { if ( fabs(kernel->positive_range + kernel->negative_range) >= MagickEpsilon ) /* non-zero-summing kernel (generally positive) */ pos_scale = fabs(kernel->positive_range + kernel->negative_range); else /* zero-summing kernel */ pos_scale = kernel->positive_range; } /* Force kernel into a normalized zero-summing kernel */ if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) { pos_scale = ( fabs(kernel->positive_range) >= MagickEpsilon ) ? kernel->positive_range : 1.0; neg_scale = ( fabs(kernel->negative_range) >= MagickEpsilon ) ? -kernel->negative_range : 1.0; } else neg_scale = pos_scale; /* finialize scaling_factor for positive and negative components */ pos_scale = scaling_factor/pos_scale; neg_scale = scaling_factor/neg_scale; for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) if (!IsNaN(kernel->values[i])) kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale; /* convolution output range */ kernel->positive_range *= pos_scale; kernel->negative_range *= neg_scale; /* maximum and minimum values in kernel */ kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale; kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale; /* swap kernel settings if user's scaling factor is negative */ if ( scaling_factor < MagickEpsilon ) { double t; t = kernel->positive_range; kernel->positive_range = kernel->negative_range; kernel->negative_range = t; t = kernel->maximum; kernel->maximum = kernel->minimum; kernel->minimum = 1; } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h o w K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShowKernelInfo() outputs the details of the given kernel defination to % standard error, generally due to a users 'morphology:showKernel' option % request. % % The format of the ShowKernel method is: % % void ShowKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickPrivate void ShowKernelInfo(const KernelInfo *kernel) { const KernelInfo *k; size_t c, i, u, v; for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) { (void) FormatLocaleFile(thread_stderr, "Kernel"); if ( kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(thread_stderr, " #%lu", (unsigned long) c ); (void) FormatLocaleFile(thread_stderr, " \"%s", CommandOptionToMnemonic(MagickKernelOptions, k->type) ); if ( fabs(k->angle) >= MagickEpsilon ) (void) FormatLocaleFile(thread_stderr, "@%lg", k->angle); (void) FormatLocaleFile(thread_stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long) k->width,(unsigned long) k->height,(long) k->x,(long) k->y); (void) FormatLocaleFile(thread_stderr, " with values from %.*lg to %.*lg\n", GetMagickPrecision(), k->minimum, GetMagickPrecision(), k->maximum); (void) FormatLocaleFile(thread_stderr, "Forming a output range from %.*lg to %.*lg", GetMagickPrecision(), k->negative_range, GetMagickPrecision(), k->positive_range); if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon ) (void) FormatLocaleFile(thread_stderr, " (Zero-Summing)\n"); else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon ) (void) FormatLocaleFile(thread_stderr, " (Normalized)\n"); else (void) FormatLocaleFile(thread_stderr, " (Sum %.*lg)\n", GetMagickPrecision(), k->positive_range+k->negative_range); for (i=v=0; v < k->height; v++) { (void) FormatLocaleFile(thread_stderr, "%2lu:", (unsigned long) v ); for (u=0; u < k->width; u++, i++) if (IsNaN(k->values[i])) (void) FormatLocaleFile(thread_stderr," %*s", GetMagickPrecision()+3, "nan"); else (void) FormatLocaleFile(thread_stderr," %*.*lg", GetMagickPrecision()+3, GetMagickPrecision(), (double) k->values[i]); (void) FormatLocaleFile(thread_stderr,"\n"); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n i t y A d d K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel % to the given pre-scaled and normalized Kernel. This in effect adds that % amount of the original image into the resulting convolution kernel. This % value is usually provided by the user as a percentage value in the % 'convolve:scale' setting. % % The resulting effect is to convert the defined kernels into blended % soft-blurs, unsharp kernels or into sharpening kernels. % % The format of the UnityAdditionKernelInfo method is: % % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scale: % scaling factor for the unity kernel to be added to % the given kernel. % */ MagickExport void UnityAddKernelInfo(KernelInfo *kernel, const double scale) { /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) UnityAddKernelInfo(kernel->next, scale); /* Add the scaled unity kernel to the existing kernel */ kernel->values[kernel->x+kernel->y*kernel->width] += scale; CalcKernelMetaData(kernel); /* recalculate the meta-data */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Z e r o K e r n e l N a n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroKernelNans() replaces any special 'nan' value that may be present in % the kernel with a zero value. This is typically done when the kernel will % be used in special hardware (GPU) convolution processors, to simply % matters. % % The format of the ZeroKernelNans method is: % % void ZeroKernelNans (KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickPrivate void ZeroKernelNans(KernelInfo *kernel) { register size_t i; /* do the other kernels in a multi-kernel list first */ if (kernel->next != (KernelInfo *) NULL) ZeroKernelNans(kernel->next); for (i=0; i < (kernel->width*kernel->height); i++) if (IsNaN(kernel->values[i])) kernel->values[i]=0.0; return; }
expected_output.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> //--------------------------------------------------------------------- // program LU //--------------------------------------------------------------------- //---------- // Class S: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ //---------- // Class W: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ //---------- // Class A: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ //---------- // Class B: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ //---------- // Class C: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ //---------- // Class D: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ //---------- // Class E: //---------- /*full problem size*/ /*number of iterations and how often to print the norm*/ struct anon_NAS_LU_c_109 { double real; double imag; }; typedef struct anon_NAS_LU_c_109 dcomplex; //--------------------------------------------------------------------- // parameters which can be overridden in runtime config file // isiz1,isiz2,isiz3 give the maximum size // ipr = 1 to print out verbose information // omega = 2.0 is correct for all classes // tolrsd is tolerance levels for steady state residuals //--------------------------------------------------------------------- //--------------------------------------------------------------------- // grid //--------------------------------------------------------------------- /*common/cgcon/*/ double dxi; double deta; double dzeta; double tx1; double tx2; double tx3; double ty1; double ty2; double ty3; double tz1; double tz2; double tz3; int nx; int ny; int nz; int nx0; int ny0; int nz0; int ist; int iend; int jst; int jend; int ii1; int ii2; int ji1; int ji2; int ki1; int ki2; //--------------------------------------------------------------------- // dissipation //--------------------------------------------------------------------- /*common/disp/*/ double dx1; double dx2; double dx3; double dx4; double dx5; double dy1; double dy2; double dy3; double dy4; double dy5; double dz1; double dz2; double dz3; double dz4; double dz5; double dssp; //--------------------------------------------------------------------- // field variables and residuals // to improve cache performance, second two dimensions padded by 1 // for even number sizes only. // Note: corresponding array (called "v") in routines blts, buts, // and l2norm are similarly padded //--------------------------------------------------------------------- /*common/cvar/*/ double u[33][33][33][5]; double rsd[33][33][33][5]; double frct[33][33][33][5]; double flux[33][5]; double qs[33][33][33]; double rho_i[33][33][33]; //--------------------------------------------------------------------- // output control parameters //--------------------------------------------------------------------- /*common/cprcon/*/ int ipr; int inorm; //--------------------------------------------------------------------- // newton-raphson iteration control parameters //--------------------------------------------------------------------- /*common/ctscon/*/ double dt; double omega; double tolrsd[5]; double rsdnm[5]; double errnm[5]; double frc; double ttotal; int itmax; int invert; /*common/cjac/*/ double a[33][33][5][5]; double b[33][33][5][5]; double c[33][33][5][5]; double d[33][33][5][5]; //--------------------------------------------------------------------- // coefficients of the exact solution //--------------------------------------------------------------------- /*common/cexact/*/ double ce[5][13]; //--------------------------------------------------------------------- // timers //--------------------------------------------------------------------- /*common/timer/*/ double maxtime; void read_input(); void domain(); void setcoeff(); void setbv(); void exact(int i, int j, int k, double u000ijk[]); void setiv(); void erhs(); void ssor(int niter); void rhs(); void l2norm(int ldx, int ldy, int ldz, int nx0, int ny0, int nz0, int ist, int iend, int jst, int jend, double v[][ldy / 2 * 2 + 1][ldx / 2 * 2 + 1][5], double sum[5]); void jacld(int k); void blts(int ldmx, int ldmy, int ldmz, int nx, int ny, int nz, int k, double omega, double v[][ldmy / 2 * 2 + 1][ldmx / 2 * 2 + 1][5], double ldz[ldmy][ldmx / 2 * 2 + 1][5][5], double ldy[ldmy][ldmx / 2 * 2 + 1][5][5], double ldx[ldmy][ldmx / 2 * 2 + 1][5][5], double d[ldmy][ldmx / 2 * 2 + 1][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0); void jacu(int k); void buts(int ldmx, int ldmy, int ldmz, int nx, int ny, int nz, int k, double omega, double v[][ldmy / 2 * 2 + 1][ldmx / 2 * 2 + 1][5], double tv[ldmy][ldmx / 2 * 2 + 1][5], double d[ldmy][ldmx / 2 * 2 + 1][5][5], double udx[ldmy][ldmx / 2 * 2 + 1][5][5], double udy[ldmy][ldmx / 2 * 2 + 1][5][5], double udz[ldmy][ldmx / 2 * 2 + 1][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0); void error(); void pintgr(); void verify(double xcr[5], double xce[5], double xci, char *Class, int *verified); void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified); double start[64]; double elapsed[64]; double elapsed_time(); void timer_clear(int n); void timer_start(int n); void timer_stop(int n); double timer_read(int n); void wtime(double *t); int main(int argc, char *argv[]) { char Class; int verified; double mflops; double t; double tmax; double trecs[12]; int i; char *t_names[12]; //--------------------------------------------------------------------- // read input data //--------------------------------------------------------------------- read_input(); //--------------------------------------------------------------------- // set up domain sizes //--------------------------------------------------------------------- domain(); //--------------------------------------------------------------------- // set up coefficients //--------------------------------------------------------------------- setcoeff(); //--------------------------------------------------------------------- // set the boundary values for dependent variables //--------------------------------------------------------------------- setbv(); //--------------------------------------------------------------------- // set the initial values for dependent variables //--------------------------------------------------------------------- setiv(); //--------------------------------------------------------------------- // compute the forcing term based on prescribed exact solution //--------------------------------------------------------------------- erhs(); //--------------------------------------------------------------------- // perform one SSOR iteration to touch all pages //--------------------------------------------------------------------- ssor(1); //--------------------------------------------------------------------- // reset the boundary and initial values //--------------------------------------------------------------------- setbv(); setiv(); //--------------------------------------------------------------------- // perform the SSOR iterations //--------------------------------------------------------------------- ssor(itmax); //--------------------------------------------------------------------- // compute the solution error //--------------------------------------------------------------------- error(); //--------------------------------------------------------------------- // compute the surface integral //--------------------------------------------------------------------- pintgr(); //--------------------------------------------------------------------- // verification test //--------------------------------------------------------------------- verify(rsdnm, errnm, frc, &Class, &verified); mflops = (double) itmax * (1984.77 * (double) nx0 * (double) ny0 * (double) nz0 - 10923.3 * pow(((double) (nx0 + ny0 + nz0) / 3.0), 2.0) + 27770.9 * (double) (nx0 + ny0 + nz0) / 3.0 - 144010.0) / (maxtime * 1000000.0); print_results("LU", Class, nx0, ny0, nz0, itmax, maxtime, mflops, " floating point", verified); int exitValue = verified ? 0 : 1; return exitValue; } //--------------------------------------------------------------------- // // compute the regular-sparse, block lower triangular solution: // // v <-- ( L-inv ) * v // //--------------------------------------------------------------------- //--------------------------------------------------------------------- // To improve cache performance, second two dimensions padded by 1 // for even number sizes only. Only needed in v. //--------------------------------------------------------------------- void blts(int ldmx, int ldmy, int ldmz, int nx, int ny, int nz, int k, double omega, double v[][ldmy / 2 * 2 + 1][ldmx / 2 * 2 + 1][5], double ldz[ldmy][ldmx / 2 * 2 + 1][5][5], double ldy[ldmy][ldmx / 2 * 2 + 1][5][5], double ldx[ldmy][ldmx / 2 * 2 + 1][5][5], double d[ldmy][ldmx / 2 * 2 + 1][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, m; double tmp, tmp1; double tmat[5][5]; double tv[5]; // Since gcc 4.4.3 generates the following warning for v: // warning: '({anonymous})' may be used uninitialized in this function // we use casted pointers. double (*vk)[ldmx / 2 * 2 + 1][5] = v[k]; double (*vkm1)[ldmx / 2 * 2 + 1][5] = v[k - 1]; #pragma omp parallel for default(shared) private(j, i, m) firstprivate(jst, jend, ist, iend, omega, ldz, vkm1) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, j, omega, ldz, vkm1) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { vk[j][i][m] = vk[j][i][m] - omega * (ldz[j][i][0][m] * vkm1[j][i][0] + ldz[j][i][1][m] * vkm1[j][i][1] + ldz[j][i][2][m] * vkm1[j][i][2] + ldz[j][i][3][m] * vkm1[j][i][3] + ldz[j][i][4][m] * vkm1[j][i][4]); } } } /*************** Clava msgError ************** unsolved dependency for arrayAccess vk use : RW ****************************************/ for(j = jst; j < jend; j++) { /*************** Clava msgError ************** unsolved dependency for arrayAccess vk use : RW ****************************************/ for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { tv[m] = vk[j][i][m] - omega * (ldy[j][i][0][m] * vk[j - 1][i][0] + ldx[j][i][0][m] * vk[j][i - 1][0] + ldy[j][i][1][m] * vk[j - 1][i][1] + ldx[j][i][1][m] * vk[j][i - 1][1] + ldy[j][i][2][m] * vk[j - 1][i][2] + ldx[j][i][2][m] * vk[j][i - 1][2] + ldy[j][i][3][m] * vk[j - 1][i][3] + ldx[j][i][3][m] * vk[j][i - 1][3] + ldy[j][i][4][m] * vk[j - 1][i][4] + ldx[j][i][4][m] * vk[j][i - 1][4]); } //--------------------------------------------------------------------- // diagonal block inversion // // forward elimination //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { tmat[m][0] = d[j][i][0][m]; tmat[m][1] = d[j][i][1][m]; tmat[m][2] = d[j][i][2][m]; tmat[m][3] = d[j][i][3][m]; tmat[m][4] = d[j][i][4][m]; } tmp1 = 1.0 / tmat[0][0]; tmp = tmp1 * tmat[1][0]; tmat[1][1] = tmat[1][1] - tmp * tmat[0][1]; tmat[1][2] = tmat[1][2] - tmp * tmat[0][2]; tmat[1][3] = tmat[1][3] - tmp * tmat[0][3]; tmat[1][4] = tmat[1][4] - tmp * tmat[0][4]; tv[1] = tv[1] - tv[0] * tmp; tmp = tmp1 * tmat[2][0]; tmat[2][1] = tmat[2][1] - tmp * tmat[0][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[0][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[0][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[0][4]; tv[2] = tv[2] - tv[0] * tmp; tmp = tmp1 * tmat[3][0]; tmat[3][1] = tmat[3][1] - tmp * tmat[0][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[0][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[0][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[0][4]; tv[3] = tv[3] - tv[0] * tmp; tmp = tmp1 * tmat[4][0]; tmat[4][1] = tmat[4][1] - tmp * tmat[0][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[0][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[0][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[0][4]; tv[4] = tv[4] - tv[0] * tmp; tmp1 = 1.0 / tmat[1][1]; tmp = tmp1 * tmat[2][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[1][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[1][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[1][4]; tv[2] = tv[2] - tv[1] * tmp; tmp = tmp1 * tmat[3][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[1][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[1][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[1][4]; tv[3] = tv[3] - tv[1] * tmp; tmp = tmp1 * tmat[4][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[1][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[1][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[1][4]; tv[4] = tv[4] - tv[1] * tmp; tmp1 = 1.0 / tmat[2][2]; tmp = tmp1 * tmat[3][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[2][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[2][4]; tv[3] = tv[3] - tv[2] * tmp; tmp = tmp1 * tmat[4][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[2][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[2][4]; tv[4] = tv[4] - tv[2] * tmp; tmp1 = 1.0 / tmat[3][3]; tmp = tmp1 * tmat[4][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[3][4]; tv[4] = tv[4] - tv[3] * tmp; //--------------------------------------------------------------------- // back substitution //--------------------------------------------------------------------- vk[j][i][4] = tv[4] / tmat[4][4]; tv[3] = tv[3] - tmat[3][4] * vk[j][i][4]; vk[j][i][3] = tv[3] / tmat[3][3]; tv[2] = tv[2] - tmat[2][3] * vk[j][i][3] - tmat[2][4] * vk[j][i][4]; vk[j][i][2] = tv[2] / tmat[2][2]; tv[1] = tv[1] - tmat[1][2] * vk[j][i][2] - tmat[1][3] * vk[j][i][3] - tmat[1][4] * vk[j][i][4]; vk[j][i][1] = tv[1] / tmat[1][1]; tv[0] = tv[0] - tmat[0][1] * vk[j][i][1] - tmat[0][2] * vk[j][i][2] - tmat[0][3] * vk[j][i][3] - tmat[0][4] * vk[j][i][4]; vk[j][i][0] = tv[0] / tmat[0][0]; } } } //--------------------------------------------------------------------- // // compute the regular-sparse, block upper triangular solution: // // v <-- ( U-inv ) * v // //--------------------------------------------------------------------- //--------------------------------------------------------------------- // To improve cache performance, second two dimensions padded by 1 // for even number sizes only. Only needed in v. //--------------------------------------------------------------------- void buts(int ldmx, int ldmy, int ldmz, int nx, int ny, int nz, int k, double omega, double v[][ldmy / 2 * 2 + 1][ldmx / 2 * 2 + 1][5], double tv[ldmy][ldmx / 2 * 2 + 1][5], double d[ldmy][ldmx / 2 * 2 + 1][5][5], double udx[ldmy][ldmx / 2 * 2 + 1][5][5], double udy[ldmy][ldmx / 2 * 2 + 1][5][5], double udz[ldmy][ldmx / 2 * 2 + 1][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, m; double tmp, tmp1; double tmat[5][5]; #pragma omp parallel for default(shared) private(j, i, m) firstprivate(jend, jst, iend, ist, k, omega, udz, v) for(j = jend - 1; j >= jst; j--) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(iend, ist, k, j, omega, udz, v) for(i = iend - 1; i >= ist; i--) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { tv[j][i][m] = omega * (udz[j][i][0][m] * v[k + 1][j][i][0] + udz[j][i][1][m] * v[k + 1][j][i][1] + udz[j][i][2][m] * v[k + 1][j][i][2] + udz[j][i][3][m] * v[k + 1][j][i][3] + udz[j][i][4][m] * v[k + 1][j][i][4]); } } } /*************** Clava msgError ************** unsolved dependency for arrayAccess v use : RW ****************************************/ for(j = jend - 1; j >= jst; j--) { /*************** Clava msgError ************** unsolved dependency for arrayAccess v use : RW ****************************************/ for(i = iend - 1; i >= ist; i--) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { tv[j][i][m] = tv[j][i][m] + omega * (udy[j][i][0][m] * v[k][j + 1][i][0] + udx[j][i][0][m] * v[k][j][i + 1][0] + udy[j][i][1][m] * v[k][j + 1][i][1] + udx[j][i][1][m] * v[k][j][i + 1][1] + udy[j][i][2][m] * v[k][j + 1][i][2] + udx[j][i][2][m] * v[k][j][i + 1][2] + udy[j][i][3][m] * v[k][j + 1][i][3] + udx[j][i][3][m] * v[k][j][i + 1][3] + udy[j][i][4][m] * v[k][j + 1][i][4] + udx[j][i][4][m] * v[k][j][i + 1][4]); } //--------------------------------------------------------------------- // diagonal block inversion //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { tmat[m][0] = d[j][i][0][m]; tmat[m][1] = d[j][i][1][m]; tmat[m][2] = d[j][i][2][m]; tmat[m][3] = d[j][i][3][m]; tmat[m][4] = d[j][i][4][m]; } tmp1 = 1.0 / tmat[0][0]; tmp = tmp1 * tmat[1][0]; tmat[1][1] = tmat[1][1] - tmp * tmat[0][1]; tmat[1][2] = tmat[1][2] - tmp * tmat[0][2]; tmat[1][3] = tmat[1][3] - tmp * tmat[0][3]; tmat[1][4] = tmat[1][4] - tmp * tmat[0][4]; tv[j][i][1] = tv[j][i][1] - tv[j][i][0] * tmp; tmp = tmp1 * tmat[2][0]; tmat[2][1] = tmat[2][1] - tmp * tmat[0][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[0][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[0][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[0][4]; tv[j][i][2] = tv[j][i][2] - tv[j][i][0] * tmp; tmp = tmp1 * tmat[3][0]; tmat[3][1] = tmat[3][1] - tmp * tmat[0][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[0][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[0][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[0][4]; tv[j][i][3] = tv[j][i][3] - tv[j][i][0] * tmp; tmp = tmp1 * tmat[4][0]; tmat[4][1] = tmat[4][1] - tmp * tmat[0][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[0][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[0][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[0][4]; tv[j][i][4] = tv[j][i][4] - tv[j][i][0] * tmp; tmp1 = 1.0 / tmat[1][1]; tmp = tmp1 * tmat[2][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[1][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[1][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[1][4]; tv[j][i][2] = tv[j][i][2] - tv[j][i][1] * tmp; tmp = tmp1 * tmat[3][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[1][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[1][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[1][4]; tv[j][i][3] = tv[j][i][3] - tv[j][i][1] * tmp; tmp = tmp1 * tmat[4][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[1][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[1][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[1][4]; tv[j][i][4] = tv[j][i][4] - tv[j][i][1] * tmp; tmp1 = 1.0 / tmat[2][2]; tmp = tmp1 * tmat[3][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[2][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[2][4]; tv[j][i][3] = tv[j][i][3] - tv[j][i][2] * tmp; tmp = tmp1 * tmat[4][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[2][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[2][4]; tv[j][i][4] = tv[j][i][4] - tv[j][i][2] * tmp; tmp1 = 1.0 / tmat[3][3]; tmp = tmp1 * tmat[4][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[3][4]; tv[j][i][4] = tv[j][i][4] - tv[j][i][3] * tmp; //--------------------------------------------------------------------- // back substitution //--------------------------------------------------------------------- tv[j][i][4] = tv[j][i][4] / tmat[4][4]; tv[j][i][3] = tv[j][i][3] - tmat[3][4] * tv[j][i][4]; tv[j][i][3] = tv[j][i][3] / tmat[3][3]; tv[j][i][2] = tv[j][i][2] - tmat[2][3] * tv[j][i][3] - tmat[2][4] * tv[j][i][4]; tv[j][i][2] = tv[j][i][2] / tmat[2][2]; tv[j][i][1] = tv[j][i][1] - tmat[1][2] * tv[j][i][2] - tmat[1][3] * tv[j][i][3] - tmat[1][4] * tv[j][i][4]; tv[j][i][1] = tv[j][i][1] / tmat[1][1]; tv[j][i][0] = tv[j][i][0] - tmat[0][1] * tv[j][i][1] - tmat[0][2] * tv[j][i][2] - tmat[0][3] * tv[j][i][3] - tmat[0][4] * tv[j][i][4]; tv[j][i][0] = tv[j][i][0] / tmat[0][0]; v[k][j][i][0] = v[k][j][i][0] - tv[j][i][0]; v[k][j][i][1] = v[k][j][i][1] - tv[j][i][1]; v[k][j][i][2] = v[k][j][i][2] - tv[j][i][2]; v[k][j][i][3] = v[k][j][i][3] - tv[j][i][3]; v[k][j][i][4] = v[k][j][i][4] - tv[j][i][4]; } } } void domain() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- nx = nx0; ny = ny0; nz = nz0; //--------------------------------------------------------------------- // check the sub-domain size //--------------------------------------------------------------------- if((nx < 4) || (ny < 4) || (nz < 4)) { printf(" SUBDOMAIN SIZE IS TOO SMALL - \n ADJUST PROBLEM SIZE OR NUMBER OF PROCESSORS\n SO THAT NX, NY AND NZ ARE GREATER THAN OR EQUAL\n TO 4 THEY ARE CURRENTLY%3d%3d%3d\n", nx, ny, nz); exit(1); } if((nx > 33) || (ny > 33) || (nz > 33)) { printf(" SUBDOMAIN SIZE IS TOO LARGE - \n ADJUST PROBLEM SIZE OR NUMBER OF PROCESSORS\n SO THAT NX, NY AND NZ ARE LESS THAN OR EQUAL TO \n ISIZ1, ISIZ2 AND ISIZ3 RESPECTIVELY. THEY ARE\n CURRENTLYi%4d%4d%4d\n", nx, ny, nz); exit(1); } //--------------------------------------------------------------------- // set up the start and end in i and j extents for all processors //--------------------------------------------------------------------- ist = 1; iend = nx - 1; jst = 1; jend = ny - 1; ii1 = 1; ii2 = nx0 - 1; ji1 = 1; ji2 = ny0 - 2; ki1 = 2; ki2 = nz0 - 1; } //--------------------------------------------------------------------- // // compute the right hand side based on exact solution // //--------------------------------------------------------------------- void erhs() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; double xi, eta, zeta; double q; double u21, u31, u41; double tmp; double u21i, u31i, u41i, u51i; double u21j, u31j, u41j, u51j; double u21k, u31k, u41k, u51k; double u21im1, u31im1, u41im1, u51im1; double u21jm1, u31jm1, u41jm1, u51jm1; double u21km1, u31km1, u41km1, u51km1; #pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz, ny, nx) for(k = 0; k < nz; k++) { // #pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny, nx, k) for(j = 0; j < ny; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(nx, k, j) for(i = 0; i < nx; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = 0.0; } } } } #pragma omp parallel for default(shared) private(k, j, i, m, zeta, eta, xi) firstprivate(nz, ny, ny0, nx, nx0, ce) for(k = 0; k < nz; k++) { zeta = ((double) k) / (nz - 1); // #pragma omp parallel for default(shared) private(j, i, m, eta, xi) firstprivate(ny, ny0, nx, nx0, zeta, k, ce) for(j = 0; j < ny; j++) { eta = ((double) j) / (ny0 - 1); // #pragma omp parallel for default(shared) private(i, m, xi) firstprivate(nx, nx0, eta, zeta, k, j, ce) for(i = 0; i < nx; i++) { xi = ((double) i) / (nx0 - 1); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = ce[m][0] + (ce[m][1] + (ce[m][4] + (ce[m][7] + ce[m][10] * xi) * xi) * xi) * xi + (ce[m][2] + (ce[m][5] + (ce[m][8] + ce[m][11] * eta) * eta) * eta) * eta + (ce[m][3] + (ce[m][6] + (ce[m][9] + ce[m][12] * zeta) * zeta) * zeta) * zeta; } } } } //--------------------------------------------------------------------- // xi-direction flux differences //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, j, i, m, u21, q, tmp, u21i, u31i, u41i, u51i, u21im1, u31im1, u41im1, u51im1) firstprivate(nz, jst, jend, nx, ist, iend, tx2, tx3, dx1, tx1, dx2, dx3, dx4, dx5, dssp, rsd, flux) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(j, i, m, u21, q, tmp, u21i, u31i, u41i, u51i, u21im1, u31im1, u41im1, u51im1) firstprivate(jst, jend, nx, k, ist, iend, tx2, tx3, dx1, tx1, dx2, dx3, dx4, dx5, dssp, rsd, flux) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, u21, q) firstprivate(nx, k, j, rsd) for(i = 0; i < nx; i++) { flux[i][0] = rsd[k][j][i][1]; u21 = rsd[k][j][i][1] / rsd[k][j][i][0]; q = 0.50 * (rsd[k][j][i][1] * rsd[k][j][i][1] + rsd[k][j][i][2] * rsd[k][j][i][2] + rsd[k][j][i][3] * rsd[k][j][i][3]) / rsd[k][j][i][0]; flux[i][1] = rsd[k][j][i][1] * u21 + 0.40e+00 * (rsd[k][j][i][4] - q); flux[i][2] = rsd[k][j][i][2] * u21; flux[i][3] = rsd[k][j][i][3] * u21; flux[i][4] = (1.40e+00 * rsd[k][j][i][4] - 0.40e+00 * q) * u21; } // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, tx2, k, j, flux) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = frct[k][j][i][m] - tx2 * (flux[i + 1][m] - flux[i - 1][m]); } } // #pragma omp parallel for default(shared) private(i, tmp, u21i, u31i, u41i, u51i, u21im1, u31im1, u41im1, u51im1) firstprivate(ist, nx, k, j, tx3, rsd) for(i = ist; i < nx; i++) { tmp = 1.0 / rsd[k][j][i][0]; u21i = tmp * rsd[k][j][i][1]; u31i = tmp * rsd[k][j][i][2]; u41i = tmp * rsd[k][j][i][3]; u51i = tmp * rsd[k][j][i][4]; tmp = 1.0 / rsd[k][j][i - 1][0]; u21im1 = tmp * rsd[k][j][i - 1][1]; u31im1 = tmp * rsd[k][j][i - 1][2]; u41im1 = tmp * rsd[k][j][i - 1][3]; u51im1 = tmp * rsd[k][j][i - 1][4]; flux[i][1] = (4.0 / 3.0) * tx3 * (u21i - u21im1); flux[i][2] = tx3 * (u31i - u31im1); flux[i][3] = tx3 * (u41i - u41im1); flux[i][4] = 0.50 * (1.0 - 1.40e+00 * 1.40e+00) * tx3 * ((u21i * u21i + u31i * u31i + u41i * u41i) - (u21im1 * u21im1 + u31im1 * u31im1 + u41im1 * u41im1)) + (1.0 / 6.0) * tx3 * (u21i * u21i - u21im1 * u21im1) + 1.40e+00 * 1.40e+00 * tx3 * (u51i - u51im1); } // #pragma omp parallel for default(shared) private(i) firstprivate(ist, iend, k, j, dx1, tx1, tx3, dx2, dx3, dx4, dx5, rsd, flux) for(i = ist; i < iend; i++) { frct[k][j][i][0] = frct[k][j][i][0] + dx1 * tx1 * (rsd[k][j][i - 1][0] - 2.0 * rsd[k][j][i][0] + rsd[k][j][i + 1][0]); frct[k][j][i][1] = frct[k][j][i][1] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][1] - flux[i][1]) + dx2 * tx1 * (rsd[k][j][i - 1][1] - 2.0 * rsd[k][j][i][1] + rsd[k][j][i + 1][1]); frct[k][j][i][2] = frct[k][j][i][2] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][2] - flux[i][2]) + dx3 * tx1 * (rsd[k][j][i - 1][2] - 2.0 * rsd[k][j][i][2] + rsd[k][j][i + 1][2]); frct[k][j][i][3] = frct[k][j][i][3] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][3] - flux[i][3]) + dx4 * tx1 * (rsd[k][j][i - 1][3] - 2.0 * rsd[k][j][i][3] + rsd[k][j][i + 1][3]); frct[k][j][i][4] = frct[k][j][i][4] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][4] - flux[i][4]) + dx5 * tx1 * (rsd[k][j][i - 1][4] - 2.0 * rsd[k][j][i][4] + rsd[k][j][i + 1][4]); } //--------------------------------------------------------------------- // Fourth-order dissipation //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][1][m] = frct[k][j][1][m] - dssp * (+5.0 * rsd[k][j][1][m] - 4.0 * rsd[k][j][2][m] + rsd[k][j][3][m]); frct[k][j][2][m] = frct[k][j][2][m] - dssp * (-4.0 * rsd[k][j][1][m] + 6.0 * rsd[k][j][2][m] - 4.0 * rsd[k][j][3][m] + rsd[k][j][4][m]); } // #pragma omp parallel for default(shared) private(i, m) firstprivate(nx, k, j, dssp, rsd) for(i = 3; i < nx - 3; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = frct[k][j][i][m] - dssp * (rsd[k][j][i - 2][m] - 4.0 * rsd[k][j][i - 1][m] + 6.0 * rsd[k][j][i][m] - 4.0 * rsd[k][j][i + 1][m] + rsd[k][j][i + 2][m]); } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][nx - 3][m] = frct[k][j][nx - 3][m] - dssp * (rsd[k][j][nx - 5][m] - 4.0 * rsd[k][j][nx - 4][m] + 6.0 * rsd[k][j][nx - 3][m] - 4.0 * rsd[k][j][nx - 2][m]); frct[k][j][nx - 2][m] = frct[k][j][nx - 2][m] - dssp * (rsd[k][j][nx - 4][m] - 4.0 * rsd[k][j][nx - 3][m] + 5.0 * rsd[k][j][nx - 2][m]); } } } //--------------------------------------------------------------------- // eta-direction flux differences //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, i, j, m, u31, q, tmp, u21j, u31j, u41j, u51j, u21jm1, u31jm1, u41jm1, u51jm1) firstprivate(nz, ist, iend, ny, jst, jend, ty2, ty3, dy1, ty1, dy2, dy3, dy4, dy5, dssp, rsd, flux) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(i, j, m, u31, q, tmp, u21j, u31j, u41j, u51j, u21jm1, u31jm1, u41jm1, u51jm1) firstprivate(ist, iend, ny, k, jst, jend, ty2, ty3, dy1, ty1, dy2, dy3, dy4, dy5, dssp, rsd, flux) for(i = ist; i < iend; i++) { // #pragma omp parallel for default(shared) private(j, u31, q) firstprivate(ny, k, i, rsd) for(j = 0; j < ny; j++) { flux[j][0] = rsd[k][j][i][2]; u31 = rsd[k][j][i][2] / rsd[k][j][i][0]; q = 0.50 * (rsd[k][j][i][1] * rsd[k][j][i][1] + rsd[k][j][i][2] * rsd[k][j][i][2] + rsd[k][j][i][3] * rsd[k][j][i][3]) / rsd[k][j][i][0]; flux[j][1] = rsd[k][j][i][1] * u31; flux[j][2] = rsd[k][j][i][2] * u31 + 0.40e+00 * (rsd[k][j][i][4] - q); flux[j][3] = rsd[k][j][i][3] * u31; flux[j][4] = (1.40e+00 * rsd[k][j][i][4] - 0.40e+00 * q) * u31; } // #pragma omp parallel for default(shared) private(j, m) firstprivate(jst, jend, ty2, k, i, flux) for(j = jst; j < jend; j++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = frct[k][j][i][m] - ty2 * (flux[j + 1][m] - flux[j - 1][m]); } } // #pragma omp parallel for default(shared) private(j, tmp, u21j, u31j, u41j, u51j, u21jm1, u31jm1, u41jm1, u51jm1) firstprivate(jst, ny, k, i, ty3, rsd) for(j = jst; j < ny; j++) { tmp = 1.0 / rsd[k][j][i][0]; u21j = tmp * rsd[k][j][i][1]; u31j = tmp * rsd[k][j][i][2]; u41j = tmp * rsd[k][j][i][3]; u51j = tmp * rsd[k][j][i][4]; tmp = 1.0 / rsd[k][j - 1][i][0]; u21jm1 = tmp * rsd[k][j - 1][i][1]; u31jm1 = tmp * rsd[k][j - 1][i][2]; u41jm1 = tmp * rsd[k][j - 1][i][3]; u51jm1 = tmp * rsd[k][j - 1][i][4]; flux[j][1] = ty3 * (u21j - u21jm1); flux[j][2] = (4.0 / 3.0) * ty3 * (u31j - u31jm1); flux[j][3] = ty3 * (u41j - u41jm1); flux[j][4] = 0.50 * (1.0 - 1.40e+00 * 1.40e+00) * ty3 * ((u21j * u21j + u31j * u31j + u41j * u41j) - (u21jm1 * u21jm1 + u31jm1 * u31jm1 + u41jm1 * u41jm1)) + (1.0 / 6.0) * ty3 * (u31j * u31j - u31jm1 * u31jm1) + 1.40e+00 * 1.40e+00 * ty3 * (u51j - u51jm1); } // #pragma omp parallel for default(shared) private(j) firstprivate(jst, jend, k, i, dy1, ty1, ty3, dy2, dy3, dy4, dy5, rsd, flux) for(j = jst; j < jend; j++) { frct[k][j][i][0] = frct[k][j][i][0] + dy1 * ty1 * (rsd[k][j - 1][i][0] - 2.0 * rsd[k][j][i][0] + rsd[k][j + 1][i][0]); frct[k][j][i][1] = frct[k][j][i][1] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][1] - flux[j][1]) + dy2 * ty1 * (rsd[k][j - 1][i][1] - 2.0 * rsd[k][j][i][1] + rsd[k][j + 1][i][1]); frct[k][j][i][2] = frct[k][j][i][2] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][2] - flux[j][2]) + dy3 * ty1 * (rsd[k][j - 1][i][2] - 2.0 * rsd[k][j][i][2] + rsd[k][j + 1][i][2]); frct[k][j][i][3] = frct[k][j][i][3] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][3] - flux[j][3]) + dy4 * ty1 * (rsd[k][j - 1][i][3] - 2.0 * rsd[k][j][i][3] + rsd[k][j + 1][i][3]); frct[k][j][i][4] = frct[k][j][i][4] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][4] - flux[j][4]) + dy5 * ty1 * (rsd[k][j - 1][i][4] - 2.0 * rsd[k][j][i][4] + rsd[k][j + 1][i][4]); } //--------------------------------------------------------------------- // fourth-order dissipation //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][1][i][m] = frct[k][1][i][m] - dssp * (+5.0 * rsd[k][1][i][m] - 4.0 * rsd[k][2][i][m] + rsd[k][3][i][m]); frct[k][2][i][m] = frct[k][2][i][m] - dssp * (-4.0 * rsd[k][1][i][m] + 6.0 * rsd[k][2][i][m] - 4.0 * rsd[k][3][i][m] + rsd[k][4][i][m]); } // #pragma omp parallel for default(shared) private(j, m) firstprivate(ny, k, i, dssp, rsd) for(j = 3; j < ny - 3; j++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = frct[k][j][i][m] - dssp * (rsd[k][j - 2][i][m] - 4.0 * rsd[k][j - 1][i][m] + 6.0 * rsd[k][j][i][m] - 4.0 * rsd[k][j + 1][i][m] + rsd[k][j + 2][i][m]); } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][ny - 3][i][m] = frct[k][ny - 3][i][m] - dssp * (rsd[k][ny - 5][i][m] - 4.0 * rsd[k][ny - 4][i][m] + 6.0 * rsd[k][ny - 3][i][m] - 4.0 * rsd[k][ny - 2][i][m]); frct[k][ny - 2][i][m] = frct[k][ny - 2][i][m] - dssp * (rsd[k][ny - 4][i][m] - 4.0 * rsd[k][ny - 3][i][m] + 5.0 * rsd[k][ny - 2][i][m]); } } } //--------------------------------------------------------------------- // zeta-direction flux differences //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j, i, k, m, u41, q, tmp, u21k, u31k, u41k, u51k, u21km1, u31km1, u41km1, u51km1) firstprivate(jst, jend, ist, iend, nz, tz2, tz3, dz1, tz1, dz2, dz3, dz4, dz5, dssp, rsd, flux) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, k, m, u41, q, tmp, u21k, u31k, u41k, u51k, u21km1, u31km1, u41km1, u51km1) firstprivate(ist, iend, nz, j, tz2, tz3, dz1, tz1, dz2, dz3, dz4, dz5, dssp, rsd, flux) for(i = ist; i < iend; i++) { // #pragma omp parallel for default(shared) private(k, u41, q) firstprivate(nz, j, i, rsd) for(k = 0; k < nz; k++) { flux[k][0] = rsd[k][j][i][3]; u41 = rsd[k][j][i][3] / rsd[k][j][i][0]; q = 0.50 * (rsd[k][j][i][1] * rsd[k][j][i][1] + rsd[k][j][i][2] * rsd[k][j][i][2] + rsd[k][j][i][3] * rsd[k][j][i][3]) / rsd[k][j][i][0]; flux[k][1] = rsd[k][j][i][1] * u41; flux[k][2] = rsd[k][j][i][2] * u41; flux[k][3] = rsd[k][j][i][3] * u41 + 0.40e+00 * (rsd[k][j][i][4] - q); flux[k][4] = (1.40e+00 * rsd[k][j][i][4] - 0.40e+00 * q) * u41; } // #pragma omp parallel for default(shared) private(k, m) firstprivate(nz, tz2, j, i, flux) for(k = 1; k < nz - 1; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = frct[k][j][i][m] - tz2 * (flux[k + 1][m] - flux[k - 1][m]); } } // #pragma omp parallel for default(shared) private(k, tmp, u21k, u31k, u41k, u51k, u21km1, u31km1, u41km1, u51km1) firstprivate(nz, j, i, tz3, rsd) for(k = 1; k < nz; k++) { tmp = 1.0 / rsd[k][j][i][0]; u21k = tmp * rsd[k][j][i][1]; u31k = tmp * rsd[k][j][i][2]; u41k = tmp * rsd[k][j][i][3]; u51k = tmp * rsd[k][j][i][4]; tmp = 1.0 / rsd[k - 1][j][i][0]; u21km1 = tmp * rsd[k - 1][j][i][1]; u31km1 = tmp * rsd[k - 1][j][i][2]; u41km1 = tmp * rsd[k - 1][j][i][3]; u51km1 = tmp * rsd[k - 1][j][i][4]; flux[k][1] = tz3 * (u21k - u21km1); flux[k][2] = tz3 * (u31k - u31km1); flux[k][3] = (4.0 / 3.0) * tz3 * (u41k - u41km1); flux[k][4] = 0.50 * (1.0 - 1.40e+00 * 1.40e+00) * tz3 * ((u21k * u21k + u31k * u31k + u41k * u41k) - (u21km1 * u21km1 + u31km1 * u31km1 + u41km1 * u41km1)) + (1.0 / 6.0) * tz3 * (u41k * u41k - u41km1 * u41km1) + 1.40e+00 * 1.40e+00 * tz3 * (u51k - u51km1); } // #pragma omp parallel for default(shared) private(k) firstprivate(nz, j, i, dz1, tz1, tz3, dz2, dz3, dz4, dz5, rsd, flux) for(k = 1; k < nz - 1; k++) { frct[k][j][i][0] = frct[k][j][i][0] + dz1 * tz1 * (rsd[k + 1][j][i][0] - 2.0 * rsd[k][j][i][0] + rsd[k - 1][j][i][0]); frct[k][j][i][1] = frct[k][j][i][1] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][1] - flux[k][1]) + dz2 * tz1 * (rsd[k + 1][j][i][1] - 2.0 * rsd[k][j][i][1] + rsd[k - 1][j][i][1]); frct[k][j][i][2] = frct[k][j][i][2] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][2] - flux[k][2]) + dz3 * tz1 * (rsd[k + 1][j][i][2] - 2.0 * rsd[k][j][i][2] + rsd[k - 1][j][i][2]); frct[k][j][i][3] = frct[k][j][i][3] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][3] - flux[k][3]) + dz4 * tz1 * (rsd[k + 1][j][i][3] - 2.0 * rsd[k][j][i][3] + rsd[k - 1][j][i][3]); frct[k][j][i][4] = frct[k][j][i][4] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][4] - flux[k][4]) + dz5 * tz1 * (rsd[k + 1][j][i][4] - 2.0 * rsd[k][j][i][4] + rsd[k - 1][j][i][4]); } //--------------------------------------------------------------------- // fourth-order dissipation //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[1][j][i][m] = frct[1][j][i][m] - dssp * (+5.0 * rsd[1][j][i][m] - 4.0 * rsd[2][j][i][m] + rsd[3][j][i][m]); frct[2][j][i][m] = frct[2][j][i][m] - dssp * (-4.0 * rsd[1][j][i][m] + 6.0 * rsd[2][j][i][m] - 4.0 * rsd[3][j][i][m] + rsd[4][j][i][m]); } // #pragma omp parallel for default(shared) private(k, m) firstprivate(nz, j, i, dssp, rsd) for(k = 3; k < nz - 3; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[k][j][i][m] = frct[k][j][i][m] - dssp * (rsd[k - 2][j][i][m] - 4.0 * rsd[k - 1][j][i][m] + 6.0 * rsd[k][j][i][m] - 4.0 * rsd[k + 1][j][i][m] + rsd[k + 2][j][i][m]); } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { frct[nz - 3][j][i][m] = frct[nz - 3][j][i][m] - dssp * (rsd[nz - 5][j][i][m] - 4.0 * rsd[nz - 4][j][i][m] + 6.0 * rsd[nz - 3][j][i][m] - 4.0 * rsd[nz - 2][j][i][m]); frct[nz - 2][j][i][m] = frct[nz - 2][j][i][m] - dssp * (rsd[nz - 4][j][i][m] - 4.0 * rsd[nz - 3][j][i][m] + 5.0 * rsd[nz - 2][j][i][m]); } } } } //--------------------------------------------------------------------- // // compute the solution error // //--------------------------------------------------------------------- void error() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; double tmp; double u000ijk[5]; /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { errnm[m] = 0.0; } #pragma omp parallel for default(shared) private(k, j, i, m, tmp) firstprivate(nz, jst, jend, ist, iend, nx0, ny0, ce, u, u000ijk) reduction(+ : errnm[:5]) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(j, i, m, tmp) firstprivate(jst, jend, ist, iend, k, nx0, ny0, nz, ce, u, u000ijk) reduction(+ : errnm[:5]) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, m, tmp) firstprivate(ist, iend, k, j, nx0, ny0, nz, ce, u, u000ijk) reduction(+ : errnm[:5]) for(i = ist; i < iend; i++) { exact(i, j, k, u000ijk); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { tmp = (u000ijk[m] - u[k][j][i][m]); errnm[m] = errnm[m] + tmp * tmp; } } } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { errnm[m] = sqrt(errnm[m] / ((nx0 - 2) * (ny0 - 2) * (nz0 - 2))); } /* printf(" \n RMS-norm of error in soln. to first pde = %12.5E\n" " RMS-norm of error in soln. to second pde = %12.5E\n" " RMS-norm of error in soln. to third pde = %12.5E\n" " RMS-norm of error in soln. to fourth pde = %12.5E\n" " RMS-norm of error in soln. to fifth pde = %12.5E\n", errnm[0], errnm[1], errnm[2], errnm[3], errnm[4]); */ } //--------------------------------------------------------------------- // // compute the exact solution at (i,j,k) // //--------------------------------------------------------------------- void exact(int i, int j, int k, double u000ijk[]) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int m; double xi, eta, zeta; xi = ((double) i) / (nx0 - 1); eta = ((double) j) / (ny0 - 1); zeta = ((double) k) / (nz - 1); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { u000ijk[m] = ce[m][0] + (ce[m][1] + (ce[m][4] + (ce[m][7] + ce[m][10] * xi) * xi) * xi) * xi + (ce[m][2] + (ce[m][5] + (ce[m][8] + ce[m][11] * eta) * eta) * eta) * eta + (ce[m][3] + (ce[m][6] + (ce[m][9] + ce[m][12] * zeta) * zeta) * zeta) * zeta; } } //--------------------------------------------------------------------- // compute the lower triangular part of the jacobian matrix //--------------------------------------------------------------------- void jacld(int k) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j; double r43; double c1345; double c34; double tmp1, tmp2, tmp3; r43 = (4.0 / 3.0); c1345 = 1.40e+00 * 1.00e-01 * 1.00e+00 * 1.40e+00; c34 = 1.00e-01 * 1.00e+00; #pragma omp parallel for default(shared) private(j, i, tmp1, tmp2, tmp3) firstprivate(jst, jend, ist, iend, k, tx1, dx1, ty1, dy1, tz1, dz1, dt, r43, c34, dx2, dy2, dz2, dx3, dy3, dz3, dx4, dy4, dz4, c1345, dx5, dy5, dz5, tz2, ty2, tx2, rho_i, u, qs) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, tmp1, tmp2, tmp3) firstprivate(ist, iend, k, j, tx1, dx1, ty1, dy1, tz1, dz1, dt, r43, c34, dx2, dy2, dz2, dx3, dy3, dz3, dx4, dy4, dz4, c1345, dx5, dy5, dz5, tz2, ty2, tx2, rho_i, u, qs) for(i = ist; i < iend; i++) { //--------------------------------------------------------------------- // form the block daigonal //--------------------------------------------------------------------- tmp1 = rho_i[k][j][i]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; d[j][i][0][0] = 1.0 + dt * 2.0 * (tx1 * dx1 + ty1 * dy1 + tz1 * dz1); d[j][i][1][0] = 0.0; d[j][i][2][0] = 0.0; d[j][i][3][0] = 0.0; d[j][i][4][0] = 0.0; d[j][i][0][1] = -dt * 2.0 * (tx1 * r43 + ty1 + tz1) * c34 * tmp2 * u[k][j][i][1]; d[j][i][1][1] = 1.0 + dt * 2.0 * c34 * tmp1 * (tx1 * r43 + ty1 + tz1) + dt * 2.0 * (tx1 * dx2 + ty1 * dy2 + tz1 * dz2); d[j][i][2][1] = 0.0; d[j][i][3][1] = 0.0; d[j][i][4][1] = 0.0; d[j][i][0][2] = -dt * 2.0 * (tx1 + ty1 * r43 + tz1) * c34 * tmp2 * u[k][j][i][2]; d[j][i][1][2] = 0.0; d[j][i][2][2] = 1.0 + dt * 2.0 * c34 * tmp1 * (tx1 + ty1 * r43 + tz1) + dt * 2.0 * (tx1 * dx3 + ty1 * dy3 + tz1 * dz3); d[j][i][3][2] = 0.0; d[j][i][4][2] = 0.0; d[j][i][0][3] = -dt * 2.0 * (tx1 + ty1 + tz1 * r43) * c34 * tmp2 * u[k][j][i][3]; d[j][i][1][3] = 0.0; d[j][i][2][3] = 0.0; d[j][i][3][3] = 1.0 + dt * 2.0 * c34 * tmp1 * (tx1 + ty1 + tz1 * r43) + dt * 2.0 * (tx1 * dx4 + ty1 * dy4 + tz1 * dz4); d[j][i][4][3] = 0.0; d[j][i][0][4] = -dt * 2.0 * (((tx1 * (r43 * c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (c34 - c1345)) * (u[k][j][i][1] * u[k][j][i][1]) + (tx1 * (c34 - c1345) + ty1 * (r43 * c34 - c1345) + tz1 * (c34 - c1345)) * (u[k][j][i][2] * u[k][j][i][2]) + (tx1 * (c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (r43 * c34 - c1345)) * (u[k][j][i][3] * u[k][j][i][3])) * tmp3 + (tx1 + ty1 + tz1) * c1345 * tmp2 * u[k][j][i][4]); d[j][i][1][4] = dt * 2.0 * tmp2 * u[k][j][i][1] * (tx1 * (r43 * c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (c34 - c1345)); d[j][i][2][4] = dt * 2.0 * tmp2 * u[k][j][i][2] * (tx1 * (c34 - c1345) + ty1 * (r43 * c34 - c1345) + tz1 * (c34 - c1345)); d[j][i][3][4] = dt * 2.0 * tmp2 * u[k][j][i][3] * (tx1 * (c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (r43 * c34 - c1345)); d[j][i][4][4] = 1.0 + dt * 2.0 * (tx1 + ty1 + tz1) * c1345 * tmp1 + dt * 2.0 * (tx1 * dx5 + ty1 * dy5 + tz1 * dz5); //--------------------------------------------------------------------- // form the first block sub-diagonal //--------------------------------------------------------------------- tmp1 = rho_i[k - 1][j][i]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; a[j][i][0][0] = -dt * tz1 * dz1; a[j][i][1][0] = 0.0; a[j][i][2][0] = 0.0; a[j][i][3][0] = -dt * tz2; a[j][i][4][0] = 0.0; a[j][i][0][1] = -dt * tz2 * (-(u[k - 1][j][i][1] * u[k - 1][j][i][3]) * tmp2) - dt * tz1 * (-c34 * tmp2 * u[k - 1][j][i][1]); a[j][i][1][1] = -dt * tz2 * (u[k - 1][j][i][3] * tmp1) - dt * tz1 * c34 * tmp1 - dt * tz1 * dz2; a[j][i][2][1] = 0.0; a[j][i][3][1] = -dt * tz2 * (u[k - 1][j][i][1] * tmp1); a[j][i][4][1] = 0.0; a[j][i][0][2] = -dt * tz2 * (-(u[k - 1][j][i][2] * u[k - 1][j][i][3]) * tmp2) - dt * tz1 * (-c34 * tmp2 * u[k - 1][j][i][2]); a[j][i][1][2] = 0.0; a[j][i][2][2] = -dt * tz2 * (u[k - 1][j][i][3] * tmp1) - dt * tz1 * (c34 * tmp1) - dt * tz1 * dz3; a[j][i][3][2] = -dt * tz2 * (u[k - 1][j][i][2] * tmp1); a[j][i][4][2] = 0.0; a[j][i][0][3] = -dt * tz2 * (-(u[k - 1][j][i][3] * tmp1) * (u[k - 1][j][i][3] * tmp1) + 0.40e+00 * qs[k - 1][j][i] * tmp1) - dt * tz1 * (-r43 * c34 * tmp2 * u[k - 1][j][i][3]); a[j][i][1][3] = -dt * tz2 * (-0.40e+00 * (u[k - 1][j][i][1] * tmp1)); a[j][i][2][3] = -dt * tz2 * (-0.40e+00 * (u[k - 1][j][i][2] * tmp1)); a[j][i][3][3] = -dt * tz2 * (2.0 - 0.40e+00) * (u[k - 1][j][i][3] * tmp1) - dt * tz1 * (r43 * c34 * tmp1) - dt * tz1 * dz4; a[j][i][4][3] = -dt * tz2 * 0.40e+00; a[j][i][0][4] = -dt * tz2 * ((0.40e+00 * 2.0 * qs[k - 1][j][i] - 1.40e+00 * u[k - 1][j][i][4]) * u[k - 1][j][i][3] * tmp2) - dt * tz1 * (-(c34 - c1345) * tmp3 * (u[k - 1][j][i][1] * u[k - 1][j][i][1]) - (c34 - c1345) * tmp3 * (u[k - 1][j][i][2] * u[k - 1][j][i][2]) - (r43 * c34 - c1345) * tmp3 * (u[k - 1][j][i][3] * u[k - 1][j][i][3]) - c1345 * tmp2 * u[k - 1][j][i][4]); a[j][i][1][4] = -dt * tz2 * (-0.40e+00 * (u[k - 1][j][i][1] * u[k - 1][j][i][3]) * tmp2) - dt * tz1 * (c34 - c1345) * tmp2 * u[k - 1][j][i][1]; a[j][i][2][4] = -dt * tz2 * (-0.40e+00 * (u[k - 1][j][i][2] * u[k - 1][j][i][3]) * tmp2) - dt * tz1 * (c34 - c1345) * tmp2 * u[k - 1][j][i][2]; a[j][i][3][4] = -dt * tz2 * (1.40e+00 * (u[k - 1][j][i][4] * tmp1) - 0.40e+00 * (qs[k - 1][j][i] * tmp1 + u[k - 1][j][i][3] * u[k - 1][j][i][3] * tmp2)) - dt * tz1 * (r43 * c34 - c1345) * tmp2 * u[k - 1][j][i][3]; a[j][i][4][4] = -dt * tz2 * (1.40e+00 * (u[k - 1][j][i][3] * tmp1)) - dt * tz1 * c1345 * tmp1 - dt * tz1 * dz5; //--------------------------------------------------------------------- // form the second block sub-diagonal //--------------------------------------------------------------------- tmp1 = rho_i[k][j - 1][i]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; b[j][i][0][0] = -dt * ty1 * dy1; b[j][i][1][0] = 0.0; b[j][i][2][0] = -dt * ty2; b[j][i][3][0] = 0.0; b[j][i][4][0] = 0.0; b[j][i][0][1] = -dt * ty2 * (-(u[k][j - 1][i][1] * u[k][j - 1][i][2]) * tmp2) - dt * ty1 * (-c34 * tmp2 * u[k][j - 1][i][1]); b[j][i][1][1] = -dt * ty2 * (u[k][j - 1][i][2] * tmp1) - dt * ty1 * (c34 * tmp1) - dt * ty1 * dy2; b[j][i][2][1] = -dt * ty2 * (u[k][j - 1][i][1] * tmp1); b[j][i][3][1] = 0.0; b[j][i][4][1] = 0.0; b[j][i][0][2] = -dt * ty2 * (-(u[k][j - 1][i][2] * tmp1) * (u[k][j - 1][i][2] * tmp1) + 0.40e+00 * (qs[k][j - 1][i] * tmp1)) - dt * ty1 * (-r43 * c34 * tmp2 * u[k][j - 1][i][2]); b[j][i][1][2] = -dt * ty2 * (-0.40e+00 * (u[k][j - 1][i][1] * tmp1)); b[j][i][2][2] = -dt * ty2 * ((2.0 - 0.40e+00) * (u[k][j - 1][i][2] * tmp1)) - dt * ty1 * (r43 * c34 * tmp1) - dt * ty1 * dy3; b[j][i][3][2] = -dt * ty2 * (-0.40e+00 * (u[k][j - 1][i][3] * tmp1)); b[j][i][4][2] = -dt * ty2 * 0.40e+00; b[j][i][0][3] = -dt * ty2 * (-(u[k][j - 1][i][2] * u[k][j - 1][i][3]) * tmp2) - dt * ty1 * (-c34 * tmp2 * u[k][j - 1][i][3]); b[j][i][1][3] = 0.0; b[j][i][2][3] = -dt * ty2 * (u[k][j - 1][i][3] * tmp1); b[j][i][3][3] = -dt * ty2 * (u[k][j - 1][i][2] * tmp1) - dt * ty1 * (c34 * tmp1) - dt * ty1 * dy4; b[j][i][4][3] = 0.0; b[j][i][0][4] = -dt * ty2 * ((0.40e+00 * 2.0 * qs[k][j - 1][i] - 1.40e+00 * u[k][j - 1][i][4]) * (u[k][j - 1][i][2] * tmp2)) - dt * ty1 * (-(c34 - c1345) * tmp3 * (u[k][j - 1][i][1] * u[k][j - 1][i][1]) - (r43 * c34 - c1345) * tmp3 * (u[k][j - 1][i][2] * u[k][j - 1][i][2]) - (c34 - c1345) * tmp3 * (u[k][j - 1][i][3] * u[k][j - 1][i][3]) - c1345 * tmp2 * u[k][j - 1][i][4]); b[j][i][1][4] = -dt * ty2 * (-0.40e+00 * (u[k][j - 1][i][1] * u[k][j - 1][i][2]) * tmp2) - dt * ty1 * (c34 - c1345) * tmp2 * u[k][j - 1][i][1]; b[j][i][2][4] = -dt * ty2 * (1.40e+00 * (u[k][j - 1][i][4] * tmp1) - 0.40e+00 * (qs[k][j - 1][i] * tmp1 + u[k][j - 1][i][2] * u[k][j - 1][i][2] * tmp2)) - dt * ty1 * (r43 * c34 - c1345) * tmp2 * u[k][j - 1][i][2]; b[j][i][3][4] = -dt * ty2 * (-0.40e+00 * (u[k][j - 1][i][2] * u[k][j - 1][i][3]) * tmp2) - dt * ty1 * (c34 - c1345) * tmp2 * u[k][j - 1][i][3]; b[j][i][4][4] = -dt * ty2 * (1.40e+00 * (u[k][j - 1][i][2] * tmp1)) - dt * ty1 * c1345 * tmp1 - dt * ty1 * dy5; //--------------------------------------------------------------------- // form the third block sub-diagonal //--------------------------------------------------------------------- tmp1 = rho_i[k][j][i - 1]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; c[j][i][0][0] = -dt * tx1 * dx1; c[j][i][1][0] = -dt * tx2; c[j][i][2][0] = 0.0; c[j][i][3][0] = 0.0; c[j][i][4][0] = 0.0; c[j][i][0][1] = -dt * tx2 * (-(u[k][j][i - 1][1] * tmp1) * (u[k][j][i - 1][1] * tmp1) + 0.40e+00 * qs[k][j][i - 1] * tmp1) - dt * tx1 * (-r43 * c34 * tmp2 * u[k][j][i - 1][1]); c[j][i][1][1] = -dt * tx2 * ((2.0 - 0.40e+00) * (u[k][j][i - 1][1] * tmp1)) - dt * tx1 * (r43 * c34 * tmp1) - dt * tx1 * dx2; c[j][i][2][1] = -dt * tx2 * (-0.40e+00 * (u[k][j][i - 1][2] * tmp1)); c[j][i][3][1] = -dt * tx2 * (-0.40e+00 * (u[k][j][i - 1][3] * tmp1)); c[j][i][4][1] = -dt * tx2 * 0.40e+00; c[j][i][0][2] = -dt * tx2 * (-(u[k][j][i - 1][1] * u[k][j][i - 1][2]) * tmp2) - dt * tx1 * (-c34 * tmp2 * u[k][j][i - 1][2]); c[j][i][1][2] = -dt * tx2 * (u[k][j][i - 1][2] * tmp1); c[j][i][2][2] = -dt * tx2 * (u[k][j][i - 1][1] * tmp1) - dt * tx1 * (c34 * tmp1) - dt * tx1 * dx3; c[j][i][3][2] = 0.0; c[j][i][4][2] = 0.0; c[j][i][0][3] = -dt * tx2 * (-(u[k][j][i - 1][1] * u[k][j][i - 1][3]) * tmp2) - dt * tx1 * (-c34 * tmp2 * u[k][j][i - 1][3]); c[j][i][1][3] = -dt * tx2 * (u[k][j][i - 1][3] * tmp1); c[j][i][2][3] = 0.0; c[j][i][3][3] = -dt * tx2 * (u[k][j][i - 1][1] * tmp1) - dt * tx1 * (c34 * tmp1) - dt * tx1 * dx4; c[j][i][4][3] = 0.0; c[j][i][0][4] = -dt * tx2 * ((0.40e+00 * 2.0 * qs[k][j][i - 1] - 1.40e+00 * u[k][j][i - 1][4]) * u[k][j][i - 1][1] * tmp2) - dt * tx1 * (-(r43 * c34 - c1345) * tmp3 * (u[k][j][i - 1][1] * u[k][j][i - 1][1]) - (c34 - c1345) * tmp3 * (u[k][j][i - 1][2] * u[k][j][i - 1][2]) - (c34 - c1345) * tmp3 * (u[k][j][i - 1][3] * u[k][j][i - 1][3]) - c1345 * tmp2 * u[k][j][i - 1][4]); c[j][i][1][4] = -dt * tx2 * (1.40e+00 * (u[k][j][i - 1][4] * tmp1) - 0.40e+00 * (u[k][j][i - 1][1] * u[k][j][i - 1][1] * tmp2 + qs[k][j][i - 1] * tmp1)) - dt * tx1 * (r43 * c34 - c1345) * tmp2 * u[k][j][i - 1][1]; c[j][i][2][4] = -dt * tx2 * (-0.40e+00 * (u[k][j][i - 1][2] * u[k][j][i - 1][1]) * tmp2) - dt * tx1 * (c34 - c1345) * tmp2 * u[k][j][i - 1][2]; c[j][i][3][4] = -dt * tx2 * (-0.40e+00 * (u[k][j][i - 1][3] * u[k][j][i - 1][1]) * tmp2) - dt * tx1 * (c34 - c1345) * tmp2 * u[k][j][i - 1][3]; c[j][i][4][4] = -dt * tx2 * (1.40e+00 * (u[k][j][i - 1][1] * tmp1)) - dt * tx1 * c1345 * tmp1 - dt * tx1 * dx5; } } } //--------------------------------------------------------------------- // compute the upper triangular part of the jacobian matrix //--------------------------------------------------------------------- void jacu(int k) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j; double r43; double c1345; double c34; double tmp1, tmp2, tmp3; r43 = (4.0 / 3.0); c1345 = 1.40e+00 * 1.00e-01 * 1.00e+00 * 1.40e+00; c34 = 1.00e-01 * 1.00e+00; #pragma omp parallel for default(shared) private(j, i, tmp1, tmp2, tmp3) firstprivate(jst, jend, ist, iend, k, tx1, dx1, ty1, dy1, tz1, dz1, dt, r43, c34, dx2, dy2, dz2, dx3, dy3, dz3, dx4, dy4, dz4, c1345, dx5, dy5, dz5, tx2, ty2, tz2, rho_i, u, qs) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, tmp1, tmp2, tmp3) firstprivate(ist, iend, k, j, tx1, dx1, ty1, dy1, tz1, dz1, dt, r43, c34, dx2, dy2, dz2, dx3, dy3, dz3, dx4, dy4, dz4, c1345, dx5, dy5, dz5, tx2, ty2, tz2, rho_i, u, qs) for(i = ist; i < iend; i++) { //--------------------------------------------------------------------- // form the block daigonal //--------------------------------------------------------------------- tmp1 = rho_i[k][j][i]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; d[j][i][0][0] = 1.0 + dt * 2.0 * (tx1 * dx1 + ty1 * dy1 + tz1 * dz1); d[j][i][1][0] = 0.0; d[j][i][2][0] = 0.0; d[j][i][3][0] = 0.0; d[j][i][4][0] = 0.0; d[j][i][0][1] = dt * 2.0 * (-tx1 * r43 - ty1 - tz1) * (c34 * tmp2 * u[k][j][i][1]); d[j][i][1][1] = 1.0 + dt * 2.0 * c34 * tmp1 * (tx1 * r43 + ty1 + tz1) + dt * 2.0 * (tx1 * dx2 + ty1 * dy2 + tz1 * dz2); d[j][i][2][1] = 0.0; d[j][i][3][1] = 0.0; d[j][i][4][1] = 0.0; d[j][i][0][2] = dt * 2.0 * (-tx1 - ty1 * r43 - tz1) * (c34 * tmp2 * u[k][j][i][2]); d[j][i][1][2] = 0.0; d[j][i][2][2] = 1.0 + dt * 2.0 * c34 * tmp1 * (tx1 + ty1 * r43 + tz1) + dt * 2.0 * (tx1 * dx3 + ty1 * dy3 + tz1 * dz3); d[j][i][3][2] = 0.0; d[j][i][4][2] = 0.0; d[j][i][0][3] = dt * 2.0 * (-tx1 - ty1 - tz1 * r43) * (c34 * tmp2 * u[k][j][i][3]); d[j][i][1][3] = 0.0; d[j][i][2][3] = 0.0; d[j][i][3][3] = 1.0 + dt * 2.0 * c34 * tmp1 * (tx1 + ty1 + tz1 * r43) + dt * 2.0 * (tx1 * dx4 + ty1 * dy4 + tz1 * dz4); d[j][i][4][3] = 0.0; d[j][i][0][4] = -dt * 2.0 * (((tx1 * (r43 * c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (c34 - c1345)) * (u[k][j][i][1] * u[k][j][i][1]) + (tx1 * (c34 - c1345) + ty1 * (r43 * c34 - c1345) + tz1 * (c34 - c1345)) * (u[k][j][i][2] * u[k][j][i][2]) + (tx1 * (c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (r43 * c34 - c1345)) * (u[k][j][i][3] * u[k][j][i][3])) * tmp3 + (tx1 + ty1 + tz1) * c1345 * tmp2 * u[k][j][i][4]); d[j][i][1][4] = dt * 2.0 * (tx1 * (r43 * c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (c34 - c1345)) * tmp2 * u[k][j][i][1]; d[j][i][2][4] = dt * 2.0 * (tx1 * (c34 - c1345) + ty1 * (r43 * c34 - c1345) + tz1 * (c34 - c1345)) * tmp2 * u[k][j][i][2]; d[j][i][3][4] = dt * 2.0 * (tx1 * (c34 - c1345) + ty1 * (c34 - c1345) + tz1 * (r43 * c34 - c1345)) * tmp2 * u[k][j][i][3]; d[j][i][4][4] = 1.0 + dt * 2.0 * (tx1 + ty1 + tz1) * c1345 * tmp1 + dt * 2.0 * (tx1 * dx5 + ty1 * dy5 + tz1 * dz5); //--------------------------------------------------------------------- // form the first block sub-diagonal //--------------------------------------------------------------------- tmp1 = rho_i[k][j][i + 1]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; a[j][i][0][0] = -dt * tx1 * dx1; a[j][i][1][0] = dt * tx2; a[j][i][2][0] = 0.0; a[j][i][3][0] = 0.0; a[j][i][4][0] = 0.0; a[j][i][0][1] = dt * tx2 * (-(u[k][j][i + 1][1] * tmp1) * (u[k][j][i + 1][1] * tmp1) + 0.40e+00 * qs[k][j][i + 1] * tmp1) - dt * tx1 * (-r43 * c34 * tmp2 * u[k][j][i + 1][1]); a[j][i][1][1] = dt * tx2 * ((2.0 - 0.40e+00) * (u[k][j][i + 1][1] * tmp1)) - dt * tx1 * (r43 * c34 * tmp1) - dt * tx1 * dx2; a[j][i][2][1] = dt * tx2 * (-0.40e+00 * (u[k][j][i + 1][2] * tmp1)); a[j][i][3][1] = dt * tx2 * (-0.40e+00 * (u[k][j][i + 1][3] * tmp1)); a[j][i][4][1] = dt * tx2 * 0.40e+00; a[j][i][0][2] = dt * tx2 * (-(u[k][j][i + 1][1] * u[k][j][i + 1][2]) * tmp2) - dt * tx1 * (-c34 * tmp2 * u[k][j][i + 1][2]); a[j][i][1][2] = dt * tx2 * (u[k][j][i + 1][2] * tmp1); a[j][i][2][2] = dt * tx2 * (u[k][j][i + 1][1] * tmp1) - dt * tx1 * (c34 * tmp1) - dt * tx1 * dx3; a[j][i][3][2] = 0.0; a[j][i][4][2] = 0.0; a[j][i][0][3] = dt * tx2 * (-(u[k][j][i + 1][1] * u[k][j][i + 1][3]) * tmp2) - dt * tx1 * (-c34 * tmp2 * u[k][j][i + 1][3]); a[j][i][1][3] = dt * tx2 * (u[k][j][i + 1][3] * tmp1); a[j][i][2][3] = 0.0; a[j][i][3][3] = dt * tx2 * (u[k][j][i + 1][1] * tmp1) - dt * tx1 * (c34 * tmp1) - dt * tx1 * dx4; a[j][i][4][3] = 0.0; a[j][i][0][4] = dt * tx2 * ((0.40e+00 * 2.0 * qs[k][j][i + 1] - 1.40e+00 * u[k][j][i + 1][4]) * (u[k][j][i + 1][1] * tmp2)) - dt * tx1 * (-(r43 * c34 - c1345) * tmp3 * (u[k][j][i + 1][1] * u[k][j][i + 1][1]) - (c34 - c1345) * tmp3 * (u[k][j][i + 1][2] * u[k][j][i + 1][2]) - (c34 - c1345) * tmp3 * (u[k][j][i + 1][3] * u[k][j][i + 1][3]) - c1345 * tmp2 * u[k][j][i + 1][4]); a[j][i][1][4] = dt * tx2 * (1.40e+00 * (u[k][j][i + 1][4] * tmp1) - 0.40e+00 * (u[k][j][i + 1][1] * u[k][j][i + 1][1] * tmp2 + qs[k][j][i + 1] * tmp1)) - dt * tx1 * (r43 * c34 - c1345) * tmp2 * u[k][j][i + 1][1]; a[j][i][2][4] = dt * tx2 * (-0.40e+00 * (u[k][j][i + 1][2] * u[k][j][i + 1][1]) * tmp2) - dt * tx1 * (c34 - c1345) * tmp2 * u[k][j][i + 1][2]; a[j][i][3][4] = dt * tx2 * (-0.40e+00 * (u[k][j][i + 1][3] * u[k][j][i + 1][1]) * tmp2) - dt * tx1 * (c34 - c1345) * tmp2 * u[k][j][i + 1][3]; a[j][i][4][4] = dt * tx2 * (1.40e+00 * (u[k][j][i + 1][1] * tmp1)) - dt * tx1 * c1345 * tmp1 - dt * tx1 * dx5; //--------------------------------------------------------------------- // form the second block sub-diagonal //--------------------------------------------------------------------- tmp1 = rho_i[k][j + 1][i]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; b[j][i][0][0] = -dt * ty1 * dy1; b[j][i][1][0] = 0.0; b[j][i][2][0] = dt * ty2; b[j][i][3][0] = 0.0; b[j][i][4][0] = 0.0; b[j][i][0][1] = dt * ty2 * (-(u[k][j + 1][i][1] * u[k][j + 1][i][2]) * tmp2) - dt * ty1 * (-c34 * tmp2 * u[k][j + 1][i][1]); b[j][i][1][1] = dt * ty2 * (u[k][j + 1][i][2] * tmp1) - dt * ty1 * (c34 * tmp1) - dt * ty1 * dy2; b[j][i][2][1] = dt * ty2 * (u[k][j + 1][i][1] * tmp1); b[j][i][3][1] = 0.0; b[j][i][4][1] = 0.0; b[j][i][0][2] = dt * ty2 * (-(u[k][j + 1][i][2] * tmp1) * (u[k][j + 1][i][2] * tmp1) + 0.40e+00 * (qs[k][j + 1][i] * tmp1)) - dt * ty1 * (-r43 * c34 * tmp2 * u[k][j + 1][i][2]); b[j][i][1][2] = dt * ty2 * (-0.40e+00 * (u[k][j + 1][i][1] * tmp1)); b[j][i][2][2] = dt * ty2 * ((2.0 - 0.40e+00) * (u[k][j + 1][i][2] * tmp1)) - dt * ty1 * (r43 * c34 * tmp1) - dt * ty1 * dy3; b[j][i][3][2] = dt * ty2 * (-0.40e+00 * (u[k][j + 1][i][3] * tmp1)); b[j][i][4][2] = dt * ty2 * 0.40e+00; b[j][i][0][3] = dt * ty2 * (-(u[k][j + 1][i][2] * u[k][j + 1][i][3]) * tmp2) - dt * ty1 * (-c34 * tmp2 * u[k][j + 1][i][3]); b[j][i][1][3] = 0.0; b[j][i][2][3] = dt * ty2 * (u[k][j + 1][i][3] * tmp1); b[j][i][3][3] = dt * ty2 * (u[k][j + 1][i][2] * tmp1) - dt * ty1 * (c34 * tmp1) - dt * ty1 * dy4; b[j][i][4][3] = 0.0; b[j][i][0][4] = dt * ty2 * ((0.40e+00 * 2.0 * qs[k][j + 1][i] - 1.40e+00 * u[k][j + 1][i][4]) * (u[k][j + 1][i][2] * tmp2)) - dt * ty1 * (-(c34 - c1345) * tmp3 * (u[k][j + 1][i][1] * u[k][j + 1][i][1]) - (r43 * c34 - c1345) * tmp3 * (u[k][j + 1][i][2] * u[k][j + 1][i][2]) - (c34 - c1345) * tmp3 * (u[k][j + 1][i][3] * u[k][j + 1][i][3]) - c1345 * tmp2 * u[k][j + 1][i][4]); b[j][i][1][4] = dt * ty2 * (-0.40e+00 * (u[k][j + 1][i][1] * u[k][j + 1][i][2]) * tmp2) - dt * ty1 * (c34 - c1345) * tmp2 * u[k][j + 1][i][1]; b[j][i][2][4] = dt * ty2 * (1.40e+00 * (u[k][j + 1][i][4] * tmp1) - 0.40e+00 * (qs[k][j + 1][i] * tmp1 + u[k][j + 1][i][2] * u[k][j + 1][i][2] * tmp2)) - dt * ty1 * (r43 * c34 - c1345) * tmp2 * u[k][j + 1][i][2]; b[j][i][3][4] = dt * ty2 * (-0.40e+00 * (u[k][j + 1][i][2] * u[k][j + 1][i][3]) * tmp2) - dt * ty1 * (c34 - c1345) * tmp2 * u[k][j + 1][i][3]; b[j][i][4][4] = dt * ty2 * (1.40e+00 * (u[k][j + 1][i][2] * tmp1)) - dt * ty1 * c1345 * tmp1 - dt * ty1 * dy5; //--------------------------------------------------------------------- // form the third block sub-diagonal //--------------------------------------------------------------------- tmp1 = rho_i[k + 1][j][i]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; c[j][i][0][0] = -dt * tz1 * dz1; c[j][i][1][0] = 0.0; c[j][i][2][0] = 0.0; c[j][i][3][0] = dt * tz2; c[j][i][4][0] = 0.0; c[j][i][0][1] = dt * tz2 * (-(u[k + 1][j][i][1] * u[k + 1][j][i][3]) * tmp2) - dt * tz1 * (-c34 * tmp2 * u[k + 1][j][i][1]); c[j][i][1][1] = dt * tz2 * (u[k + 1][j][i][3] * tmp1) - dt * tz1 * c34 * tmp1 - dt * tz1 * dz2; c[j][i][2][1] = 0.0; c[j][i][3][1] = dt * tz2 * (u[k + 1][j][i][1] * tmp1); c[j][i][4][1] = 0.0; c[j][i][0][2] = dt * tz2 * (-(u[k + 1][j][i][2] * u[k + 1][j][i][3]) * tmp2) - dt * tz1 * (-c34 * tmp2 * u[k + 1][j][i][2]); c[j][i][1][2] = 0.0; c[j][i][2][2] = dt * tz2 * (u[k + 1][j][i][3] * tmp1) - dt * tz1 * (c34 * tmp1) - dt * tz1 * dz3; c[j][i][3][2] = dt * tz2 * (u[k + 1][j][i][2] * tmp1); c[j][i][4][2] = 0.0; c[j][i][0][3] = dt * tz2 * (-(u[k + 1][j][i][3] * tmp1) * (u[k + 1][j][i][3] * tmp1) + 0.40e+00 * (qs[k + 1][j][i] * tmp1)) - dt * tz1 * (-r43 * c34 * tmp2 * u[k + 1][j][i][3]); c[j][i][1][3] = dt * tz2 * (-0.40e+00 * (u[k + 1][j][i][1] * tmp1)); c[j][i][2][3] = dt * tz2 * (-0.40e+00 * (u[k + 1][j][i][2] * tmp1)); c[j][i][3][3] = dt * tz2 * (2.0 - 0.40e+00) * (u[k + 1][j][i][3] * tmp1) - dt * tz1 * (r43 * c34 * tmp1) - dt * tz1 * dz4; c[j][i][4][3] = dt * tz2 * 0.40e+00; c[j][i][0][4] = dt * tz2 * ((0.40e+00 * 2.0 * qs[k + 1][j][i] - 1.40e+00 * u[k + 1][j][i][4]) * (u[k + 1][j][i][3] * tmp2)) - dt * tz1 * (-(c34 - c1345) * tmp3 * (u[k + 1][j][i][1] * u[k + 1][j][i][1]) - (c34 - c1345) * tmp3 * (u[k + 1][j][i][2] * u[k + 1][j][i][2]) - (r43 * c34 - c1345) * tmp3 * (u[k + 1][j][i][3] * u[k + 1][j][i][3]) - c1345 * tmp2 * u[k + 1][j][i][4]); c[j][i][1][4] = dt * tz2 * (-0.40e+00 * (u[k + 1][j][i][1] * u[k + 1][j][i][3]) * tmp2) - dt * tz1 * (c34 - c1345) * tmp2 * u[k + 1][j][i][1]; c[j][i][2][4] = dt * tz2 * (-0.40e+00 * (u[k + 1][j][i][2] * u[k + 1][j][i][3]) * tmp2) - dt * tz1 * (c34 - c1345) * tmp2 * u[k + 1][j][i][2]; c[j][i][3][4] = dt * tz2 * (1.40e+00 * (u[k + 1][j][i][4] * tmp1) - 0.40e+00 * (qs[k + 1][j][i] * tmp1 + u[k + 1][j][i][3] * u[k + 1][j][i][3] * tmp2)) - dt * tz1 * (r43 * c34 - c1345) * tmp2 * u[k + 1][j][i][3]; c[j][i][4][4] = dt * tz2 * (1.40e+00 * (u[k + 1][j][i][3] * tmp1)) - dt * tz1 * c1345 * tmp1 - dt * tz1 * dz5; } } } //--------------------------------------------------------------------- // to compute the l2-norm of vector v. //--------------------------------------------------------------------- //--------------------------------------------------------------------- // To improve cache performance, second two dimensions padded by 1 // for even number sizes only. Only needed in v. //--------------------------------------------------------------------- void l2norm(int ldx, int ldy, int ldz, int nx0, int ny0, int nz0, int ist, int iend, int jst, int jend, double v[][ldy / 2 * 2 + 1][ldx / 2 * 2 + 1][5], double sum[5]) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { sum[m] = 0.0; } #pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz0, jst, jend, ist, iend, v) reduction(+ : sum[:5]) for(k = 1; k < nz0 - 1; k++) { // #pragma omp parallel for default(shared) private(j, i, m) firstprivate(jst, jend, ist, iend, k, v) reduction(+ : sum[:5]) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, k, j, v) reduction(+ : sum[:5]) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { sum[m] = sum[m] + v[k][j][i][m] * v[k][j][i][m]; } } } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { sum[m] = sqrt(sum[m] / ((nx0 - 2) * (ny0 - 2) * (nz0 - 2))); } } void pintgr() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k; int ibeg, ifin, ifin1; int jbeg, jfin, jfin1; double phi1[35][35]; double phi2[35][35]; double frc1, frc2, frc3; //--------------------------------------------------------------------- // set up the sub-domains for integeration in each processor //--------------------------------------------------------------------- ibeg = ii1; ifin = ii2; jbeg = ji1; jfin = ji2; ifin1 = ifin - 1; jfin1 = jfin - 1; //--------------------------------------------------------------------- // initialize //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(k = 0; k <= 33 + 1; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(i = 0; i <= 33 + 1; i++) { phi1[k][i] = 0.0; phi2[k][i] = 0.0; } } #pragma omp parallel for default(shared) private(j, i, k) firstprivate(jbeg, jfin, ibeg, ifin, ki1, ki2, u) for(j = jbeg; j < jfin; j++) { // #pragma omp parallel for default(shared) private(i, k) firstprivate(ibeg, ifin, ki1, j, ki2, u) for(i = ibeg; i < ifin; i++) { k = ki1; phi1[j][i] = 0.40e+00 * (u[k][j][i][4] - 0.50 * (u[k][j][i][1] * u[k][j][i][1] + u[k][j][i][2] * u[k][j][i][2] + u[k][j][i][3] * u[k][j][i][3]) / u[k][j][i][0]); k = ki2 - 1; phi2[j][i] = 0.40e+00 * (u[k][j][i][4] - 0.50 * (u[k][j][i][1] * u[k][j][i][1] + u[k][j][i][2] * u[k][j][i][2] + u[k][j][i][3] * u[k][j][i][3]) / u[k][j][i][0]); } } frc1 = 0.0; #pragma omp parallel for default(shared) private(j, i) firstprivate(jbeg, jfin1, ibeg, ifin1, phi1, phi2) reduction(+ : frc1) for(j = jbeg; j < jfin1; j++) { // #pragma omp parallel for default(shared) private(i) firstprivate(ibeg, ifin1, j, phi1, phi2) reduction(+ : frc1) for(i = ibeg; i < ifin1; i++) { frc1 = frc1 + (phi1[j][i] + phi1[j][i + 1] + phi1[j + 1][i] + phi1[j + 1][i + 1] + phi2[j][i] + phi2[j][i + 1] + phi2[j + 1][i] + phi2[j + 1][i + 1]); } } frc1 = dxi * deta * frc1; //--------------------------------------------------------------------- // initialize //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(k = 0; k <= 33 + 1; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(i = 0; i <= 33 + 1; i++) { phi1[k][i] = 0.0; phi2[k][i] = 0.0; } } if(jbeg == ji1) { #pragma omp parallel for default(shared) private(k, i) firstprivate(ki1, ki2, ibeg, ifin, jbeg, u) for(k = ki1; k < ki2; k++) { // #pragma omp parallel for default(shared) private(i) firstprivate(ibeg, ifin, k, jbeg, u) for(i = ibeg; i < ifin; i++) { phi1[k][i] = 0.40e+00 * (u[k][jbeg][i][4] - 0.50 * (u[k][jbeg][i][1] * u[k][jbeg][i][1] + u[k][jbeg][i][2] * u[k][jbeg][i][2] + u[k][jbeg][i][3] * u[k][jbeg][i][3]) / u[k][jbeg][i][0]); } } } if(jfin == ji2) { #pragma omp parallel for default(shared) private(k, i) firstprivate(ki1, ki2, ibeg, ifin, jfin, u) for(k = ki1; k < ki2; k++) { // #pragma omp parallel for default(shared) private(i) firstprivate(ibeg, ifin, jfin, k, u) for(i = ibeg; i < ifin; i++) { phi2[k][i] = 0.40e+00 * (u[k][jfin - 1][i][4] - 0.50 * (u[k][jfin - 1][i][1] * u[k][jfin - 1][i][1] + u[k][jfin - 1][i][2] * u[k][jfin - 1][i][2] + u[k][jfin - 1][i][3] * u[k][jfin - 1][i][3]) / u[k][jfin - 1][i][0]); } } } frc2 = 0.0; #pragma omp parallel for default(shared) private(k, i) firstprivate(ki1, ki2, ibeg, ifin1, phi1, phi2) reduction(+ : frc2) for(k = ki1; k < ki2 - 1; k++) { // #pragma omp parallel for default(shared) private(i) firstprivate(ibeg, ifin1, k, phi1, phi2) reduction(+ : frc2) for(i = ibeg; i < ifin1; i++) { frc2 = frc2 + (phi1[k][i] + phi1[k][i + 1] + phi1[k + 1][i] + phi1[k + 1][i + 1] + phi2[k][i] + phi2[k][i + 1] + phi2[k + 1][i] + phi2[k + 1][i + 1]); } } frc2 = dxi * dzeta * frc2; //--------------------------------------------------------------------- // initialize //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(k = 0; k <= 33 + 1; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(i = 0; i <= 33 + 1; i++) { phi1[k][i] = 0.0; phi2[k][i] = 0.0; } } if(ibeg == ii1) { #pragma omp parallel for default(shared) private(k, j) firstprivate(ki1, ki2, jbeg, jfin, ibeg, u) for(k = ki1; k < ki2; k++) { // #pragma omp parallel for default(shared) private(j) firstprivate(jbeg, jfin, k, ibeg, u) for(j = jbeg; j < jfin; j++) { phi1[k][j] = 0.40e+00 * (u[k][j][ibeg][4] - 0.50 * (u[k][j][ibeg][1] * u[k][j][ibeg][1] + u[k][j][ibeg][2] * u[k][j][ibeg][2] + u[k][j][ibeg][3] * u[k][j][ibeg][3]) / u[k][j][ibeg][0]); } } } if(ifin == ii2) { #pragma omp parallel for default(shared) private(k, j) firstprivate(ki1, ki2, jbeg, jfin, ifin, u) for(k = ki1; k < ki2; k++) { // #pragma omp parallel for default(shared) private(j) firstprivate(jbeg, jfin, ifin, k, u) for(j = jbeg; j < jfin; j++) { phi2[k][j] = 0.40e+00 * (u[k][j][ifin - 1][4] - 0.50 * (u[k][j][ifin - 1][1] * u[k][j][ifin - 1][1] + u[k][j][ifin - 1][2] * u[k][j][ifin - 1][2] + u[k][j][ifin - 1][3] * u[k][j][ifin - 1][3]) / u[k][j][ifin - 1][0]); } } } frc3 = 0.0; #pragma omp parallel for default(shared) private(k, j) firstprivate(ki1, ki2, jbeg, jfin1, phi1, phi2) reduction(+ : frc3) for(k = ki1; k < ki2 - 1; k++) { // #pragma omp parallel for default(shared) private(j) firstprivate(jbeg, jfin1, k, phi1, phi2) reduction(+ : frc3) for(j = jbeg; j < jfin1; j++) { frc3 = frc3 + (phi1[k][j] + phi1[k][j + 1] + phi1[k + 1][j] + phi1[k + 1][j + 1] + phi2[k][j] + phi2[k][j + 1] + phi2[k + 1][j] + phi2[k + 1][j + 1]); } } frc3 = deta * dzeta * frc3; frc = 0.25 * (frc1 + frc2 + frc3); //printf("\n\n surface integral = %12.5E\n\n\n", frc); } void read_input() { FILE *fp; int result; //--------------------------------------------------------------------- // if input file does not exist, it uses defaults // ipr = 1 for detailed progress output // inorm = how often the norm is printed (once every inorm iterations) // itmax = number of pseudo time steps // dt = time step // omega 1 over-relaxation factor for SSOR // tolrsd = steady state residual tolerance levels // nx, ny, nz = number of grid points in x, y, z directions //--------------------------------------------------------------------- printf("\n\n NAS Parallel Benchmarks (NPB3.3-SER-C) - LU Benchmark\n\n"); if((fp = fopen("inputlu.data", "r")) != ((void *) 0)) { printf("Reading from input file inputlu.data\n"); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); result = fscanf(fp, "%d%d", &ipr, &inorm); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); result = fscanf(fp, "%d", &itmax); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); result = fscanf(fp, "%lf", &dt); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); result = fscanf(fp, "%lf", &omega); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); result = fscanf(fp, "%lf%lf%lf%lf%lf", &tolrsd[0], &tolrsd[1], &tolrsd[2], &tolrsd[3], &tolrsd[4]); while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); result = fscanf(fp, "%d%d%d", &nx0, &ny0, &nz0); fclose(fp); } else { ipr = 1; inorm = 300; itmax = 300; dt = 1.5e-3; omega = 1.2; tolrsd[0] = 1.0e-08; tolrsd[1] = 1.0e-08; tolrsd[2] = 1.0e-08; tolrsd[3] = 1.0e-08; tolrsd[4] = 1.0e-08; nx0 = 33; ny0 = 33; nz0 = 33; } //--------------------------------------------------------------------- // check problem size //--------------------------------------------------------------------- if((nx0 < 4) || (ny0 < 4) || (nz0 < 4)) { printf(" PROBLEM SIZE IS TOO SMALL - \n SET EACH OF NX, NY AND NZ AT LEAST EQUAL TO 5\n"); exit(1); } if((nx0 > 33) || (ny0 > 33) || (nz0 > 33)) { printf(" PROBLEM SIZE IS TOO LARGE - \n NX, NY AND NZ SHOULD BE EQUAL TO \n ISIZ1, ISIZ2 AND ISIZ3 RESPECTIVELY\n"); exit(1); } printf(" Size: %4dx%4dx%4d\n", nx0, ny0, nz0); printf(" Iterations: %4d\n", itmax); printf("\n"); } //--------------------------------------------------------------------- // compute the right hand sides //--------------------------------------------------------------------- void rhs() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; double q; double tmp; double utmp[33][6]; double rtmp[33][5]; double u21, u31, u41; double u21i, u31i, u41i, u51i; double u21j, u31j, u41j, u51j; double u21k, u31k, u41k, u51k; double u21im1, u31im1, u41im1, u51im1; double u21jm1, u31jm1, u41jm1, u51jm1; double u21km1, u31km1, u41km1, u51km1; #pragma omp parallel for default(shared) private(k, j, i, m, tmp) firstprivate(nz, ny, nx, frct, u) for(k = 0; k < nz; k++) { // #pragma omp parallel for default(shared) private(j, i, m, tmp) firstprivate(ny, nx, k, frct, u) for(j = 0; j < ny; j++) { // #pragma omp parallel for default(shared) private(i, m, tmp) firstprivate(nx, k, j, frct, u) for(i = 0; i < nx; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = -frct[k][j][i][m]; } tmp = 1.0 / u[k][j][i][0]; rho_i[k][j][i] = tmp; qs[k][j][i] = 0.50 * (u[k][j][i][1] * u[k][j][i][1] + u[k][j][i][2] * u[k][j][i][2] + u[k][j][i][3] * u[k][j][i][3]) * tmp; } } } //--------------------------------------------------------------------- // xi-direction flux differences //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, j, i, m, u21, q, tmp, u21i, u31i, u41i, u51i, u21im1, u31im1, u41im1, u51im1) firstprivate(nz, jst, jend, nx, ist, iend, tx2, tx3, dx1, tx1, dx2, dx3, dx4, dx5, dssp, u, rho_i, qs, flux) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(j, i, m, u21, q, tmp, u21i, u31i, u41i, u51i, u21im1, u31im1, u41im1, u51im1) firstprivate(jst, jend, nx, k, ist, iend, tx2, tx3, dx1, tx1, dx2, dx3, dx4, dx5, dssp, u, rho_i, qs, flux) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, u21, q) firstprivate(nx, k, j, u, rho_i, qs) for(i = 0; i < nx; i++) { flux[i][0] = u[k][j][i][1]; u21 = u[k][j][i][1] * rho_i[k][j][i]; q = qs[k][j][i]; flux[i][1] = u[k][j][i][1] * u21 + 0.40e+00 * (u[k][j][i][4] - q); flux[i][2] = u[k][j][i][2] * u21; flux[i][3] = u[k][j][i][3] * u21; flux[i][4] = (1.40e+00 * u[k][j][i][4] - 0.40e+00 * q) * u21; } // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, tx2, k, j, flux) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = rsd[k][j][i][m] - tx2 * (flux[i + 1][m] - flux[i - 1][m]); } } // #pragma omp parallel for default(shared) private(i, tmp, u21i, u31i, u41i, u51i, u21im1, u31im1, u41im1, u51im1) firstprivate(ist, nx, k, j, tx3, rho_i, u) for(i = ist; i < nx; i++) { tmp = rho_i[k][j][i]; u21i = tmp * u[k][j][i][1]; u31i = tmp * u[k][j][i][2]; u41i = tmp * u[k][j][i][3]; u51i = tmp * u[k][j][i][4]; tmp = rho_i[k][j][i - 1]; u21im1 = tmp * u[k][j][i - 1][1]; u31im1 = tmp * u[k][j][i - 1][2]; u41im1 = tmp * u[k][j][i - 1][3]; u51im1 = tmp * u[k][j][i - 1][4]; flux[i][1] = (4.0 / 3.0) * tx3 * (u21i - u21im1); flux[i][2] = tx3 * (u31i - u31im1); flux[i][3] = tx3 * (u41i - u41im1); flux[i][4] = 0.50 * (1.0 - 1.40e+00 * 1.40e+00) * tx3 * ((u21i * u21i + u31i * u31i + u41i * u41i) - (u21im1 * u21im1 + u31im1 * u31im1 + u41im1 * u41im1)) + (1.0 / 6.0) * tx3 * (u21i * u21i - u21im1 * u21im1) + 1.40e+00 * 1.40e+00 * tx3 * (u51i - u51im1); } // #pragma omp parallel for default(shared) private(i) firstprivate(ist, iend, k, j, dx1, tx1, tx3, dx2, dx3, dx4, dx5, u, flux) for(i = ist; i < iend; i++) { rsd[k][j][i][0] = rsd[k][j][i][0] + dx1 * tx1 * (u[k][j][i - 1][0] - 2.0 * u[k][j][i][0] + u[k][j][i + 1][0]); rsd[k][j][i][1] = rsd[k][j][i][1] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][1] - flux[i][1]) + dx2 * tx1 * (u[k][j][i - 1][1] - 2.0 * u[k][j][i][1] + u[k][j][i + 1][1]); rsd[k][j][i][2] = rsd[k][j][i][2] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][2] - flux[i][2]) + dx3 * tx1 * (u[k][j][i - 1][2] - 2.0 * u[k][j][i][2] + u[k][j][i + 1][2]); rsd[k][j][i][3] = rsd[k][j][i][3] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][3] - flux[i][3]) + dx4 * tx1 * (u[k][j][i - 1][3] - 2.0 * u[k][j][i][3] + u[k][j][i + 1][3]); rsd[k][j][i][4] = rsd[k][j][i][4] + tx3 * 1.00e-01 * 1.00e+00 * (flux[i + 1][4] - flux[i][4]) + dx5 * tx1 * (u[k][j][i - 1][4] - 2.0 * u[k][j][i][4] + u[k][j][i + 1][4]); } //--------------------------------------------------------------------- // Fourth-order dissipation //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][1][m] = rsd[k][j][1][m] - dssp * (+5.0 * u[k][j][1][m] - 4.0 * u[k][j][2][m] + u[k][j][3][m]); rsd[k][j][2][m] = rsd[k][j][2][m] - dssp * (-4.0 * u[k][j][1][m] + 6.0 * u[k][j][2][m] - 4.0 * u[k][j][3][m] + u[k][j][4][m]); } // #pragma omp parallel for default(shared) private(i, m) firstprivate(nx, k, j, dssp, u) for(i = 3; i < nx - 3; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = rsd[k][j][i][m] - dssp * (u[k][j][i - 2][m] - 4.0 * u[k][j][i - 1][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j][i + 1][m] + u[k][j][i + 2][m]); } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][nx - 3][m] = rsd[k][j][nx - 3][m] - dssp * (u[k][j][nx - 5][m] - 4.0 * u[k][j][nx - 4][m] + 6.0 * u[k][j][nx - 3][m] - 4.0 * u[k][j][nx - 2][m]); rsd[k][j][nx - 2][m] = rsd[k][j][nx - 2][m] - dssp * (u[k][j][nx - 4][m] - 4.0 * u[k][j][nx - 3][m] + 5.0 * u[k][j][nx - 2][m]); } } } //--------------------------------------------------------------------- // eta-direction flux differences //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, i, j, m, u31, q, tmp, u21j, u31j, u41j, u51j, u21jm1, u31jm1, u41jm1, u51jm1) firstprivate(nz, ist, iend, ny, jst, jend, ty2, ty3, dy1, ty1, dy2, dy3, dy4, dy5, dssp, u, rho_i, qs, flux) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(i, j, m, u31, q, tmp, u21j, u31j, u41j, u51j, u21jm1, u31jm1, u41jm1, u51jm1) firstprivate(ist, iend, ny, k, jst, jend, ty2, ty3, dy1, ty1, dy2, dy3, dy4, dy5, u, rho_i, qs, flux) for(i = ist; i < iend; i++) { // #pragma omp parallel for default(shared) private(j, u31, q) firstprivate(ny, k, i, u, rho_i, qs) for(j = 0; j < ny; j++) { flux[j][0] = u[k][j][i][2]; u31 = u[k][j][i][2] * rho_i[k][j][i]; q = qs[k][j][i]; flux[j][1] = u[k][j][i][1] * u31; flux[j][2] = u[k][j][i][2] * u31 + 0.40e+00 * (u[k][j][i][4] - q); flux[j][3] = u[k][j][i][3] * u31; flux[j][4] = (1.40e+00 * u[k][j][i][4] - 0.40e+00 * q) * u31; } // #pragma omp parallel for default(shared) private(j, m) firstprivate(jst, jend, ty2, k, i, flux) for(j = jst; j < jend; j++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = rsd[k][j][i][m] - ty2 * (flux[j + 1][m] - flux[j - 1][m]); } } // #pragma omp parallel for default(shared) private(j, tmp, u21j, u31j, u41j, u51j, u21jm1, u31jm1, u41jm1, u51jm1) firstprivate(jst, ny, k, i, ty3, rho_i, u) for(j = jst; j < ny; j++) { tmp = rho_i[k][j][i]; u21j = tmp * u[k][j][i][1]; u31j = tmp * u[k][j][i][2]; u41j = tmp * u[k][j][i][3]; u51j = tmp * u[k][j][i][4]; tmp = rho_i[k][j - 1][i]; u21jm1 = tmp * u[k][j - 1][i][1]; u31jm1 = tmp * u[k][j - 1][i][2]; u41jm1 = tmp * u[k][j - 1][i][3]; u51jm1 = tmp * u[k][j - 1][i][4]; flux[j][1] = ty3 * (u21j - u21jm1); flux[j][2] = (4.0 / 3.0) * ty3 * (u31j - u31jm1); flux[j][3] = ty3 * (u41j - u41jm1); flux[j][4] = 0.50 * (1.0 - 1.40e+00 * 1.40e+00) * ty3 * ((u21j * u21j + u31j * u31j + u41j * u41j) - (u21jm1 * u21jm1 + u31jm1 * u31jm1 + u41jm1 * u41jm1)) + (1.0 / 6.0) * ty3 * (u31j * u31j - u31jm1 * u31jm1) + 1.40e+00 * 1.40e+00 * ty3 * (u51j - u51jm1); } // #pragma omp parallel for default(shared) private(j) firstprivate(jst, jend, k, i, dy1, ty1, ty3, dy2, dy3, dy4, dy5, u, flux) for(j = jst; j < jend; j++) { rsd[k][j][i][0] = rsd[k][j][i][0] + dy1 * ty1 * (u[k][j - 1][i][0] - 2.0 * u[k][j][i][0] + u[k][j + 1][i][0]); rsd[k][j][i][1] = rsd[k][j][i][1] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][1] - flux[j][1]) + dy2 * ty1 * (u[k][j - 1][i][1] - 2.0 * u[k][j][i][1] + u[k][j + 1][i][1]); rsd[k][j][i][2] = rsd[k][j][i][2] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][2] - flux[j][2]) + dy3 * ty1 * (u[k][j - 1][i][2] - 2.0 * u[k][j][i][2] + u[k][j + 1][i][2]); rsd[k][j][i][3] = rsd[k][j][i][3] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][3] - flux[j][3]) + dy4 * ty1 * (u[k][j - 1][i][3] - 2.0 * u[k][j][i][3] + u[k][j + 1][i][3]); rsd[k][j][i][4] = rsd[k][j][i][4] + ty3 * 1.00e-01 * 1.00e+00 * (flux[j + 1][4] - flux[j][4]) + dy5 * ty1 * (u[k][j - 1][i][4] - 2.0 * u[k][j][i][4] + u[k][j + 1][i][4]); } } //--------------------------------------------------------------------- // fourth-order dissipation //--------------------------------------------------------------------- // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, k, dssp, u) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][1][i][m] = rsd[k][1][i][m] - dssp * (+5.0 * u[k][1][i][m] - 4.0 * u[k][2][i][m] + u[k][3][i][m]); rsd[k][2][i][m] = rsd[k][2][i][m] - dssp * (-4.0 * u[k][1][i][m] + 6.0 * u[k][2][i][m] - 4.0 * u[k][3][i][m] + u[k][4][i][m]); } } // #pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny, ist, iend, k, dssp, u) for(j = 3; j < ny - 3; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, j, k, dssp, u) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = rsd[k][j][i][m] - dssp * (u[k][j - 2][i][m] - 4.0 * u[k][j - 1][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j + 1][i][m] + u[k][j + 2][i][m]); } } } // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, ny, k, dssp, u) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][ny - 3][i][m] = rsd[k][ny - 3][i][m] - dssp * (u[k][ny - 5][i][m] - 4.0 * u[k][ny - 4][i][m] + 6.0 * u[k][ny - 3][i][m] - 4.0 * u[k][ny - 2][i][m]); rsd[k][ny - 2][i][m] = rsd[k][ny - 2][i][m] - dssp * (u[k][ny - 4][i][m] - 4.0 * u[k][ny - 3][i][m] + 5.0 * u[k][ny - 2][i][m]); } } } //--------------------------------------------------------------------- // zeta-direction flux differences //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j, i, k, m, u41, q, tmp, u21k, u31k, u41k, u51k, u21km1, u31km1, u41km1, u51km1) firstprivate(jst, jend, ist, iend, nz, tz2, tz3, dz1, tz1, dz2, dz3, dz4, dz5, dssp, u, rho_i, qs, utmp, flux, rtmp) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, k, m, u41, q, tmp, u21k, u31k, u41k, u51k, u21km1, u31km1, u41km1, u51km1) firstprivate(ist, iend, nz, j, tz2, tz3, dz1, tz1, dz2, dz3, dz4, dz5, dssp, u, rho_i, qs, utmp, flux, rtmp) for(i = ist; i < iend; i++) { // #pragma omp parallel for default(shared) private(k) firstprivate(nz, j, i, u, rho_i) for(k = 0; k < nz; k++) { utmp[k][0] = u[k][j][i][0]; utmp[k][1] = u[k][j][i][1]; utmp[k][2] = u[k][j][i][2]; utmp[k][3] = u[k][j][i][3]; utmp[k][4] = u[k][j][i][4]; utmp[k][5] = rho_i[k][j][i]; } // #pragma omp parallel for default(shared) private(k, u41, q) firstprivate(nz, j, i, utmp, qs) for(k = 0; k < nz; k++) { flux[k][0] = utmp[k][3]; u41 = utmp[k][3] * utmp[k][5]; q = qs[k][j][i]; flux[k][1] = utmp[k][1] * u41; flux[k][2] = utmp[k][2] * u41; flux[k][3] = utmp[k][3] * u41 + 0.40e+00 * (utmp[k][4] - q); flux[k][4] = (1.40e+00 * utmp[k][4] - 0.40e+00 * q) * u41; } // #pragma omp parallel for default(shared) private(k, m) firstprivate(nz, tz2, j, i, flux, rsd) for(k = 1; k < nz - 1; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rtmp[k][m] = rsd[k][j][i][m] - tz2 * (flux[k + 1][m] - flux[k - 1][m]); } } // #pragma omp parallel for default(shared) private(k, tmp, u21k, u31k, u41k, u51k, u21km1, u31km1, u41km1, u51km1) firstprivate(nz, tz3, utmp) for(k = 1; k < nz; k++) { tmp = utmp[k][5]; u21k = tmp * utmp[k][1]; u31k = tmp * utmp[k][2]; u41k = tmp * utmp[k][3]; u51k = tmp * utmp[k][4]; tmp = utmp[k - 1][5]; u21km1 = tmp * utmp[k - 1][1]; u31km1 = tmp * utmp[k - 1][2]; u41km1 = tmp * utmp[k - 1][3]; u51km1 = tmp * utmp[k - 1][4]; flux[k][1] = tz3 * (u21k - u21km1); flux[k][2] = tz3 * (u31k - u31km1); flux[k][3] = (4.0 / 3.0) * tz3 * (u41k - u41km1); flux[k][4] = 0.50 * (1.0 - 1.40e+00 * 1.40e+00) * tz3 * ((u21k * u21k + u31k * u31k + u41k * u41k) - (u21km1 * u21km1 + u31km1 * u31km1 + u41km1 * u41km1)) + (1.0 / 6.0) * tz3 * (u41k * u41k - u41km1 * u41km1) + 1.40e+00 * 1.40e+00 * tz3 * (u51k - u51km1); } // #pragma omp parallel for default(shared) private(k) firstprivate(nz, dz1, tz1, tz3, dz2, dz3, dz4, dz5, utmp, flux) for(k = 1; k < nz - 1; k++) { rtmp[k][0] = rtmp[k][0] + dz1 * tz1 * (utmp[k - 1][0] - 2.0 * utmp[k][0] + utmp[k + 1][0]); rtmp[k][1] = rtmp[k][1] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][1] - flux[k][1]) + dz2 * tz1 * (utmp[k - 1][1] - 2.0 * utmp[k][1] + utmp[k + 1][1]); rtmp[k][2] = rtmp[k][2] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][2] - flux[k][2]) + dz3 * tz1 * (utmp[k - 1][2] - 2.0 * utmp[k][2] + utmp[k + 1][2]); rtmp[k][3] = rtmp[k][3] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][3] - flux[k][3]) + dz4 * tz1 * (utmp[k - 1][3] - 2.0 * utmp[k][3] + utmp[k + 1][3]); rtmp[k][4] = rtmp[k][4] + tz3 * 1.00e-01 * 1.00e+00 * (flux[k + 1][4] - flux[k][4]) + dz5 * tz1 * (utmp[k - 1][4] - 2.0 * utmp[k][4] + utmp[k + 1][4]); } //--------------------------------------------------------------------- // fourth-order dissipation //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[1][j][i][m] = rtmp[1][m] - dssp * (+5.0 * utmp[1][m] - 4.0 * utmp[2][m] + utmp[3][m]); rsd[2][j][i][m] = rtmp[2][m] - dssp * (-4.0 * utmp[1][m] + 6.0 * utmp[2][m] - 4.0 * utmp[3][m] + utmp[4][m]); } // #pragma omp parallel for default(shared) private(k, m) firstprivate(nz, dssp, j, i, utmp, rtmp) for(k = 3; k < nz - 3; k++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = rtmp[k][m] - dssp * (utmp[k - 2][m] - 4.0 * utmp[k - 1][m] + 6.0 * utmp[k][m] - 4.0 * utmp[k + 1][m] + utmp[k + 2][m]); } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[nz - 3][j][i][m] = rtmp[nz - 3][m] - dssp * (utmp[nz - 5][m] - 4.0 * utmp[nz - 4][m] + 6.0 * utmp[nz - 3][m] - 4.0 * utmp[nz - 2][m]); rsd[nz - 2][j][i][m] = rtmp[nz - 2][m] - dssp * (utmp[nz - 4][m] - 4.0 * utmp[nz - 3][m] + 5.0 * utmp[nz - 2][m]); } } } } //--------------------------------------------------------------------- // set the boundary values of dependent variables //--------------------------------------------------------------------- void setbv() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; double temp1[5]; double temp2[5]; //--------------------------------------------------------------------- // set the dependent variable values along the top and bottom faces //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny, nx, nx0, ny0, nz, ce, temp1, temp2) for(j = 0; j < ny; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(nx, j, nx0, ny0, nz, ce, temp1, temp2) for(i = 0; i < nx; i++) { exact(i, j, 0, temp1); exact(i, j, nz - 1, temp2); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { u[0][j][i][m] = temp1[m]; u[nz - 1][j][i][m] = temp2[m]; } } } //--------------------------------------------------------------------- // set the dependent variable values along north and south faces //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, i, m) firstprivate(nz, nx, nx0, ny0, ny, ce, temp1, temp2) for(k = 0; k < nz; k++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(nx, k, nx0, ny0, nz, ny, ce, temp1, temp2) for(i = 0; i < nx; i++) { exact(i, 0, k, temp1); exact(i, ny - 1, k, temp2); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { u[k][0][i][m] = temp1[m]; u[k][ny - 1][i][m] = temp2[m]; } } } //--------------------------------------------------------------------- // set the dependent variable values along east and west faces //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, j, m) firstprivate(nz, ny, nx0, ny0, nx, ce, temp1, temp2) for(k = 0; k < nz; k++) { // #pragma omp parallel for default(shared) private(j, m) firstprivate(ny, k, nx0, ny0, nz, nx, ce, temp1, temp2) for(j = 0; j < ny; j++) { exact(0, j, k, temp1); exact(nx - 1, j, k, temp2); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { u[k][j][0][m] = temp1[m]; u[k][j][nx - 1][m] = temp2[m]; } } } } //--------------------------------------------------------------------- // // set the initial values of independent variables based on tri-linear // interpolation of boundary values in the computational space. // //--------------------------------------------------------------------- void setiv() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; double xi, eta, zeta; double pxi, peta, pzeta; double ue_1jk[5]; double ue_nx0jk[5]; double ue_i1k[5]; double ue_iny0k[5]; double ue_ij1[5]; double ue_ijnz[5]; #pragma omp parallel for default(shared) private(k, j, i, m, zeta, eta, xi, pxi, peta, pzeta) firstprivate(nz, ny, ny0, nx, nx0, ce, ue_1jk, ue_nx0jk, ue_i1k, ue_iny0k, ue_ij1, ue_ijnz) for(k = 1; k < nz - 1; k++) { zeta = ((double) k) / (nz - 1); // #pragma omp parallel for default(shared) private(j, i, m, eta, xi, pxi, peta, pzeta) firstprivate(ny, ny0, nx, nx0, k, nz, zeta, ce, ue_1jk, ue_nx0jk, ue_i1k, ue_iny0k, ue_ij1, ue_ijnz) for(j = 1; j < ny - 1; j++) { eta = ((double) j) / (ny0 - 1); // #pragma omp parallel for default(shared) private(i, m, xi, pxi, peta, pzeta) firstprivate(nx, nx0, k, j, ny0, nz, eta, zeta, ce, ue_1jk, ue_nx0jk, ue_i1k, ue_iny0k, ue_ij1, ue_ijnz) for(i = 1; i < nx - 1; i++) { xi = ((double) i) / (nx0 - 1); exact(0, j, k, ue_1jk); exact(nx0 - 1, j, k, ue_nx0jk); exact(i, 0, k, ue_i1k); exact(i, ny0 - 1, k, ue_iny0k); exact(i, j, 0, ue_ij1); exact(i, j, nz - 1, ue_ijnz); /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { pxi = (1.0 - xi) * ue_1jk[m] + xi * ue_nx0jk[m]; peta = (1.0 - eta) * ue_i1k[m] + eta * ue_iny0k[m]; pzeta = (1.0 - zeta) * ue_ij1[m] + zeta * ue_ijnz[m]; u[k][j][i][m] = pxi + peta + pzeta - pxi * peta - peta * pzeta - pzeta * pxi + pxi * peta * pzeta; } } } } } //--------------------------------------------------------------------- // to perform pseudo-time stepping SSOR iterations // for five nonlinear pde's. //--------------------------------------------------------------------- void ssor(int niter) { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m, n; int istep; double tmp; double tv[33][33][5]; double delunm[5]; //--------------------------------------------------------------------- // begin pseudo-time stepping iterations //--------------------------------------------------------------------- tmp = 1.0 / (omega * (2.0 - omega)); //--------------------------------------------------------------------- // initialize a,b,c,d to zero (guarantees that page tables have been // formed, if applicable on given architecture, before timestepping). //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(j = 0; j < 33; j++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(i = 0; i < 33; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(n = 0; n < 5; n++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { a[j][i][n][m] = 0.0; b[j][i][n][m] = 0.0; c[j][i][n][m] = 0.0; d[j][i][n][m] = 0.0; } } } } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(i = 1; i <= 11; i++) { timer_clear(i); } //--------------------------------------------------------------------- // compute the steady-state residuals //--------------------------------------------------------------------- rhs(); //--------------------------------------------------------------------- // compute the L2 norms of newton iteration residuals //--------------------------------------------------------------------- l2norm(33, 33, 33, nx0, ny0, nz0, ist, iend, jst, jend, rsd, rsdnm); /* if ( ipr == 1 ) { printf(" Initial residual norms\n"); printf("\n"); printf(" \n RMS-norm of steady-state residual for " "first pde = %12.5E\n" " RMS-norm of steady-state residual for " "second pde = %12.5E\n" " RMS-norm of steady-state residual for " "third pde = %12.5E\n" " RMS-norm of steady-state residual for " "fourth pde = %12.5E\n" " RMS-norm of steady-state residual for " "fifth pde = %12.5E\n", rsdnm[0], rsdnm[1], rsdnm[2], rsdnm[3], rsdnm[4]); printf("\nIteration RMS-residual of 5th PDE\n"); } */ /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(i = 1; i <= 11; i++) { timer_clear(i); } timer_start(1); //--------------------------------------------------------------------- // the timestep loop //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop contains Invalid Statement -> BreakStmt#3142 ****************************************/ for(istep = 1; istep <= niter; istep++) { //if ( ( (istep % inorm) == 0 ) && ipr == 1 ) { // printf(" \n pseudo-time SSOR iteration no.=%4d\n\n", istep); //} if((istep % 20) == 0 || istep == itmax || istep == 1) { if(niter > 1) printf(" Time step %4d\n", istep); } //--------------------------------------------------------------------- // perform SSOR iteration //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz, jst, jend, ist, iend, dt) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(j, i, m) firstprivate(jst, jend, ist, iend, dt, k) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, dt, k, j) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { rsd[k][j][i][m] = dt * rsd[k][j][i][m]; } } } } /*************** Clava msgError ************** unsolved dependency for arrayAccess vk_16 use : RW ****************************************/ for(k = 1; k < nz - 1; k++) { //--------------------------------------------------------------------- // form the lower triangular part of the jacobian matrix //--------------------------------------------------------------------- jacld(k); //--------------------------------------------------------------------- // perform the lower triangular solution //--------------------------------------------------------------------- blts(33, 33, 33, nx, ny, nz, k, omega, rsd, a, b, c, d, ist, iend, jst, jend, nx0, ny0); } /*************** Clava msgError ************** unsolved dependency for arrayAccess rsd use : RW ****************************************/ for(k = nz - 2; k > 0; k--) { //--------------------------------------------------------------------- // form the strictly upper triangular part of the jacobian matrix //--------------------------------------------------------------------- jacu(k); //--------------------------------------------------------------------- // perform the upper triangular solution //--------------------------------------------------------------------- buts(33, 33, 33, nx, ny, nz, k, omega, rsd, tv, d, a, b, c, ist, iend, jst, jend, nx0, ny0); } //--------------------------------------------------------------------- // update the variables //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz, jst, jend, ist, iend, tmp, rsd) for(k = 1; k < nz - 1; k++) { // #pragma omp parallel for default(shared) private(j, i, m) firstprivate(jst, jend, ist, iend, tmp, k, rsd) for(j = jst; j < jend; j++) { // #pragma omp parallel for default(shared) private(i, m) firstprivate(ist, iend, tmp, k, j, rsd) for(i = ist; i < iend; i++) { /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { u[k][j][i][m] = u[k][j][i][m] + tmp * rsd[k][j][i][m]; } } } } //--------------------------------------------------------------------- // compute the max-norms of newton iteration corrections //--------------------------------------------------------------------- if((istep % inorm) == 0) { l2norm(33, 33, 33, nx0, ny0, nz0, ist, iend, jst, jend, rsd, delunm); /* if ( ipr == 1 ) { printf(" \n RMS-norm of SSOR-iteration correction " "for first pde = %12.5E\n" " RMS-norm of SSOR-iteration correction " "for second pde = %12.5E\n" " RMS-norm of SSOR-iteration correction " "for third pde = %12.5E\n" " RMS-norm of SSOR-iteration correction " "for fourth pde = %12.5E\n", " RMS-norm of SSOR-iteration correction " "for fifth pde = %12.5E\n", delunm[0], delunm[1], delunm[2], delunm[3], delunm[4]); } else if ( ipr == 2 ) { printf("(%5d,%15.6f)\n", istep, delunm[4]); } */ } //--------------------------------------------------------------------- // compute the steady-state residuals //--------------------------------------------------------------------- rhs(); //--------------------------------------------------------------------- // compute the max-norms of newton iteration residuals //--------------------------------------------------------------------- if(((istep % inorm) == 0) || (istep == itmax)) { l2norm(33, 33, 33, nx0, ny0, nz0, ist, iend, jst, jend, rsd, rsdnm); /* if ( ipr == 1 ) { printf(" \n RMS-norm of steady-state residual for " "first pde = %12.5E\n" " RMS-norm of steady-state residual for " "second pde = %12.5E\n" " RMS-norm of steady-state residual for " "third pde = %12.5E\n" " RMS-norm of steady-state residual for " "fourth pde = %12.5E\n" " RMS-norm of steady-state residual for " "fifth pde = %12.5E\n", rsdnm[0], rsdnm[1], rsdnm[2], rsdnm[3], rsdnm[4]); } */ } //--------------------------------------------------------------------- // check the newton-iteration residuals against the tolerance levels //--------------------------------------------------------------------- if((rsdnm[0] < tolrsd[0]) && (rsdnm[1] < tolrsd[1]) && (rsdnm[2] < tolrsd[2]) && (rsdnm[3] < tolrsd[3]) && (rsdnm[4] < tolrsd[4])) { //if (ipr == 1 ) { printf(" \n convergence was achieved after %4d pseudo-time steps\n", istep); //} break; } } timer_stop(1); maxtime = timer_read(1); } //--------------------------------------------------------------------- // verification routine //--------------------------------------------------------------------- void verify(double xcr[5], double xce[5], double xci, char *Class, int *verified) { double xcrref[5]; double xceref[5]; double xciref; double xcrdif[5]; double xcedif[5]; double xcidif; double epsilon, dtref = 0.0; int m; //--------------------------------------------------------------------- // tolerance level //--------------------------------------------------------------------- epsilon = 1.0e-08; *Class = 'U'; *verified = 1; /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { xcrref[m] = 1.0; xceref[m] = 1.0; } xciref = 1.0; if((nx0 == 12) && (ny0 == 12) && (nz0 == 12) && (itmax == 50)) { *Class = 'S'; dtref = 5.0e-1; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, for the (12X12X12) grid, // after 50 time steps, with DT = 5.0e-01 //--------------------------------------------------------------------- xcrref[0] = 1.6196343210976702e-02; xcrref[1] = 2.1976745164821318e-03; xcrref[2] = 1.5179927653399185e-03; xcrref[3] = 1.5029584435994323e-03; xcrref[4] = 3.4264073155896461e-02; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, // for the (12X12X12) grid, // after 50 time steps, with DT = 5.0e-01 //--------------------------------------------------------------------- xceref[0] = 6.4223319957960924e-04; xceref[1] = 8.4144342047347926e-05; xceref[2] = 5.8588269616485186e-05; xceref[3] = 5.8474222595157350e-05; xceref[4] = 1.3103347914111294e-03; //--------------------------------------------------------------------- // Reference value of surface integral, for the (12X12X12) grid, // after 50 time steps, with DT = 5.0e-01 //--------------------------------------------------------------------- xciref = 7.8418928865937083e+00; } else if((nx0 == 33) && (ny0 == 33) && (nz0 == 33) && (itmax == 300)) { *Class = 'W'; //SPEC95fp size dtref = 1.5e-3; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, for the (33x33x33) grid, // after 300 time steps, with DT = 1.5e-3 //--------------------------------------------------------------------- xcrref[0] = 0.1236511638192e+02; xcrref[1] = 0.1317228477799e+01; xcrref[2] = 0.2550120713095e+01; xcrref[3] = 0.2326187750252e+01; xcrref[4] = 0.2826799444189e+02; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, // for the (33X33X33) grid, //--------------------------------------------------------------------- xceref[0] = 0.4867877144216e+00; xceref[1] = 0.5064652880982e-01; xceref[2] = 0.9281818101960e-01; xceref[3] = 0.8570126542733e-01; xceref[4] = 0.1084277417792e+01; //--------------------------------------------------------------------- // Reference value of surface integral, for the (33X33X33) grid, // after 300 time steps, with DT = 1.5e-3 //--------------------------------------------------------------------- xciref = 0.1161399311023e+02; } else if((nx0 == 64) && (ny0 == 64) && (nz0 == 64) && (itmax == 250)) { *Class = 'A'; dtref = 2.0e+0; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, for the (64X64X64) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xcrref[0] = 7.7902107606689367e+02; xcrref[1] = 6.3402765259692870e+01; xcrref[2] = 1.9499249727292479e+02; xcrref[3] = 1.7845301160418537e+02; xcrref[4] = 1.8384760349464247e+03; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, // for the (64X64X64) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xceref[0] = 2.9964085685471943e+01; xceref[1] = 2.8194576365003349e+00; xceref[2] = 7.3473412698774742e+00; xceref[3] = 6.7139225687777051e+00; xceref[4] = 7.0715315688392578e+01; //--------------------------------------------------------------------- // Reference value of surface integral, for the (64X64X64) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xciref = 2.6030925604886277e+01; } else if((nx0 == 102) && (ny0 == 102) && (nz0 == 102) && (itmax == 250)) { *Class = 'B'; dtref = 2.0e+0; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, for the (102X102X102) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xcrref[0] = 3.5532672969982736e+03; xcrref[1] = 2.6214750795310692e+02; xcrref[2] = 8.8333721850952190e+02; xcrref[3] = 7.7812774739425265e+02; xcrref[4] = 7.3087969592545314e+03; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, for the (102X102X102) // grid, after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xceref[0] = 1.1401176380212709e+02; xceref[1] = 8.1098963655421574e+00; xceref[2] = 2.8480597317698308e+01; xceref[3] = 2.5905394567832939e+01; xceref[4] = 2.6054907504857413e+02; //--------------------------------------------------------------------- // Reference value of surface integral, for the (102X102X102) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xciref = 4.7887162703308227e+01; } else if((nx0 == 162) && (ny0 == 162) && (nz0 == 162) && (itmax == 250)) { *Class = 'C'; dtref = 2.0e+0; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, for the (162X162X162) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xcrref[0] = 1.03766980323537846e+04; xcrref[1] = 8.92212458801008552e+02; xcrref[2] = 2.56238814582660871e+03; xcrref[3] = 2.19194343857831427e+03; xcrref[4] = 1.78078057261061185e+04; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, for the (162X162X162) // grid, after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xceref[0] = 2.15986399716949279e+02; xceref[1] = 1.55789559239863600e+01; xceref[2] = 5.41318863077207766e+01; xceref[3] = 4.82262643154045421e+01; xceref[4] = 4.55902910043250358e+02; //--------------------------------------------------------------------- // Reference value of surface integral, for the (162X162X162) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xciref = 6.66404553572181300e+01; //--------------------------------------------------------------------- // Reference value of surface integral, for the (162X162X162) grid, // after 250 time steps, with DT = 2.0e+00 //--------------------------------------------------------------------- xciref = 6.66404553572181300e+01; } else if((nx0 == 408) && (ny0 == 408) && (nz0 == 408) && (itmax == 300)) { *Class = 'D'; dtref = 1.0e+0; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, for the (408X408X408) grid, // after 300 time steps, with DT = 1.0e+00 //--------------------------------------------------------------------- xcrref[0] = 0.4868417937025e+05; xcrref[1] = 0.4696371050071e+04; xcrref[2] = 0.1218114549776e+05; xcrref[3] = 0.1033801493461e+05; xcrref[4] = 0.7142398413817e+05; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, for the (408X408X408) // grid, after 300 time steps, with DT = 1.0e+00 //--------------------------------------------------------------------- xceref[0] = 0.3752393004482e+03; xceref[1] = 0.3084128893659e+02; xceref[2] = 0.9434276905469e+02; xceref[3] = 0.8230686681928e+02; xceref[4] = 0.7002620636210e+03; //--------------------------------------------------------------------- // Reference value of surface integral, for the (408X408X408) grid, // after 300 time steps, with DT = 1.0e+00 //--------------------------------------------------------------------- xciref = 0.8334101392503e+02; } else if((nx0 == 1020) && (ny0 == 1020) && (nz0 == 1020) && (itmax == 300)) { *Class = 'E'; dtref = 0.5e+0; //--------------------------------------------------------------------- // Reference values of RMS-norms of residual, // for the (1020X1020X1020) grid, // after 300 time steps, with DT = 0.5e+00 //--------------------------------------------------------------------- xcrref[0] = 0.2099641687874e+06; xcrref[1] = 0.2130403143165e+05; xcrref[2] = 0.5319228789371e+05; xcrref[3] = 0.4509761639833e+05; xcrref[4] = 0.2932360006590e+06; //--------------------------------------------------------------------- // Reference values of RMS-norms of solution error, // for the (1020X1020X1020) // grid, after 300 time steps, with DT = 0.5e+00 //--------------------------------------------------------------------- xceref[0] = 0.4800572578333e+03; xceref[1] = 0.4221993400184e+02; xceref[2] = 0.1210851906824e+03; xceref[3] = 0.1047888986770e+03; xceref[4] = 0.8363028257389e+03; //--------------------------------------------------------------------- // Reference value of surface integral, for the (1020X1020X1020) grid, // after 300 time steps, with DT = 0.5e+00 //--------------------------------------------------------------------- xciref = 0.9512163272273e+02; } else { *verified = 0; } //--------------------------------------------------------------------- // verification test for residuals if gridsize is one of // the defined grid sizes above (*Class != 'U') //--------------------------------------------------------------------- //--------------------------------------------------------------------- // Compute the difference of solution values and the known reference values. //--------------------------------------------------------------------- /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { xcrdif[m] = fabs((xcr[m] - xcrref[m]) / xcrref[m]); xcedif[m] = fabs((xce[m] - xceref[m]) / xceref[m]); } xcidif = fabs((xci - xciref) / xciref); //--------------------------------------------------------------------- // Output the comparison of computed results to known cases. //--------------------------------------------------------------------- if(*Class != 'U') { printf("\n Verification being performed for class %c\n", *Class); printf(" Accuracy setting for epsilon = %20.13E\n", epsilon); *verified = (fabs(dt - dtref) <= epsilon); if(!(*verified)) { *Class = 'U'; printf(" DT does not match the reference value of %15.8E\n", dtref); } } else { printf(" Unknown class\n"); } if(*Class != 'U') { printf(" Comparison of RMS-norms of residual\n"); } else { printf(" RMS-norms of residual\n"); } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { if(*Class == 'U') { printf(" %2d %20.13E\n", m + 1, xcr[m]); } else if(xcrdif[m] <= epsilon) { printf(" %2d %20.13E%20.13E%20.13E\n", m + 1, xcr[m], xcrref[m], xcrdif[m]); } else { *verified = 0; printf(" FAILURE: %2d %20.13E%20.13E%20.13E\n", m + 1, xcr[m], xcrref[m], xcrdif[m]); } } if(*Class != 'U') { printf(" Comparison of RMS-norms of solution error\n"); } else { printf(" RMS-norms of solution error\n"); } /*************** Clava msgError ************** Loop Iteration number is too low ****************************************/ for(m = 0; m < 5; m++) { if(*Class == 'U') { printf(" %2d %20.13E\n", m + 1, xce[m]); } else if(xcedif[m] <= epsilon) { printf(" %2d %20.13E%20.13E%20.13E\n", m + 1, xce[m], xceref[m], xcedif[m]); } else { *verified = 0; printf(" FAILURE: %2d %20.13E%20.13E%20.13E\n", m + 1, xce[m], xceref[m], xcedif[m]); } } if(*Class != 'U') { printf(" Comparison of surface integral\n"); } else { printf(" Surface integral\n"); } if(*Class == 'U') { printf(" %20.13E\n", xci); } else if(xcidif <= epsilon) { printf(" %20.13E%20.13E%20.13E\n", xci, xciref, xcidif); } else { *verified = 0; printf(" FAILURE: %20.13E%20.13E%20.13E\n", xci, xciref, xcidif); } if(*Class == 'U') { printf(" No reference values provided\n"); printf("No verification performed\n"); } else if(*verified) { printf(" Verification Successful\n"); } else { printf(" Verification failed\n"); } } void setcoeff() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- //--------------------------------------------------------------------- // set up coefficients //--------------------------------------------------------------------- dxi = 1.0 / (nx0 - 1); deta = 1.0 / (ny0 - 1); dzeta = 1.0 / (nz0 - 1); tx1 = 1.0 / (dxi * dxi); tx2 = 1.0 / (2.0 * dxi); tx3 = 1.0 / dxi; ty1 = 1.0 / (deta * deta); ty2 = 1.0 / (2.0 * deta); ty3 = 1.0 / deta; tz1 = 1.0 / (dzeta * dzeta); tz2 = 1.0 / (2.0 * dzeta); tz3 = 1.0 / dzeta; //--------------------------------------------------------------------- // diffusion coefficients //--------------------------------------------------------------------- dx1 = 0.75; dx2 = dx1; dx3 = dx1; dx4 = dx1; dx5 = dx1; dy1 = 0.75; dy2 = dy1; dy3 = dy1; dy4 = dy1; dy5 = dy1; dz1 = 1.00; dz2 = dz1; dz3 = dz1; dz4 = dz1; dz5 = dz1; //--------------------------------------------------------------------- // fourth difference dissipation //--------------------------------------------------------------------- dssp = (((((dx1) > (dy1) ? (dx1) : (dy1))) > (dz1) ? (((dx1) > (dy1) ? (dx1) : (dy1))) : (dz1))) / 4.0; //--------------------------------------------------------------------- // coefficients of the exact solution to the first pde //--------------------------------------------------------------------- ce[0][0] = 2.0; ce[0][1] = 0.0; ce[0][2] = 0.0; ce[0][3] = 4.0; ce[0][4] = 5.0; ce[0][5] = 3.0; ce[0][6] = 5.0e-01; ce[0][7] = 2.0e-02; ce[0][8] = 1.0e-02; ce[0][9] = 3.0e-02; ce[0][10] = 5.0e-01; ce[0][11] = 4.0e-01; ce[0][12] = 3.0e-01; //--------------------------------------------------------------------- // coefficients of the exact solution to the second pde //--------------------------------------------------------------------- ce[1][0] = 1.0; ce[1][1] = 0.0; ce[1][2] = 0.0; ce[1][3] = 0.0; ce[1][4] = 1.0; ce[1][5] = 2.0; ce[1][6] = 3.0; ce[1][7] = 1.0e-02; ce[1][8] = 3.0e-02; ce[1][9] = 2.0e-02; ce[1][10] = 4.0e-01; ce[1][11] = 3.0e-01; ce[1][12] = 5.0e-01; //--------------------------------------------------------------------- // coefficients of the exact solution to the third pde //--------------------------------------------------------------------- ce[2][0] = 2.0; ce[2][1] = 2.0; ce[2][2] = 0.0; ce[2][3] = 0.0; ce[2][4] = 0.0; ce[2][5] = 2.0; ce[2][6] = 3.0; ce[2][7] = 4.0e-02; ce[2][8] = 3.0e-02; ce[2][9] = 5.0e-02; ce[2][10] = 3.0e-01; ce[2][11] = 5.0e-01; ce[2][12] = 4.0e-01; //--------------------------------------------------------------------- // coefficients of the exact solution to the fourth pde //--------------------------------------------------------------------- ce[3][0] = 2.0; ce[3][1] = 2.0; ce[3][2] = 0.0; ce[3][3] = 0.0; ce[3][4] = 0.0; ce[3][5] = 2.0; ce[3][6] = 3.0; ce[3][7] = 3.0e-02; ce[3][8] = 5.0e-02; ce[3][9] = 4.0e-02; ce[3][10] = 2.0e-01; ce[3][11] = 1.0e-01; ce[3][12] = 3.0e-01; //--------------------------------------------------------------------- // coefficients of the exact solution to the fifth pde //--------------------------------------------------------------------- ce[4][0] = 5.0; ce[4][1] = 4.0; ce[4][2] = 3.0; ce[4][3] = 2.0; ce[4][4] = 1.0e-01; ce[4][5] = 4.0e-01; ce[4][6] = 3.0e-01; ce[4][7] = 5.0e-02; ce[4][8] = 4.0e-02; ce[4][9] = 3.0e-02; ce[4][10] = 1.0e-01; ce[4][11] = 3.0e-01; ce[4][12] = 2.0e-01; } void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified) { char size[16]; int j; printf("\n\n %s Benchmark Completed.\n", name); printf(" Class = %12c\n", class); // If this is not a grid-based problem (EP, FT, CG), then // we only print n1, which contains some measure of the // problem size. In that case, n2 and n3 are both zero. // Otherwise, we print the grid size n1xn2xn3 if((n2 == 0) && (n3 == 0)) { if((name[0] == 'E') && (name[1] == 'P')) { sprintf(size, "%15.0lf", pow(2.0, n1)); j = 14; if(size[j] == '.') { size[j] = ' '; j--; } size[j + 1] = '\0'; printf(" Size = %15s\n", size); } else { printf(" Size = %12d\n", n1); } } else { printf(" Size = %4dx%4dx%4d\n", n1, n2, n3); } printf(" Iterations = %12d\n", niter); printf(" Time in seconds = %12.2lf\n", t); printf(" Mop/s total = %15.2lf\n", mops); printf(" Operation type = %24s\n", optype); if(verified) printf(" Verification = %12s\n", "SUCCESSFUL"); else printf(" Verification = %12s\n", "UNSUCCESSFUL"); } void wtime(double *t) { static int sec = -1; struct timeval tv; gettimeofday(&tv, (void *) 0); if(sec < 0) sec = tv.tv_sec; *t = (tv.tv_sec - sec) + 1.0e-6 * tv.tv_usec; } /*****************************************************************/ /****** E L A P S E D _ T I M E ******/ /*****************************************************************/ double elapsed_time() { double t; wtime(&t); return (t); } /*****************************************************************/ /****** T I M E R _ C L E A R ******/ /*****************************************************************/ void timer_clear(int n) { elapsed[n] = 0.0; } /*****************************************************************/ /****** T I M E R _ S T A R T ******/ /*****************************************************************/ void timer_start(int n) { start[n] = elapsed_time(); } /*****************************************************************/ /****** T I M E R _ S T O P ******/ /*****************************************************************/ void timer_stop(int n) { double t, now; now = elapsed_time(); t = now - start[n]; elapsed[n] += t; } /*****************************************************************/ /****** T I M E R _ R E A D ******/ /*****************************************************************/ double timer_read(int n) { return (elapsed[n]); }
DRB067-restrictpointer1-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ /* restrict pointers: no aliasing Array initialization using assignments. C99 is needed to compile this code e.g. gcc -std=c99 -c Stress-1.c */ #include "omprace.h" #include <omp.h> #include <stdlib.h> typedef double real8; //modified to successfully compile with clang //void foo(real8 * restrict newSxx, real8 * restrict newSyy, int length) void foo(real8 * newSxx, real8 * newSyy, int length) { int i; #pragma omp parallel for private (i) firstprivate (length) for (i = 0; i <= length - 1; i += 1) { newSxx[i] = 0.0; newSyy[i] = 0.0; } } int main() { omprace_init(); int length=1000; real8* newSxx =(real8*) malloc (length* sizeof (real8)); real8* newSyy =(real8*) malloc (length* sizeof (real8)); foo(newSxx, newSyy, length); free (newSxx); free (newSyy); omprace_fini(); return 0; }
nthrs_dynamic.c
/* In this case when running with no dynamic threads: Parallel time: 7.000000 Sequential time: 9.000000 When running with dynamic threads: Parallel time: 11.000000 Sequential time: 9.000000 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <omp.h> const static void power(double *array, double factor, unsigned int start, unsigned int chunck) { for(unsigned int i = 0; i < chunck; i++) array[start+i] = pow(array[start+i], factor); } int main(int argc, char **argv) { unsigned int this_thread = 0, n_threads, n = 100000000, chunck = 0, start = 0, end = 0; double counter = 0.0; double *array_parallel = malloc(sizeof(double) * n), *array_sequential = malloc(sizeof(double) * n); float start_parallel = 0, end_parallel = 0, start_sequential = 0, end_sequential = 0; for(unsigned int i = 0; i < n; i++) { array_parallel[i] = counter; array_sequential[i] = counter; counter += 1.0; } start_parallel = clock()/CLOCKS_PER_SEC; /* FALSE */ // omp_set_dynamic(0); /* TRUE */ omp_set_dynamic(1); #pragma omp parallel num_threads(10) { n_threads = omp_get_num_threads(); this_thread = omp_get_thread_num(); chunck = n/n_threads; start = this_thread*chunck; if(n_threads-1 == this_thread) chunck = n - start; printf("#%d thread doing pow for index %d to %d\n", this_thread, start, chunck); power(array_parallel, 3.0, start, chunck); } end_parallel = clock()/CLOCKS_PER_SEC; start_sequential = clock()/CLOCKS_PER_SEC; power(array_sequential, 3.0, 0, n); end_sequential = clock()/CLOCKS_PER_SEC; printf("\nParallel time: %f\n", end_parallel - start_parallel); printf("Sequential time: %f\n", end_sequential - start_sequential); free(array_parallel); free(array_sequential); return 0; }
pbkdf2_hmac_sha256_fmt_plug.c
/* This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net> * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * Based on hmac-sha512 by magnum * * Minor fixes, format unification and OMP support done by Dhiru Kholia * <dhiru@openwall.com> * * Fixed for supporting $ml$ "dave" format as well as GRUB native format by * magnum 2013. Note: We support a binary size of >512 bits (64 bytes / 128 * chars of hex) but we currently do not calculate it even in cmp_exact(). The * chance for a 512-bit hash collision should be pretty dang slim. * * the pbkdf2_sha256_hmac was so messed up, I simply copied sha512 over the top * of it, replacing the code in totality. JimF. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_pbkdf2_hmac_sha256; #elif FMT_REGISTERS_H john_register_one(&fmt_pbkdf2_hmac_sha256); #else #include <ctype.h> #include <string.h> #include <assert.h> #include "misc.h" #include "arch.h" #include "common.h" #include "formats.h" #include "base64_convert.h" #include "sha2.h" #include "johnswap.h" #include "stdint.h" #include "pbkdf2_hmac_sha256.h" #include "pbkdf2_hmac_common.h" #define FORMAT_LABEL "PBKDF2-HMAC-SHA256" #define FORMAT_NAME "" #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA256 " SHA256_ALGORITHM_NAME #else #if ARCH_BITS >= 64 #define ALGORITHM_NAME "PBKDF2-SHA256 64/" ARCH_BITS_STR " " SHA2_LIB #else #define ALGORITHM_NAME "PBKDF2-SHA256 32/" ARCH_BITS_STR " " SHA2_LIB #endif #endif #define MAX_CIPHERTEXT_LENGTH 1024 /* Bump this and code will adopt */ #define SALT_SIZE sizeof(struct custom_salt) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define BENCHMARK_LENGTH -1 #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 4 #endif #endif #include "memdbg.h" #define PAD_SIZE 128 #define PLAINTEXT_LENGTH 125 static struct custom_salt { uint8_t length; uint8_t salt[PBKDF2_32_MAX_SALT_SIZE + 3]; uint32_t rounds; } *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[PBKDF2_SHA256_BINARY_SIZE / sizeof(ARCH_WORD_32)]; static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static void *get_salt(char *ciphertext) { static struct custom_salt salt; char *p, *c = ciphertext; uint32_t rounds; memset(&salt, 0, sizeof(salt)); c += PBKDF2_SHA256_TAG_LEN; rounds = strtol(c, NULL, 10); c = strchr(c, '$') + 1; p = strchr(c, '$'); if (p-c==14 && rounds==20000) { // for now, assume this is a cisco8 hash strnzcpy((char*)(salt.salt), c, 15); salt.length = 14; salt.rounds = rounds; return (void*)&salt; } salt.length = base64_convert(c, e_b64_mime, p-c, salt.salt, e_b64_raw, sizeof(salt.salt), flg_Base64_MIME_PLUS_TO_DOT, 0); salt.rounds = rounds; return (void *)&salt; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) { #ifdef SSE_GROUP_SZ_SHA256 int lens[SSE_GROUP_SZ_SHA256], i; unsigned char *pin[SSE_GROUP_SZ_SHA256]; union { ARCH_WORD_32 *pout[SSE_GROUP_SZ_SHA256]; unsigned char *poutc; } x; for (i = 0; i < SSE_GROUP_SZ_SHA256; ++i) { lens[i] = strlen(saved_key[index+i]); pin[i] = (unsigned char*)saved_key[index+i]; x.pout[i] = crypt_out[index+i]; } pbkdf2_sha256_sse((const unsigned char **)pin, lens, cur_salt->salt, cur_salt->length, cur_salt->rounds, &(x.poutc), PBKDF2_SHA256_BINARY_SIZE, 0); #else pbkdf2_sha256((const unsigned char*)(saved_key[index]), strlen(saved_key[index]), cur_salt->salt, cur_salt->length, cur_salt->rounds, (unsigned char*)crypt_out[index], PBKDF2_SHA256_BINARY_SIZE, 0); #endif } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], PBKDF2_SHA256_BINARY_SIZE); } /* Check the FULL binary, just for good measure. There is no chance we'll have a false positive here but this function is not performance sensitive. This function not done linke pbkdf2_hmac_sha512. Simply return 1. */ static int cmp_exact(char *source, int index) { return 1; } static void set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->rounds; } struct fmt_main fmt_pbkdf2_hmac_sha256 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, PBKDF2_SHA256_BINARY_SIZE, PBKDF2_32_BINARY_ALIGN, SALT_SIZE, sizeof(ARCH_WORD), MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", }, { PBKDF2_SHA256_FORMAT_TAG, FORMAT_TAG_CISCO8 }, pbkdf2_hmac_sha256_common_tests }, { init, done, fmt_default_reset, pbkdf2_hmac_sha256_prepare, pbkdf2_hmac_sha256_valid, fmt_default_split, pbkdf2_hmac_sha256_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
cgetri.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zgetri.c, normal z -> c, Fri Sep 28 17:38:06 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_getri * * Computes the inverse of a matrix A using the LU factorization computed * by plasma_cgetrf. * ******************************************************************************* * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] pA * On entry, the LU factors computed by plasma_cgetrf. * On exit, the inverse of A, overwriting the factors. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * * @param[in] ipiv * The pivot indices computed by plasma_cgetrf. * ******************************************************************************* * * @retval PLASMA_SUCCESS successful exit * @retval < 0 if -i, the i-th argument had an illegal value * @retval > 0 if i, the (i,i) element of the factor U or L is * zero, and the inverse could not be computed. * ******************************************************************************* * * @sa plasma_cgetri * @sa plasma_dgetri * @sa plasma_sgetri * ******************************************************************************/ int plasma_cgetri(int n, plasma_complex32_t *pA, int lda, int *ipiv) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if (n < 0) { plasma_error("illegal value of n"); return -1; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -3; } // quick return if (imax(n, 0) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_getrf(plasma, PlasmaComplexFloat, n, n); // Set tiling parameters. int nb = plasma->nb; // Create tile matrix. plasma_desc_t A; plasma_desc_t W; int retval; retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb, n, nb, 0, 0, n, nb, &W); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_cge2desc(pA, lda, A, &sequence, &request); // Perform computation. plasma_omp_cgetri(A, ipiv, W, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_cdesc2ge(A, pA, lda, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&W); plasma_desc_destroy(&A); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * Computes the inverse of a matrix A using the LU factorization. * Non-blocking tile version of plasma_cgbsv(). * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] A * On entry, the LU factors computed by plasma_cgetrf. * On exit, the inverse of A, overwriting the factors. * * @param[in] ipiv * The pivot indices computed by plasma_cgetrf. * * @param[out] W * Workspace of dimension (n, nb) * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_cgetri * @sa plasma_omp_cgetri * @sa plasma_omp_cgetri * @sa plasma_omp_dgetri * @sa plasma_omp_sgetri * ******************************************************************************/ void plasma_omp_cgetri(plasma_desc_t A, int *ipiv, plasma_desc_t W, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(W) != PlasmaSuccess) { plasma_error("invalid W"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (A.n == 0) return; // Invert triangular part. plasma_pctrtri(PlasmaUpper, PlasmaNonUnit, A, sequence, request); // Compute product of inverse of the upper and lower triangles. plasma_pcgetri_aux(A, W, sequence, request); // Apply pivot. plasma_pcgeswp(PlasmaColumnwise, A, ipiv, -1, sequence, request); }
ast-dump-openmp-teams-distribute-simd.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test_one(int x) { #pragma omp target #pragma omp teams distribute simd for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp target #pragma omp teams distribute simd for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp target #pragma omp teams distribute simd collapse(1) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_four(int x, int y) { #pragma omp target #pragma omp teams distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_five(int x, int y, int z) { #pragma omp target #pragma omp teams distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) for (int i = 0; i < z; i++) ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-teams-distribute-simd.c:3:1, line:8:1> line:3:6 test_one 'void (int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:8:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:4:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:6:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:9, col:34> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:34> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:34> openmp_structured_block // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:5:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:6:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <col:3, line:7:5> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <col:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:6:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:5:9, col:34> openmp_structured_block // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:5:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:6:23> col:23 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <col:3, line:7:5> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <col:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:10:1, line:16:1> line:10:6 test_two 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:16:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:11:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:13:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:12:9, col:34> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:34> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:34> openmp_structured_block // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:13:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:11:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:11:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:12:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:13:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:14:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:13:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:11:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:11:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:13:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:14:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:12:9, col:34> openmp_structured_block // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:13:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:11:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:11:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:12:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:13:23> col:23 implicit 'int &' // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:14:25> col:25 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:13:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:18:1, line:24:1> line:18:6 test_three 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:24:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:19:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:21:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:20:9, col:46> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:46> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:46> openmp_structured_block // CHECK-NEXT: | | | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 1 // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:21:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:19:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:19:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:20:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:21:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:22:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:21:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:19:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:19:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:21:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:22:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:20:9, col:46> openmp_structured_block // CHECK-NEXT: | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 1 // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:21:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:19:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:19:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:20:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:21:23> col:23 implicit 'int &' // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:22:25> col:25 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:21:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:26:1, line:32:1> line:26:6 test_four 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:32:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:27:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:28:9, col:46> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:46> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:46> openmp_structured_block // CHECK-NEXT: | | | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:27:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:27:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:28:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:29:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:30:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:29:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:30:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <line:29:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, line:30:28> 'long' '*' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <line:29:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <line:30:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:27:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:27:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:29:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:30:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:28:9, col:46> openmp_structured_block // CHECK-NEXT: | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:27:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:27:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:28:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:29:23> col:23 implicit 'int &' // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:30:25> col:25 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:29:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:30:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <line:29:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, line:30:28> 'long' '*' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <line:29:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <line:30:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:34:1, line:41:1> line:34:6 test_five 'void (int, int, int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:41:1> // CHECK-NEXT: `-OMPTargetDirective {{.*}} <line:35:9, col:19> // CHECK-NEXT: |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: `-CapturedStmt {{.*}} <line:36:9, col:46> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-CapturedStmt {{.*}} <col:9, col:46> // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:46> openmp_structured_block // CHECK-NEXT: | | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | | | `-CapturedStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:35:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:35:9) *const restrict' // CHECK-NEXT: | | | |-RecordDecl {{.*}} <line:36:9> col:9 implicit struct definition // CHECK-NEXT: | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:37:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:38:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | `-FieldDecl {{.*}} <line:39:27> col:27 implicit 'int &' // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | |-OMPCapturedExprDecl {{.*}} <line:37:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-OMPCapturedExprDecl {{.*}} <line:38:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | `-OMPCapturedExprDecl {{.*}} <line:37:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:3, line:38:28> 'long' '*' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <line:37:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <line:38:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:35:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:35:9) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:37:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:38:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-FieldDecl {{.*}} <line:39:27> col:27 implicit 'int' // CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-OMPTeamsDistributeSimdDirective {{.*}} <line:36:9, col:46> openmp_structured_block // CHECK-NEXT: | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | `-CapturedStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:35:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:35:9) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <line:36:9> col:9 implicit struct definition // CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:37:23> col:23 implicit 'int &' // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:38:25> col:25 implicit 'int &' // CHECK-NEXT: | | `-FieldDecl {{.*}} <line:39:27> col:27 implicit 'int &' // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | |-OMPCapturedExprDecl {{.*}} <line:37:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | |-OMPCapturedExprDecl {{.*}} <line:38:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-OMPCapturedExprDecl {{.*}} <line:37:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | |-BinaryOperator {{.*}} <col:3, line:38:28> 'long' '*' // CHECK-NEXT: | | |-ImplicitCastExpr {{.*}} <line:37:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <line:38:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
GB_binop__lxor_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__lxor_int32 // A.*B function (eWiseMult): GB_AemultB__lxor_int32 // A*D function (colscale): GB_AxD__lxor_int32 // D*A function (rowscale): GB_DxB__lxor_int32 // C+=B function (dense accum): GB_Cdense_accumB__lxor_int32 // C+=b function (dense accum): GB_Cdense_accumb__lxor_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lxor_int32 // C=scalar+B GB_bind1st__lxor_int32 // C=scalar+B' GB_bind1st_tran__lxor_int32 // C=A+scalar GB_bind2nd__lxor_int32 // C=A'+scalar GB_bind2nd_tran__lxor_int32 // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = ((x != 0) != (y != 0)) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LXOR || GxB_NO_INT32 || GxB_NO_LXOR_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__lxor_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__lxor_int32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__lxor_int32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__lxor_int32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__lxor_int32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__lxor_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lxor_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lxor_int32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t bij = Bx [p] ; Cx [p] = ((x != 0) != (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__lxor_int32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; Cx [p] = ((aij != 0) != (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__lxor_int32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__lxor_int32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
gbdt.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_BOOSTING_GBDT_H_ #define LIGHTGBM_BOOSTING_GBDT_H_ #include <LightGBM/boosting.h> #include <LightGBM/objective_function.h> #include <LightGBM/prediction_early_stop.h> #include <string> #include <algorithm> #include <cstdio> #include <fstream> #include <map> #include <memory> #include <mutex> #include <unordered_map> #include <utility> #include <vector> #include <LightGBM/json11.hpp> #include "score_updater.hpp" using namespace json11; namespace LightGBM { /*! * \brief GBDT algorithm implementation. including Training, prediction, bagging. */ class GBDT : public GBDTBase { public: /*! * \brief Constructor */ GBDT(); /*! * \brief Destructor */ ~GBDT(); /*! * \brief Initialization logic * \param gbdt_config Config for boosting * \param train_data Training data * \param objective_function Training objective function * \param training_metrics Training metrics */ void Init(const Config* gbdt_config, const Dataset* train_data, const ObjectiveFunction* objective_function, const std::vector<const Metric*>& training_metrics) override; /*! * \brief Merge model from other boosting object. Will insert to the front of current boosting object * \param other */ void MergeFrom(const Boosting* other) override { auto other_gbdt = reinterpret_cast<const GBDT*>(other); // tmp move to other vector auto original_models = std::move(models_); models_ = std::vector<std::unique_ptr<Tree>>(); // push model from other first for (const auto& tree : other_gbdt->models_) { auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get()))); models_.push_back(std::move(new_tree)); } num_init_iteration_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; // push model in current object for (const auto& tree : original_models) { auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get()))); models_.push_back(std::move(new_tree)); } num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; } void ShuffleModels(int start_iter, int end_iter) override { int total_iter = static_cast<int>(models_.size()) / num_tree_per_iteration_; start_iter = std::max(0, start_iter); if (end_iter <= 0) { end_iter = total_iter; } end_iter = std::min(total_iter, end_iter); auto original_models = std::move(models_); std::vector<int> indices(total_iter); for (int i = 0; i < total_iter; ++i) { indices[i] = i; } Random tmp_rand(17); for (int i = start_iter; i < end_iter - 1; ++i) { int j = tmp_rand.NextShort(i + 1, end_iter); std::swap(indices[i], indices[j]); } models_ = std::vector<std::unique_ptr<Tree>>(); for (int i = 0; i < total_iter; ++i) { for (int j = 0; j < num_tree_per_iteration_; ++j) { int tree_idx = indices[i] * num_tree_per_iteration_ + j; auto new_tree = std::unique_ptr<Tree>(new Tree(*(original_models[tree_idx].get()))); models_.push_back(std::move(new_tree)); } } } /*! * \brief Reset the training data * \param train_data New Training data * \param objective_function Training objective function * \param training_metrics Training metrics */ void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function, const std::vector<const Metric*>& training_metrics) override; /*! * \brief Reset Boosting Config * \param gbdt_config Config for boosting */ void ResetConfig(const Config* gbdt_config) override; /*! * \brief Adding a validation dataset * \param valid_data Validation dataset * \param valid_metrics Metrics for validation dataset */ void AddValidDataset(const Dataset* valid_data, const std::vector<const Metric*>& valid_metrics) override; /*! * \brief Perform a full training procedure * \param snapshot_freq frequence of snapshot * \param model_output_path path of model file */ void Train(int snapshot_freq, const std::string& model_output_path) override; void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) override; /*! * \brief Training logic * \param gradients nullptr for using default objective, otherwise use self-defined boosting * \param hessians nullptr for using default objective, otherwise use self-defined boosting * \return True if cannot train any more */ virtual bool TrainOneIter(const score_t* gradients, const score_t* hessians) override; /*! * \brief Rollback one iteration */ void RollbackOneIter() override; /*! * \brief Get current iteration */ int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_tree_per_iteration_; } /*! * \brief Can use early stopping for prediction or not * \return True if cannot use early stopping for prediction */ bool NeedAccuratePrediction() const override { if (objective_function_ == nullptr) { return true; } else { return objective_function_->NeedAccuratePrediction(); } } /*! * \brief Get evaluation result at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \return evaluation result */ std::vector<double> GetEvalAt(int data_idx) const override; /*! * \brief Get current training score * \param out_len length of returned score * \return training score */ virtual const double* GetTrainingScore(int64_t* out_len) override; /*! * \brief Get size of prediction at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \return The size of prediction */ virtual int64_t GetNumPredictAt(int data_idx) const override { CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size())); data_size_t num_data = train_data_->num_data(); if (data_idx > 0) { num_data = valid_score_updater_[data_idx - 1]->num_data(); } return num_data * num_class_; } /*! * \brief Get prediction result at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \param result used to store prediction result, should allocate memory before call this function * \param out_len length of returned score */ void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override; /*! * \brief Get number of prediction for one data * \param num_iteration number of used iterations * \param is_pred_leaf True if predicting leaf index * \param is_pred_contrib True if predicting feature contribution * \return number of prediction */ inline int NumPredictOneRow(int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const override { int num_preb_in_one_row = num_class_; if (is_pred_leaf) { int max_iteration = GetCurrentIteration(); if (num_iteration > 0) { num_preb_in_one_row *= static_cast<int>(std::min(max_iteration, num_iteration)); } else { num_preb_in_one_row *= max_iteration; } } else if (is_pred_contrib) { num_preb_in_one_row = num_tree_per_iteration_ * (max_feature_idx_ + 2); // +1 for 0-based indexing, +1 for baseline } return num_preb_in_one_row; } void PredictRaw(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; void PredictRawByMap(const std::unordered_map<int, double>& features, double* output, const PredictionEarlyStopInstance* early_stop) const override; void Predict(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; void PredictByMap(const std::unordered_map<int, double>& features, double* output, const PredictionEarlyStopInstance* early_stop) const override; void PredictLeafIndex(const double* features, double* output) const override; void PredictLeafIndexByMap(const std::unordered_map<int, double>& features, double* output) const override; void PredictContrib(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; /*! * \brief Dump model to json format string * \param start_iteration The model will be saved start from * \param num_iteration Number of iterations that want to dump, -1 means dump all * \return Json format string of model */ std::string DumpModel(int start_iteration, int num_iteration) const override; /*! * \brief Translate model to if-else statement * \param num_iteration Number of iterations that want to translate, -1 means translate all * \return if-else format codes of model */ std::string ModelToIfElse(int num_iteration) const override; /*! * \brief Translate model to if-else statement * \param num_iteration Number of iterations that want to translate, -1 means translate all * \param filename Filename that want to save to * \return is_finish Is training finished or not */ bool SaveModelToIfElse(int num_iteration, const char* filename) const override; /*! * \brief Save model to file * \param start_iteration The model will be saved start from * \param num_iterations Number of model that want to save, -1 means save all * \param filename Filename that want to save to * \return is_finish Is training finished or not */ virtual bool SaveModelToFile(int start_iteration, int num_iterations, const char* filename) const override; /*! * \brief Save model to string * \param start_iteration The model will be saved start from * \param num_iterations Number of model that want to save, -1 means save all * \return Non-empty string if succeeded */ virtual std::string SaveModelToString(int start_iteration, int num_iterations) const override; /*! * \brief Restore from a serialized buffer */ bool LoadModelFromString(const char* buffer, size_t len) override; /*! * \brief Calculate feature importances * \param num_iteration Number of model that want to use for feature importance, -1 means use all * \param importance_type: 0 for split, 1 for gain * \return vector of feature_importance */ std::vector<double> FeatureImportance(int num_iteration, int importance_type) const override; /*! * \brief Get max feature index of this model * \return Max feature index of this model */ inline int MaxFeatureIdx() const override { return max_feature_idx_; } /*! * \brief Get feature names of this model * \return Feature names of this model */ inline std::vector<std::string> FeatureNames() const override { return feature_names_; } /*! * \brief Get index of label column * \return index of label column */ inline int LabelIdx() const override { return label_idx_; } /*! * \brief Get number of weak sub-models * \return Number of weak sub-models */ inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); } /*! * \brief Get number of tree per iteration * \return number of tree per iteration */ inline int NumModelPerIteration() const override { return num_tree_per_iteration_; } /*! * \brief Get number of classes * \return Number of classes */ inline int NumberOfClasses() const override { return num_class_; } inline void InitPredict(int num_iteration, bool is_pred_contrib) override { num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; if (num_iteration > 0) { num_iteration_for_pred_ = std::min(num_iteration, num_iteration_for_pred_); } if (is_pred_contrib) { #pragma omp parallel for schedule(static) for (int i = 0; i < static_cast<int>(models_.size()); ++i) { models_[i]->RecomputeMaxDepth(); } } } inline double GetLeafValue(int tree_idx, int leaf_idx) const override { CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size()); CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves()); return models_[tree_idx]->LeafOutput(leaf_idx); } inline void SetLeafValue(int tree_idx, int leaf_idx, double val) override { CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size()); CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves()); models_[tree_idx]->SetLeafOutput(leaf_idx, val); } /*! * \brief Get Type name of this boosting object */ virtual const char* SubModelName() const override { return "tree"; } protected: /*! * \brief Print eval result and check early stopping */ virtual bool EvalAndCheckEarlyStopping(); /*! * \brief reset config for bagging */ void ResetBaggingConfig(const Config* config, bool is_change_dataset); /*! * \brief Implement bagging logic * \param iter Current interation */ virtual void Bagging(int iter); /*! * \brief Helper function for bagging, used for multi-threading optimization * \param start start indice of bagging * \param cnt count * \param buffer output buffer * \return count of left size */ data_size_t BaggingHelper(Random& cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer); /*! * \brief calculate the object function */ virtual void Boosting(); /*! * \brief updating score after tree was trained * \param tree Trained tree of this iteration * \param cur_tree_id Current tree for multiclass training */ virtual void UpdateScore(const Tree* tree, const int cur_tree_id); /*! * \brief eval results for one metric */ virtual std::vector<double> EvalOneMetric(const Metric* metric, const double* score) const; /*! * \brief Print metric result of current iteration * \param iter Current interation * \return best_msg if met early_stopping */ std::string OutputMetric(int iter); double BoostFromAverage(int class_id, bool update_scorer); /*! \brief current iteration */ int iter_; /*! \brief Pointer to training data */ const Dataset* train_data_; /*! \brief Config of gbdt */ std::unique_ptr<Config> config_; /*! \brief Tree learner, will use this class to learn trees */ std::unique_ptr<TreeLearner> tree_learner_; /*! \brief Objective function */ const ObjectiveFunction* objective_function_; /*! \brief Store and update training data's score */ std::unique_ptr<ScoreUpdater> train_score_updater_; /*! \brief Metrics for training data */ std::vector<const Metric*> training_metrics_; /*! \brief Store and update validation data's scores */ std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_; /*! \brief Metric for validation data */ std::vector<std::vector<const Metric*>> valid_metrics_; /*! \brief Number of rounds for early stopping */ int early_stopping_round_; /*! \brief Only use first metric for early stopping */ bool es_first_metric_only_; /*! \brief Best iteration(s) for early stopping */ std::vector<std::vector<int>> best_iter_; /*! \brief Best score(s) for early stopping */ std::vector<std::vector<double>> best_score_; /*! \brief output message of best iteration */ std::vector<std::vector<std::string>> best_msg_; /*! \brief Trained models(trees) */ std::vector<std::unique_ptr<Tree>> models_; /*! \brief Max feature index of training data*/ int max_feature_idx_; /*! \brief First order derivative of training data */ std::vector<score_t> gradients_; /*! \brief Secend order derivative of training data */ std::vector<score_t> hessians_; /*! \brief Store the indices of in-bag data */ std::vector<data_size_t> bag_data_indices_; /*! \brief Number of in-bag data */ data_size_t bag_data_cnt_; /*! \brief Store the indices of in-bag data */ std::vector<data_size_t> tmp_indices_; /*! \brief Number of training data */ data_size_t num_data_; /*! \brief Number of trees per iterations */ int num_tree_per_iteration_; /*! \brief Number of class */ int num_class_; /*! \brief Index of label column */ data_size_t label_idx_; /*! \brief number of used model */ int num_iteration_for_pred_; /*! \brief Shrinkage rate for one iteration */ double shrinkage_rate_; /*! \brief Number of loaded initial models */ int num_init_iteration_; /*! \brief Feature names */ std::vector<std::string> feature_names_; std::vector<std::string> feature_infos_; /*! \brief number of threads */ int num_threads_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> offsets_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> left_cnts_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> right_cnts_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> left_write_pos_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> right_write_pos_buf_; std::unique_ptr<Dataset> tmp_subset_; bool is_use_subset_; std::vector<bool> class_need_train_; bool is_constant_hessian_; std::unique_ptr<ObjectiveFunction> loaded_objective_; bool average_output_; bool need_re_bagging_; std::string loaded_parameter_; Json forced_splits_json_; }; } // namespace LightGBM #endif // LightGBM_BOOSTING_GBDT_H_
GB_unop__log_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__log_fp32_fp32) // op(A') function: GB (_unop_tran__log_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = logf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = logf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = logf (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOG || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__log_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = logf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = logf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__log_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__tan_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__tan_fp64_fp64) // op(A') function: GB (_unop_tran__tan_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = tan (aij) #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = tan (x) ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = tan (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TAN || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__tan_fp64_fp64) ( double *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = tan (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = aij ; Cx [p] = tan (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__tan_fp64_fp64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
sqrtpinofalseshare.c
#include<stdio.h> #include<omp.h> #define NUM_THREADS 40 static long num_steps = 1000000000; double step; int main() { double x, pi, sum = 0.0; step = 1.0/(double) num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel { int ID = omp_get_thread_num(); double thread_sum = 0.0; int i; for(i = ID; i < num_steps; i += NUM_THREADS) { x = (i + 0.5) * step; thread_sum = thread_sum + 4.0/(1.0 + x * x); } #pragma omp critical pi += thread_sum * step; } printf("pi = (%f)\n", pi); }
opm-c.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #define MAX_PRODUCTION2_NUM 128 #define MAX_PRODUCTION1_NUM 128 #define MAX_VN_NUM 128 #define MAX_VT_NUM 128 #define MAX_STRING_LENGTH 800 typedef struct SubTree { /* map 数组实现 */ unsigned vn[MAX_VN_NUM]; /* set 数组实现 */ int keys[MAX_VN_NUM]; int mark[MAX_VN_NUM]; int key_cnt; int initialized; } SubTree; /* Vn的数目 */ int vnNum; /* <Vn>::=Vt map 数组实现 key为vt value为vn 可能存在多个vn 所以需要cnt 所以 production1[key][cnt] = value cnt = production1_cnt[key] */ int production1[128][MAX_VT_NUM]; int production1_cnt[128]; /* dp[i][j]记录着两个东西: 1、Map<int,int> vn:代表str[i][j]可能存在多少种Vn(Vn->str[i][j]),以及每种Vn对应的数目。key为Vn,value为数目。 2、Set<int> keys:存储所有的Vn */ SubTree dp[MAX_STRING_LENGTH][MAX_STRING_LENGTH]; /* 对于<vn-l>:=<vn-r1><vn-r2> vnIndex[vn-r1][vn-r2][cnt] = vn-l 因为可能存在相同的vn-r1和vn-r2对应不同的vn-l 所以需要cnt cnt = vnIndex_num[vn-r1][vn-r2] */ int vnIndex[MAX_VN_NUM][MAX_VN_NUM][MAX_PRODUCTION2_NUM]; int vnIndex_num[MAX_VN_NUM][MAX_VN_NUM]; /* 输入字符串 */ char solve[MAX_STRING_LENGTH]; /* 字符串长度 */ int slen; void input() { int production1_num, production2_num; freopen("input2.txt", "r", stdin); scanf("%d\n", &vnNum); scanf("%d\n", &production2_num); for (int i = 0; i < production2_num; i++) { int key, value1, value2; scanf("<%d>::=<%d><%d>\n", &key, &value1, &value2); vnIndex[value1][value2][vnIndex_num[value1][value2]++] = key; } scanf("%d\n", &production1_num); for (int i = 0; i < production1_num; i++) { char key; int value; scanf("<%d>::=%c\n", &value, &key); production1[key][production1_cnt[key]++] = value; } scanf("%d\n", &slen); scanf("%s\n", solve); SubTree* char_map[128]; memset(char_map, NULL, sizeof(SubTree*) * 128); for (int i = 0; i < slen; i++) { char c = solve[i]; if (char_map[c] && char_map[c]->initialized == -1) { dp[i][i] = *char_map[c]; } else { for (int index = 0; index < production1_cnt[c]; ++index) { int integer = production1[c][index]; dp[i][i].vn[integer] = 1; if (!dp[i][i].mark[integer]) { dp[i][i].keys[dp[i][i].key_cnt++] = integer; dp[i][i].mark[integer] = 1; } } char_map[c] = &dp[i][i]; char_map[c]->initialized = -1; } } } int main() { clock_t start, end; start = clock(); input(); for (int len = 2; len <= slen; len++) { //#pragma omp parallel for for (int left = 0; left <= slen - len; left++) { //#pragma omp parallel for for (int right = left + 1; right < left + len; right++) { for (int leftIndex = 0; leftIndex < dp[left][right - 1].key_cnt; leftIndex++) { int leftVn = dp[left][right - 1].keys[leftIndex]; int leftNum = dp[left][right - 1].vn[leftVn]; for (int rightIndex = 0; rightIndex < dp[right][left + len - 1].key_cnt; rightIndex++) { int rightVn = dp[right][left + len - 1].keys[rightIndex]; int rightNum = dp[right][left + len - 1].vn[rightVn]; if (vnIndex_num[leftVn][rightVn] <= 0) continue; int tmpNum = vnIndex_num[leftVn][rightVn]; int total = leftNum * rightNum; for (int index = 0; index < tmpNum; index++) { int i = vnIndex[leftVn][rightVn][index]; if (!dp[left][left + len - 1].mark[i]) { dp[left][left + len - 1].keys[dp[left][left + len - 1].key_cnt++] = i; dp[left][left + len - 1].mark[i] = 1; } dp[left][left + len - 1].vn[i] += total; } } } } } } if (dp[0][slen - 1].vn[0] != 0) { printf("%u\n", dp[0][slen - 1].vn[0]); } else { printf("%u\n", 0); } end = clock(); printf("%lfms\n", (double)(end - start)); }
GB_unop__identity_uint16_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint16_fc32) // op(A') function: GB (_unop_tran__identity_uint16_fc32) // C type: uint16_t // A type: GxB_FC32_t // cast: uint16_t cij = GB_cast_to_uint16_t ((double) crealf (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint16_t z = GB_cast_to_uint16_t ((double) crealf (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = GB_cast_to_uint16_t ((double) crealf (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT16 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint16_fc32) ( uint16_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; uint16_t z = GB_cast_to_uint16_t ((double) crealf (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; uint16_t z = GB_cast_to_uint16_t ((double) crealf (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_uint16_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd foo // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd safelen(4) void test_no_clause() { int i; #pragma omp simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp simd' must be a for loop}} #pragma omp simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd; for (i = 0; i < 16; ++i) ; // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd firstprivate(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd safelen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd safelen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, ) for (i = 0; i < 16; ++i) ; // xxpected-error@+1 {{expected expression}} #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd safelen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd simdlen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd simdlen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd simdlen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_safelen_simdlen() { int i; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd simdlen(6) safelen(5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // xxpected-error@+1 {{expected expression}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} #pragma omp simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as reduction}} #pragma omp parallel #pragma omp simd collapse(2) reduction(+ : i) for (i = 0; i < 16; ++i) // expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for' directive into a parallel or another task region?}} for (int j = 0; j < 16; ++j) // expected-error@+2 2 {{reduction variable must be shared}} // expected-error@+1 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; #pragma omp parallel #pragma omp for for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp simd reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_linear() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd linear(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd linear(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd linear(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd linear(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd linear(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // expected-error@+1 {{expected expression}} #pragma omp simd linear(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be linear}} #pragma omp simd linear(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as private}} // expected-error@+1 {{private variable cannot be linear}} #pragma omp simd private(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be private}} #pragma omp simd linear(x) private(x) for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{zero linear step (x and other variables in clause should probably be const)}} #pragma omp simd linear(x, y : 0) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be lastprivate}} #pragma omp simd linear(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as lastprivate}} // expected-error@+1 {{lastprivate variable cannot be linear}} #pragma omp simd lastprivate(x) linear(x) for (i = 0; i < 16; ++i) ; } void test_aligned() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd aligned(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd aligned(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; int *x, y, z[25]; // expected-note 4 {{'y' defined here}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as aligned}} // expected-error@+1 {{a variable cannot appear in more than one aligned clause}} #pragma omp simd aligned(x) aligned(z, x) for (i = 0; i < 16; ++i) ; // expected-note@+3 {{defined as aligned}} // expected-error@+2 {{a variable cannot appear in more than one aligned clause}} // expected-error@+1 2 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) aligned(y, z) for (i = 0; i < 16; ++i) ; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_firstprivate() { int i; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-error@+1 {{expected expression}} #pragma omp simd firstprivate( for (i = 0; i < 16; ++i) ; } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_reduction() { int i, x, y; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction() for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction( : x) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(, for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(+ for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+: for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ : x, + : y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction(% : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(+ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(* : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(- : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(^ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(&& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(|| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(max : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(min : x) for (i = 0; i < 16; ++i) ; struct X { int x; }; struct X X; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : X.x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : x + x) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void linear_modifiers(int argc) { int f; #pragma omp simd linear(f) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(val(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(ref(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(foo(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; }
bcnn_maxpool_layer.c
/* * Copyright (c) 2016-present Jean-Noel Braun. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "bcnn_maxpool_layer.h" #include <float.h> #include <math.h> #include <bh/bh_log.h> #include <bh/bh_string.h> #include "bcnn_net.h" #include "bcnn_tensor.h" #include "bcnn_utils.h" #include <bh/bh_timer.h> #ifdef BCNN_USE_NEON #include <arm_neon.h> #include <bh/bh_macros.h> #endif bcnn_status bcnn_add_maxpool_layer(bcnn_net *net, int size, int stride, bcnn_padding padding, const char *src_id, const char *dst_id) { bcnn_node node = {0}; bcnn_tensor dst_tensor = {0}; if (net->num_nodes > 0) { int is_src_node_found = 0; for (int i = net->num_tensors - 1; i >= 0; --i) { if (strcmp(net->tensors[i].name, src_id) == 0) { bcnn_node_add_input(net, &node, i); is_src_node_found = 1; break; } } BCNN_CHECK_AND_LOG( net->log_ctx, is_src_node_found, BCNN_INVALID_PARAMETER, "Maxpool layer: invalid input node name %s\n", src_id); } else { bcnn_node_add_input(net, &node, 0); } // Compute output size according to padding option int out_h = (padding == BCNN_PADDING_SAME) ? (net->tensors[node.src[0]].h + stride - 1) / stride : (padding == BCNN_PADDING_VALID) ? (net->tensors[node.src[0]].h - size + stride) / stride : (padding == BCNN_PADDING_CAFFE) ? ((int)(ceil( (float)(net->tensors[node.src[0]].h - size) / stride)) + 1) : 0; int out_w = (padding == BCNN_PADDING_SAME) ? (net->tensors[node.src[0]].w + stride - 1) / stride : (padding == BCNN_PADDING_VALID) ? (net->tensors[node.src[0]].w - size + stride) / stride : (padding == BCNN_PADDING_CAFFE) ? ((int)(ceil( (float)(net->tensors[node.src[0]].w - size) / stride)) + 1) : 0; bcnn_tensor_set_shape(&dst_tensor, net->tensors[node.src[0]].n, // batch size net->tensors[node.src[0]].c, // depth out_h, // height out_w, // width 1); bcnn_tensor_allocate(&dst_tensor, net->mode); bh_strfill(&dst_tensor.name, dst_id); // Add node to net bcnn_net_add_tensor(net, dst_tensor); // Add tensor output index to node bcnn_node_add_output(net, &node, net->num_tensors - 1); int sz = bcnn_tensor_size(&net->tensors[node.dst[0]]); node.type = BCNN_LAYER_MAXPOOL; node.param_size = sizeof(bcnn_maxpool_param); node.param = (bcnn_maxpool_param *)calloc(1, node.param_size); bcnn_maxpool_param *param = (bcnn_maxpool_param *)node.param; param->size = size; param->stride = stride; param->padding = padding; param->indexes = (int *)calloc(sz, sizeof(int)); #ifdef BCNN_USE_CUDA param->indexes_gpu = bcnn_cuda_malloc_i32(sz); #ifdef BCNN_USE_CUDNN bcnn_cudnn_check(cudnnCreateTensorDescriptor(&param->src_tensor_desc)); bcnn_cudnn_check(cudnnCreateTensorDescriptor(&param->dst_tensor_desc)); bcnn_cudnn_check(cudnnCreatePoolingDescriptor(&param->pooling_desc)); bcnn_cudnn_check(cudnnSetPooling2dDescriptor( param->pooling_desc, CUDNN_POOLING_MAX, CUDNN_NOT_PROPAGATE_NAN, param->size, param->size, 0, 0, param->stride, param->stride)); bcnn_cudnn_check(cudnnSetTensor4dDescriptor( param->src_tensor_desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, net->tensors[node.src[0]].n, net->tensors[node.src[0]].c, net->tensors[node.src[0]].h, net->tensors[node.src[0]].w)); bcnn_cudnn_check(cudnnSetTensor4dDescriptor( param->dst_tensor_desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, net->tensors[node.dst[0]].n, net->tensors[node.dst[0]].c, net->tensors[node.dst[0]].h, net->tensors[node.dst[0]].w)); #endif #endif node.forward = bcnn_forward_maxpool_layer; node.backward = bcnn_backward_maxpool_layer; node.release_param = bcnn_release_param_maxpool_layer; bcnn_net_add_node(net, node); char node_opname[256]; snprintf(node_opname, 256, BH_LOG_BOLDBLUE "[Maxpool]" BH_LOG_RESET " "); BCNN_INFO( net->log_ctx, "%-48s %-8s (%4d x%4d x%4d) -> %-8s (%4d x%4d x%4d) %12d x %2d / %2d\n", node_opname, net->tensors[node.src[0]].name, net->tensors[node.src[0]].w, net->tensors[node.src[0]].h, net->tensors[node.src[0]].c, net->tensors[node.dst[0]].name, net->tensors[node.dst[0]].w, net->tensors[node.dst[0]].h, net->tensors[node.dst[0]].c, size, size, stride); return 0; } void bcnn_forward_maxpool_layer_cpu(bcnn_net *net, bcnn_node *node) { bcnn_tensor *src_tensor = &net->tensors[node->src[0]]; bcnn_tensor *dst_tensor = &net->tensors[node->dst[0]]; bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; int size = param->size; int stride = param->stride; int *indexes = param->indexes; int batch_size = dst_tensor->n; for (int b = 0; b < batch_size; ++b) { // batch_size int offset0 = dst_tensor->c * b; #pragma omp parallel for num_threads(net->num_threads) for (int k = 0; k < dst_tensor->c; ++k) { // depth int offset1 = dst_tensor->h * (k + offset0); for (int i = 0; i < dst_tensor->h; ++i) { // height int offset2 = dst_tensor->w * (offset1 + i); for (int j = 0; j < dst_tensor->w; ++j) { // width int dst_index = j + offset2; float max_f = -FLT_MAX; int max_i = -1; for (int n = 0; n < size; ++n) { // pooling window for (int m = 0; m < size; ++m) { int cur_h = i * stride + n; int cur_w = j * stride + m; int src_index = cur_w + src_tensor->w * (cur_h + src_tensor->h * (k + b * src_tensor->c)); int valid = (cur_h >= 0 && cur_h < src_tensor->h && cur_w >= 0 && cur_w < src_tensor->w); float val = (valid != 0) ? src_tensor->data[src_index] : -FLT_MAX; if (val > max_f) { max_f = val; max_i = src_index; } } } dst_tensor->data[dst_index] = max_f; indexes[dst_index] = max_i; } } } } return; } #ifdef BCNN_USE_NEON void bcnn_forward_maxpool_layer_cpu_neon_2x2(bcnn_tensor *src_tensor, bcnn_tensor *dst_tensor) { const int tail = src_tensor->w + (src_tensor->w - 2 * dst_tensor->w); for (int b = 0; b < dst_tensor->n; ++b) { // batch_size int offset0 = dst_tensor->c * b; for (int k = 0; k < dst_tensor->c; ++k) { // depth const float *p_src0 = src_tensor->data + src_tensor->h * src_tensor->w * (k + src_tensor->c * b); const float *p_src1 = src_tensor->data + src_tensor->h * src_tensor->w * (k + offset0) + src_tensor->w; float *outptr = dst_tensor->data + dst_tensor->h * dst_tensor->w * (k + offset0); for (int i = 0; i < dst_tensor->h; i++) { int half = dst_tensor->w >> 2; int last = dst_tensor->w - (half << 2); for (int x = 0; x < (half << 2); ++x) { float32x2_t max0, max1; max0 = vld1_f32(p_src0); p_src0 += 2; max1 = vld1_f32(p_src1); p_src1 += 2; max0 = vmax_f32(max0, max1); max0 = vpmax_f32(max0, max0); vst1_lane_f32(outptr, max0, 0); outptr++; } for (; last > 0; last--) { float max0 = bh_max(p_src0[0], p_src0[1]); float max1 = bh_max(p_src1[0], p_src1[1]); *outptr = bh_max(max0, max1); p_src0 += 2; p_src1 += 2; outptr++; } p_src0 += tail; p_src1 += tail; } } } return; } #endif void bcnn_forward_maxpool_layer(bcnn_net *net, bcnn_node *node) { #ifdef BCNN_USE_CUDA return bcnn_forward_maxpool_layer_gpu(net, node); #else #ifdef BCNN_USE_NEON bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; if (param->size == 2 && param->stride == 2) { bcnn_tensor *src = &net->tensors[node->src[0]]; bcnn_tensor *dst = &net->tensors[node->dst[0]]; return bcnn_forward_maxpool_layer_cpu_neon_2x2(src, dst); } else { return bcnn_forward_maxpool_layer_cpu(net, node); } #else return bcnn_forward_maxpool_layer_cpu(net, node); #endif // BCNN_USE_NEON #endif // BCNN_USE_CUDA } void bcnn_backward_maxpool_layer_cpu(bcnn_net *net, bcnn_node *node) { bcnn_tensor *src_tensor = &net->tensors[node->src[0]]; bcnn_tensor *dst_tensor = &net->tensors[node->dst[0]]; bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; int *indexes = param->indexes; int i, index; int sz = bcnn_tensor_size(dst_tensor); for (i = 0; i < sz; ++i) { index = indexes[i]; src_tensor->grad_data[index] += dst_tensor->grad_data[i]; } return; } void bcnn_backward_maxpool_layer(bcnn_net *net, bcnn_node *node) { #ifdef BCNN_USE_CUDA return bcnn_backward_maxpool_layer_gpu(net, node); #else return bcnn_backward_maxpool_layer_cpu(net, node); #endif return; } void bcnn_release_param_maxpool_layer(bcnn_node *node) { bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; bh_free(param->indexes); #ifdef BCNN_USE_CUDA if (param->indexes_gpu) { bcnn_cuda_free(param->indexes_gpu); } #ifdef BCNN_USE_CUDNN cudnnDestroyTensorDescriptor(param->src_tensor_desc); cudnnDestroyTensorDescriptor(param->dst_tensor_desc); cudnnDestroyPoolingDescriptor(param->pooling_desc); #endif #endif return; }
cancellation_for_sections.c
// RUN: %libomp-compile && env OMP_CANCELLATION=true %libomp-run // Clang had a bug until version 4.0.1 which resulted in a hang. // UNSUPPORTED: clang-3, clang-4.0.0 // Regression test for a bug in cancellation to cover effect of `#pragma omp cancel` // in a loop construct, on sections construct. // Pass condition: Cancellation status from `for` does not persist // to `sections`. #include <stdio.h> #include <omp.h> int result[2] = {0, 0}; void cq416850_for_sections() { unsigned i; // 1) loop #pragma omp for for (i = 0; i < 1; i++) { result[0] = 1; #pragma omp cancel for result[0] = 2; } // printf("thread %d: result[0] = %d, result[1] = %d \n", omp_get_thread_num(), result[0], result[1]); // 2) sections #pragma omp sections { #pragma omp section { result[1] = 1; #pragma omp cancellation point sections result[1] = 2; } } } int main(void) { if(!omp_get_cancellation()) { printf("Cancellation not enabled!\n"); return 2; } #pragma omp parallel num_threads(4) { cq416850_for_sections(); } if (result[0] != 1 || result[1] != 2) { printf("Incorrect values. " "result[0] = %d (expected 1), " "result[1] = %d (expected 2).\n", result[0], result[1]); printf("FAILED\n"); return 1; } printf("PASSED\n"); return 0; }
target_teams_distribute_simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd foo void test_no_clause(void) { int i; #pragma omp target teams distribute simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target teams distribute simd' must be a for loop}} #pragma omp target teams distribute simd ++i; } void test_branch_protected_scope(void) { int i = 0; L1: ++i; int x[24]; #pragma omp target teams distribute simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause(void) { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers(void) { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(void); void test_collapse(void) { int i; // expected-error@+1 {{expected '('}} #pragma omp target teams distribute simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target teams distribute simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} #pragma omp target teams distribute simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+1 {{integer constant expression}} #pragma omp target teams distribute simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp target teams distribute simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-error@+4 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp target teams distribute simd collapse(2) firstprivate(i) // expected-note {{defined as firstprivate}} for (i = 0; i < 16; ++i) // expected-error {{loop iteration variable in the associated loop of 'omp target teams distribute simd' directive may not be firstprivate, predetermined as lastprivate}} for (int j = 0; j < 16; ++j) #pragma omp parallel for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_private(void) { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate(void) { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate(void) { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; // expected-error@+1 {{lastprivate variable cannot be firstprivate}} expected-note@+1 {{defined as lastprivate}} #pragma omp target teams distribute simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{lastprivate variable cannot be firstprivate}} expected-note@+1 2 {{defined as lastprivate}} #pragma omp target teams distribute simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 3 {{lastprivate variable cannot be firstprivate}} expected-note@+1 3 {{defined as lastprivate}} #pragma omp target teams distribute simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp target teams distribute simd simdlen(64) safelen(8) for (i = 0; i < 16; ++i) ; } void test_loop_messages(void) { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void test_nontemporal(void) { int i; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd nontemporal( for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd nontemporal(, for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd nontemporal(, ) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd nontemporal() for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd nontemporal(int) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} omp50-error@+1 {{expected variable name}} #pragma omp target teams distribute simd nontemporal(0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp target teams distribute simd nontemporal(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp target teams distribute simd nontemporal(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp target teams distribute simd nontemporal(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd nontemporal(x :) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} #pragma omp target teams distribute simd nontemporal(x :, ) for (i = 0; i < 16; ++i) ; // omp50-note@+2 {{defined as nontemporal}} // omp45-error@+1 2 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}} #pragma omp target teams distribute simd nontemporal(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd private(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd nontemporal(x) private(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} #pragma omp target teams distribute simd nontemporal(x, y : 0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd nontemporal(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd lastprivate(x) nontemporal(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd order // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp target teams distribute simd'}} expected-error {{expected '(' after 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd order( // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp target teams distribute simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd order(none // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp target teams distribute simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd order(concurrent // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp target teams distribute simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd order(concurrent) // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp target teams distribute simd'}} for (int i = 0; i < 10; ++i) ; }
myd09ga.c
#include<stdio.h> #include "gdal.h" #include "arrays.h" #include<omp.h> /* MODLAND QA Bits 500m long int bits[0-1] * 00 -> class 0: Corrected product produced at ideal quality -- all bands * 01 -> class 1: Corrected product produced at less than idel quality -- some or all bands * 10 -> class 2: Corrected product NOT produced due to cloud effect -- all bands * 11 -> class 3: Corrected product NOT produced due to other reasons -- some or all bands mayb be fill value (Note that a value of [11] overrides a value of [01]) */ unsigned int myd09GAa(unsigned int pixel) { /* Select bit 0 and 1 (right-side). * hexadecimal "0x03" => binary "11" * this will set all other bits to null */ return (pixel & 0x03); } /* Band-wise Data Quality 500m long Int * bits[2-5][6-9][10-13][14-17][18-21][22-25][26-29] * 0000 -> class 0: highest quality * 0111 -> class 1: noisy detector * 1000 -> class 2: dead detector; data interpolated in L1B * 1001 -> class 3: solar zenith >= 86 degrees * 1010 -> class 4: solar zenith >= 85 and < 86 degrees * 1011 -> class 5: missing input * 1100 -> class 6: internal constant used in place of climatological data for at least one atmospheric constant * 1101 -> class 7: correction out of bounds, pixel constrained to extreme allowable value * 1110 -> class 8: L1B data faulty * 1111 -> class 9: not processed due to deep ocean or cloud * Class 10-15: Combination of bits unused */ unsigned int myd09GAc(unsigned int pixel, int bandno) { unsigned int qctemp; pixel >>= 2 + (4 * (bandno - 1)); /* bitshift [] to [0-3] etc. */ qctemp = pixel & 0x0F; return qctemp; } void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./myd09ga inQA inB3\n"); printf( "\tout\n"); printf( "-----------------------------------------\n"); printf( "inQA\t\tModis myd09GA QC_500m_1\n"); printf( "inB3\t\tModis myd09GA Band3\n"); printf( "out\tQA corrected B3 output [-]\n"); return; } int main( int argc, char *argv[] ) { if( argc < 4 ) { usage(); return (EXIT_FAILURE); } char *inB = argv[1]; //QA char *inB3 = argv[2]; //B3 char *outF = argv[3]; //Loading the input files GDALAllRegister(); GDALDatasetH hD = GDALOpen(inB,GA_ReadOnly);//QA GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//B3 if(hD==NULL||hD3==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(EXIT_FAILURE); } //Loading the file infos GDALDriverH hDr3 = GDALGetDatasetDriver(hD3); char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); //Creating output file GDALDatasetH hDOut = GDALCreateCopy(hDr3,outF,hD3,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); //Loading the file bands GDALRasterBandH hB = GDALGetRasterBand(hD,1);//QA GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//B3 //Loading the data in RAM int nX = GDALGetRasterBandXSize(hB3); int nY = GDALGetRasterBandYSize(hB3); int N=nX*nY; unsigned int *l = aui1d(N); int *l3 = ai1d(N); int *lOut = ai1d(N); int rowcol, qa, qa1; //myd09GA QA 500m GDALRasterIO(hB,GF_Read,0,0,nX,nY,l,nX,nY,GDT_UInt32,0,0); //myd09GA B3 GDALRasterIO(hB3,GF_Read,0,0,nX,nY,l3,nX,nY,GDT_Int32,0,0); #pragma omp parallel for default(none) \ private (rowcol, qa, qa1) shared (N, l, l3, lOut) for(rowcol=0;rowcol<N;rowcol++){ qa=myd09GAa(l[rowcol]); qa1=myd09GAc(l3[rowcol],3); if( qa == 0 || qa1 == 0 ) lOut[rowcol] = l3[rowcol]; else lOut[rowcol] = -28768; } #pragma omp barrier GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Int32,0,0); if( l != NULL ) free( l ); if( l3 != NULL ) free( l3 ); GDALClose(hD); GDALClose(hD3); GDALClose(hDOut); return(EXIT_SUCCESS); }
14_omp_nested.c
// clang-format off // RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s // RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s // RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | %apply-typeart -typeart-alloca -call-filter -S | FileCheck %s --check-prefix=check-inst // RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -S | FileCheck %s --check-prefix=check-inst // REQUIRES: openmp // clang-format on extern void MPI_call(void*); void func(int* x) { #pragma omp parallel { MPI_call(x); } } void foo() { // check-inst: define {{.*}} @foo // check-inst: %x = alloca // check-inst: %0 = bitcast i32* %x to i8* // check-inst: call void @__typeart_alloc_stack(i8* %0, i32 2, i64 1) // check-inst-not: __typeart_alloc_stack_omp int x; #pragma omp parallel { func(&x); } } // CHECK: TypeArtPass [Heap & Stack] // CHECK-NEXT: Malloc : 0 // CHECK-NEXT: Free : 0 // CHECK-NEXT: Alloca : 1 // CHECK-NEXT: Global : 0
SpatialConvolutionMap.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SpatialConvolutionMap.c" #else static int nn_(SpatialConvolutionMap_updateOutput)(lua_State *L) { THTensor *input = luaT_checkudata(L, 2, torch_Tensor); int kW = luaT_getfieldcheckint(L, 1, "kW"); int kH = luaT_getfieldcheckint(L, 1, "kH"); int dW = luaT_getfieldcheckint(L, 1, "dW"); int dH = luaT_getfieldcheckint(L, 1, "dH"); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); THTensor *connTable = luaT_getfieldcheckudata(L, 1, "connTable", torch_Tensor); THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor); THTensor *bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor); THTensor *output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor); real *input_data; real *output_data; real *weight_data; real *bias_data; real *connTable_data; long input_h; long input_w; long output_h; long output_w; long weight_h; long weight_w; long p; int nweight; luaL_argcheck(L, input->nDimension == 3, 2, "3D tensor expected"); luaL_argcheck(L, input->size[0] >= nInputPlane, 2, "invalid number of input planes"); luaL_argcheck(L, input->size[2] >= kW && input->size[1] >= kH, 2, "input image smaller than kernel size"); THTensor_(resize3d)(output, nOutputPlane, (input->size[1] - kH) / dH + 1, (input->size[2] - kW) / dW + 1); /* contiguous */ input = THTensor_(newContiguous)(input); output = THTensor_(newContiguous)(output); /* get raw pointers */ input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); weight_data = THTensor_(data)(weight); bias_data = THTensor_(data)(bias); connTable_data = THTensor_(data)(connTable); /* and dims */ input_h = input->size[1]; input_w = input->size[2]; output_h = output->size[1]; output_w = output->size[2]; weight_h = weight->size[1]; weight_w = weight->size[2]; #pragma omp parallel for private(p) for (p = 0; p < nOutputPlane; p++) { /* add bias */ real *ptr_output = output_data + p*output_w*output_h; long j,k; for(j = 0; j < output_h*output_w; j++) ptr_output[j] = bias_data[p]; /* convolve all maps */ nweight = connTable->size[0]; for (k = 0; k < nweight; k++) { /* get offsets for input/output */ int o = (int)connTable_data[k*2+1]-1; int i = (int)connTable_data[k*2+0]-1; if (o == p) { THTensor_(validXCorr2Dptr)(output_data + o*output_w*output_h, 1.0, input_data + i*input_w*input_h, input_h, input_w, weight_data + k*weight_w*weight_h, weight_h, weight_w, dH, dW); } } } /* clean up */ THTensor_(free)(input); THTensor_(free)(output); return 1; } static int nn_(SpatialConvolutionMap_updateGradInput)(lua_State *L) { THTensor *input = luaT_checkudata(L, 2, torch_Tensor); THTensor *gradOutput = luaT_checkudata(L, 3, torch_Tensor); int dW = luaT_getfieldcheckint(L, 1, "dW"); int dH = luaT_getfieldcheckint(L, 1, "dH"); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); THTensor *connTable = luaT_getfieldcheckudata(L, 1, "connTable", torch_Tensor); THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor); THTensor *gradInput = luaT_getfieldcheckudata(L, 1, "gradInput", torch_Tensor); real *gradInput_data; real *gradOutput_data; real *weight_data; real *connTable_data; long input_h; long input_w; long output_h; long output_w; long weight_h; long weight_w; long p; /* contiguous */ gradInput = THTensor_(newContiguous)(gradInput); gradOutput = THTensor_(newContiguous)(gradOutput); /* Resize/Zero */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); /* get raw pointers */ gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); weight_data = THTensor_(data)(weight); connTable_data = THTensor_(data)(connTable); /* and dims */ input_h = input->size[1]; input_w = input->size[2]; output_h = gradOutput->size[1]; output_w = gradOutput->size[2]; weight_h = weight->size[1]; weight_w = weight->size[2]; #pragma omp parallel for private(p) for(p = 0; p < nInputPlane; p++) { long k; /* backward all */ int nkernel = connTable->size[0]; for(k = 0; k < nkernel; k++) { int o = (int)connTable_data[k*2+1]-1; int i = (int)connTable_data[k*2+0]-1; if (i == p) { /* gradient to input */ THTensor_(fullConv2Dptr)(gradInput_data + i*input_w*input_h, 1.0, gradOutput_data + o*output_w*output_h, output_h, output_w, weight_data + k*weight_w*weight_h, weight_h, weight_w, dH, dW); } } } /* clean up */ THTensor_(free)(gradInput); THTensor_(free)(gradOutput); return 1; } static int nn_(SpatialConvolutionMap_accGradParameters)(lua_State *L) { THTensor *input = luaT_checkudata(L, 2, torch_Tensor); THTensor *gradOutput = luaT_checkudata(L, 3, torch_Tensor); int dW = luaT_getfieldcheckint(L, 1, "dW"); int dH = luaT_getfieldcheckint(L, 1, "dH"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); real scale = luaL_optnumber(L, 4, 1); THTensor *connTable = luaT_getfieldcheckudata(L, 1, "connTable", torch_Tensor); THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor); THTensor *gradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor); THTensor *gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor); real *input_data; real *gradOutput_data; real *gradWeight_data; real *gradBias_data; /* and dims */ long input_h; long input_w; long output_h; long output_w; long weight_h; long weight_w; long k; int nkernel; /* contiguous */ input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); /* get raw pointers */ input_data = THTensor_(data)(input); gradOutput_data = THTensor_(data)(gradOutput); gradWeight_data = THTensor_(data)(gradWeight); gradBias_data = THTensor_(data)(gradBias); /* and dims */ input_h = input->size[1]; input_w = input->size[2]; output_h = gradOutput->size[1]; output_w = gradOutput->size[2]; weight_h = weight->size[1]; weight_w = weight->size[2]; /* gradients wrt bias */ #pragma omp parallel for private(k) for(k = 0; k < nOutputPlane; k++) { real *ptr_gradOutput = gradOutput_data + k*output_w*output_h; long l; for(l = 0; l < output_h*output_w; l++) gradBias_data[k] += scale*ptr_gradOutput[l]; } /* gradients wrt weight */ nkernel = connTable->size[0]; #pragma omp parallel for private(k) for(k = 0; k < nkernel; k++) { int o = (int)THTensor_(get2d)(connTable,k,1)-1; int i = (int)THTensor_(get2d)(connTable,k,0)-1; /* gradient to kernel */ THTensor_(validXCorr2DRevptr)(gradWeight_data + k*weight_w*weight_h, scale, input_data + i*input_w*input_h, input_h, input_w, gradOutput_data + o*output_w*output_h, output_h, output_w, dH, dW); } /* clean up */ THTensor_(free)(input); THTensor_(free)(gradOutput); return 0; } static const struct luaL_Reg nn_(SpatialConvolutionMap__) [] = { {"SpatialConvolutionMap_updateOutput", nn_(SpatialConvolutionMap_updateOutput)}, {"SpatialConvolutionMap_updateGradInput", nn_(SpatialConvolutionMap_updateGradInput)}, {"SpatialConvolutionMap_accGradParameters", nn_(SpatialConvolutionMap_accGradParameters)}, {NULL, NULL} }; static void nn_(SpatialConvolutionMap_init)(lua_State *L) { luaT_pushmetatable(L, torch_Tensor); luaT_registeratname(L, nn_(SpatialConvolutionMap__), "nn"); lua_pop(L,1); } #endif
kmp_sch_simd_guided.c
// RUN: %libomp-compile-and-run /* Test for the 'schedule(simd:guided)' clause. Compiler needs to generate a dynamic dispatching and pass the schedule value 46 to the OpenMP RTL. Test uses numerous loop parameter combinations. */ #include <stdio.h> #include <omp.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> #define delay() Sleep(1); #else #include <unistd.h> #define delay() usleep(10); #endif // uncomment for debug diagnostics: //#define DEBUG #define SIMD_LEN 4 // --------------------------------------------------------------------------- // Various definitions copied from OpenMP RTL enum sched { kmp_sch_static_balanced_chunked = 45, kmp_sch_guided_simd = 46, kmp_sch_runtime_simd = 47, }; typedef unsigned u32; typedef long long i64; typedef unsigned long long u64; typedef struct { int reserved_1; int flags; int reserved_2; int reserved_3; char *psource; } id; extern int __kmpc_global_thread_num(id*); extern void __kmpc_barrier(id*, int gtid); extern void __kmpc_dispatch_init_4(id*, int, enum sched, int, int, int, int); extern void __kmpc_dispatch_init_8(id*, int, enum sched, i64, i64, i64, i64); extern int __kmpc_dispatch_next_4(id*, int, void*, void*, void*, void*); extern int __kmpc_dispatch_next_8(id*, int, void*, void*, void*, void*); // End of definitions copied from OpenMP RTL. // --------------------------------------------------------------------------- static id loc = {0, 2, 0, 0, ";file;func;0;0;;"}; // --------------------------------------------------------------------------- int run_loop_64(i64 loop_lb, i64 loop_ub, i64 loop_st, int loop_chunk) { int err = 0; static int volatile loop_sync = 0; i64 lb; // Chunk lower bound i64 ub; // Chunk upper bound i64 st; // Chunk stride int rc; int tid = omp_get_thread_num(); int gtid = tid; int last; #if DEBUG printf("run_loop_<%d>(lb=%d, ub=%d, st=%d, ch=%d)\n", (int)sizeof(i64), gtid, tid, (int)loop_lb, (int)loop_ub, (int)loop_st, loop_chunk); #endif // Don't test degenerate cases that should have been discovered by codegen if (loop_st == 0) return 0; if (loop_st > 0 ? loop_lb > loop_ub : loop_lb < loop_ub) return 0; __kmpc_dispatch_init_8(&loc, gtid, kmp_sch_guided_simd, loop_lb, loop_ub, loop_st, loop_chunk); if (tid == 0) { // Let the master thread handle the chunks alone int chunk; // No of current chunk i64 next_lb; // Lower bound of the next chunk i64 last_ub; // Upper bound of the last processed chunk u64 cur; // Number of interations in current chunk u64 max; // Max allowed iterations for current chunk int undersized = 0; chunk = 0; next_lb = loop_lb; max = (loop_ub - loop_lb) / loop_st + 1; // The first chunk can consume all iterations while (__kmpc_dispatch_next_8(&loc, gtid, &last, &lb, &ub, &st)) { ++ chunk; #if DEBUG printf("chunk=%d, lb=%d, ub=%d\n", chunk, (int)lb, (int)ub); #endif // Check if previous chunk (it is not the final chunk) is undersized if (undersized) { printf("Error with chunk %d\n", chunk); err++; } // Check lower and upper bounds if (lb != next_lb) { printf("Error with lb %d, %d, ch %d\n", (int)lb, (int)next_lb, chunk); err++; } if (loop_st > 0) { if (!(ub <= loop_ub)) { printf("Error with ub %d, %d, ch %d\n", (int)ub, (int)loop_ub, chunk); err++; } if (!(lb <= ub)) { printf("Error with bounds %d, %d, %d\n", (int)lb, (int)ub, chunk); err++; } } else { if (!(ub >= loop_ub)) { printf("Error with ub %d, %d, %d\n", (int)ub, (int)loop_ub, chunk); err++; } if (!(lb >= ub)) { printf("Error with bounds %d, %d, %d\n", (int)lb, (int)ub, chunk); err++; } }; // if // Stride should not change if (!(st == loop_st)) { printf("Error with st %d, %d, ch %d\n", (int)st, (int)loop_st, chunk); err++; } cur = (ub - lb) / loop_st + 1; // Guided scheduling uses FP computations, so current chunk may // be a bit bigger (+1) than allowed maximum if (!(cur <= max + 1)) { printf("Error with iter %d, %d\n", cur, max); err++; } // Update maximum for the next chunk if (cur < max) max = cur; next_lb = ub + loop_st; last_ub = ub; undersized = (cur < loop_chunk); }; // while // Must have at least one chunk if (!(chunk > 0)) { printf("Error with chunk %d\n", chunk); err++; } // Must have the right last iteration index if (loop_st > 0) { if (!(last_ub <= loop_ub)) { printf("Error with last1 %d, %d, ch %d\n", (int)last_ub, (int)loop_ub, chunk); err++; } if (!(last_ub + loop_st > loop_ub)) { printf("Error with last2 %d, %d, %d, ch %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk); err++; } } else { if (!(last_ub >= loop_ub)) { printf("Error with last1 %d, %d, ch %d\n", (int)last_ub, (int)loop_ub, chunk); err++; } if (!(last_ub + loop_st < loop_ub)) { printf("Error with last2 %d, %d, %d, ch %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk); err++; } }; // if // Let non-master threads go loop_sync = 1; } else { int i; // Workers wait for master thread to finish, then call __kmpc_dispatch_next for (i = 0; i < 1000000; ++ i) { if (loop_sync != 0) { break; }; // if }; // for i while (loop_sync == 0) { delay(); }; // while // At this moment we do not have any more chunks -- all the chunks already // processed by master thread rc = __kmpc_dispatch_next_8(&loc, gtid, &last, &lb, &ub, &st); if (rc) { printf("Error return value\n"); err++; } }; // if __kmpc_barrier(&loc, gtid); if (tid == 0) { loop_sync = 0; // Restore original state #if DEBUG printf("run_loop_64(): at the end\n"); #endif }; // if __kmpc_barrier(&loc, gtid); return err; } // run_loop // --------------------------------------------------------------------------- int run_loop_32(int loop_lb, int loop_ub, int loop_st, int loop_chunk) { int err = 0; static int volatile loop_sync = 0; int lb; // Chunk lower bound int ub; // Chunk upper bound int st; // Chunk stride int rc; int tid = omp_get_thread_num(); int gtid = tid; int last; #if DEBUG printf("run_loop_<%d>(lb=%d, ub=%d, st=%d, ch=%d)\n", (int)sizeof(int), gtid, tid, (int)loop_lb, (int)loop_ub, (int)loop_st, loop_chunk); #endif // Don't test degenerate cases that should have been discovered by codegen if (loop_st == 0) return 0; if (loop_st > 0 ? loop_lb > loop_ub : loop_lb < loop_ub) return 0; __kmpc_dispatch_init_4(&loc, gtid, kmp_sch_guided_simd, loop_lb, loop_ub, loop_st, loop_chunk); if (tid == 0) { // Let the master thread handle the chunks alone int chunk; // No of current chunk int next_lb; // Lower bound of the next chunk int last_ub; // Upper bound of the last processed chunk u64 cur; // Number of interations in current chunk u64 max; // Max allowed iterations for current chunk int undersized = 0; chunk = 0; next_lb = loop_lb; max = (loop_ub - loop_lb) / loop_st + 1; // The first chunk can consume all iterations while (__kmpc_dispatch_next_4(&loc, gtid, &last, &lb, &ub, &st)) { ++ chunk; #if DEBUG printf("chunk=%d, lb=%d, ub=%d\n", chunk, (int)lb, (int)ub); #endif // Check if previous chunk (it is not the final chunk) is undersized if (undersized) { printf("Error with chunk %d\n", chunk); err++; } // Check lower and upper bounds if (lb != next_lb) { printf("Error with lb %d, %d, ch %d\n", (int)lb, (int)next_lb, chunk); err++; } if (loop_st > 0) { if (!(ub <= loop_ub)) { printf("Error with ub %d, %d, ch %d\n", (int)ub, (int)loop_ub, chunk); err++; } if (!(lb <= ub)) { printf("Error with bounds %d, %d, %d\n", (int)lb, (int)ub, chunk); err++; } } else { if (!(ub >= loop_ub)) { printf("Error with ub %d, %d, %d\n", (int)ub, (int)loop_ub, chunk); err++; } if (!(lb >= ub)) { printf("Error with bounds %d, %d, %d\n", (int)lb, (int)ub, chunk); err++; } }; // if // Stride should not change if (!(st == loop_st)) { printf("Error with st %d, %d, ch %d\n", (int)st, (int)loop_st, chunk); err++; } cur = (ub - lb) / loop_st + 1; // Guided scheduling uses FP computations, so current chunk may // be a bit bigger (+1) than allowed maximum if (!(cur <= max + 1)) { printf("Error with iter %d, %d\n", cur, max); err++; } // Update maximum for the next chunk if (cur < max) max = cur; next_lb = ub + loop_st; last_ub = ub; undersized = (cur < loop_chunk); }; // while // Must have at least one chunk if (!(chunk > 0)) { printf("Error with chunk %d\n", chunk); err++; } // Must have the right last iteration index if (loop_st > 0) { if (!(last_ub <= loop_ub)) { printf("Error with last1 %d, %d, ch %d\n", (int)last_ub, (int)loop_ub, chunk); err++; } if (!(last_ub + loop_st > loop_ub)) { printf("Error with last2 %d, %d, %d, ch %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk); err++; } } else { if (!(last_ub >= loop_ub)) { printf("Error with last1 %d, %d, ch %d\n", (int)last_ub, (int)loop_ub, chunk); err++; } if (!(last_ub + loop_st < loop_ub)) { printf("Error with last2 %d, %d, %d, ch %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk); err++; } }; // if // Let non-master threads go loop_sync = 1; } else { int i; // Workers wait for master thread to finish, then call __kmpc_dispatch_next for (i = 0; i < 1000000; ++ i) { if (loop_sync != 0) { break; }; // if }; // for i while (loop_sync == 0) { delay(); }; // while // At this moment we do not have any more chunks -- all the chunks already // processed by the master thread rc = __kmpc_dispatch_next_4(&loc, gtid, &last, &lb, &ub, &st); if (rc) { printf("Error return value\n"); err++; } }; // if __kmpc_barrier(&loc, gtid); if (tid == 0) { loop_sync = 0; // Restore original state #if DEBUG printf("run_loop<>(): at the end\n"); #endif }; // if __kmpc_barrier(&loc, gtid); return err; } // run_loop // --------------------------------------------------------------------------- int run_64(int num_th) { int err = 0; #pragma omp parallel num_threads(num_th) { int chunk; i64 st, lb, ub; for (chunk = SIMD_LEN; chunk <= 3*SIMD_LEN; chunk += SIMD_LEN) { for (st = 1; st <= 3; ++ st) { for (lb = -3 * num_th * st; lb <= 3 * num_th * st; ++ lb) { for (ub = lb; ub < lb + num_th * (chunk+1) * st; ++ ub) { err += run_loop_64(lb, ub, st, chunk); err += run_loop_64(ub, lb, -st, chunk); }; // for ub }; // for lb }; // for st }; // for chunk } return err; } // run_all int run_32(int num_th) { int err = 0; #pragma omp parallel num_threads(num_th) { int chunk, st, lb, ub; for (chunk = SIMD_LEN; chunk <= 3*SIMD_LEN; chunk += SIMD_LEN) { for (st = 1; st <= 3; ++ st) { for (lb = -3 * num_th * st; lb <= 3 * num_th * st; ++ lb) { for (ub = lb; ub < lb + num_th * (chunk+1) * st; ++ ub) { err += run_loop_32(lb, ub, st, chunk); err += run_loop_32(ub, lb, -st, chunk); }; // for ub }; // for lb }; // for st }; // for chunk } return err; } // run_all // --------------------------------------------------------------------------- int main() { int n, err = 0; for (n = 1; n <= 4; ++ n) { err += run_32(n); err += run_64(n); }; // for n if (err) printf("failed with %d errors\n", err); else printf("passed\n"); return err; }
firstlastprivate-clause.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main() { int i, n = 7; int a[n], suma=0; for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for firstprivate(suma) lastprivate(suma) for (i=0; i<n; i++) { suma = suma + a[i]; printf(" thread %d suma a[%d] suma=%d \n",omp_get_thread_num(),i,suma); } printf("\nFuera de la construcción parallel suma=%d\n",suma); }
race64.c
#include <ctype.h> #include <errno.h> #include <stdio.h> #include <string.h> #define VERSION "1.0.0" #define GROUPS_PER_LINE 19 // 1 group = 3 octets, 4 base64 digits #define LINES_PER_BLOCK (1 << 14) // tweaked experimentally #if __clang__ # define UNROLL _Pragma("unroll") #else # define UNROLL #endif /** * Encode from one file stream to another as fast as possible. Input and * output errors are detected by not communicated by this interface, so * check the streams' error indicators (e.g. ferror()) afterward. */ static void encode(FILE *fin, FILE *fout) { static unsigned char base64[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f }; static unsigned char in[LINES_PER_BLOCK][GROUPS_PER_LINE * 3]; static unsigned char out[LINES_PER_BLOCK][GROUPS_PER_LINE * 4 + 1]; /* Pre-write all the newlines */ for (int i = 0; i < LINES_PER_BLOCK; i++) out[i][sizeof(out[0]) - 1] = 0x0a; for (;;) { size_t len = fread(in, 1, sizeof(in), fin); if (!len) break; memset((char *)in + len, 0, sizeof(in) - len); /* Convert entire block at once with minimal branching */ int n; #pragma omp parallel for for (n = 0; n < LINES_PER_BLOCK; n++) { unsigned char *pi = in[n]; unsigned char *po = out[n]; /* Unrolling this inner loop has HUGE performance gains. */ UNROLL for (int i = 0; i < GROUPS_PER_LINE; i++) { po[i*4+0] = base64[(pi[i*3+0] >> 2)]; po[i*4+1] = base64[(pi[i*3+0] << 4 | pi[i*3+1] >> 4) & 0xff]; po[i*4+2] = base64[(pi[i*3+1] << 2 | pi[i*3+2] >> 6) & 0xff]; po[i*4+3] = base64[(pi[i*3+1] << 6 | pi[i*3+2] >> 0) & 0xff]; } } if (len < sizeof(in)) { /* Do a partial final write */ int nout = (len + sizeof(in[0]) - 1) / sizeof(in[0]); int linelen = len % sizeof(in[0]); int end = (linelen + 2) / 3 * 4; if (end) { /* Truncate last line */ switch (linelen % 3) { case 1: out[nout - 1][end - 2] = 0x3d; /* fallthrough */ case 2: out[nout - 1][end - 1] = 0x3d; /* fallthrough */ case 0: out[nout - 1][end - 0] = 0x0a; } fwrite(out, (nout - 1) * sizeof(out[0]) + end + 1, 1, fout); } else { /* Last line is whole */ fwrite(out, nout * sizeof(out[0]), 1, fout); } break; } else if (!fwrite(out, sizeof(out), 1, fout)) { /* Output error */ break; } } } /** * Decode from one file stream to another as fast as possible. Returns the * line number of the earliest detected syntax error, or 0 for success. * However, if input and output errors are not communicated by this * interface, so check the streams' error indicator (e.g. ferror()) * afterward. */ static unsigned long long decode(FILE *fin, FILE *fout) { static const unsigned char val[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; static unsigned char in[LINES_PER_BLOCK][GROUPS_PER_LINE * 4 + 1]; static unsigned char out[LINES_PER_BLOCK][GROUPS_PER_LINE * 3]; /* Initialize input block with valid inputs, for validation */ memset(in, 0x41, sizeof(in)); for (int i = 0; i < LINES_PER_BLOCK; i++) in[i][sizeof(in[0]) - 1] = 0x0a; for (unsigned long long nblocks = 0; ; nblocks++) { size_t out_len; size_t in_len = fread(in, 1, sizeof(in), fin); if (!in_len) { break; } else if (in_len < sizeof(in)) { /* This is a partial block. Compute the output size and leave * error detection to block processing. */ int nlines = (in_len + sizeof(in[0]) - 1) / sizeof(in[0]); int ntail = in_len - (nlines - 1) * sizeof(in[0]); unsigned char *end = in[nlines - 1] + ntail; if (ntail < 5 || ntail % 4 != 1) { /* Invalid input. Damage it and let block processing catch * the error. */ end[-1] = 0x0a; out_len = 0; } else { out_len = (nlines - 1) * GROUPS_PER_LINE * 3 + ntail / 4 * 3; if (end[-1] != 0x0a) { /* Invalid input. Damage it for later detection. */ end[-1] = 0x0a; } else if (ntail != sizeof(in[0])) { /* Change newline to zero bits so it's not detected as * an error later. */ end[-1] = 0x41; } if (end[-2] == '=') { out_len--; end[-2] = 0x41; } if (end[-3] == '=') { out_len--; end[-3] = 0x41; } } } else { out_len = sizeof(out); } /* Convert entire block no matter the input length */ int n; int badline = LINES_PER_BLOCK; #pragma omp parallel for for (n = 0; n < LINES_PER_BLOCK; n++) { unsigned char *pi = in[n]; unsigned char *po = out[n]; int check[2]; check[1] = 0; /* Unrolling this inner loop has HUGE performance gains. */ UNROLL for (int i = 0; i < GROUPS_PER_LINE; i++) { po[i*3+0] = val[pi[i*4+0]] << 2 | val[pi[i*4+1]] >> 4; po[i*3+1] = val[pi[i*4+1]] << 4 | val[pi[i*4+2]] >> 2; po[i*3+2] = val[pi[i*4+2]] << 6 | val[pi[i*4+3]] >> 0; check[val[pi[i*4+0]] >> 7] = 1; check[val[pi[i*4+1]] >> 7] = 1; check[val[pi[i*4+2]] >> 7] = 1; check[val[pi[i*4+3]] >> 7] = 1; } if (check[1] || pi[sizeof(in[0]) - 1] != 0x0a) { /* Remember this line if it's the earliest error. If this * code is reached, performance no longer matters. */ #pragma omp critical badline = n < badline ? n : badline; } } /* An error was discovered, report the line number. */ if (badline != LINES_PER_BLOCK) { return nblocks * LINES_PER_BLOCK + badline + 1; } /* Every looks good, write the output. */ if (!fwrite(out, out_len, 1, fout)) { /* Output error */ break; } /* Was this the last block? */ if (out_len < sizeof(out)) break; } return 0; } static int xoptind = 1; static int xoptopt; static char *xoptarg; /* Same as getopt(3) but never prints errors. */ static int xgetopt(int argc, char * const argv[], const char *optstring) { static int optpos = 1; const char *arg; arg = xoptind < argc ? argv[xoptind] : 0; if (arg && arg[0] == '-' && arg[1] == '-' && !arg[2]) { xoptind++; return -1; } else if (!arg || arg[0] != '-' || !isalnum(arg[1])) { return -1; } else { const char *opt = strchr(optstring, arg[optpos]); xoptopt = arg[optpos]; if (!opt) { return '?'; } else if (opt[1] == ':') { if (arg[optpos + 1]) { xoptarg = (char *)arg + optpos + 1; xoptind++; optpos = 1; return xoptopt; } else if (argv[xoptind + 1]) { xoptarg = (char *)argv[xoptind + 1]; xoptind += 2; optpos = 1; return xoptopt; } else { return ':'; } } else { if (!arg[++optpos]) { xoptind++; optpos = 1; } return xoptopt; } } } static int usage(FILE *f) { static const char usage[] = "usage: race64 [-dh] [-o OUTFILE] [INFILE]\n" " -d Decode input (default: encode)\n" " -h Print this help message\n" " -o FILE Output to file instead of standard output\n" " -V Print version information\n"; return fwrite(usage, sizeof(usage)-1, 1, f) && !fflush(f); } static int version(void) { static const char version[] = "race64 " VERSION "\n"; return fwrite(version, sizeof(version)-1, 1, stdout) && !fflush(stdout); } static const char * run(int argc, char **argv) { enum {MODE_ENCODE, MODE_DECODE} mode = MODE_ENCODE; const char *outfile = 0; FILE *in = stdin; FILE *out = stdout; static char err[256]; unsigned long long lineno; int option; #ifdef _WIN32 int _setmode(int, int); _setmode(_fileno(stdout), 0x8000); _setmode(_fileno(stdin), 0x8000); #endif while ((option = xgetopt(argc, argv, "dho:V")) != -1) { switch (option) { case 'd': mode = MODE_DECODE; break; case 'h': return usage(stdout) ? 0 : "<stdout>"; case 'o': outfile = xoptarg; break; case 'V': return version() ? 0 : "<stdout>"; case ':': usage(stderr); snprintf(err, sizeof(err), "missing argument: -%c", xoptopt); return err; case '?': usage(stderr); snprintf(err, sizeof(err), "illegal option: -%c", xoptopt); return err; } } /* Configure input */ const char *infile = argv[xoptind]; if (infile) { if (argv[xoptind+1]) { return "too many arguments"; } in = fopen(infile, "rb"); if (!in) { return infile; } } setvbuf(in, 0, _IONBF, 0); /* Configure output */ if (outfile) { out = fopen(outfile, "wb"); if (!out) { return outfile; } } setvbuf(out, 0, _IONBF, 0); switch (mode) { case MODE_ENCODE: encode(in, out); break; case MODE_DECODE: lineno = decode(in, out); if (lineno) { snprintf(err, sizeof(err), "%s:%llu:invalid input", outfile ? outfile : "<stdin>", lineno); return err; } break; } if (ferror(in)) { return infile ? infile : "<stdin>"; } fflush(out); if (ferror(out)) { return outfile ? outfile : "<stdout>"; } return 0; } int main(int argc, char **argv) { const char *err = run(argc, argv); if (err) { fputs("race64: ", stderr); if (errno) { fputs(strerror(errno), stderr); fputs(": ", stderr); } fputs(err, stderr); fputs("\n", stderr); return 1; } return 0; }
image.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % % % MagickCore Image Methods % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/animate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/timer.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/version.h" #include "magick/xwindow-private.h" /* Constant declaration. */ const char BackgroundColor[] = "#ffffff", /* white */ BorderColor[] = "#dfdfdf", /* gray */ DefaultTileFrame[] = "15x15+3+3", DefaultTileGeometry[] = "120x120+4+3>", DefaultTileLabel[] = "%f\n%G\n%b", ForegroundColor[] = "#000", /* black */ LoadImageTag[] = "Load/Image", LoadImagesTag[] = "Load/Images", MatteColor[] = "#bdbdbd", /* gray */ PSDensityGeometry[] = "72.0x72.0", PSPageGeometry[] = "612x792", SaveImageTag[] = "Save/Image", SaveImagesTag[] = "Save/Images", TransparentColor[] = "#00000000"; /* transparent black */ const double DefaultResolution = 72.0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImage() returns a pointer to an image structure initialized to % default values. % % The format of the AcquireImage method is: % % Image *AcquireImage(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % */ MagickExport Image *AcquireImage(const ImageInfo *image_info) { const char *option; Image *image; MagickStatusType flags; /* Allocate image structure. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); image=(Image *) AcquireMagickMemory(sizeof(*image)); if (image == (Image *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(image,0,sizeof(*image)); /* Initialize Image structure. */ (void) CopyMagickString(image->magick,"MIFF",MaxTextExtent); image->storage_class=DirectClass; image->depth=MAGICKCORE_QUANTUM_DEPTH; image->colorspace=sRGBColorspace; image->rendering_intent=PerceptualIntent; image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.red_primary.z=0.0300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.green_primary.z=0.1000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.blue_primary.z=0.7900f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->chromaticity.white_point.z=0.3583f; image->interlace=NoInterlace; image->ticks_per_second=UndefinedTicksPerSecond; image->compose=OverCompositeOp; image->blur=1.0; GetExceptionInfo(&image->exception); (void) QueryColorDatabase(BackgroundColor,&image->background_color, &image->exception); (void) QueryColorDatabase(BorderColor,&image->border_color,&image->exception); (void) QueryColorDatabase(MatteColor,&image->matte_color,&image->exception); (void) QueryColorDatabase(TransparentColor,&image->transparent_color, &image->exception); GetTimerInfo(&image->timer); image->ping=MagickFalse; image->cache=AcquirePixelCache(0); image->blob=CloneBlobInfo((BlobInfo *) NULL); image->timestamp=time((time_t *) NULL); image->debug=IsEventLogging(); image->reference_count=1; image->semaphore=AllocateSemaphoreInfo(); image->signature=MagickSignature; if (image_info == (ImageInfo *) NULL) return(image); /* Transfer image info. */ SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue : MagickFalse); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent); if (image_info->size != (char *) NULL) { (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info); image->columns=image->extract_info.width; image->rows=image->extract_info.height; image->offset=image->extract_info.x; image->extract_info.x=0; image->extract_info.y=0; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; flags=ParseAbsoluteGeometry(image_info->extract,&geometry); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { image->extract_info=geometry; Swap(image->columns,image->extract_info.width); Swap(image->rows,image->extract_info.height); } } image->compression=image_info->compression; image->quality=image_info->quality; image->endian=image_info->endian; image->interlace=image_info->interlace; image->units=image_info->units; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->page != (char *) NULL) { char *geometry; image->page=image->extract_info; geometry=GetPageGeometry(image_info->page); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } if (image_info->depth != 0) image->depth=image_info->depth; image->dither=image_info->dither; image->background_color=image_info->background_color; image->border_color=image_info->border_color; image->matte_color=image_info->matte_color; image->transparent_color=image_info->transparent_color; image->ping=image_info->ping; image->progress_monitor=image_info->progress_monitor; image->client_data=image_info->client_data; if (image_info->cache != (void *) NULL) ClonePixelCacheMethods(image->cache,image_info->cache); (void) SyncImageSettings(image_info,image); option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageInfo() allocates the ImageInfo structure. % % The format of the AcquireImageInfo method is: % % ImageInfo *AcquireImageInfo(void) % */ MagickExport ImageInfo *AcquireImageInfo(void) { ImageInfo *image_info; image_info=(ImageInfo *) AcquireMagickMemory(sizeof(*image_info)); if (image_info == (ImageInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetImageInfo(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % The format of the AcquireNextImage method is: % % void AcquireNextImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % */ MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image) { /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->next=AcquireImage(image_info); if (GetNextImageInList(image) == (Image *) NULL) return; (void) CopyMagickString(GetNextImageInList(image)->filename,image->filename, MaxTextExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MaxTextExtent); DestroyBlob(GetNextImageInList(image)); image->next->blob=ReferenceBlob(image->blob); image->next->endian=image->endian; image->next->scene=image->scene+1; image->next->previous=image; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A p p e n d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AppendImages() takes all images from the current image pointer to the end % of the image list and appends them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the AppendImages method is: % % Image *AppendImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AppendImages(const Image *images, const MagickBooleanType stack,ExceptionInfo *exception) { #define AppendImageTag "Append/Image" CacheView *append_view; Image *append_image; MagickBooleanType matte, status; MagickOffsetType n; RectangleInfo geometry; register const Image *next; size_t height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); matte=images->matte; number_images=1; width=images->columns; height=images->rows; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->matte != MagickFalse) matte=MagickTrue; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; continue; } width+=next->columns; if (next->rows > height) height=next->rows; } /* Append images. */ append_image=CloneImage(images,width,height,MagickTrue,exception); if (append_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(append_image,DirectClass) == MagickFalse) { InheritException(exception,&append_image->exception); append_image=DestroyImage(append_image); return((Image *) NULL); } append_image->matte=matte; (void) SetImageBackgroundColor(append_image); status=MagickTrue; x_offset=0; y_offset=0; next=images; append_view=AcquireAuthenticCacheView(append_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { CacheView *image_view; Image *image; MagickBooleanType proceed; image=CloneImage(next,0,0,MagickTrue,exception); if (image == (Image *) NULL) break; status=TransformImageColorspace(image,append_image->colorspace); if (status == MagickFalse) break; SetGeometry(append_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict append_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); append_indexes=GetCacheViewAuthenticIndexQueue(append_view); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); if ((image->colorspace == CMYKColorspace) && (append_image->colorspace == CMYKColorspace)) SetPixelIndex(append_indexes+x,GetPixelIndex(indexes+x)); p++; q++; } sync=SyncCacheViewAuthenticPixels(append_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=DestroyImage(image); proceed=SetImageProgress(append_image,AppendImageTag,n,number_images); if (proceed == MagickFalse) break; next=GetNextImageInList(next); } append_view=DestroyCacheView(append_view); if (status == MagickFalse) append_image=DestroyImage(append_image); return(append_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a t c h I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CatchImageException() returns if no exceptions are found in the image % sequence, otherwise it determines the most severe exception and reports % it as a warning or error depending on the severity. % % The format of the CatchImageException method is: % % ExceptionType CatchImageException(Image *image) % % A description of each parameter follows: % % o image: An image sequence. % */ MagickExport ExceptionType CatchImageException(Image *image) { ExceptionInfo *exception; ExceptionType severity; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); GetImageException(image,exception); CatchException(exception); severity=exception->severity; exception=DestroyExceptionInfo(exception); return(severity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipImagePath() sets the image clip mask based any clipping path information % if it exists. % % The format of the ClipImagePath method is: % % MagickBooleanType ClipImagePath(Image *image,const char *pathname, % const MagickBooleanType inside) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % */ MagickExport MagickBooleanType ClipImage(Image *image) { return(ClipImagePath(image,"#1",MagickTrue)); } MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname, const MagickBooleanType inside) { #define ClipImagePathTag "ClipPath/Image" char *property; const char *value; Image *clip_mask; ImageInfo *image_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MaxTextExtent,"8BIM:1999,2998:%s", pathname); value=GetImageProperty(image,property); property=DestroyString(property); if (value == (const char *) NULL) { ThrowFileException(&image->exception,OptionError,"NoClipPathDefined", image->filename); return(MagickFalse); } image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,image->filename,MaxTextExtent); (void) ConcatenateMagickString(image_info->filename,pathname,MaxTextExtent); clip_mask=BlobToImage(image_info,value,strlen(value),&image->exception); image_info=DestroyImageInfo(image_info); if (clip_mask == (Image *) NULL) return(MagickFalse); if (clip_mask->storage_class == PseudoClass) { (void) SyncImage(clip_mask); if (SetImageStorageClass(clip_mask,DirectClass) == MagickFalse) return(MagickFalse); } if (inside == MagickFalse) (void) NegateImage(clip_mask,MagickFalse); (void) FormatLocaleString(clip_mask->magick_filename,MaxTextExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageClipMask(image,clip_mask); clip_mask=DestroyImage(clip_mask); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImage() copies an image and returns the copy as a new image object. % % If the specified columns and rows is 0, an exact copy of the image is % returned, otherwise the pixel data is undefined and must be initialized % with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On % failure, a NULL image is returned and exception describes the reason for the % failure. % % The format of the CloneImage method is: % % Image *CloneImage(const Image *image,const size_t columns, % const size_t rows,const MagickBooleanType orphan, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the cloned image. % % o rows: the number of rows in the cloned image. % % o detach: With a value other than 0, the cloned image is detached from % its parent I/O stream. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { double scale; Image *clone_image; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image)); if (clone_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickSignature; clone_image->storage_class=image->storage_class; clone_image->channels=image->channels; clone_image->colorspace=image->colorspace; clone_image->matte=image->matte; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; if (image->colormap != (PixelPacket *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelPacket *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); GetExceptionInfo(&clone_image->exception); InheritException(&clone_image->exception,&image->exception); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MaxTextExtent); (void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent); (void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); clone_image->clip_mask=NewImageList(); clone_image->mask=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AllocateSemaphoreInfo(); if ((columns == 0) && (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); if (image->clip_mask != (Image *) NULL) clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue, exception); if (image->mask != (Image *) NULL) clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } if ((columns == image->columns) && (rows == image->rows)) { if (image->clip_mask != (Image *) NULL) clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue, exception); if (image->mask != (Image *) NULL) clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception); } scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->columns=columns; clone_image->rows=rows; clone_image->cache=ClonePixelCache(image->cache); return(clone_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageInfo() makes a copy of the given image info structure. If % NULL is specified, a new image info structure is created initialized to % default values. % % The format of the CloneImageInfo method is: % % ImageInfo *CloneImageInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info) { ImageInfo *clone_info; clone_info=AcquireImageInfo(); if (image_info == (ImageInfo *) NULL) return(clone_info); clone_info->compression=image_info->compression; clone_info->temporary=image_info->temporary; clone_info->adjoin=image_info->adjoin; clone_info->antialias=image_info->antialias; clone_info->scene=image_info->scene; clone_info->number_scenes=image_info->number_scenes; clone_info->depth=image_info->depth; (void) CloneString(&clone_info->size,image_info->size); (void) CloneString(&clone_info->extract,image_info->extract); (void) CloneString(&clone_info->scenes,image_info->scenes); (void) CloneString(&clone_info->page,image_info->page); clone_info->interlace=image_info->interlace; clone_info->endian=image_info->endian; clone_info->units=image_info->units; clone_info->quality=image_info->quality; (void) CloneString(&clone_info->sampling_factor,image_info->sampling_factor); (void) CloneString(&clone_info->server_name,image_info->server_name); (void) CloneString(&clone_info->font,image_info->font); (void) CloneString(&clone_info->texture,image_info->texture); (void) CloneString(&clone_info->density,image_info->density); clone_info->pointsize=image_info->pointsize; clone_info->fuzz=image_info->fuzz; clone_info->pen=image_info->pen; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_color; clone_info->matte_color=image_info->matte_color; clone_info->transparent_color=image_info->transparent_color; clone_info->dither=image_info->dither; clone_info->monochrome=image_info->monochrome; clone_info->colors=image_info->colors; clone_info->colorspace=image_info->colorspace; clone_info->type=image_info->type; clone_info->orientation=image_info->orientation; clone_info->preview_type=image_info->preview_type; clone_info->group=image_info->group; clone_info->ping=image_info->ping; clone_info->verbose=image_info->verbose; (void) CloneString(&clone_info->view,image_info->view); (void) CloneString(&clone_info->authenticate,image_info->authenticate); (void) CloneImageOptions(clone_info,image_info); clone_info->progress_monitor=image_info->progress_monitor; clone_info->client_data=image_info->client_data; clone_info->cache=image_info->cache; if (image_info->cache != (void *) NULL) clone_info->cache=ReferencePixelCache(image_info->cache); if (image_info->profile != (void *) NULL) clone_info->profile=(void *) CloneStringInfo((StringInfo *) image_info->profile); SetImageInfoFile(clone_info,image_info->file); SetImageInfoBlob(clone_info,image_info->blob,image_info->length); clone_info->stream=image_info->stream; clone_info->virtual_pixel_method=image_info->virtual_pixel_method; (void) CopyMagickString(clone_info->magick,image_info->magick,MaxTextExtent); (void) CopyMagickString(clone_info->unique,image_info->unique,MaxTextExtent); (void) CopyMagickString(clone_info->zero,image_info->zero,MaxTextExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MaxTextExtent); clone_info->subimage=image_info->scene; /* deprecated */ clone_info->subrange=image_info->number_scenes; /* deprecated */ clone_info->channel=image_info->channel; clone_info->debug=IsEventLogging(); clone_info->signature=image_info->signature; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImage() dereferences an image, deallocating memory associated with % the image if the reference count becomes zero. % % The format of the DestroyImage method is: % % Image *DestroyImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *DestroyImage(Image *image) { MagickBooleanType destroy; /* Dereference image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); destroy=MagickFalse; LockSemaphoreInfo(image->semaphore); image->reference_count--; if (image->reference_count == 0) destroy=MagickTrue; UnlockSemaphoreInfo(image->semaphore); if (destroy == MagickFalse) return((Image *) NULL); /* Destroy image. */ DestroyImagePixels(image); if (image->clip_mask != (Image *) NULL) image->clip_mask=DestroyImage(image->clip_mask); if (image->mask != (Image *) NULL) image->mask=DestroyImage(image->mask); if (image->montage != (char *) NULL) image->montage=DestroyString(image->montage); if (image->directory != (char *) NULL) image->directory=DestroyString(image->directory); if (image->colormap != (PixelPacket *) NULL) image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap); if (image->geometry != (char *) NULL) image->geometry=DestroyString(image->geometry); DestroyImageProfiles(image); DestroyImageProperties(image); DestroyImageArtifacts(image); if (image->ascii85 != (Ascii85Info*) NULL) image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85); DestroyBlob(image); (void) DestroyExceptionInfo(&image->exception); if (image->semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&image->semaphore); image->signature=(~MagickSignature); image=(Image *) RelinquishMagickMemory(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageInfo() deallocates memory associated with an ImageInfo % structure. % % The format of the DestroyImageInfo method is: % % ImageInfo *DestroyImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); if (image_info->scenes != (char *) NULL) image_info->scenes=DestroyString(image_info->scenes); if (image_info->page != (char *) NULL) image_info->page=DestroyString(image_info->page); if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); if (image_info->view != (char *) NULL) image_info->view=DestroyString(image_info->view); if (image_info->authenticate != (char *) NULL) image_info->authenticate=DestroyString( image_info->authenticate); DestroyImageOptions(image_info); if (image_info->cache != (void *) NULL) image_info->cache=DestroyPixelCache(image_info->cache); if (image_info->profile != (StringInfo *) NULL) image_info->profile=(void *) DestroyStringInfo((StringInfo *) image_info->profile); image_info->signature=(~MagickSignature); image_info=(ImageInfo *) RelinquishMagickMemory(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s a s s o c i a t e I m a g e S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisassociateImageStream() disassociates the image stream. % % The format of the DisassociateImageStream method is: % % MagickBooleanType DisassociateImageStream(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DisassociateImageStream(Image *image) { assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) DetachBlob(image->blob); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C l i p M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageClipMask() returns the clip path associated with the image. % % The format of the GetImageClipMask method is: % % Image *GetImageClipMask(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *GetImageClipMask(const Image *image, ExceptionInfo *exception) { assert(image != (const Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (image->clip_mask == (Image *) NULL) return((Image *) NULL); return(CloneImage(image->clip_mask,0,0,MagickTrue,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageException() traverses an image sequence and returns any % error more severe than noted by the exception parameter. % % The format of the GetImageException method is: % % void GetImageException(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Specifies a pointer to a list of one or more images. % % o exception: return the highest severity exception. % */ MagickExport void GetImageException(Image *image,ExceptionInfo *exception) { register Image *next; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->exception.severity == UndefinedException) continue; if (next->exception.severity > exception->severity) InheritException(exception,&next->exception); next->exception.severity=UndefinedException; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfo() initializes image_info to default values. % % The format of the GetImageInfo method is: % % void GetImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport void GetImageInfo(ImageInfo *image_info) { char *synchronize; ExceptionInfo *exception; /* File and image dimension members. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info != (ImageInfo *) NULL); (void) ResetMagickMemory(image_info,0,sizeof(*image_info)); image_info->adjoin=MagickTrue; image_info->interlace=NoInterlace; image_info->channel=DefaultChannels; image_info->quality=UndefinedCompressionQuality; image_info->antialias=MagickTrue; image_info->dither=MagickTrue; synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { image_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } exception=AcquireExceptionInfo(); (void) QueryColorDatabase(BackgroundColor,&image_info->background_color, exception); (void) QueryColorDatabase(BorderColor,&image_info->border_color,exception); (void) QueryColorDatabase(MatteColor,&image_info->matte_color,exception); (void) QueryColorDatabase(TransparentColor,&image_info->transparent_color, exception); exception=DestroyExceptionInfo(exception); image_info->debug=IsEventLogging(); image_info->signature=MagickSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfoFile() returns the image info file member. % % The format of the GetImageInfoFile method is: % % FILE *GetImageInfoFile(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info) { return(image_info->file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMask() returns the mask associated with the image. % % The format of the GetImageMask method is: % % Image *GetImageMask(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *GetImageMask(const Image *image,ExceptionInfo *exception) { assert(image != (const Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (image->mask == (Image *) NULL) return((Image *) NULL); return(CloneImage(image->mask,0,0,MagickTrue,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannels() returns the number of pixel channels associated with the % specified image. % % The format of the GetChannels method is: % % size_t GetImageChannels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport size_t GetImageChannels(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(image->channels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e R e f e r e n c e C o u n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageReferenceCount() returns the image reference count. % % The format of the GetReferenceCount method is: % % ssize_t GetImageReferenceCount(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport ssize_t GetImageReferenceCount(Image *image) { ssize_t reference_count; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); LockSemaphoreInfo(image->semaphore); reference_count=image->reference_count; UnlockSemaphoreInfo(image->semaphore); return(reference_count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageVirtualPixelMethod() gets the "virtual pixels" method for the % image. A virtual pixel is any pixel access that is outside the boundaries % of the image cache. % % The format of the GetImageVirtualPixelMethod() method is: % % VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(GetPixelCacheVirtualMethod(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageFilename() interprets embedded characters in an image filename. % The filename length is returned. % % The format of the InterpretImageFilename method is: % % size_t InterpretImageFilename(const ImageInfo *image_info,Image *image, % const char *format,int value,char *filename) % % A description of each parameter follows. % % o image_info: the image info.. % % o image: the image. % % o format: A filename describing the format to use to write the numeric % argument. Only the first numeric format identifier is replaced. % % o value: Numeric value to substitute into format filename. % % o filename: return the formatted filename in this character buffer. % */ MagickExport size_t InterpretImageFilename(const ImageInfo *image_info, Image *image,const char *format,int value,char *filename) { char *q; int c; MagickBooleanType canonical; register const char *p; size_t length; canonical=MagickFalse; length=0; (void) CopyMagickString(filename,format,MaxTextExtent); for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%')) { q=(char *) p+1; if (*q == '%') { p=q+1; continue; } if (*q == '0') { ssize_t value; value=(ssize_t) strtol(q,&q,10); (void) value; } switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format),(size_t) (MaxTextExtent- (p-format)),p,value); *q=c; (void) ConcatenateMagickString(filename,q,MaxTextExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MaxTextExtent]; const char *value; register char *r; register ssize_t i; ssize_t depth; /* Image option. */ if (strchr(p,']') == (char *) NULL) break; depth=1; r=q+1; for (i=0; (i < (MaxTextExtent-1L)) && (*r != '\0'); i++) { if (*r == '[') depth++; if (*r == ']') depth--; if (depth <= 0) break; pattern[i]=(*r++); } pattern[i]='\0'; if (LocaleNCompare(pattern,"filename:",9) != 0) break; value=(const char *) NULL; #if 0 // FUTURE: remove this code. -- Anthony 29 Arpil 2012 // Removed as GetMagickProperty() will will never match a "filename:" // string as this is not a 'known' image property. // if ((image_info != (const ImageInfo *) NULL) && (image != (const Image *) NULL)) value=GetMagickProperty(image_info,image,pattern); else #endif if (image != (Image *) NULL) value=GetImageProperty(image,pattern); if ((value == (const char *) NULL) && (image != (Image *) NULL)) value=GetImageArtifact(image,pattern); if ((value == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) value=GetImageOption(image_info,pattern); if (value == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-length),value,(size_t) (MaxTextExtent-(p-format-length))); length+=strlen(pattern)-1; *q=c; (void) ConcatenateMagickString(filename,r+1,MaxTextExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } default: break; } } for (q=filename; *q != '\0'; q++) if ((*q == '%') && (*(q+1) == '%')) { (void) CopyMagickString(q,q+1,(size_t) (MaxTextExtent-(q-filename))); canonical=MagickTrue; } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MaxTextExtent); return(strlen(filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s H i g h D y n a m i c R a n g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsHighDynamicRangeImage() returns MagickTrue if any pixel component is % non-integer or exceeds the bounds of the quantum depth (e.g. for Q16 % 0..65535. % % The format of the IsHighDynamicRangeImage method is: % % MagickBooleanType IsHighDynamicRangeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image, ExceptionInfo *exception) { #if !defined(MAGICKCORE_HDRI_SUPPORT) (void) image; (void) exception; return(MagickFalse); #else CacheView *image_view; MagickBooleanType status; MagickPixelPacket zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; GetMagickPixelPacket(image,&zero); image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((pixel.red < 0.0) || (pixel.red > QuantumRange) || (pixel.red != (QuantumAny) pixel.red)) break; if ((pixel.green < 0.0) || (pixel.green > QuantumRange) || (pixel.green != (QuantumAny) pixel.green)) break; if ((pixel.blue < 0.0) || (pixel.blue > QuantumRange) || (pixel.blue != (QuantumAny) pixel.blue)) break; if (pixel.matte != MagickFalse) { if ((pixel.opacity < 0.0) || (pixel.opacity > QuantumRange) || (pixel.opacity != (QuantumAny) pixel.opacity)) break; } if (pixel.colorspace == CMYKColorspace) { if ((pixel.index < 0.0) || (pixel.index > QuantumRange) || (pixel.index != (QuantumAny) pixel.index)) break; } p++; } if (x < (ssize_t) image->columns) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status != MagickFalse ? MagickFalse : MagickTrue); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e O b j e c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageObject() returns MagickTrue if the image sequence contains a valid % set of image objects. % % The format of the IsImageObject method is: % % MagickBooleanType IsImageObject(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsImageObject(const Image *image) { register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) if (p->signature != MagickSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTaintImage() returns MagickTrue any pixel in the image has been altered % since it was first constituted. % % The format of the IsTaintImage method is: % % MagickBooleanType IsTaintImage(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsTaintImage(const Image *image) { char magick[MaxTextExtent], filename[MaxTextExtent]; register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); (void) CopyMagickString(magick,image->magick,MaxTextExtent); (void) CopyMagickString(filename,image->filename,MaxTextExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { if (p->taint != MagickFalse) return(MagickTrue); if (LocaleCompare(p->magick,magick) != 0) return(MagickTrue); if (LocaleCompare(p->filename,filename) != 0) return(MagickTrue); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModifyImage() ensures that there is only a single reference to the image % to be modified, updating the provided image pointer to point to a clone of % the original image if necessary. % % The format of the ModifyImage method is: % % MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ModifyImage(Image **image, ExceptionInfo *exception) { Image *clone_image; assert(image != (Image **) NULL); assert(*image != (Image *) NULL); assert((*image)->signature == MagickSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); if (GetImageReferenceCount(*image) <= 1) return(MagickTrue); clone_image=CloneImage(*image,0,0,MagickTrue,exception); LockSemaphoreInfo((*image)->semaphore); (*image)->reference_count--; UnlockSemaphoreInfo((*image)->semaphore); *image=clone_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w M a g i c k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewMagickImage() creates a blank image canvas of the specified size and % background color. % % The format of the NewMagickImage method is: % % Image *NewMagickImage(const ImageInfo *image_info, % const size_t width,const size_t height, % const MagickPixelPacket *background) % % A description of each parameter follows: % % o image: the image. % % o width: the image width. % % o height: the image height. % % o background: the image color. % */ MagickExport Image *NewMagickImage(const ImageInfo *image_info, const size_t width,const size_t height, const MagickPixelPacket *background) { CacheView *image_view; ExceptionInfo *exception; Image *image; ssize_t y; MagickBooleanType status; assert(image_info != (const ImageInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info->signature == MagickSignature); assert(background != (const MagickPixelPacket *) NULL); image=AcquireImage(image_info); image->columns=width; image->rows=height; image->colorspace=background->colorspace; image->matte=background->matte; image->fuzz=background->fuzz; image->depth=background->depth; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelPacket(image,background,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e f e r e n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferenceImage() increments the reference count associated with an image % returning a pointer to the image. % % The format of the ReferenceImage method is: % % Image *ReferenceImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *ReferenceImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); LockSemaphoreInfo(image->semaphore); image->reference_count++; UnlockSemaphoreInfo(image->semaphore); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePage() resets the image page canvas and position. % % The format of the ResetImagePage method is: % % MagickBooleanType ResetImagePage(Image *image,const char *page) % % A description of each parameter follows: % % o image: the image. % % o page: the relative page specification. % */ MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageBackgroundColor() initializes the image pixels to the image % background color. The background color is defined by the background_color % member of the image structure. % % The format of the SetImage method is: % % MagickBooleanType SetImageBackgroundColor(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType SetImageBackgroundColor(Image *image) { CacheView *image_view; ExceptionInfo *exception; IndexPacket index; MagickBooleanType status; MagickPixelPacket background; PixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if ((IsPixelGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) TransformImageColorspace(image,RGBColorspace); if ((image->background_color.opacity != OpaqueOpacity) && (image->matte == MagickFalse)) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); GetMagickPixelPacket(image,&background); SetMagickPixelPacket(image,&image->background_color,(const IndexPacket *) NULL,&background); if (image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&background); index=0; SetPixelPacket(image,&background,&pixel,&index); /* Set image background color. */ status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) *q++=pixel; if (image->colorspace == CMYKColorspace) { register IndexPacket *restrict indexes; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,index); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannels() sets the number of pixels channels associated with the % image. % % The format of the SetImageChannels method is: % % MagickBooleanType SetImageChannels(Image *image,const size_t channels) % % A description of each parameter follows: % % o image: the image. % % o channels: The number of pixel channels. % */ MagickExport MagickBooleanType SetImageChannels(Image *image, const size_t channels) { image->channels=channels; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColor() set the entire image canvas to the specified color. % % The format of the SetImageColor method is: % % MagickBooleanType SetImageColor(Image *image, % const MagickPixelPacket *color) % % A description of each parameter follows: % % o image: the image. % % o background: the image color. % */ MagickExport MagickBooleanType SetImageColor(Image *image, const MagickPixelPacket *color) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); assert(color != (const MagickPixelPacket *) NULL); image->colorspace=color->colorspace; image->matte=color->matte; image->fuzz=color->fuzz; image->depth=color->depth; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelPacket(image,color,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageStorageClass() sets the image class: DirectClass for true color % images or PseudoClass for colormapped images. % % The format of the SetImageStorageClass method is: % % MagickBooleanType SetImageStorageClass(Image *image, % const ClassType storage_class) % % A description of each parameter follows: % % o image: the image. % % o storage_class: The image class. % */ MagickExport MagickBooleanType SetImageStorageClass(Image *image, const ClassType storage_class) { image->storage_class=storage_class; return(SyncImagePixelCache(image,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C l i p M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageClipMask() associates a clip path with the image. The clip path % must be the same dimensions as the image. Set any pixel component of % the clip path to TransparentOpacity to prevent that corresponding image % pixel component from being updated when SyncAuthenticPixels() is applied. % % The format of the SetImageClipMask method is: % % MagickBooleanType SetImageClipMask(Image *image,const Image *clip_mask) % % A description of each parameter follows: % % o image: the image. % % o clip_mask: the image clip path. % */ MagickExport MagickBooleanType SetImageClipMask(Image *image, const Image *clip_mask) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (clip_mask != (const Image *) NULL) if ((clip_mask->columns != image->columns) || (clip_mask->rows != image->rows)) ThrowBinaryException(ImageError,"ImageSizeDiffers",image->filename); if (image->clip_mask != (Image *) NULL) image->clip_mask=DestroyImage(image->clip_mask); image->clip_mask=NewImageList(); if (clip_mask == (Image *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); image->clip_mask=CloneImage(clip_mask,0,0,MagickTrue,&image->exception); if (image->clip_mask == (Image *) NULL) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageExtent() sets the image size (i.e. columns & rows). % % The format of the SetImageExtent method is: % % MagickBooleanType SetImageExtent(Image *image, % const size_t columns,const size_t rows) % % A description of each parameter follows: % % o image: the image. % % o columns: The image width in pixels. % % o rows: The image height in pixels. % */ MagickExport MagickBooleanType SetImageExtent(Image *image, const size_t columns,const size_t rows) { if ((columns == 0) || (rows == 0)) return(MagickFalse); image->columns=columns; image->rows=rows; return(SyncImagePixelCache(image,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfo() initializes the `magick' field of the ImageInfo structure. % It is set to a type of image format based on the prefix or suffix of the % filename. For example, `ps:image' returns PS indicating a Postscript image. % JPEG is returned for this filename: `image.jpg'. The filename prefix has % precendence over the suffix. Use an optional index enclosed in brackets % after a file name to specify a desired scene of a multi-resolution image % format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value % indicates success. % % The format of the SetImageInfo method is: % % MagickBooleanType SetImageInfo(ImageInfo *image_info, % const unsigned int frames,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o frames: the number of images you intend to write. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char extension[MaxTextExtent], filename[MaxTextExtent], magic[MaxTextExtent], *q, subimage[MaxTextExtent]; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; unsigned char magick[2*MaxTextExtent]; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *subimage='\0'; if (frames == 0) { GetPathComponent(image_info->filename,SubimagePath,subimage); if (*subimage != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(subimage,MagickFalse) == MagickFalse) { if (IsGeometry(subimage) != MagickFalse) (void) CloneString(&image_info->extract,subimage); } else { size_t first, last; (void) CloneString(&image_info->scenes,subimage); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; image_info->subimage=image_info->scene; image_info->subrange=image_info->number_scenes; } } } *extension='\0'; GetPathComponent(image_info->filename,ExtensionPath,extension); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*extension != '\0') if ((LocaleCompare(extension,"gz") == 0) || (LocaleCompare(extension,"Z") == 0) || (LocaleCompare(extension,"svgz") == 0) || (LocaleCompare(extension,"wmz") == 0)) { char path[MaxTextExtent]; (void) CopyMagickString(path,image_info->filename,MaxTextExtent); path[strlen(path)-strlen(extension)-1]='\0'; GetPathComponent(path,ExtensionPath,extension); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*extension != '\0') if (LocaleCompare(extension,"bz2") == 0) { char path[MaxTextExtent]; (void) CopyMagickString(path,image_info->filename,MaxTextExtent); path[strlen(path)-strlen(extension)-1]='\0'; GetPathComponent(path,ExtensionPath,extension); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if (*extension != '\0') { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "EPHEMERAL", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,extension,MaxTextExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MaxTextExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MaxTextExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') (void) CopyMagickString(magic,image_info->magick,MaxTextExtent); else { /* User specified image format. */ LocaleUpper(magic); if (IsMagickConflict(magic) == MagickFalse) { (void) CopyMagickString(image_info->magick,magic,MaxTextExtent); if (LocaleCompare(magic,"EPHEMERAL") != 0) image_info->affirm=MagickTrue; else image_info->temporary=MagickTrue; } } magick_info=GetMagickInfo(magic,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; GetPathComponent(image_info->filename,CanonicalPath,filename); (void) CopyMagickString(image_info->filename,filename,MaxTextExtent); if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,filename); if ((LocaleCompare(filename,image_info->filename) != 0) && (strchr(filename,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { /* Determine the image format from the first few bytes of the file. */ image=AcquireImage(image_info); (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy standard input or pipe to temporary file. */ *filename='\0'; status=ImageToFile(image,filename,exception); (void) CloseBlob(image); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,filename,MaxTextExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,filename,MaxTextExtent); image_info->temporary=MagickTrue; } (void) ResetMagickMemory(magick,0,sizeof(magick)); count=ReadBlob(image,2*MaxTextExtent,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic.xml configuration file. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { (void) CopyMagickString(image_info->magick,GetMagicName(magic_info), MaxTextExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoBlob() sets the image info blob member. % % The format of the SetImageInfoBlob method is: % % void SetImageInfoBlob(ImageInfo *image_info,const void *blob, % const size_t length) % % A description of each parameter follows: % % o image_info: the image info. % % o blob: the blob. % % o length: the blob length. % */ MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob, const size_t length) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->blob=(void *) blob; image_info->length=length; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoFile() sets the image info file member. % % The format of the SetImageInfoFile method is: % % void SetImageInfoFile(ImageInfo *image_info,FILE *file) % % A description of each parameter follows: % % o image_info: the image info. % % o file: the file. % */ MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->file=file; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMask() associates a mask with the image. The mask must be the same % dimensions as the image. % % The format of the SetImageMask method is: % % MagickBooleanType SetImageMask(Image *image,const Image *mask) % % A description of each parameter follows: % % o image: the image. % % o mask: the image mask. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const Image *mask) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (mask != (const Image *) NULL) if ((mask->columns != image->columns) || (mask->rows != image->rows)) ThrowBinaryException(ImageError,"ImageSizeDiffers",image->filename); if (image->mask != (Image *) NULL) image->mask=DestroyImage(image->mask); image->mask=NewImageList(); if (mask == (Image *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); image->mask=CloneImage(mask,0,0,MagickTrue,&image->exception); if (image->mask == (Image *) NULL) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e O p a c i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageOpacity() sets the opacity levels of the image. % % The format of the SetImageOpacity method is: % % MagickBooleanType SetImageOpacity(Image *image,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o opacity: the level of transparency: 0 is fully opaque and QuantumRange is % fully transparent. % */ MagickExport MagickBooleanType SetImageOpacity(Image *image, const Quantum opacity) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); image->matte=MagickTrue; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,opacity); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageVirtualPixelMethod() sets the "virtual pixels" method for the % image and returns the previous setting. A virtual pixel is any pixel access % that is outside the boundaries of the image cache. % % The format of the SetImageVirtualPixelMethod() method is: % % VirtualPixelMethod SetImageVirtualPixelMethod(const Image *image, % const VirtualPixelMethod virtual_pixel_method) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % */ MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(const Image *image, const VirtualPixelMethod virtual_pixel_method) { assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(SetPixelCacheVirtualMethod(image,virtual_pixel_method)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S m u s h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SmushImages() takes all images from the current image pointer to the end % of the image list and smushes them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the SmushImages method is: % % Image *SmushImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o offset: minimum distance in pixels between images. % % o exception: return any errors or warnings in this structure. % */ static ssize_t SmushXGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *left_view, *right_view; const Image *left_image, *right_image; RectangleInfo left_geometry, right_geometry; register const PixelPacket *p; register ssize_t i, y; size_t gap; ssize_t x; if (images->previous == (Image *) NULL) return(0); right_image=images; SetGeometry(smush_image,&right_geometry); GravityAdjustGeometry(right_image->columns,right_image->rows, right_image->gravity,&right_geometry); left_image=images->previous; SetGeometry(smush_image,&left_geometry); GravityAdjustGeometry(left_image->columns,left_image->rows, left_image->gravity,&left_geometry); gap=right_image->columns; left_view=AcquireVirtualCacheView(left_image,exception); right_view=AcquireVirtualCacheView(right_image,exception); for (y=0; y < (ssize_t) smush_image->rows; y++) { for (x=(ssize_t) left_image->columns-1; x > 0; x--) { p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception); if ((p == (const PixelPacket *) NULL) || (GetPixelOpacity(p) != TransparentOpacity) || ((left_image->columns-x-1) >= gap)) break; } i=(ssize_t) left_image->columns-x-1; for (x=0; x < (ssize_t) right_image->columns; x++) { p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1, exception); if ((p == (const PixelPacket *) NULL) || (GetPixelOpacity(p) != TransparentOpacity) || ((x+i) >= (ssize_t) gap)) break; } if ((x+i) < (ssize_t) gap) gap=(size_t) (x+i); } right_view=DestroyCacheView(right_view); left_view=DestroyCacheView(left_view); if (y < (ssize_t) smush_image->rows) return(offset); return((ssize_t) gap-offset); } static ssize_t SmushYGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *bottom_view, *top_view; const Image *bottom_image, *top_image; RectangleInfo bottom_geometry, top_geometry; register const PixelPacket *p; register ssize_t i, x; size_t gap; ssize_t y; if (images->previous == (Image *) NULL) return(0); bottom_image=images; SetGeometry(smush_image,&bottom_geometry); GravityAdjustGeometry(bottom_image->columns,bottom_image->rows, bottom_image->gravity,&bottom_geometry); top_image=images->previous; SetGeometry(smush_image,&top_geometry); GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity, &top_geometry); gap=bottom_image->rows; top_view=AcquireVirtualCacheView(top_image,exception); bottom_view=AcquireVirtualCacheView(bottom_image,exception); for (x=0; x < (ssize_t) smush_image->columns; x++) { for (y=(ssize_t) top_image->rows-1; y > 0; y--) { p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception); if ((p == (const PixelPacket *) NULL) || (GetPixelOpacity(p) != TransparentOpacity) || ((top_image->rows-y-1) >= gap)) break; } i=(ssize_t) top_image->rows-y-1; for (y=0; y < (ssize_t) bottom_image->rows; y++) { p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1, exception); if ((p == (const PixelPacket *) NULL) || (GetPixelOpacity(p) != TransparentOpacity) || ((y+i) >= (ssize_t) gap)) break; } if ((y+i) < (ssize_t) gap) gap=(size_t) (y+i); } bottom_view=DestroyCacheView(bottom_view); top_view=DestroyCacheView(top_view); if (x < (ssize_t) smush_image->columns) return(offset); return((ssize_t) gap-offset); } MagickExport Image *SmushImages(const Image *images, const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception) { #define SmushImageTag "Smush/Image" CacheView *smush_view; const Image *image; Image *smush_image; MagickBooleanType matte, proceed, status; MagickOffsetType n; RectangleInfo geometry; register const Image *next; size_t height, number_images, width; ssize_t x_offset, y_offset; /* Compute maximum area of smushed area. */ assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=images; matte=image->matte; number_images=1; width=image->columns; height=image->rows; next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->matte != MagickFalse) matte=MagickTrue; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; if (next->previous != (Image *) NULL) height+=offset; continue; } width+=next->columns; if (next->previous != (Image *) NULL) width+=offset; if (next->rows > height) height=next->rows; } /* Smush images. */ smush_image=CloneImage(image,width,height,MagickTrue,exception); if (smush_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(smush_image,DirectClass) == MagickFalse) { InheritException(exception,&smush_image->exception); smush_image=DestroyImage(smush_image); return((Image *) NULL); } smush_image->matte=matte; (void) SetImageBackgroundColor(smush_image); status=MagickTrue; x_offset=0; y_offset=0; smush_view=AcquireVirtualCacheView(smush_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { SetGeometry(smush_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) { x_offset-=geometry.x; y_offset-=SmushYGap(smush_image,image,offset,exception); } else { x_offset-=SmushXGap(smush_image,image,offset,exception); y_offset-=geometry.y; } status=CompositeImage(smush_image,OverCompositeOp,image,x_offset,y_offset); proceed=SetImageProgress(image,SmushImageTag,n,number_images); if (proceed == MagickFalse) break; if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=GetNextImageInList(image); } if (stack == MagickFalse) smush_image->columns=(size_t) x_offset; else smush_image->rows=(size_t) y_offset; smush_view=DestroyCacheView(smush_view); if (status == MagickFalse) smush_image=DestroyImage(smush_image); return(smush_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StripImage() strips an image of all profiles and comments. % % The format of the StripImage method is: % % MagickBooleanType StripImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType StripImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); DestroyImageProfiles(image); (void) DeleteImageProperty(image,"comment"); (void) DeleteImageProperty(image,"date:create"); (void) DeleteImageProperty(image,"date:modify"); (void) SetImageArtifact(image,"png:include-chunk","none,trns,gama"); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImage() initializes the red, green, and blue intensities of each pixel % as defined by the colormap index. % % The format of the SyncImage method is: % % MagickBooleanType SyncImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline IndexPacket PushColormapIndex(Image *image, const size_t index,MagickBooleanType *range_exception) { if (index < image->colors) return((IndexPacket) index); *range_exception=MagickTrue; return((IndexPacket) 0); } MagickExport MagickBooleanType SyncImage(Image *image) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType range_exception, status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (image->storage_class == DirectClass) return(MagickFalse); range_exception=MagickFalse; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(range_exception,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { IndexPacket index; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { index=PushColormapIndex(image,(size_t) GetPixelIndex(indexes+x), &range_exception); if (image->matte == MagickFalse) SetPixelRgb(q,image->colormap+(ssize_t) index) else SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageError,"InvalidColormapIndex","`%s'",image->filename); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e S e t t i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageSettings() syncs image_info options into per-image attributes. % % The format of the SyncImageSettings method is: % % MagickBooleanType SyncImageSettings(const ImageInfo *image_info, % Image *image) % MagickBooleanType SyncImagesSettings(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info, Image *images) { Image *image; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) (void) SyncImageSettings(image_info,image); (void) DeleteImageOption(image_info,"page"); return(MagickTrue); } MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info, Image *image) { char property[MaxTextExtent]; const char *option, *value; GeometryInfo geometry_info; MagickStatusType flags; ResolutionType units; /* Sync image options. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); option=GetImageOption(image_info,"background"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&image->background_color, &image->exception); option=GetImageOption(image_info,"bias"); if (option != (const char *) NULL) image->bias=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"black-point-compensation"); if (option != (const char *) NULL) image->black_point_compensation=(MagickBooleanType) ParseCommandOption( MagickBooleanOptions,MagickFalse,option); option=GetImageOption(image_info,"blue-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x; } option=GetImageOption(image_info,"bordercolor"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&image->border_color,&image->exception); option=GetImageOption(image_info,"colors"); if (option != (const char *) NULL) image->colors=StringToUnsignedLong(option); option=GetImageOption(image_info,"compose"); if (option != (const char *) NULL) image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,option); option=GetImageOption(image_info,"compress"); if (option != (const char *) NULL) image->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,option); option=GetImageOption(image_info,"debug"); if (option != (const char *) NULL) image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { GeometryInfo geometry_info; /* Set image density. */ flags=ParseGeometry(option,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } option=GetImageOption(image_info,"depth"); if (option != (const char *) NULL) image->depth=StringToUnsignedLong(option); option=GetImageOption(image_info,"endian"); if (option != (const char *) NULL) image->endian=(EndianType) ParseCommandOption(MagickEndianOptions, MagickFalse,option); option=GetImageOption(image_info,"filter"); if (option != (const char *) NULL) image->filter=(FilterTypes) ParseCommandOption(MagickFilterOptions, MagickFalse,option); option=GetImageOption(image_info,"fuzz"); if (option != (const char *) NULL) image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(image_info,"green-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y=image->chromaticity.green_primary.x; } option=GetImageOption(image_info,"intensity"); if (option != (const char *) NULL) image->intensity=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,option); option=GetImageOption(image_info,"intent"); if (option != (const char *) NULL) image->rendering_intent=(RenderingIntent) ParseCommandOption( MagickIntentOptions,MagickFalse,option); option=GetImageOption(image_info,"interlace"); if (option != (const char *) NULL) image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions, MagickFalse,option); option=GetImageOption(image_info,"interpolate"); if (option != (const char *) NULL) image->interpolate=(InterpolatePixelMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,option); option=GetImageOption(image_info,"loop"); if (option != (const char *) NULL) image->iterations=StringToUnsignedLong(option); option=GetImageOption(image_info,"mattecolor"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&image->matte_color,&image->exception); option=GetImageOption(image_info,"orient"); if (option != (const char *) NULL) image->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,option); option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) image->quality=StringToUnsignedLong(option); option=GetImageOption(image_info,"red-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y=image->chromaticity.red_primary.x; } if (image_info->quality != UndefinedCompressionQuality) image->quality=image_info->quality; option=GetImageOption(image_info,"scene"); if (option != (const char *) NULL) image->scene=StringToUnsignedLong(option); option=GetImageOption(image_info,"taint"); if (option != (const char *) NULL) image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"tile-offset"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"transparent-color"); if (option != (const char *) NULL) (void) QueryColorDatabase(option,&image->transparent_color, &image->exception); option=GetImageOption(image_info,"type"); if (option != (const char *) NULL) image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, option); option=GetImageOption(image_info,"units"); if (option != (const char *) NULL) units=(ResolutionType) ParseCommandOption(MagickResolutionOptions, MagickFalse,option); else units = image_info->units; if (units != UndefinedResolution) { if (image->units != units) switch (image->units) { case PixelsPerInchResolution: { if (units == PixelsPerCentimeterResolution) { image->x_resolution/=2.54; image->y_resolution/=2.54; } break; } case PixelsPerCentimeterResolution: { if (units == PixelsPerInchResolution) { image->x_resolution=(double) ((size_t) (100.0*2.54* image->x_resolution+0.5))/100.0; image->y_resolution=(double) ((size_t) (100.0*2.54* image->y_resolution+0.5))/100.0; } break; } default: break; } image->units=units; } option=GetImageOption(image_info,"white-point"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y=image->chromaticity.white_point.x; } ResetImageOptionIterator(image_info); for (option=GetNextImageOption(image_info); option != (const char *) NULL; ) { value=GetImageOption(image_info,option); if (value != (const char *) NULL) { (void) FormatLocaleString(property,MaxTextExtent,"%s",option); (void) SetImageArtifact(image,property,value); } option=GetNextImageOption(image_info); } return(MagickTrue); }
builder.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef BUILDER_H_ #define BUILDER_H_ #include <algorithm> #include <cinttypes> #include <fstream> #include <functional> #include <type_traits> #include <utility> #include "command_line.h" #include "generator.h" #include "graph.h" #include "platform_atomics.h" #include "pvector.h" #include "reader.h" #include "timer.h" #include "util.h" /* GAP Benchmark Suite Class: BuilderBase Author: Scott Beamer Given arguements from the command line (cli), returns a built graph - MakeGraph() will parse cli and obtain edgelist and call MakeGraphFromEL(edgelist) to perform actual graph construction - edgelist can be from file (reader) or synthetically generated (generator) - Common case: BuilderBase typedef'd (w/ params) to be Builder (benchmark.h) */ template <typename NodeID_, typename DestID_ = NodeID_, typename WeightT_ = NodeID_, bool invert = true> class BuilderBase { typedef EdgePair<NodeID_, DestID_> Edge; typedef pvector<Edge> EdgeList; const CLBase &cli_; bool symmetrize_; bool needs_weights_; int64_t num_nodes_ = -1; public: explicit BuilderBase(const CLBase &cli) : cli_(cli) { symmetrize_ = cli_.symmetrize(); needs_weights_ = !std::is_same<NodeID_, DestID_>::value; } DestID_ GetSource(EdgePair<NodeID_, NodeID_> e) { return e.u; } DestID_ GetSource(EdgePair<NodeID_, NodeWeight<NodeID_, WeightT_>> e) { return NodeWeight<NodeID_, WeightT_>(e.u, e.v.w, e.v.t); } NodeID_ FindMaxNodeID(const EdgeList &el) { NodeID_ max_seen = 0; #pragma omp parallel for reduction(max : max_seen) for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; max_seen = std::max(max_seen, e.u); max_seen = std::max(max_seen, (NodeID_) e.v); } return max_seen; } pvector<NodeID_> CountDegrees(const EdgeList &el, bool transpose) { pvector<NodeID_> degrees(num_nodes_, 0); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) { fetch_and_add(degrees[e.u], 1); } // if (symmetrize_ || (!symmetrize_ && transpose)) { // // note: adding inverse edge; commenting it because we are dealing with undirected graph // fetch_and_add(degrees[(NodeID_) e.v], 1); // } } return degrees; } static pvector<SGOffset> PrefixSum(const pvector<NodeID_> &degrees) { pvector<SGOffset> sums(degrees.size() + 1); SGOffset total = 0; for (size_t n=0; n < degrees.size(); n++) { sums[n] = total; total += degrees[n]; } sums[degrees.size()] = total; return sums; } static pvector<SGOffset> ParallelPrefixSum(const pvector<NodeID_> &degrees) { const size_t block_size = 1<<20; const size_t num_blocks = (degrees.size() + block_size - 1) / block_size; pvector<SGOffset> local_sums(num_blocks); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset lsum = 0; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) lsum += degrees[i]; local_sums[block] = lsum; } pvector<SGOffset> bulk_prefix(num_blocks+1); SGOffset total = 0; for (size_t block=0; block < num_blocks; block++) { bulk_prefix[block] = total; total += local_sums[block]; } bulk_prefix[num_blocks] = total; pvector<SGOffset> prefix(degrees.size() + 1); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset local_total = bulk_prefix[block]; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) { prefix[i] = local_total; local_total += degrees[i]; } } prefix[degrees.size()] = bulk_prefix[num_blocks]; return prefix; } // Removes self-loops and redundant edges // Side effect: neighbor IDs will be sorted void SquishCSR(const CSRGraph<NodeID_, DestID_, invert> &g, bool transpose, DestID_*** sq_index, DestID_** sq_neighs) { pvector<NodeID_> diffs(g.num_nodes()); DestID_ *n_start, *n_end; #pragma omp parallel for private(n_start, n_end) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) { n_start = g.in_neigh(n).begin(); n_end = g.in_neigh(n).end(); } else { n_start = g.out_neigh(n).begin(); n_end = g.out_neigh(n).end(); } //std::sort(n_start, n_end); DestID_ *new_end = std::unique(n_start, n_end); // remove redundant edges new_end = std::remove(n_start, new_end, n); // remove self-loops diffs[n] = new_end - n_start; } pvector<SGOffset> sq_offsets = ParallelPrefixSum(diffs); *sq_neighs = new DestID_[sq_offsets[g.num_nodes()]]; *sq_index = CSRGraph<NodeID_, DestID_>::GenIndex(sq_offsets, *sq_neighs); #pragma omp parallel for private(n_start) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) n_start = g.in_neigh(n).begin(); else n_start = g.out_neigh(n).begin(); std::copy(n_start, n_start+diffs[n], (*sq_index)[n]); } } CSRGraph<NodeID_, DestID_, invert> SquishGraph( const CSRGraph<NodeID_, DestID_, invert> &g) { DestID_ **out_index, *out_neighs, **in_index, *in_neighs; SquishCSR(g, false, &out_index, &out_neighs); if (g.directed()) { if (invert) SquishCSR(g, true, &in_index, &in_neighs); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs, in_index, in_neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs); } } /* Graph Bulding Steps (for CSR): - Read edgelist once to determine vertex degrees (CountDegrees) - Determine vertex offsets by a prefix sum (ParallelPrefixSum) - Allocate storage and set points according to offsets (GenIndex) - Copy edges into storage */ void MakeCSR(const EdgeList &el, bool transpose, DestID_*** index, DestID_** neighs) { pvector<NodeID_> degrees = CountDegrees(el, transpose); pvector<SGOffset> offsets = ParallelPrefixSum(degrees); *neighs = new DestID_[offsets[num_nodes_]]; *index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, *neighs); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) { (*neighs)[fetch_and_add(offsets[e.u], 1)] = e.v; } // if (symmetrize_ || (!symmetrize_ && transpose)) { // // note: adding inverse edge; commenting it because we are dealing with undirected graph // (*neighs)[fetch_and_add(offsets[static_cast<NodeID_>(e.v)], 1)] = GetSource(e); // } } } CSRGraph<NodeID_, DestID_, invert> MakeGraphFromEL(EdgeList &el) { DestID_ **index = nullptr, **inv_index = nullptr; DestID_ *neighs = nullptr, *inv_neighs = nullptr; Timer t; t.Start(); if (num_nodes_ == -1) num_nodes_ = FindMaxNodeID(el)+1; if (needs_weights_) Generator<NodeID_, DestID_, WeightT_>::InsertWeights(el); MakeCSR(el, false, &index, &neighs); if (!symmetrize_ && invert) MakeCSR(el, true, &inv_index, &inv_neighs); t.Stop(); PrintTime("Build Time", t.Seconds()); if (symmetrize_) return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs); else return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs, inv_index, inv_neighs); } CSRGraph<NodeID_, DestID_, invert> MakeGraph() { CSRGraph<NodeID_, DestID_, invert> g; { // extra scope to trigger earlier deletion of el (save memory) EdgeList el; if (cli_.filename() != "") { Reader<NodeID_, DestID_, WeightT_, invert> r(cli_.filename()); if ((r.GetSuffix() == ".sg") || (r.GetSuffix() == ".wsg")) { return r.ReadSerializedGraph(); } else { el = r.ReadFile(needs_weights_); } } else if (cli_.scale() != -1) { Generator<NodeID_, DestID_> gen(cli_.scale(), cli_.degree()); el = gen.GenerateEL(cli_.uniform()); } // std::cout << "needs_weights: " << needs_weights_ << std::endl; g = MakeGraphFromEL(el); } return SquishGraph(g); } // Relabels (and rebuilds) graph by order of decreasing degree static CSRGraph<NodeID_, DestID_, invert> RelabelByDegree( const CSRGraph<NodeID_, DestID_, invert> &g) { if (g.directed()) { std::cout << "Cannot relabel directed graph" << std::endl; std::exit(-11); } Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); std::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> new_ids(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[n] = degree_id_pairs[n].first; new_ids[degree_id_pairs[n].second] = n; } pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; std::sort(index[new_ids[u]], index[new_ids[u]+1]); } t.Stop(); PrintTime("Relabel", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } }; #endif // BUILDER_H_
image.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % % % MagickCore Image Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/magick-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/timer.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xwindow-private.h" /* Constant declaration. */ const char BackgroundColor[] = "#ffffff", /* white */ BorderColor[] = "#dfdfdf", /* gray */ DefaultTileFrame[] = "15x15+3+3", DefaultTileGeometry[] = "120x120+4+3>", DefaultTileLabel[] = "%f\n%G\n%b", ForegroundColor[] = "#000", /* black */ LoadImageTag[] = "Load/Image", LoadImagesTag[] = "Load/Images", MatteColor[] = "#bdbdbd", /* gray */ PSDensityGeometry[] = "72.0x72.0", PSPageGeometry[] = "612x792", SaveImageTag[] = "Save/Image", SaveImagesTag[] = "Save/Images", TransparentColor[] = "#00000000"; /* transparent black */ const double DefaultResolution = 72.0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImage() returns a pointer to an image structure initialized to % default values. % % The format of the AcquireImage method is: % % Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AcquireImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; Image *image; MagickStatusType flags; /* Allocate image structure. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); image=(Image *) AcquireCriticalMemory(sizeof(*image)); (void) ResetMagickMemory(image,0,sizeof(*image)); /* Initialize Image structure. */ (void) CopyMagickString(image->magick,"MIFF",MagickPathExtent); image->storage_class=DirectClass; image->depth=MAGICKCORE_QUANTUM_DEPTH; image->colorspace=sRGBColorspace; image->rendering_intent=PerceptualIntent; image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.red_primary.z=0.0300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.green_primary.z=0.1000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.blue_primary.z=0.7900f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->chromaticity.white_point.z=0.3583f; image->interlace=NoInterlace; image->ticks_per_second=UndefinedTicksPerSecond; image->compose=OverCompositeOp; (void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color, exception); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image->transparent_color,exception); GetTimerInfo(&image->timer); image->cache=AcquirePixelCache(0); image->channel_mask=DefaultChannels; image->channel_map=AcquirePixelChannelMap(); image->blob=CloneBlobInfo((BlobInfo *) NULL); image->timestamp=time((time_t *) NULL); image->debug=IsEventLogging(); image->reference_count=1; image->semaphore=AcquireSemaphoreInfo(); image->signature=MagickCoreSignature; if (image_info == (ImageInfo *) NULL) return(image); /* Transfer image info. */ SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue : MagickFalse); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent); if (image_info->size != (char *) NULL) { (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info); image->columns=image->extract_info.width; image->rows=image->extract_info.height; image->offset=image->extract_info.x; image->extract_info.x=0; image->extract_info.y=0; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; flags=ParseAbsoluteGeometry(image_info->extract,&geometry); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { image->extract_info=geometry; Swap(image->columns,image->extract_info.width); Swap(image->rows,image->extract_info.height); } } image->compression=image_info->compression; image->quality=image_info->quality; image->endian=image_info->endian; image->interlace=image_info->interlace; image->units=image_info->units; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (image_info->page != (char *) NULL) { char *geometry; image->page=image->extract_info; geometry=GetPageGeometry(image_info->page); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } if (image_info->depth != 0) image->depth=image_info->depth; image->dither=image_info->dither; image->matte_color=image_info->matte_color; image->background_color=image_info->background_color; image->border_color=image_info->border_color; image->transparent_color=image_info->transparent_color; image->ping=image_info->ping; image->progress_monitor=image_info->progress_monitor; image->client_data=image_info->client_data; if (image_info->cache != (void *) NULL) ClonePixelCacheMethods(image->cache,image_info->cache); /* Set all global options that map to per-image settings. */ (void) SyncImageSettings(image_info,image,exception); /* Global options that are only set for new images. */ option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageInfo() allocates the ImageInfo structure. % % The format of the AcquireImageInfo method is: % % ImageInfo *AcquireImageInfo(void) % */ MagickExport ImageInfo *AcquireImageInfo(void) { ImageInfo *image_info; image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info)); GetImageInfo(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % The format of the AcquireNextImage method is: % % void AcquireNextImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->next=AcquireImage(image_info,exception); if (GetNextImageInList(image) == (Image *) NULL) return; (void) CopyMagickString(GetNextImageInList(image)->filename,image->filename, MagickPathExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MagickPathExtent); DestroyBlob(GetNextImageInList(image)); image->next->blob=ReferenceBlob(image->blob); image->next->endian=image->endian; image->next->scene=image->scene+1; image->next->previous=image; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A p p e n d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AppendImages() takes all images from the current image pointer to the end % of the image list and appends them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting effects how the image is justified in the % final image. % % The format of the AppendImages method is: % % Image *AppendImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AppendImages(const Image *images, const MagickBooleanType stack,ExceptionInfo *exception) { #define AppendImageTag "Append/Image" CacheView *append_view; Image *append_image; MagickBooleanType homogeneous_colorspace, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t depth, height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); alpha_trait=images->alpha_trait; number_images=1; width=images->columns; height=images->rows; depth=images->depth; homogeneous_colorspace=MagickTrue; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->depth > depth) depth=next->depth; if (next->colorspace != images->colorspace) homogeneous_colorspace=MagickFalse; if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; continue; } width+=next->columns; if (next->rows > height) height=next->rows; } /* Append images. */ append_image=CloneImage(images,width,height,MagickTrue,exception); if (append_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse) { append_image=DestroyImage(append_image); return((Image *) NULL); } if (homogeneous_colorspace == MagickFalse) (void) SetImageColorspace(append_image,sRGBColorspace,exception); append_image->depth=depth; append_image->alpha_trait=alpha_trait; append_image->page=images->page; (void) SetImageBackgroundColor(append_image,exception); status=MagickTrue; x_offset=0; y_offset=0; next=images; append_view=AcquireAuthenticCacheView(append_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { CacheView *image_view; MagickBooleanType proceed; SetGeometry(append_image,&geometry); GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(next,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(next,next,next->rows,1) #endif for (y=0; y < (ssize_t) next->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, next->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(next,&pixel); for (x=0; x < (ssize_t) next->columns; x++) { if (GetPixelWriteMask(next,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(append_image,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); continue; } GetPixelInfoPixel(next,p,&pixel); SetPixelViaPixelInfo(append_image,&pixel,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); } sync=SyncCacheViewAuthenticPixels(append_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (stack == MagickFalse) { x_offset+=(ssize_t) next->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) next->rows; } proceed=SetImageProgress(append_image,AppendImageTag,n,number_images); if (proceed == MagickFalse) break; next=GetNextImageInList(next); } append_view=DestroyCacheView(append_view); if (status == MagickFalse) append_image=DestroyImage(append_image); return(append_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a t c h I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CatchImageException() returns if no exceptions are found in the image % sequence, otherwise it determines the most severe exception and reports % it as a warning or error depending on the severity. % % The format of the CatchImageException method is: % % ExceptionType CatchImageException(Image *image) % % A description of each parameter follows: % % o image: An image sequence. % */ MagickExport ExceptionType CatchImageException(Image *image) { ExceptionInfo *exception; ExceptionType severity; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); CatchException(exception); severity=exception->severity; exception=DestroyExceptionInfo(exception); return(severity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipImagePath() sets the image clip mask based any clipping path information % if it exists. % % The format of the ClipImagePath method is: % % MagickBooleanType ClipImagePath(Image *image,const char *pathname, % const MagickBooleanType inside,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception) { return(ClipImagePath(image,"#1",MagickTrue,exception)); } MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname, const MagickBooleanType inside,ExceptionInfo *exception) { #define ClipImagePathTag "ClipPath/Image" char *property; const char *value; Image *clip_mask; ImageInfo *image_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s", pathname); value=GetImageProperty(image,property,exception); property=DestroyString(property); if (value == (const char *) NULL) { ThrowFileException(exception,OptionError,"NoClipPathDefined", image->filename); return(MagickFalse); } image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,image->filename, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,pathname, MagickPathExtent); clip_mask=BlobToImage(image_info,value,strlen(value),exception); image_info=DestroyImageInfo(image_info); if (clip_mask == (Image *) NULL) return(MagickFalse); if (clip_mask->storage_class == PseudoClass) { (void) SyncImage(clip_mask,exception); if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (inside != MagickFalse) (void) NegateImage(clip_mask,MagickFalse,exception); (void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageMask(image,WritePixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImage() copies an image and returns the copy as a new image object. % % If the specified columns and rows is 0, an exact copy of the image is % returned, otherwise the pixel data is undefined and must be initialized % with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On % failure, a NULL image is returned and exception describes the reason for the % failure. % % The format of the CloneImage method is: % % Image *CloneImage(const Image *image,const size_t columns, % const size_t rows,const MagickBooleanType orphan, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the cloned image. % % o rows: the number of rows in the cloned image. % % o detach: With a value other than 0, the cloned image is detached from % its parent I/O stream. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image)); (void) ResetMagickMemory(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->read_mask=image->read_mask; clone_image->write_mask=image->write_mask; clone_image->alpha_trait=image->alpha_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse) clone_image=DestroyImage(clone_image); return(clone_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageInfo() makes a copy of the given image info structure. If % NULL is specified, a new image info structure is created initialized to % default values. % % The format of the CloneImageInfo method is: % % ImageInfo *CloneImageInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info) { ImageInfo *clone_info; clone_info=AcquireImageInfo(); if (image_info == (ImageInfo *) NULL) return(clone_info); clone_info->compression=image_info->compression; clone_info->temporary=image_info->temporary; clone_info->adjoin=image_info->adjoin; clone_info->antialias=image_info->antialias; clone_info->scene=image_info->scene; clone_info->number_scenes=image_info->number_scenes; clone_info->depth=image_info->depth; if (image_info->size != (char *) NULL) (void) CloneString(&clone_info->size,image_info->size); if (image_info->extract != (char *) NULL) (void) CloneString(&clone_info->extract,image_info->extract); if (image_info->scenes != (char *) NULL) (void) CloneString(&clone_info->scenes,image_info->scenes); if (image_info->page != (char *) NULL) (void) CloneString(&clone_info->page,image_info->page); clone_info->interlace=image_info->interlace; clone_info->endian=image_info->endian; clone_info->units=image_info->units; clone_info->quality=image_info->quality; if (image_info->sampling_factor != (char *) NULL) (void) CloneString(&clone_info->sampling_factor, image_info->sampling_factor); if (image_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,image_info->server_name); if (image_info->font != (char *) NULL) (void) CloneString(&clone_info->font,image_info->font); if (image_info->texture != (char *) NULL) (void) CloneString(&clone_info->texture,image_info->texture); if (image_info->density != (char *) NULL) (void) CloneString(&clone_info->density,image_info->density); clone_info->pointsize=image_info->pointsize; clone_info->fuzz=image_info->fuzz; clone_info->matte_color=image_info->matte_color; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_color; clone_info->transparent_color=image_info->transparent_color; clone_info->dither=image_info->dither; clone_info->monochrome=image_info->monochrome; clone_info->colorspace=image_info->colorspace; clone_info->type=image_info->type; clone_info->orientation=image_info->orientation; clone_info->ping=image_info->ping; clone_info->verbose=image_info->verbose; clone_info->progress_monitor=image_info->progress_monitor; clone_info->client_data=image_info->client_data; clone_info->cache=image_info->cache; if (image_info->cache != (void *) NULL) clone_info->cache=ReferencePixelCache(image_info->cache); if (image_info->profile != (void *) NULL) clone_info->profile=(void *) CloneStringInfo((StringInfo *) image_info->profile); SetImageInfoFile(clone_info,image_info->file); SetImageInfoBlob(clone_info,image_info->blob,image_info->length); clone_info->stream=image_info->stream; clone_info->custom_stream=image_info->custom_stream; (void) CopyMagickString(clone_info->magick,image_info->magick, MagickPathExtent); (void) CopyMagickString(clone_info->unique,image_info->unique, MagickPathExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MagickPathExtent); clone_info->channel=image_info->channel; (void) CloneImageOptions(clone_info,image_info); clone_info->debug=IsEventLogging(); clone_info->signature=image_info->signature; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyImagePixels() copies pixels from the source image as defined by the % geometry the destination image at the specified offset. % % The format of the CopyImagePixels method is: % % MagickBooleanType CopyImagePixels(Image *image,const Image *source_image, % const RectangleInfo *geometry,const OffsetInfo *offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o image: the destination image. % % o source_image: the source image. % % o geometry: define the dimensions of the source pixel rectangle. % % o offset: define the offset in the destination image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CopyImagePixels(Image *image, const Image *source_image,const RectangleInfo *geometry, const OffsetInfo *offset,ExceptionInfo *exception) { #define CopyImageTag "Copy/Image" CacheView *image_view, *source_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(source_image != (Image *) NULL); assert(geometry != (RectangleInfo *) NULL); assert(offset != (OffsetInfo *) NULL); if ((offset->x < 0) || (offset->y < 0) || ((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) || ((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows)) ThrowBinaryException(OptionError,"GeometryDoesNotContainImage", image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Copy image pixels. */ status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,source_image,geometry->height,1) #endif for (y=0; y < (ssize_t) geometry->height; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y, geometry->width,1,exception); q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y, geometry->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) geometry->width; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0) || (source_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CopyImage) #endif proceed=SetImageProgress(image,CopyImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImage() dereferences an image, deallocating memory associated with % the image if the reference count becomes zero. % % The format of the DestroyImage method is: % % Image *DestroyImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *DestroyImage(Image *image) { MagickBooleanType destroy; /* Dereference image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); destroy=MagickFalse; LockSemaphoreInfo(image->semaphore); image->reference_count--; if (image->reference_count == 0) destroy=MagickTrue; UnlockSemaphoreInfo(image->semaphore); if (destroy == MagickFalse) return((Image *) NULL); /* Destroy image. */ DestroyImagePixels(image); image->channel_map=DestroyPixelChannelMap(image->channel_map); if (image->montage != (char *) NULL) image->montage=DestroyString(image->montage); if (image->directory != (char *) NULL) image->directory=DestroyString(image->directory); if (image->colormap != (PixelInfo *) NULL) image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); if (image->geometry != (char *) NULL) image->geometry=DestroyString(image->geometry); DestroyImageProfiles(image); DestroyImageProperties(image); DestroyImageArtifacts(image); if (image->ascii85 != (Ascii85Info *) NULL) image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85); if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); DestroyBlob(image); if (image->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&image->semaphore); image->signature=(~MagickCoreSignature); image=(Image *) RelinquishMagickMemory(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageInfo() deallocates memory associated with an ImageInfo % structure. % % The format of the DestroyImageInfo method is: % % ImageInfo *DestroyImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); if (image_info->scenes != (char *) NULL) image_info->scenes=DestroyString(image_info->scenes); if (image_info->page != (char *) NULL) image_info->page=DestroyString(image_info->page); if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); if (image_info->cache != (void *) NULL) image_info->cache=DestroyPixelCache(image_info->cache); if (image_info->profile != (StringInfo *) NULL) image_info->profile=(void *) DestroyStringInfo((StringInfo *) image_info->profile); DestroyImageOptions(image_info); image_info->signature=(~MagickCoreSignature); image_info=(ImageInfo *) RelinquishMagickMemory(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s a s s o c i a t e I m a g e S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisassociateImageStream() disassociates the image stream. It checks if the % blob of the specified image is referenced by other images. If the reference % count is higher then 1 a new blob is assigned to the specified image. % % The format of the DisassociateImageStream method is: % % void DisassociateImageStream(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DisassociateImageStream(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); DisassociateBlob(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfo() initializes image_info to default values. % % The format of the GetImageInfo method is: % % void GetImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport void GetImageInfo(ImageInfo *image_info) { char *synchronize; ExceptionInfo *exception; /* File and image dimension members. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info != (ImageInfo *) NULL); (void) ResetMagickMemory(image_info,0,sizeof(*image_info)); image_info->adjoin=MagickTrue; image_info->interlace=NoInterlace; image_info->channel=DefaultChannels; image_info->quality=UndefinedCompressionQuality; image_info->antialias=MagickTrue; image_info->dither=MagickTrue; synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { image_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } exception=AcquireExceptionInfo(); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image_info->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance, &image_info->border_color,exception); (void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image_info->transparent_color,exception); exception=DestroyExceptionInfo(exception); image_info->debug=IsEventLogging(); image_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfoFile() returns the image info file member. % % The format of the GetImageInfoFile method is: % % FILE *GetImageInfoFile(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info) { return(image_info->file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMask() returns the mask associated with the image. % % The format of the GetImageMask method is: % % Image *GetImageMask(const Image *image,const PixelMask type, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % */ MagickExport Image *GetImageMask(const Image *image,const PixelMask type, ExceptionInfo *exception) { CacheView *mask_view, *image_view; Image *mask_image; MagickBooleanType status; ssize_t y; /* Get image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); mask_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (mask_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; mask_image->alpha_trait=UndefinedPixelTrait; (void) SetImageColorspace(mask_image,GRAYColorspace,exception); mask_image->read_mask=MagickFalse; image_view=AcquireVirtualCacheView(image,exception); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { switch (type) { case WritePixelMask: { SetPixelGray(mask_image,GetPixelWriteMask(image,p),q); break; } default: { SetPixelGray(mask_image,GetPixelReadMask(image,p),q); break; } } p+=GetPixelChannels(image); q+=GetPixelChannels(mask_image); } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) mask_image=DestroyImage(mask_image); return(mask_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e R e f e r e n c e C o u n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageReferenceCount() returns the image reference count. % % The format of the GetReferenceCount method is: % % ssize_t GetImageReferenceCount(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport ssize_t GetImageReferenceCount(Image *image) { ssize_t reference_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); LockSemaphoreInfo(image->semaphore); reference_count=image->reference_count; UnlockSemaphoreInfo(image->semaphore); return(reference_count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageVirtualPixelMethod() gets the "virtual pixels" method for the % image. A virtual pixel is any pixel access that is outside the boundaries % of the image cache. % % The format of the GetImageVirtualPixelMethod() method is: % % VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(GetPixelCacheVirtualMethod(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageFilename() interprets embedded characters in an image filename. % The filename length is returned. % % The format of the InterpretImageFilename method is: % % size_t InterpretImageFilename(const ImageInfo *image_info,Image *image, % const char *format,int value,char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info.. % % o image: the image. % % o format: A filename describing the format to use to write the numeric % argument. Only the first numeric format identifier is replaced. % % o value: Numeric value to substitute into format filename. % % o filename: return the formatted filename in this character buffer. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t InterpretImageFilename(const ImageInfo *image_info, Image *image,const char *format,int value,char *filename, ExceptionInfo *exception) { char *q; int c; MagickBooleanType canonical; register const char *p; size_t length; canonical=MagickFalse; length=0; (void) CopyMagickString(filename,format,MagickPathExtent); for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%')) { q=(char *) p+1; if (*q == '%') { p=q+1; continue; } if (*q == '0') { ssize_t foo; foo=(ssize_t) strtol(q,&q,10); (void) foo; } switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format),(size_t) (MagickPathExtent-(p-format)),p,value); *q=c; (void) ConcatenateMagickString(filename,q,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MagickPathExtent]; const char *option; register char *r; register ssize_t i; ssize_t depth; /* Image option. */ /* FUTURE: Compare update with code from InterpretImageProperties() Note that a 'filename:' property should not need depth recursion. */ if (strchr(p,']') == (char *) NULL) break; depth=1; r=q+1; for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++) { if (*r == '[') depth++; if (*r == ']') depth--; if (depth <= 0) break; pattern[i]=(*r++); } pattern[i]='\0'; if (LocaleNCompare(pattern,"filename:",9) != 0) break; option=(const char *) NULL; if (image != (Image *) NULL) option=GetImageProperty(image,pattern,exception); if ((option == (const char *) NULL) && (image != (Image *) NULL)) option=GetImageArtifact(image,pattern); if ((option == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) option=GetImageOption(image_info,pattern); if (option == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-length),option,(size_t) (MagickPathExtent-(p-format-length))); length+=strlen(pattern)-1; *q=c; (void) ConcatenateMagickString(filename,r+1,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } default: break; } } for (q=filename; *q != '\0'; q++) if ((*q == '%') && (*(q+1) == '%')) { (void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename))); canonical=MagickTrue; } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MagickPathExtent); return(strlen(filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s H i g h D y n a m i c R a n g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsHighDynamicRangeImage() returns MagickTrue if any pixel component is % non-integer or exceeds the bounds of the quantum depth (e.g. for Q16 % 0..65535. % % The format of the IsHighDynamicRangeImage method is: % % MagickBooleanType IsHighDynamicRangeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image, ExceptionInfo *exception) { #if !defined(MAGICKCORE_HDRI_SUPPORT) (void) image; (void) exception; return(MagickFalse); #else CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelTrait traits; traits=GetPixelChannelTraits(image,(PixelChannel) i); if (traits == UndefinedPixelTrait) continue; pixel=(double) p[i]; if ((pixel < 0.0) || (pixel > QuantumRange) || (pixel != (double) ((QuantumAny) pixel))) break; } p+=GetPixelChannels(image); if (i < (ssize_t) GetPixelChannels(image)) status=MagickFalse; } if (x < (ssize_t) image->columns) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status != MagickFalse ? MagickFalse : MagickTrue); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e O b j e c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageObject() returns MagickTrue if the image sequence contains a valid % set of image objects. % % The format of the IsImageObject method is: % % MagickBooleanType IsImageObject(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsImageObject(const Image *image) { register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) if (p->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTaintImage() returns MagickTrue any pixel in the image has been altered % since it was first constituted. % % The format of the IsTaintImage method is: % % MagickBooleanType IsTaintImage(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsTaintImage(const Image *image) { char magick[MagickPathExtent], filename[MagickPathExtent]; register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); (void) CopyMagickString(magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { if (p->taint != MagickFalse) return(MagickTrue); if (LocaleCompare(p->magick,magick) != 0) return(MagickTrue); if (LocaleCompare(p->filename,filename) != 0) return(MagickTrue); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModifyImage() ensures that there is only a single reference to the image % to be modified, updating the provided image pointer to point to a clone of % the original image if necessary. % % The format of the ModifyImage method is: % % MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ModifyImage(Image **image, ExceptionInfo *exception) { Image *clone_image; assert(image != (Image **) NULL); assert(*image != (Image *) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); if (GetImageReferenceCount(*image) <= 1) return(MagickTrue); clone_image=CloneImage(*image,0,0,MagickTrue,exception); LockSemaphoreInfo((*image)->semaphore); (*image)->reference_count--; UnlockSemaphoreInfo((*image)->semaphore); *image=clone_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w M a g i c k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewMagickImage() creates a blank image canvas of the specified size and % background color. % % The format of the NewMagickImage method is: % % Image *NewMagickImage(const ImageInfo *image_info,const size_t width, % const size_t height,const PixelInfo *background, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the image width. % % o height: the image height. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *NewMagickImage(const ImageInfo *image_info, const size_t width,const size_t height,const PixelInfo *background, ExceptionInfo *exception) { CacheView *image_view; Image *image; MagickBooleanType status; ssize_t y; assert(image_info != (const ImageInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info->signature == MagickCoreSignature); assert(background != (const PixelInfo *) NULL); image=AcquireImage(image_info,exception); image->columns=width; image->rows=height; image->colorspace=background->colorspace; image->alpha_trait=background->alpha_trait; image->fuzz=background->fuzz; image->depth=background->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e f e r e n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferenceImage() increments the reference count associated with an image % returning a pointer to the image. % % The format of the ReferenceImage method is: % % Image *ReferenceImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *ReferenceImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); LockSemaphoreInfo(image->semaphore); image->reference_count++; UnlockSemaphoreInfo(image->semaphore); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePage() resets the image page canvas and position. % % The format of the ResetImagePage method is: % % MagickBooleanType ResetImagePage(Image *image,const char *page) % % A description of each parameter follows: % % o image: the image. % % o page: the relative page specification. % */ MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAlpha() sets the alpha levels of the image. % % The format of the SetImageAlpha method is: % % MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o Alpha: the level of transparency: 0 is fully opaque and QuantumRange is % fully transparent. % */ MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) > (QuantumRange/2)) SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageBackgroundColor() initializes the image pixels to the image % background color. The background color is defined by the background_color % member of the image structure. % % The format of the SetImage method is: % % MagickBooleanType SetImageBackgroundColor(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageBackgroundColor(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo background; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((image->background_color.alpha != OpaqueAlpha) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OnAlphaChannel,exception); ConformPixelInfo(image,&image->background_color,&background,exception); /* Set image background color. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelMask() sets the image channel mask from the specified channel % mask. % % The format of the SetImageChannelMask method is: % % ChannelType SetImageChannelMask(Image *image, % const ChannelType channel_mask) % % A description of each parameter follows: % % o image: the image. % % o channel_mask: the channel mask. % */ MagickExport ChannelType SetImageChannelMask(Image *image, const ChannelType channel_mask) { return(SetPixelChannelMask(image,channel_mask)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColor() set the entire image canvas to the specified color. % % The format of the SetImageColor method is: % % MagickBooleanType SetImageColor(Image *image,const PixelInfo *color, % ExeptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColor(Image *image, const PixelInfo *color,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); assert(color != (const PixelInfo *) NULL); image->colorspace=color->colorspace; image->alpha_trait=color->alpha_trait; image->fuzz=color->fuzz; image->depth=color->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,color,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageStorageClass() sets the image class: DirectClass for true color % images or PseudoClass for colormapped images. % % The format of the SetImageStorageClass method is: % % MagickBooleanType SetImageStorageClass(Image *image, % const ClassType storage_class,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o storage_class: The image class. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageStorageClass(Image *image, const ClassType storage_class,ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image->storage_class=storage_class; return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageExtent() sets the image size (i.e. columns & rows). % % The format of the SetImageExtent method is: % % MagickBooleanType SetImageExtent(Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: The image width in pixels. % % o rows: The image height in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { if ((columns == 0) || (rows == 0)) ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename); image->columns=columns; image->rows=rows; if (image->depth > (8*sizeof(MagickSizeType))) ThrowBinaryException(ImageError,"ImageDepthNotSupported",image->filename); return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfo() initializes the 'magick' field of the ImageInfo structure. % It is set to a type of image format based on the prefix or suffix of the % filename. For example, 'ps:image' returns PS indicating a Postscript image. % JPEG is returned for this filename: 'image.jpg'. The filename prefix has % precendence over the suffix. Use an optional index enclosed in brackets % after a file name to specify a desired scene of a multi-resolution image % format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value % indicates success. % % The format of the SetImageInfo method is: % % MagickBooleanType SetImageInfo(ImageInfo *image_info, % const unsigned int frames,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o frames: the number of images you intend to write. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char component[MagickPathExtent], magic[MagickPathExtent], *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*component != '\0') if ((LocaleCompare(component,"gz") == 0) || (LocaleCompare(component,"Z") == 0) || (LocaleCompare(component,"svgz") == 0) || (LocaleCompare(component,"wmz") == 0)) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*component != '\0') if (LocaleCompare(component,"bz2") == 0) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if (*component != '\0') { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') { (void) CopyMagickString(magic,image_info->magick,MagickPathExtent); magick_info=GetMagickInfo(magic,sans_exception); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); } else { const DelegateInfo *delegate_info; /* User specified image format. */ LocaleUpper(magic); magick_info=GetMagickInfo(magic,sans_exception); delegate_info=GetDelegateInfo(magic,"*",sans_exception); if (delegate_info == (const DelegateInfo *) NULL) delegate_info=GetDelegateInfo("*",magic,sans_exception); if (((magick_info != (const MagickInfo *) NULL) || (delegate_info != (const DelegateInfo *) NULL)) && (IsMagickConflict(magic) == MagickFalse)) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component, MagickPathExtent); } } sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy image to seekable temporary file. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireMagickMemory(magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) ResetMagickMemory(magick,0,magick_size); count=ReadBlob(image,magick_size,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic.xml configuration file. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoBlob() sets the image info blob member. % % The format of the SetImageInfoBlob method is: % % void SetImageInfoBlob(ImageInfo *image_info,const void *blob, % const size_t length) % % A description of each parameter follows: % % o image_info: the image info. % % o blob: the blob. % % o length: the blob length. % */ MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob, const size_t length) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->blob=(void *) blob; image_info->length=length; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o C u s t o m S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoCustomStream() sets the image info custom stream handlers. % % The format of the SetImageInfoCustomStream method is: % % void SetImageInfoCustomStream(ImageInfo *image_info, % CustomStreamInfo *custom_stream) % % A description of each parameter follows: % % o image_info: the image info. % % o custom_stream: your custom stream methods. % */ MagickExport void SetImageInfoCustomStream(ImageInfo *image_info, CustomStreamInfo *custom_stream) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->custom_stream=(CustomStreamInfo *) custom_stream; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoFile() sets the image info file member. % % The format of the SetImageInfoFile method is: % % void SetImageInfoFile(ImageInfo *image_info,FILE *file) % % A description of each parameter follows: % % o image_info: the image info. % % o file: the file. % */ MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->file=file; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMask() associates a mask with the image. The mask must be the same % dimensions as the image. % % The format of the SetImageMask method is: % % MagickBooleanType SetImageMask(Image *image,const PixelMask type, % const Image *mask,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o mask: the image mask. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type, const Image *mask,ExceptionInfo *exception) { CacheView *mask_view, *image_view; MagickBooleanType status; ssize_t y; /* Set image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (mask == (const Image *) NULL) { switch (type) { case WritePixelMask: image->write_mask=MagickFalse; break; default: image->read_mask=MagickFalse; break; } return(SyncImagePixelCache(image,exception)); } switch (type) { case WritePixelMask: image->write_mask=MagickTrue; break; default: image->read_mask=MagickTrue; break; } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; mask_view=AcquireVirtualCacheView(mask,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(mask,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=0.0; if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows)) intensity=GetPixelIntensity(mask,p); switch (type) { case WritePixelMask: { SetPixelWriteMask(image,ClampToQuantum(intensity),q); break; } default: { SetPixelReadMask(image,ClampToQuantum(intensity),q); break; } } p+=GetPixelChannels(mask); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e R e g i o n M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageRegionMask() associates a mask with the image as defined by the % specified region. % % The format of the SetImageRegionMask method is: % % MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type, % const RectangleInfo *region,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o geometry: the mask region. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageRegionMask(Image *image, const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Set image mask as defined by the region. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (region == (const RectangleInfo *) NULL) { switch (type) { case WritePixelMask: image->write_mask=MagickFalse; break; default: image->read_mask=MagickFalse; break; } return(SyncImagePixelCache(image,exception)); } switch (type) { case WritePixelMask: image->write_mask=MagickTrue; break; default: image->read_mask=MagickTrue; break; } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=(Quantum) 0; if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) && ((y >= region->y) && (y < (region->y+(ssize_t) region->height)))) pixel=QuantumRange; switch (type) { case WritePixelMask: { SetPixelWriteMask(image,pixel,q); break; } default: { SetPixelReadMask(image,pixel,q); break; } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageVirtualPixelMethod() sets the "virtual pixels" method for the % image and returns the previous setting. A virtual pixel is any pixel access % that is outside the boundaries of the image cache. % % The format of the SetImageVirtualPixelMethod() method is: % % VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S m u s h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SmushImages() takes all images from the current image pointer to the end % of the image list and smushes them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the SmushImages method is: % % Image *SmushImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o offset: minimum distance in pixels between images. % % o exception: return any errors or warnings in this structure. % */ static ssize_t SmushXGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *left_view, *right_view; const Image *left_image, *right_image; RectangleInfo left_geometry, right_geometry; register const Quantum *p; register ssize_t i, y; size_t gap; ssize_t x; if (images->previous == (Image *) NULL) return(0); right_image=images; SetGeometry(smush_image,&right_geometry); GravityAdjustGeometry(right_image->columns,right_image->rows, right_image->gravity,&right_geometry); left_image=images->previous; SetGeometry(smush_image,&left_geometry); GravityAdjustGeometry(left_image->columns,left_image->rows, left_image->gravity,&left_geometry); gap=right_image->columns; left_view=AcquireVirtualCacheView(left_image,exception); right_view=AcquireVirtualCacheView(right_image,exception); for (y=0; y < (ssize_t) smush_image->rows; y++) { for (x=(ssize_t) left_image->columns-1; x > 0; x--) { p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(left_image,p) != TransparentAlpha) || ((left_image->columns-x-1) >= gap)) break; } i=(ssize_t) left_image->columns-x-1; for (x=0; x < (ssize_t) right_image->columns; x++) { p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(right_image,p) != TransparentAlpha) || ((x+i) >= (ssize_t) gap)) break; } if ((x+i) < (ssize_t) gap) gap=(size_t) (x+i); } right_view=DestroyCacheView(right_view); left_view=DestroyCacheView(left_view); if (y < (ssize_t) smush_image->rows) return(offset); return((ssize_t) gap-offset); } static ssize_t SmushYGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *bottom_view, *top_view; const Image *bottom_image, *top_image; RectangleInfo bottom_geometry, top_geometry; register const Quantum *p; register ssize_t i, x; size_t gap; ssize_t y; if (images->previous == (Image *) NULL) return(0); bottom_image=images; SetGeometry(smush_image,&bottom_geometry); GravityAdjustGeometry(bottom_image->columns,bottom_image->rows, bottom_image->gravity,&bottom_geometry); top_image=images->previous; SetGeometry(smush_image,&top_geometry); GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity, &top_geometry); gap=bottom_image->rows; top_view=AcquireVirtualCacheView(top_image,exception); bottom_view=AcquireVirtualCacheView(bottom_image,exception); for (x=0; x < (ssize_t) smush_image->columns; x++) { for (y=(ssize_t) top_image->rows-1; y > 0; y--) { p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(top_image,p) != TransparentAlpha) || ((top_image->rows-y-1) >= gap)) break; } i=(ssize_t) top_image->rows-y-1; for (y=0; y < (ssize_t) bottom_image->rows; y++) { p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(bottom_image,p) != TransparentAlpha) || ((y+i) >= (ssize_t) gap)) break; } if ((y+i) < (ssize_t) gap) gap=(size_t) (y+i); } bottom_view=DestroyCacheView(bottom_view); top_view=DestroyCacheView(top_view); if (x < (ssize_t) smush_image->columns) return(offset); return((ssize_t) gap-offset); } MagickExport Image *SmushImages(const Image *images, const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception) { #define SmushImageTag "Smush/Image" const Image *image; Image *smush_image; MagickBooleanType proceed, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t height, number_images, width; ssize_t x_offset, y_offset; /* Compute maximum area of smushed area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=images; alpha_trait=image->alpha_trait; number_images=1; width=image->columns; height=image->rows; next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; if (next->previous != (Image *) NULL) height+=offset; continue; } width+=next->columns; if (next->previous != (Image *) NULL) width+=offset; if (next->rows > height) height=next->rows; } /* Smush images. */ smush_image=CloneImage(image,width,height,MagickTrue,exception); if (smush_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse) { smush_image=DestroyImage(smush_image); return((Image *) NULL); } smush_image->alpha_trait=alpha_trait; (void) SetImageBackgroundColor(smush_image,exception); status=MagickTrue; x_offset=0; y_offset=0; for (n=0; n < (MagickOffsetType) number_images; n++) { SetGeometry(smush_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) { x_offset-=geometry.x; y_offset-=SmushYGap(smush_image,image,offset,exception); } else { x_offset-=SmushXGap(smush_image,image,offset,exception); y_offset-=geometry.y; } status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset, y_offset,exception); proceed=SetImageProgress(image,SmushImageTag,n,number_images); if (proceed == MagickFalse) break; if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=GetNextImageInList(image); } if (stack == MagickFalse) smush_image->columns=(size_t) x_offset; else smush_image->rows=(size_t) y_offset; if (status == MagickFalse) smush_image=DestroyImage(smush_image); return(smush_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StripImage() strips an image of all profiles and comments. % % The format of the StripImage method is: % % MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) exception; DestroyImageProfiles(image); (void) DeleteImageProperty(image,"comment"); (void) DeleteImageProperty(image,"date:create"); (void) DeleteImageProperty(image,"date:modify"); status=SetImageArtifact(image,"png:exclude-chunk", "bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImage() initializes the red, green, and blue intensities of each pixel % as defined by the colormap index. % % The format of the SyncImage method is: % % MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PushColormapIndex(Image *image,const Quantum index, MagickBooleanType *range_exception) { if ((size_t) index < image->colors) return(index); *range_exception=MagickTrue; return((Quantum) 0); } MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType range_exception, status, taint; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->ping != MagickFalse) return(MagickTrue); if (image->storage_class != PseudoClass) return(MagickFalse); assert(image->colormap != (PixelInfo *) NULL); range_exception=MagickFalse; status=MagickTrue; taint=image->taint; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(range_exception,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum index; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->taint=taint; if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e S e t t i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageSettings() syncs any image_info global options into per-image % attributes. % % Note: in IMv6 free form 'options' were always mapped into 'artifacts', so % that operations and coders can find such settings. In IMv7 if a desired % per-image artifact is not set, then it will directly look for a global % option as a fallback, as such this copy is no longer needed, only the % link set up. % % The format of the SyncImageSettings method is: % % MagickBooleanType SyncImageSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % MagickBooleanType SyncImagesSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info, Image *images,ExceptionInfo *exception) { Image *image; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) (void) SyncImageSettings(image_info,image,exception); (void) DeleteImageOption(image_info,"page"); return(MagickTrue); } MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option; GeometryInfo geometry_info; MagickStatusType flags; ResolutionType units; /* Sync image options. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); option=GetImageOption(image_info,"background"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->background_color, exception); option=GetImageOption(image_info,"black-point-compensation"); if (option != (const char *) NULL) image->black_point_compensation=(MagickBooleanType) ParseCommandOption( MagickBooleanOptions,MagickFalse,option); option=GetImageOption(image_info,"blue-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x; } option=GetImageOption(image_info,"bordercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->border_color, exception); /* FUTURE: do not sync compose to per-image compose setting here */ option=GetImageOption(image_info,"compose"); if (option != (const char *) NULL) image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,option); /* -- */ option=GetImageOption(image_info,"compress"); if (option != (const char *) NULL) image->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,option); option=GetImageOption(image_info,"debug"); if (option != (const char *) NULL) image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } option=GetImageOption(image_info,"depth"); if (option != (const char *) NULL) image->depth=StringToUnsignedLong(option); option=GetImageOption(image_info,"endian"); if (option != (const char *) NULL) image->endian=(EndianType) ParseCommandOption(MagickEndianOptions, MagickFalse,option); option=GetImageOption(image_info,"filter"); if (option != (const char *) NULL) image->filter=(FilterType) ParseCommandOption(MagickFilterOptions, MagickFalse,option); option=GetImageOption(image_info,"fuzz"); if (option != (const char *) NULL) image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(image_info,"green-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y=image->chromaticity.green_primary.x; } option=GetImageOption(image_info,"intent"); if (option != (const char *) NULL) image->rendering_intent=(RenderingIntent) ParseCommandOption( MagickIntentOptions,MagickFalse,option); option=GetImageOption(image_info,"intensity"); if (option != (const char *) NULL) image->intensity=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,option); option=GetImageOption(image_info,"interlace"); if (option != (const char *) NULL) image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions, MagickFalse,option); option=GetImageOption(image_info,"interpolate"); if (option != (const char *) NULL) image->interpolate=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,option); option=GetImageOption(image_info,"loop"); if (option != (const char *) NULL) image->iterations=StringToUnsignedLong(option); option=GetImageOption(image_info,"mattecolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->matte_color, exception); option=GetImageOption(image_info,"orient"); if (option != (const char *) NULL) image->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,option); option=GetImageOption(image_info,"page"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) image->quality=StringToUnsignedLong(option); option=GetImageOption(image_info,"red-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y=image->chromaticity.red_primary.x; } if (image_info->quality != UndefinedCompressionQuality) image->quality=image_info->quality; option=GetImageOption(image_info,"scene"); if (option != (const char *) NULL) image->scene=StringToUnsignedLong(option); option=GetImageOption(image_info,"taint"); if (option != (const char *) NULL) image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"tile-offset"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"transparent-color"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->transparent_color, exception); option=GetImageOption(image_info,"type"); if (option != (const char *) NULL) image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, option); option=GetImageOption(image_info,"units"); units=image_info->units; if (option != (const char *) NULL) units=(ResolutionType) ParseCommandOption(MagickResolutionOptions, MagickFalse,option); if (units != UndefinedResolution) { if (image->units != units) switch (image->units) { case PixelsPerInchResolution: { if (units == PixelsPerCentimeterResolution) { image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case PixelsPerCentimeterResolution: { if (units == PixelsPerInchResolution) { image->resolution.x=(double) ((size_t) (100.0*2.54* image->resolution.x+0.5))/100.0; image->resolution.y=(double) ((size_t) (100.0*2.54* image->resolution.y+0.5))/100.0; } break; } default: break; } image->units=units; } option=GetImageOption(image_info,"virtual-pixel"); if (option != (const char *) NULL) (void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option), exception); option=GetImageOption(image_info,"white-point"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y=image->chromaticity.white_point.x; } /* Pointer to allow the lookup of pre-image artifact will fallback to a global option setting/define. This saves a lot of duplication of global options into per-image artifacts, while ensuring only specifically set per-image artifacts are preserved when parenthesis ends. */ if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); image->image_info=CloneImageInfo(image_info); return(MagickTrue); }
fftw.c
/*----------------------------------------------------------------*/ #include "hclfftw.h" #include <omp.h> /*----------------------------------------------------------------*/ int fftw1d( const int sign, const int m, const int n, fftw_complex* X, fftw_complex* Y ) { /* * 'm' number of 1D row FFTs of size 'n' */ int rank = 1; int howmany = m; int s[] = {n}; int idist = n; int odist = n; int istride = 1; int ostride = 1; int *inembed = s; int *onembed = s; fftw_plan my_plan = fftw_plan_many_dft( rank, s, howmany, X, inembed, istride, idist, Y, onembed, ostride, odist, sign, FFTW_ESTIMATE); fftw_execute(my_plan); fftw_destroy_plan(my_plan); return 0; } /*----------------------------------------------------------------*/ int fftw2dlocal( const int sign, const unsigned int* m, const int n, fftw_complex* lMatrix, double* tGroups ) { double ts = omp_get_wtime(); int rc = fftw1d( sign, *m, n, lMatrix, lMatrix); tGroups[0] += omp_get_wtime() - ts; return rc; } /*----------------------------------------------------------------*/ int fftw2dlocal2( const int sign, const unsigned int* m, const int n, const int nThreadsPerGroup, fftw_complex* lMatrix, double* tGroups ) { #pragma omp parallel sections num_threads(2) { #pragma omp section { double ts = omp_get_wtime(); fftw1d( sign, m[0], n, lMatrix, lMatrix); tGroups[0] += omp_get_wtime() - ts; } #pragma omp section { double ts = omp_get_wtime(); fftw1d( sign, m[1], n, lMatrix, lMatrix); tGroups[1] += omp_get_wtime() - ts; } } return 0; } /*----------------------------------------------------------------*/ int fftw2dlocal4( const int sign, const unsigned int* m, const int n, const int nThreadsPerGroup, fftw_complex* lMatrix, double* tGroups ) { #pragma omp parallel sections num_threads(4) { #pragma omp section { double ts = omp_get_wtime(); fftw1d( sign, m[0], n, lMatrix, lMatrix); tGroups[0] += omp_get_wtime() - ts; } #pragma omp section { double ts = omp_get_wtime(); fftw1d( sign, m[1], n, lMatrix, lMatrix); tGroups[1] += omp_get_wtime() - ts; } #pragma omp section { double ts = omp_get_wtime(); fftw1d( sign, m[2], n, lMatrix, lMatrix); tGroups[2] += omp_get_wtime() - ts; } #pragma omp section { double ts = omp_get_wtime(); fftw1d( sign, m[3], n, lMatrix, lMatrix); tGroups[3] += omp_get_wtime() - ts; } } return 0; } /*----------------------------------------------------------------*/ int fftwlocal( const int sign, const unsigned int* m, const int n, const int nThreadsPerGroup, const int nThreadGroups, fftw_complex *lMatrix, double* tGroups ) { if (nThreadGroups == 1) { fftw2dlocal( sign, m, n, lMatrix, tGroups); } if (nThreadGroups == 2) { fftw2dlocal2( sign, m, n, nThreadsPerGroup, lMatrix, tGroups); } if (nThreadGroups == 4) { fftw2dlocal4( sign, m, n, nThreadsPerGroup, lMatrix, tGroups); } return 0; } /*----------------------------------------------------------------*/
matrix.h
/*************************************************************************** * include/stxxl/bits/containers/matrix.h * * Part of the STXXL. See http://stxxl.org * * Copyright (C) 2010-2011 Raoul Steffen <R-Steffen@gmx.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #ifndef STXXL_CONTAINERS_MATRIX_HEADER #define STXXL_CONTAINERS_MATRIX_HEADER #include <algorithm> #include <vector> #include <utility> #include <tlx/counting_ptr.hpp> #include <tlx/logger/core.hpp> #include <foxxll/mng/block_scheduler.hpp> #include <stxxl/bits/containers/vector.h> #include <stxxl/bits/containers/matrix_arithmetic.h> namespace stxxl { //! \defgroup matrix matrix //! Efficient external memory matrix operations //! \ingroup stlcont //! \{ /* index-variable naming convention: * [MODIFIER_][UNIT_]DIMENSION[_in_[MODIFIER_]ENVIRONMENT] * * e.g.: * block_row = number of row measured in rows consisting of blocks * element_row_in_block = number of row measured in rows consisting of elements in the (row of) block(s) * * size-variable naming convention: * [MODIFIER_][ENVIRONMENT_]DIMENSION[_in_UNITs] * * e.g. * height_in_blocks */ // forward declaration template <typename ValueType, unsigned BlockSideLength> class matrix; //! external column-vector container for matrix multiplication //! \tparam ValueType type of contained objects (POD with no references to internal memory) template <typename ValueType> class column_vector : public vector<ValueType> { public: using vector_type = vector<ValueType>; using size_type = typename vector_type::size_type; using vector_type::size; //! \param n number of elements explicit column_vector(size_type n = 0) : vector_type(n) { } column_vector operator + (const column_vector& right) const { assert(size() == right.size()); column_vector res(size()); for (size_type i = 0; i < size(); ++i) res[i] = (*this)[i] + right[i]; return res; } column_vector operator - (const column_vector& right) const { assert(size() == right.size()); column_vector res(size()); for (size_type i = 0; i < size(); ++i) res[i] = (*this)[i] - right[i]; return res; } column_vector operator * (const ValueType scalar) const { column_vector res(size()); for (size_type i = 0; i < size(); ++i) res[i] = (*this)[i] * scalar; return res; } column_vector& operator += (const column_vector& right) { assert(size() == right.size()); for (size_type i = 0; i < size(); ++i) (*this)[i] += right[i]; return *this; } column_vector& operator -= (const column_vector& right) { assert(size() == right.size()); for (size_type i = 0; i < size(); ++i) (*this)[i] -= right[i]; return *this; } column_vector& operator *= (const ValueType scalar) { for (size_type i = 0; i < size(); ++i) (*this)[i] *= scalar; return *this; } void set_zero() { for (typename vector_type::iterator it = vector_type::begin(); it != vector_type::end(); ++it) *it = 0; } }; //! external row-vector container for matrix multiplication //! \tparam ValueType type of contained objects (POD with no references to internal memory) template <typename ValueType> class row_vector : public vector<ValueType> { public: using vector_type = vector<ValueType>; using size_type = typename vector_type::size_type; using vector_type::size; //! \param n number of elements explicit row_vector(size_type n = 0) : vector_type(n) { } row_vector operator + (const row_vector& right) const { assert(size() == right.size()); row_vector res(size()); for (size_type i = 0; i < size(); ++i) res[i] = (*this)[i] + right[i]; return res; } row_vector operator - (const row_vector& right) const { assert(size() == right.size()); row_vector res(size()); for (size_type i = 0; i < size(); ++i) res[i] = (*this)[i] - right[i]; return res; } row_vector operator * (const ValueType scalar) const { row_vector res(size()); for (size_type i = 0; i < size(); ++i) res[i] = (*this)[i] * scalar; return res; } template <unsigned BlockSideLength> row_vector operator * (const matrix<ValueType, BlockSideLength>& right) const { return right.multiply_from_left(*this); } ValueType operator * (const column_vector<ValueType>& right) const { ValueType res = 0; for (size_type i = 0; i < size(); ++i) res += (*this)[i] * right[i]; return res; } row_vector& operator += (const row_vector& right) { assert(size() == right.size()); for (size_type i = 0; i < size(); ++i) (*this)[i] += right[i]; return *this; } row_vector& operator -= (const row_vector& right) { assert(size() == right.size()); for (size_type i = 0; i < size(); ++i) (*this)[i] -= right[i]; return *this; } row_vector& operator *= (const ValueType scalar) { for (size_type i = 0; i < size(); ++i) (*this)[i] *= scalar; return *this; } void set_zero() { for (typename vector_type::iterator it = vector_type::begin(); it != vector_type::end(); ++it) *it = 0; } }; //! Specialized swappable_block that interprets uninitialized as containing zeros. //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block //! //! When initializing, all values are set to zero. template <typename ValueType, unsigned BlockSideLength> class matrix_swappable_block : public foxxll::swappable_block<ValueType, BlockSideLength* BlockSideLength> { public: using internal_block_type = typename foxxll::swappable_block<ValueType, BlockSideLength* BlockSideLength>::internal_block_type; using foxxll::swappable_block<ValueType, BlockSideLength* BlockSideLength>::get_internal_block; void fill_default() { // get_internal_block checks acquired internal_block_type& data = get_internal_block(); #if STXXL_PARALLEL #pragma omp parallel for #endif for (unsigned row = 0; row < BlockSideLength; ++row) for (unsigned col = 0; col < BlockSideLength; ++col) data[row * BlockSideLength + col] = 0; } }; //! External container for a (sub)matrix. Not intended for direct use. //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block //! //! Stores blocks only, so all measures (height, width, row, col) are in blocks. template <typename ValueType, unsigned BlockSideLength> class swappable_block_matrix : public tlx::reference_counter { public: using size_type = size_t; using elem_size_type = size_t; using block_scheduler_type = foxxll::block_scheduler<matrix_swappable_block<ValueType, BlockSideLength> >; using swappable_block_identifier_type = typename block_scheduler_type::swappable_block_identifier_type; using blocks_type = std::vector<swappable_block_identifier_type>; using Ops = matrix_local::matrix_operations<ValueType, BlockSideLength>; block_scheduler_type& bs; private: // assigning is not allowed swappable_block_matrix& operator = (const swappable_block_matrix& other); protected: //! height of the matrix in blocks size_type height, //! width of the matrix in blocks width, //! height copied from supermatrix in blocks height_from_supermatrix, //! width copied from supermatrix in blocks width_from_supermatrix; //! the matrice's blocks in row-major blocks_type blocks; //! if the elements in each block are in col-major instead of row-major bool elements_in_blocks_transposed; //! get identifier of the block at (row, col) swappable_block_identifier_type & bl(const size_type row, const size_type col) { return blocks[row * width + col]; } public: //! Create an empty swappable_block_matrix of given dimensions. swappable_block_matrix(block_scheduler_type& bs, const size_type height_in_blocks, const size_type width_in_blocks, const bool transposed = false) : bs(bs), height(height_in_blocks), width(width_in_blocks), height_from_supermatrix(0), width_from_supermatrix(0), blocks(height * width), elements_in_blocks_transposed(transposed) { for (size_type row = 0; row < height; ++row) for (size_type col = 0; col < width; ++col) bl(row, col) = bs.allocate_swappable_block(); } //! Create swappable_block_matrix of given dimensions that //! represents the submatrix of supermatrix starting at (from_row_in_blocks, from_col_in_blocks). //! //! If supermatrix is not large enough, the submatrix is padded with empty blocks. //! The supermatrix must not be destructed or transposed before the submatrix is destructed. swappable_block_matrix(const swappable_block_matrix& supermatrix, const size_type height_in_blocks, const size_type width_in_blocks, const size_type from_row_in_blocks, const size_type from_col_in_blocks) : bs(supermatrix.bs), height(height_in_blocks), width(width_in_blocks), height_from_supermatrix(std::min(supermatrix.height - from_row_in_blocks, height)), width_from_supermatrix(std::min(supermatrix.width - from_col_in_blocks, width)), blocks(height * width), elements_in_blocks_transposed(supermatrix.elements_in_blocks_transposed) { for (size_type row = 0; row < height_from_supermatrix; ++row) { for (size_type col = 0; col < width_from_supermatrix; ++col) bl(row, col) = supermatrix.block(row + from_row_in_blocks, col + from_col_in_blocks); for (size_type col = width_from_supermatrix; col < width; ++col) bl(row, col) = bs.allocate_swappable_block(); } for (size_type row = height_from_supermatrix; row < height; ++row) for (size_type col = 0; col < width; ++col) bl(row, col) = bs.allocate_swappable_block(); } //! Create swappable_block_matrix that represents the combination matrix ul ur dl dr. //! //! The submatrices are assumed to be of fitting dimensions and equal transposition. //! The submatrices must not be destructed or transposed before the matrix is destructed. swappable_block_matrix(const swappable_block_matrix& ul, const swappable_block_matrix& ur, const swappable_block_matrix& dl, const swappable_block_matrix& dr) : bs(ul.bs), height(ul.height + dl.height), width(ul.width + ur.width), height_from_supermatrix(height), width_from_supermatrix(width), blocks(height * width), elements_in_blocks_transposed(ul.elements_in_blocks_transposed) { for (size_type row = 0; row < ul.height; ++row) { for (size_type col = 0; col < ul.width; ++col) bl(row, col) = ul.block(row, col); for (size_type col = ul.width; col < width; ++col) bl(row, col) = ur.block(row, col - ul.width); } for (size_type row = ul.height; row < height; ++row) { for (size_type col = 0; col < ul.width; ++col) bl(row, col) = dl.block(row - ul.height, col); for (size_type col = ul.width; col < width; ++col) bl(row, col) = dr.block(row - ul.height, col - ul.width); } } swappable_block_matrix(const swappable_block_matrix& other) : tlx::reference_counter(other), bs(other.bs), height(other.height), width(other.width), height_from_supermatrix(0), width_from_supermatrix(0), blocks(height * width), elements_in_blocks_transposed(false) { for (size_type row = 0; row < height; ++row) for (size_type col = 0; col < width; ++col) bl(row, col) = bs.allocate_swappable_block(); // 0 + other is copying Ops::element_op(*this, other, typename Ops::addition()); } ~swappable_block_matrix() { for (size_type row = 0; row < height_from_supermatrix; ++row) { for (size_type col = width_from_supermatrix; col < width; ++col) bs.free_swappable_block(bl(row, col)); } for (size_type row = height_from_supermatrix; row < height; ++row) for (size_type col = 0; col < width; ++col) bs.free_swappable_block(bl(row, col)); } static size_type block_index_from_elem(elem_size_type index) { return index / BlockSideLength; } static elem_size_type elem_index_in_block_from_elem(elem_size_type index) { return index % BlockSideLength; } // regards transposed elem_size_type elem_index_in_block_from_elem(elem_size_type row, elem_size_type col) const { return (is_transposed()) ? row % BlockSideLength + col % BlockSideLength * BlockSideLength : row % BlockSideLength * BlockSideLength + col % BlockSideLength; } //! get identifier of the block at (row, col) const swappable_block_identifier_type & block(const size_type row, const size_type col) const { return blocks[row * width + col]; } //! get identifier of the block at (row, col) const swappable_block_identifier_type& operator () (const size_type row, const size_type col) const { return block(row, col); } const size_type & get_height() const { return height; } const size_type & get_width() const { return width; } //! if the elements inside the blocks are in transposed order i.e. column-major const bool & is_transposed() const { return elements_in_blocks_transposed; } void transpose() { // transpose matrix of blocks blocks_type bn(blocks.size()); for (size_type row = 0; row < height; ++row) for (size_type col = 0; col < width; ++col) bn[col * height + row] = bl(row, col); bn.swap(blocks); // swap dimensions std::swap(height, width); std::swap(height_from_supermatrix, width_from_supermatrix); elements_in_blocks_transposed = ! elements_in_blocks_transposed; } void set_zero() { for (typename blocks_type::iterator it = blocks.begin(); it != blocks.end(); ++it) bs.deinitialize(*it); } }; //! general iterator type that points to single elements inside a matrix //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block template <typename ValueType, unsigned BlockSideLength> class matrix_iterator { protected: using matrix_type = matrix<ValueType, BlockSideLength>; using swappable_block_matrix_type = typename matrix_type::swappable_block_matrix_type; using block_scheduler_type = typename matrix_type::block_scheduler_type; using internal_block_type = typename block_scheduler_type::internal_block_type; using elem_size_type = typename matrix_type::elem_size_type; using block_size_type = typename matrix_type::block_size_type; template <typename VT, unsigned BSL> friend class matrix; template <typename VT, unsigned BSL> friend class const_matrix_iterator; matrix_type* m; elem_size_type current_row, // \ both indices == -1 <=> empty iterator current_col; // / block_size_type current_block_row, current_block_col; internal_block_type* current_iblock; // nullptr if block is not acquired void acquire_current_iblock() { if (! current_iblock) current_iblock = &m->data->bs.acquire(m->data->block(current_block_row, current_block_col)); } void release_current_iblock() { if (current_iblock) { m->data->bs.release(m->data->block(current_block_row, current_block_col), true); current_iblock = 0; } } //! create iterator pointing to given row and col matrix_iterator(matrix_type& matrix, const elem_size_type start_row, const elem_size_type start_col) : m(&matrix), current_row(start_row), current_col(start_col), current_block_row(m->data->block_index_from_elem(start_row)), current_block_col(m->data->block_index_from_elem(start_col)), current_iblock(0) { } //! create empty iterator explicit matrix_iterator(matrix_type& matrix) : m(&matrix), current_row(static_cast<elem_size_type>(-1)), // empty iterator current_col(static_cast<elem_size_type>(-1)), current_block_row(static_cast<block_size_type>(-1)), current_block_col(static_cast<block_size_type>(-1)), current_iblock(0) { } void set_empty() { release_current_iblock(); current_row = static_cast<elem_size_type>(-1); current_col = static_cast<elem_size_type>(-1); current_block_row = static_cast<block_size_type>(-1); current_block_col = static_cast<block_size_type>(-1); } public: matrix_iterator(const matrix_iterator& other) : m(other.m), current_row(other.current_row), current_col(other.current_col), current_block_row(other.current_block_row), current_block_col(other.current_block_col), current_iblock(0) { if (other.current_iblock) acquire_current_iblock(); } matrix_iterator& operator = (const matrix_iterator& other) { set_pos(other.current_row, other.current_col); m = other.m; if (other.current_iblock) acquire_current_iblock(); return *this; } ~matrix_iterator() { release_current_iblock(); } void set_row(const elem_size_type new_row) { const block_size_type new_block_row = m->data->block_index_from_elem(new_row); if (new_block_row != current_block_row) { release_current_iblock(); current_block_row = new_block_row; } current_row = new_row; } void set_col(const elem_size_type new_col) { const block_size_type new_block_col = m->data->block_index_from_elem(new_col); if (new_block_col != current_block_col) { release_current_iblock(); current_block_col = new_block_col; } current_col = new_col; } void set_pos(const elem_size_type new_row, const elem_size_type new_col) { const block_size_type new_block_row = m->data->block_index_from_elem(new_row), new_block_col = m->data->block_index_from_elem(new_col); if (new_block_col != current_block_col || new_block_row != current_block_row) { release_current_iblock(); current_block_row = new_block_row; current_block_col = new_block_col; } current_row = new_row; current_col = new_col; } void set_pos(const std::pair<elem_size_type, elem_size_type> new_pos) { set_pos(new_pos.first, new_pos.second); } const elem_size_type & get_row() const { return current_row; } const elem_size_type & get_col() const { return current_col; } std::pair<elem_size_type, elem_size_type> get_pos() const { return std::make_pair(current_row, current_col); } bool empty() const { return current_row == static_cast<elem_size_type>(-1) && current_col == static_cast<elem_size_type>(-1); } operator bool () const { return ! empty(); } bool operator == (const matrix_iterator& other) const { return current_row == other.current_row && current_col == other.current_col && m == other.m; } //! Returns reference access to the element referenced by the iterator. //! The reference is only valid so long as the iterator is not moved. ValueType& operator * () { acquire_current_iblock(); return (*current_iblock)[m->data->elem_index_in_block_from_elem(current_row, current_col)]; } }; //! row-major iterator that points to single elements inside a matrix //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block template <typename ValueType, unsigned BlockSideLength> class matrix_row_major_iterator : public matrix_iterator<ValueType, BlockSideLength> { protected: using matrix_iterator_type = matrix_iterator<ValueType, BlockSideLength>; using matrix_type = typename matrix_iterator_type::matrix_type; using elem_size_type = typename matrix_iterator_type::elem_size_type; template <typename VT, unsigned BSL> friend class matrix; using matrix_iterator_type::m; using matrix_iterator_type::set_empty; //! create iterator pointing to given row and col matrix_row_major_iterator(matrix_type& matrix, const elem_size_type start_row, const elem_size_type start_col) : matrix_iterator_type(matrix, start_row, start_col) { } //! create empty iterator explicit matrix_row_major_iterator(matrix_type& matrix) : matrix_iterator_type(matrix) { } public: //! implicit conversion from matrix_iterator matrix_row_major_iterator(const matrix_iterator_type& matrix_iterator) // NOLINT : matrix_iterator_type(matrix_iterator) { } // Has to be not empty, else behavior is undefined. matrix_row_major_iterator& operator ++ () { if (get_col() + 1 < m->get_width()) // => not matrix_row_major_iterator the end of row, move right set_col(get_col() + 1); else if (get_row() + 1 < m->get_height()) // => at end of row but not last row, move to beginning of next row set_pos(get_row() + 1, 0); else // => at end of matrix, set to empty-state set_empty(); return *this; } // Has to be not empty, else behavior is undefined. matrix_row_major_iterator& operator -- () { if (get_col() - 1 >= 0) // => not at the beginning of row, move left set_col(get_col() - 1); else if (get_row() - 1 >= 0) // => at beginning of row but not first row, move to end of previous row set_pos(get_row() - 1, m->get_width() - 1); else // => at beginning of matrix, set to empty-state set_empty(); return *this; } using matrix_iterator_type::get_row; using matrix_iterator_type::get_col; using matrix_iterator_type::set_col; using matrix_iterator_type::set_pos; }; //! column-major iterator that points to single elements inside a matrix //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block template <typename ValueType, unsigned BlockSideLength> class matrix_col_major_iterator : public matrix_iterator<ValueType, BlockSideLength> { protected: using matrix_iterator_type = matrix_iterator<ValueType, BlockSideLength>; using matrix_type = typename matrix_iterator_type::matrix_type; using elem_size_type = typename matrix_iterator_type::elem_size_type; template <typename VT, unsigned BSL> friend class matrix; using matrix_iterator_type::m; using matrix_iterator_type::set_empty; //! create iterator pointing to given row and col matrix_col_major_iterator(matrix_type& matrix, const elem_size_type start_row, const elem_size_type start_col) : matrix_iterator_type(matrix, start_row, start_col) { } //! create empty iterator explicit matrix_col_major_iterator(matrix_type& matrix) : matrix_iterator_type(matrix) { } public: //! implicit conversion from matrix_iterator matrix_col_major_iterator(const matrix_iterator_type& matrix_iterator) // NOLINT : matrix_iterator_type(matrix_iterator) { } // Has to be not empty, else behavior is undefined. matrix_col_major_iterator& operator ++ () { if (get_row() + 1 < m->get_height()) // => not at the end of col, move down set_row(get_row() + 1); else if (get_col() + 1 < m->get_width()) // => at end of col but not last col, move to beginning of next col set_pos(0, get_col() + 1); else // => at end of matrix, set to empty-state set_empty(); return *this; } // Has to be not empty, else behavior is undefined. matrix_col_major_iterator& operator -- () { if (get_row() - 1 >= 0) // => not at the beginning of col, move up set_row(get_row() - 1); else if (get_col() - 1 >= 0) // => at beginning of col but not first col, move to end of previous col set_pos(m->get_height() - 1, get_col() - 1); else // => at beginning of matrix, set to empty-state set_empty(); return *this; } using matrix_iterator_type::get_row; using matrix_iterator_type::get_col; using matrix_iterator_type::set_row; using matrix_iterator_type::set_pos; }; //! general const_iterator type that points to single elements inside a matrix //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block template <typename ValueType, unsigned BlockSideLength> class const_matrix_iterator { protected: using matrix_type = matrix<ValueType, BlockSideLength>; using swappable_block_matrix_type = typename matrix_type::swappable_block_matrix_type; using block_scheduler_type = typename matrix_type::block_scheduler_type; using internal_block_type = typename block_scheduler_type::internal_block_type; using elem_size_type = typename matrix_type::elem_size_type; using block_size_type = typename matrix_type::block_size_type; template <typename VT, unsigned BSL> friend class matrix; const matrix_type* m; elem_size_type current_row, // \ both indices == -1 <=> empty iterator current_col; // / block_size_type current_block_row, current_block_col; internal_block_type* current_iblock; // nullptr if block is not acquired void acquire_current_iblock() { if (! current_iblock) current_iblock = &m->data->bs.acquire(m->data->block(current_block_row, current_block_col)); } void release_current_iblock() { if (current_iblock) { m->data->bs.release(m->data->block(current_block_row, current_block_col), false); current_iblock = 0; } } //! create iterator pointing to given row and col const_matrix_iterator(const matrix_type& matrix, const elem_size_type start_row, const elem_size_type start_col) : m(&matrix), current_row(start_row), current_col(start_col), current_block_row(m->data->block_index_from_elem(start_row)), current_block_col(m->data->block_index_from_elem(start_col)), current_iblock(0) { } //! create empty iterator explicit const_matrix_iterator(const matrix_type& matrix) : m(&matrix), current_row(-1), // empty iterator current_col(-1), current_block_row(-1), current_block_col(-1), current_iblock(0) { } void set_empty() { release_current_iblock(); current_row = -1; current_col = -1; current_block_row = -1; current_block_col = -1; } public: explicit const_matrix_iterator(const matrix_iterator<ValueType, BlockSideLength>& other) : m(other.m), current_row(other.current_row), current_col(other.current_col), current_block_row(other.current_block_row), current_block_col(other.current_block_col), current_iblock(0) { if (other.current_iblock) acquire_current_iblock(); } const_matrix_iterator(const const_matrix_iterator& other) : m(other.m), current_row(other.current_row), current_col(other.current_col), current_block_row(other.current_block_row), current_block_col(other.current_block_col), current_iblock(0) { if (other.current_iblock) acquire_current_iblock(); } const_matrix_iterator& operator = (const const_matrix_iterator& other) { set_pos(other.current_row, other.current_col); m = other.m; if (other.current_iblock) acquire_current_iblock(); return *this; } ~const_matrix_iterator() { release_current_iblock(); } void set_row(const elem_size_type new_row) { const block_size_type new_block_row = m->data->block_index_from_elem(new_row); if (new_block_row != current_block_row) { release_current_iblock(); current_block_row = new_block_row; } current_row = new_row; } void set_col(const elem_size_type new_col) { const block_size_type new_block_col = m->data->block_index_from_elem(new_col); if (new_block_col != current_block_col) { release_current_iblock(); current_block_col = new_block_col; } current_col = new_col; } void set_pos(const elem_size_type new_row, const elem_size_type new_col) { const block_size_type new_block_row = m->data->block_index_from_elem(new_row), new_block_col = m->data->block_index_from_elem(new_col); if (new_block_col != current_block_col || new_block_row != current_block_row) { release_current_iblock(); current_block_row = new_block_row; current_block_col = new_block_col; } current_row = new_row; current_col = new_col; } void set_pos(const std::pair<elem_size_type, elem_size_type> new_pos) { set_pos(new_pos.first, new_pos.second); } const elem_size_type & get_row() const { return current_row; } const elem_size_type & get_col() const { return current_col; } std::pair<elem_size_type, elem_size_type> get_pos() const { return std::make_pair(current_row, current_col); } bool empty() const { return current_row == static_cast<elem_size_type>(-1) && current_col == static_cast<elem_size_type>(-1); } operator bool () const { return ! empty(); } bool operator == (const const_matrix_iterator& other) const { return current_row == other.current_row && current_col == other.current_col && m == other.m; } //! Returns reference access to the element referenced by the iterator. //! The reference is only valid so long as the iterator is not moved. const ValueType& operator * () { acquire_current_iblock(); return (*current_iblock)[m->data->elem_index_in_block_from_elem(current_row, current_col)]; } }; //! row-major const_iterator that points to single elements inside a matrix //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block template <typename ValueType, unsigned BlockSideLength> class const_matrix_row_major_iterator : public const_matrix_iterator<ValueType, BlockSideLength> { protected: using const_matrix_iterator_type = const_matrix_iterator<ValueType, BlockSideLength>; using matrix_type = typename const_matrix_iterator_type::matrix_type; using elem_size_type = typename const_matrix_iterator_type::elem_size_type; template <typename VT, unsigned BSL> friend class matrix; using const_matrix_iterator_type::m; using const_matrix_iterator_type::set_empty; //! create iterator pointing to given row and col const_matrix_row_major_iterator(const matrix_type& matrix, const elem_size_type start_row, const elem_size_type start_col) : const_matrix_iterator_type(matrix, start_row, start_col) { } //! create empty iterator explicit const_matrix_row_major_iterator(const matrix_type& matrix) : const_matrix_iterator_type(matrix) { } public: //! convert from matrix_iterator const_matrix_row_major_iterator(const const_matrix_row_major_iterator& matrix_iterator) : const_matrix_iterator_type(matrix_iterator) { } //! implicit conversion from matrix_iterator const_matrix_row_major_iterator(const const_matrix_iterator_type& matrix_iterator) // NOLINT : const_matrix_iterator_type(matrix_iterator) { } // Has to be not empty, else behavior is undefined. const_matrix_row_major_iterator& operator ++ () { if (get_col() + 1 < m->get_width()) // => not matrix_row_major_iterator the end of row, move right set_col(get_col() + 1); else if (get_row() + 1 < m->get_height()) // => at end of row but not last row, move to beginning of next row set_pos(get_row() + 1, 0); else // => at end of matrix, set to empty-state set_empty(); return *this; } // Has to be not empty, else behavior is undefined. const_matrix_row_major_iterator& operator -- () { if (get_col() - 1 >= 0) // => not at the beginning of row, move left set_col(get_col() - 1); else if (get_row() - 1 >= 0) // => at beginning of row but not first row, move to end of previous row set_pos(get_row() - 1, m->get_width() - 1); else // => at beginning of matrix, set to empty-state set_empty(); return *this; } using const_matrix_iterator_type::get_row; using const_matrix_iterator_type::get_col; using const_matrix_iterator_type::set_col; using const_matrix_iterator_type::set_pos; }; //! column-major const_iterator that points to single elements inside a matrix //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block template <typename ValueType, unsigned BlockSideLength> class const_matrix_col_major_iterator : public const_matrix_iterator<ValueType, BlockSideLength> { protected: using const_matrix_iterator_type = const_matrix_iterator<ValueType, BlockSideLength>; using matrix_type = typename const_matrix_iterator_type::matrix_type; using elem_size_type = typename const_matrix_iterator_type::elem_size_type; template <typename VT, unsigned BSL> friend class matrix; using const_matrix_iterator_type::m; using const_matrix_iterator_type::set_empty; //! create iterator pointing to given row and col const_matrix_col_major_iterator(const matrix_type& matrix, const elem_size_type start_row, const elem_size_type start_col) : const_matrix_iterator_type(matrix, start_row, start_col) { } //! create empty iterator explicit const_matrix_col_major_iterator(const matrix_type& matrix) : const_matrix_iterator_type(matrix) { } public: //! implicit conversion from matrix_iterator const_matrix_col_major_iterator( // NOLINT const matrix_iterator<ValueType, BlockSideLength>& matrix_iterator) // NOLINT : const_matrix_iterator_type(matrix_iterator) { } //! implicit conversion from matrix_iterator const_matrix_col_major_iterator( // NOLINT const const_matrix_iterator_type& matrix_iterator) // NOLINT : const_matrix_iterator_type(matrix_iterator) { } // Has to be not empty, else behavior is undefined. const_matrix_col_major_iterator& operator ++ () { if (get_row() + 1 < m->get_height()) // => not at the end of col, move down set_row(get_row() + 1); else if (get_col() + 1 < m->get_width()) // => at end of col but not last col, move to beginning of next col set_pos(0, get_col() + 1); else // => at end of matrix, set to empty-state set_empty(); return *this; } // Has to be not empty, else behavior is undefined. const_matrix_col_major_iterator& operator -- () { if (get_row() - 1 >= 0) // => not at the beginning of col, move up set_row(get_row() - 1); else if (get_col() - 1 >= 0) // => at beginning of col but not first col, move to end of previous col set_pos(m->get_height() - 1, get_col() - 1); else // => at beginning of matrix, set to empty-state set_empty(); return *this; } using const_matrix_iterator_type::get_row; using const_matrix_iterator_type::get_col; using const_matrix_iterator_type::set_row; using const_matrix_iterator_type::set_pos; }; //! External matrix container. \n //! <b> Introduction </b> to matrix container: see \ref tutorial_matrix tutorial. \n //! <b> Design and Internals </b> of matrix container: see \ref design_matrix. //! //! \tparam ValueType type of contained objects (POD with no references to internal memory) //! \tparam BlockSideLength side length of a matrix block //! //! Divides the matrix in square submatrices (blocks). //! Blocks can be swapped individually to and from external memory. //! They are only swapped if necessary to minimize I/O. template <typename ValueType, unsigned BlockSideLength> class matrix { protected: using matrix_type = matrix<ValueType, BlockSideLength>; using swappable_block_matrix_type = swappable_block_matrix<ValueType, BlockSideLength>; using swappable_block_matrix_pointer_type = tlx::counting_ptr<swappable_block_matrix_type>; using block_scheduler_type = typename swappable_block_matrix_type::block_scheduler_type; using block_size_type = typename swappable_block_matrix_type::size_type; using elem_size_type = typename swappable_block_matrix_type::elem_size_type; using Ops = matrix_local::matrix_operations<ValueType, BlockSideLength>; using swappable_block_type = matrix_swappable_block<ValueType, BlockSideLength>; public: using iterator = matrix_iterator<ValueType, BlockSideLength>; using const_iterator = const_matrix_iterator<ValueType, BlockSideLength>; using row_major_iterator = matrix_row_major_iterator<ValueType, BlockSideLength>; using col_major_iterator = matrix_col_major_iterator<ValueType, BlockSideLength>; using const_row_major_iterator = const_matrix_row_major_iterator<ValueType, BlockSideLength>; using const_col_major_iterator = const_matrix_col_major_iterator<ValueType, BlockSideLength>; using column_vector_type = column_vector<ValueType>; using row_vector_type = row_vector<ValueType>; protected: template <typename VT, unsigned BSL> friend class matrix_iterator; template <typename VT, unsigned BSL> friend class const_matrix_iterator; elem_size_type height, width; swappable_block_matrix_pointer_type data; public: //! \name Constructors/Destructors //! \{ //! Creates a new matrix of given dimensions. Elements' values are set to zero. //! \param bs block scheduler used //! \param height height of the created matrix //! \param width width of the created matrix matrix(block_scheduler_type& bs, const elem_size_type height, const elem_size_type width) : height(height), width(width), data( new swappable_block_matrix_type( bs, foxxll::div_ceil(height, BlockSideLength), foxxll::div_ceil(width, BlockSideLength)) ) { } matrix(block_scheduler_type& bs, const column_vector_type& left, const row_vector_type& right) : height(static_cast<elem_size_type>(left.size())), width(static_cast<elem_size_type>(right.size())), data( new swappable_block_matrix_type( bs, foxxll::div_ceil(height, BlockSideLength), foxxll::div_ceil(width, BlockSideLength)) ) { Ops::recursive_matrix_from_vectors(*data, left, right); } ~matrix() { } //! \} //! \name Capacity //! \{ const elem_size_type & get_height() const { return height; } const elem_size_type & get_width() const { return width; } //! \} //! \name Iterators //! \{ iterator begin() { data.unify(); return iterator(*this, 0, 0); } const_iterator begin() const { return const_iterator(*this, 0, 0); } const_iterator cbegin() const { return const_iterator(*this, 0, 0); } iterator end() { data.unify(); return iterator(*this); } const_iterator end() const { return const_iterator(*this); } const_iterator cend() const { return const_iterator(*this); } const_iterator operator () (const elem_size_type row, const elem_size_type col) const { return const_iterator(*this, row, col); } iterator operator () (const elem_size_type row, const elem_size_type col) { data.unify(); return iterator(*this, row, col); } //! \} //! \name Modifiers //! \{ void transpose() { data.unify(); data->transpose(); std::swap(height, width); } void set_zero() { if (data.unique()) data->set_zero(); else data = tlx::make_counting<swappable_block_matrix_type>( data->bs, foxxll::div_ceil(height, BlockSideLength), foxxll::div_ceil(width, BlockSideLength)); } //! \} //! \name Operations //! \{ matrix_type operator + (const matrix_type& right) const { assert(height == right.height && width == right.width); matrix_type res(data->bs, height, width); Ops::element_op(*res.data, *data, *right.data, typename Ops::addition()); // more efficient than copying this and then adding right return res; } matrix_type operator - (const matrix_type& right) const { assert(height == right.height && width == right.width); matrix_type res(data->bs, height, width); Ops::element_op(*res.data, *data, *right.data, typename Ops::subtraction()); // more efficient than copying this and then subtracting right return res; } matrix_type operator * (const matrix_type& right) const { return multiply(right); } matrix_type operator * (const ValueType scalar) const { matrix_type res(data->bs, height, width); Ops::element_op(*res.data, *data, typename Ops::scalar_multiplication(scalar)); return res; } matrix_type& operator += (const matrix_type& right) { assert(height == right.height && width == right.width); data.unify(); Ops::element_op(*data, *right.data, typename Ops::addition()); return *this; } matrix_type& operator -= (const matrix_type& right) { assert(height == right.height && width == right.width); data.unify(); Ops::element_op(*data, *right.data, typename Ops::subtraction()); return *this; } matrix_type& operator *= (const matrix_type& right) { return *this = operator * (right); } // implicitly unifies by constructing a result-matrix matrix_type& operator *= (const ValueType scalar) { data.unify(); Ops::element_op(*data, typename Ops::scalar_multiplication(scalar)); return *this; } column_vector_type operator * (const column_vector_type& right) const { assert(elem_size_type(right.size()) == width); column_vector_type res(height); res.set_zero(); Ops::recursive_matrix_col_vector_multiply_and_add(*data, right, res); return res; } row_vector_type multiply_from_left(const row_vector_type& left) const { assert(elem_size_type(left.size()) == height); row_vector_type res(width); res.set_zero(); Ops::recursive_matrix_row_vector_multiply_and_add(left, *data, res); return res; } //! multiply with another matrix //! \param right matrix to multiply with //! \param multiplication_algorithm allows to choose the applied algorithm //! \param scheduling_algorithm allows to choose the applied algorithm //! //! Available algorithms are: \n //! 0: naive_multiply_and_add (I/O inefficient, slow) \n //! 1: recursive_multiply_and_add (recommended, default, stable time and I/O complexity) \n //! 2: strassen_winograd_multiply_and_add (sometimes fast but unstable time and I/O complexity) \n //! 3: multi_level_strassen_winograd_multiply_and_add (sometimes fast but unstable time and I/O complexity) \n //! 4: strassen_winograd_multiply, optimized pre- and postadditions (sometimes fast but unstable time and I/O complexity) \n //! 5: strassen_winograd_multiply_and_add_interleaved, optimized preadditions (sometimes fast but unstable time and I/O complexity) \n //! 6: multi_level_strassen_winograd_multiply_and_add_block_grained (sometimes fast but unstable time and I/O complexity) matrix_type multiply(const matrix_type& right, const int multiplication_algorithm = 1, const int scheduling_algorithm = 2) const { assert(width == right.height); assert(&data->bs == &right.data->bs); matrix_type res(data->bs, height, right.width); if (scheduling_algorithm > 0) { // all offline algos need a simulation-run delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_simulation<swappable_block_type>(data->bs)); switch (multiplication_algorithm) { case 0: Ops::naive_multiply_and_add(*data, *right.data, *res.data); break; case 1: Ops::recursive_multiply_and_add(*data, *right.data, *res.data); break; case 2: Ops::strassen_winograd_multiply_and_add(*data, *right.data, *res.data); break; case 3: Ops::multi_level_strassen_winograd_multiply_and_add(*data, *right.data, *res.data); break; case 4: Ops::strassen_winograd_multiply(*data, *right.data, *res.data); break; case 5: Ops::strassen_winograd_multiply_and_add_interleaved(*data, *right.data, *res.data); break; case 6: Ops::multi_level_strassen_winograd_multiply_and_add_block_grained(*data, *right.data, *res.data); break; default: TLX_LOG1 << "invalid multiplication-algorithm number"; break; } } switch (scheduling_algorithm) { case 0: delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_online_lru<swappable_block_type>(data->bs)); break; case 1: delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_offline_lfd<swappable_block_type>(data->bs)); break; case 2: delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_offline_lru_prefetching<swappable_block_type>(data->bs)); break; default: TLX_LOG1 << "invalid scheduling-algorithm number"; } switch (multiplication_algorithm) { case 0: Ops::naive_multiply_and_add(*data, *right.data, *res.data); break; case 1: Ops::recursive_multiply_and_add(*data, *right.data, *res.data); break; case 2: Ops::strassen_winograd_multiply_and_add(*data, *right.data, *res.data); break; case 3: Ops::multi_level_strassen_winograd_multiply_and_add(*data, *right.data, *res.data); break; case 4: Ops::strassen_winograd_multiply(*data, *right.data, *res.data); break; case 5: Ops::strassen_winograd_multiply_and_add_interleaved(*data, *right.data, *res.data); break; case 6: Ops::multi_level_strassen_winograd_multiply_and_add_block_grained(*data, *right.data, *res.data); break; default: TLX_LOG1 << "invalid multiplication-algorithm number"; break; } delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_online_lru<swappable_block_type>(data->bs)); return res; } //! Use internal memory multiplication. Designated for testing. May exceed memory limitations. matrix_type multiply_internal(const matrix_type& right, const int scheduling_algorithm = 2) const { assert(width == right.height); assert(&data->bs == &right.data->bs); matrix_type res(data->bs, height, right.width); if (scheduling_algorithm > 0) { // all offline algos need a simulation-run delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_simulation<swappable_block_type>(data->bs)); multiply_internal(right, res); } switch (scheduling_algorithm) { case 0: delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_online_lru<swappable_block_type>(data->bs)); break; case 1: delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_offline_lfd<swappable_block_type>(data->bs)); break; case 2: delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_offline_lru_prefetching<swappable_block_type>(data->bs)); break; default: TLX_LOG1 << "invalid scheduling-algorithm number"; } multiply_internal(right, res); delete data->bs.switch_algorithm_to( new foxxll::block_scheduler_algorithm_online_lru<swappable_block_type>(data->bs)); return res; } //! \} protected: void multiply_internal(const matrix_type& right, matrix_type& res) const { ValueType* A = new ValueType[height * width]; ValueType* B = new ValueType[right.height * right.width]; ValueType* C = new ValueType[res.height * res.width]; ValueType* vit; vit = A; for (const_row_major_iterator mit = cbegin(); mit != cend(); ++mit, ++vit) *vit = *mit; vit = B; for (const_row_major_iterator mit = right.cbegin(); mit != right.cend(); ++mit, ++vit) *vit = *mit; if (! res.data->bs.is_simulating()) { #if STXXL_BLAS gemm_wrapper(height, width, res.width, ValueType(1), false, A, false, B, ValueType(0), false, C); #else assert(false /* internal multiplication is only available for testing with blas */); #endif } vit = C; for (row_major_iterator mit = res.begin(); mit != res.end(); ++mit, ++vit) *mit = *vit; delete[] A; delete[] B; delete[] C; } }; //! \} } // namespace stxxl #endif // !STXXL_CONTAINERS_MATRIX_HEADER
Parallel.c
#include <omp.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> void printAll(int32_t* a, int32_t* b, int n); int main(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "arg missing! ./Parallel n t\n"); return EXIT_FAILURE; } int n = atoi(argv[1]); int t = atoi(argv[2]); printf("%d\n", n); int32_t* a = malloc(sizeof(int32_t) * n); int32_t* b = malloc(sizeof(int32_t) * n); b[0] = 0; for (int i = 0; i < n; i++) a[i] = i; printf("using %ld MB\n", (sizeof(int32_t) * n * 2) / 1000000); printAll(a, b, n); int last[255]; // last element of split array int connector[255] = {0}; // connects splited arrays printf("Threads %d\n ", t); #pragma omp parallel num_threads(t) { int t_nums = omp_get_num_threads(); int t_id = omp_get_thread_num(); int ops = n / t_nums; // nums steps per thread int offset = ops * t_id; for (int i = offset; i < offset + ops; i++) { if ((i % ops) != 0) // skip first element in array b[i] = b[i - 1] + a[i - 1]; } last[t_id] = b[offset + ops - 1] + a[offset + ops - 1]; // sum up last for connect #pragma omp barrier for (int i = 0; i < t_id; i++) { //compute own connector // p time connector[t_id] += last[i]; } #pragma omp barrier for (int i = offset; i < offset + ops; i++) b[i] += connector[t_id]; } printAll(a, b, n); free(b); free(a); } void printAll(int32_t* a, int32_t* b, int n) { if (n > 200) { puts("skipping print"); printf("LAST VALUE:%d\n", b[n - 1]); return; } puts(""); printf("b:"); for (int i = 0; i < n; i++) printf(" %d", b[i]); puts(""); printf("a:"); for (int i = 0; i < n; i++) printf(" %d", a[i]); puts(""); }
onesided.c
/* Copyright (C) 2011 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #include "common.h" #include "onesided.h" #include <mpi.h> #include <assert.h> #include <stdlib.h> #include <string.h> /* One-sided wrapper to allow emulation; a good MPI should be able to handle * the version in this file. */ #ifndef EMULATE_ONE_SIDED /* Gather from one array into another. */ struct gather { void* input; size_t elt_size; void* output; MPI_Datatype datatype; int valid; MPI_Win win; }; gather* init_gather(void* input, size_t input_count, size_t elt_size, void* output, size_t output_count, size_t nrequests_max, MPI_Datatype dt) { gather* g = (gather*)xmalloc(sizeof(gather)); g->input = input; g->elt_size = elt_size; g->output = output; g->datatype = dt; g->valid = 0; MPI_Win_create(input, input_count * elt_size, elt_size, MPI_INFO_NULL, MPI_COMM_WORLD, &g->win); return g; } void destroy_gather(gather* g) { assert (!g->valid); MPI_Win_free(&g->win); free(g); } void begin_gather(gather* g) { assert (!g->valid); g->valid = 1; MPI_Win_fence(MPI_MODE_NOPRECEDE | MPI_MODE_NOPUT, g->win); } void add_gather_request(gather* g, size_t local_idx, int remote_rank, size_t remote_idx, size_t req_id) { assert (g->valid); #pragma omp critical MPI_Get(g->output + local_idx * g->elt_size, 1, g->datatype, remote_rank, remote_idx, 1, g->datatype, g->win); } void end_gather(gather* g) { assert (g->valid); MPI_Win_fence(MPI_MODE_NOSUCCEED, g->win); g->valid = 0; } /* Scatter a constant to various locations in an array. */ struct scatter_constant { void* array; size_t elt_size; void* constant; MPI_Datatype datatype; int valid; MPI_Win win; }; scatter_constant* init_scatter_constant(void* array, size_t array_count, size_t elt_size, void* constant, size_t nrequests_max, MPI_Datatype dt) { scatter_constant* sc = (scatter_constant*)xmalloc(sizeof(scatter_constant)); sc->array = array; sc->elt_size = elt_size; sc->constant = constant; sc->datatype = dt; sc->valid = 0; MPI_Win_create(array, array_count * elt_size, elt_size, MPI_INFO_NULL, MPI_COMM_WORLD, &sc->win); return sc; } void destroy_scatter_constant(scatter_constant* sc) { assert (!sc->valid); MPI_Win_free(&sc->win); free(sc); } void begin_scatter_constant(scatter_constant* sc) { assert (!sc->valid); sc->valid = 1; MPI_Win_fence(MPI_MODE_NOPRECEDE, sc->win); } void add_scatter_constant_request(scatter_constant* sc, int remote_rank, size_t remote_idx, size_t req_id) { assert (sc->valid); #pragma omp critical MPI_Put(sc->constant, 1, sc->datatype, remote_rank, remote_idx, 1, sc->datatype, sc->win); } void end_scatter_constant(scatter_constant* sc) { assert (sc->valid); MPI_Win_fence(MPI_MODE_NOSUCCEED | MPI_MODE_NOSTORE, sc->win); sc->valid = 0; } /* Scatter values to various locations in an array using MPI_REPLACE. */ struct scatter { void* array; size_t elt_size; size_t request_count; size_t nrequests_max; char* send_data; MPI_Datatype datatype; int valid; MPI_Win win; }; scatter* init_scatter(void* array, size_t array_count, size_t elt_size, size_t nrequests_max, MPI_Datatype dt) { scatter* sc = (scatter*)xmalloc(sizeof(scatter)); sc->array = array; sc->elt_size = elt_size; sc->request_count = 0; sc->nrequests_max = nrequests_max; sc->send_data = (char *)xmalloc(nrequests_max * elt_size); sc->datatype = dt; sc->valid = 0; MPI_Win_create(array, array_count * elt_size, elt_size, MPI_INFO_NULL, MPI_COMM_WORLD, &sc->win); return sc; } void destroy_scatter(scatter* sc) { assert (!sc->valid); MPI_Win_free(&sc->win); free(sc->send_data); free(sc); } void begin_scatter(scatter* sc) { assert (!sc->valid); sc->valid = 1; sc->request_count = 0; MPI_Win_fence(MPI_MODE_NOPRECEDE, sc->win); } void add_scatter_request(scatter* sc, const char* local_data, int remote_rank, size_t remote_idx, size_t req_id) { assert (sc->valid); assert (sc->request_count < sc->nrequests_max); memcpy(sc->send_data + sc->request_count * sc->elt_size, local_data, sc->elt_size); #pragma omp critical MPI_Put(sc->send_data + sc->request_count * sc->elt_size, 1, sc->datatype, remote_rank, remote_idx, 1, sc->datatype, sc->win); ++sc->request_count; } void end_scatter(scatter* sc) { assert (sc->valid); MPI_Win_fence(MPI_MODE_NOSUCCEED | MPI_MODE_NOSTORE, sc->win); sc->valid = 0; } #endif /* !EMULATE_ONE_SIDED */
zgeswp.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" /******************************************************************************/ int plasma_zgeswp(plasma_enum_t colrow, int m, int n, plasma_complex64_t *pA, int lda, int *ipiv, int incx) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((colrow != PlasmaColumnwise) && (colrow != PlasmaRowwise)) { plasma_error("illegal value of colrow"); return -1; } if (m < 0) { plasma_error("illegal value of m"); return -2; } if (n < 0) { plasma_error("illegal value of n"); return -3; } if (lda < imax(1, m)) { plasma_error("illegal value of lda"); return -5; } // quick return if (imin(n, m) == 0) return PlasmaSuccess; // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_general_desc_create() failed"); return retval; } // Create sequence. plasma_sequence_t *sequence = NULL; retval = plasma_sequence_create(&sequence); if (retval != PlasmaSuccess) { plasma_error("plasma_sequence_create() failed"); return retval; } // Initialize request. plasma_request_t request = PlasmaRequestInitializer; // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, sequence, &request); // Call tile async function. #pragma omp taskwait plasma_omp_zgeswp(colrow, A, ipiv, incx, sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(A, pA, lda, sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); // Return status. int status = sequence->status; plasma_sequence_destroy(sequence); return status; } /******************************************************************************/ void plasma_omp_zgeswp(plasma_enum_t colrow, plasma_desc_t A, int *ipiv, int incx, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((colrow != PlasmaColumnwise) && (colrow != PlasmaRowwise)) { plasma_error("illegal value of colrow"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (imin(A.m, A.n) == 0) return; // Call the parallel function. plasma_pzgeswp(colrow, A, ipiv, incx, sequence, request); }
test.c
#include <stdio.h> #pragma omp requires unified_shared_memory #include "../utilities/check.h" #define N 100 int test_aligned(){ int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; int *b = a; // offload #pragma omp target map(tofrom: b[0:100]) { #pragma omp teams #pragma omp distribute simd aligned(b: 8*sizeof(int)) for(int k=0; k<N; k++) b[k] = k; } // host for(i=0; i<N; i++) aa[i] = i; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return error; } } return error; } int test_collapsed(){ int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; // offload #pragma omp target map(tofrom: a[0:100]) { #pragma omp teams #pragma omp distribute simd collapse(2) for(int k=0; k<N/4; k++) for(int l=0; l<4; l++) a[k*4+l] = k*4+l; } // host for(i=0; i<N; i++) aa[i] = i; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return error; } } return error; } int test_lastprivate(){ int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; // offload int n; #pragma omp target map(tofrom: a[0:100]) private(n) { #pragma omp teams num_teams(1) { #pragma omp distribute simd lastprivate(n) for(int k=0; k<N; k++) { a[k] = k; n = k; } a[0] = n; } } // host for(i=0; i<N; i++) aa[i] = i; aa[0] = N-1; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return error; } } return error; } int test_linear(){ int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; int l = 0; // offload #pragma omp target map(tofrom: a[0:100]) { #pragma omp teams num_teams(1) #pragma omp distribute simd for(int k=0; k<N; k++) { l = 2*k; a[k] = l; } } // host for(i=0; i<N; i++) aa[i] = 2*i; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return error;; } } return error; } int test_private(){ int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; int n; // offload #pragma omp target map(tofrom: a[0:100]) { #pragma omp teams #pragma omp distribute simd private(n) for(int k=0; k<N; k++) { n = k; a[k] = n; } } // host for(i=0; i<N; i++) aa[i] = i; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return error; } } return error; } int test_safelen(){ int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; // offload #pragma omp target map(tofrom: a[0:100]) { #pragma omp teams num_teams(1) #pragma omp distribute simd safelen(2) for(int k=0; k<100; k++) { if (k > 1){ a[k] = a[k-2] + 2; } else{ a[k] = k; } } } // host for(i=0; i<N; i++) aa[i] = i; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return error; } } return error; } int main() { int error = 0; check_offloading(); // Clauses error += test_aligned(); error += test_collapsed(); error += test_lastprivate(); error += test_linear(); error += test_private(); error += test_safelen(); // report printf("done with %d errors\n", error); return error; }
nn_openmp.ref.c
#include <sys/time.h> #include <time.h> #include <stdio.h> static unsigned long long current_time_ns() { #ifdef __MACH__ clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); unsigned long long s = 1000000000ULL * (unsigned long long)mts.tv_sec; return (unsigned long long)mts.tv_nsec + s; #else struct timespec t ={0,0}; clock_gettime(CLOCK_MONOTONIC, &t); unsigned long long s = 1000000000ULL * (unsigned long long)t.tv_sec; return (((unsigned long long)t.tv_nsec)) + s; #endif } #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <sys/time.h> #include <omp.h> #include <assert.h> #include <time.h> #define MAX_ARGS 10 #define REC_LENGTH 49 // size of a record in db #define REC_WINDOW 10 // number of records to read at a time #define LATITUDE_POS 28 // location of latitude coordinates in input record #define OPEN 10000 // initial value of nearest neighbors struct neighbor { char entry[REC_LENGTH]; double dist; }; /** * This program finds the k-nearest neighbors * Usage: ./nn <filelist> <num> <target latitude> <target longitude> * filelist: File with the filenames to the records * num: Number of nearest neighbors to find * target lat: Latitude coordinate for distance calculations * target long: Longitude coordinate for distance calculations * The filelist and data are generated by hurricane_gen.c * REC_WINDOW has been arbitrarily assigned; A larger value would allow more work for the threads */ int main(int argc, char* argv[]) { long long time0 = clock(); FILE *flist,*fp; int i=0,j=0, k=0, rec_count=0, done=0; char sandbox[REC_LENGTH * REC_WINDOW], *rec_iter,*rec_iter2, dbname[64]; struct neighbor *neighbors = NULL; float target_lat, target_long, tmp_lat=0, tmp_long=0; char filename_buf[1024]; char *rodinia_data_dir = getenv("RODINIA_DATA_DIR"); assert(rodinia_data_dir); memcpy(filename_buf, rodinia_data_dir, strlen(rodinia_data_dir)); if(argc < 5) { fprintf(stderr, "Invalid set of arguments\n"); exit(-1); } flist = fopen(argv[1], "r"); if(!flist) { printf("error opening flist\n"); exit(1); } k = atoi(argv[2]); target_lat = atof(argv[3]); target_long = atof(argv[4]); neighbors = (struct neighbor *)malloc(k*sizeof(struct neighbor)); if(neighbors == NULL) { fprintf(stderr, "no room for neighbors\n"); exit(0); } for( j = 0 ; j < k ; j++ ) { //Initialize list of nearest neighbors to very large dist neighbors[j].dist = OPEN; } /**** main processing ****/ if(fscanf(flist, "%s\n", dbname) != 1) { fprintf(stderr, "error reading filelist\n"); exit(0); } memcpy(filename_buf + strlen(rodinia_data_dir), dbname, strlen(dbname) + 1); fp = fopen(filename_buf, "r"); if(!fp) { printf("error opening file %s\n", filename_buf); exit(1); } float *z; z = (float *) malloc(REC_WINDOW * sizeof(float)); const unsigned long long full_program_start = current_time_ns(); while(!done) { //Read in REC_WINDOW number of records rec_count = fread(sandbox, REC_LENGTH, REC_WINDOW, fp); if( rec_count != REC_WINDOW ) { if(!ferror(flist)) {// an eof occured fclose(fp); if(feof(flist)) done = 1; else { if(fscanf(flist, "%s\n", dbname) != 1) { fprintf(stderr, "error reading filelist\n"); exit(0); } memcpy(filename_buf + strlen(rodinia_data_dir), dbname, strlen(dbname) + 1); fp = fopen(filename_buf, "r"); if(!fp) { printf("error opening a db\n"); exit(1); } } } else { perror("Error"); exit(0); } } { const unsigned long long parallel_for_start = current_time_ns(); #pragma omp parallel for shared (z, target_lat, target_long) private(i,rec_iter) for (i = 0; i < rec_count; i++){ rec_iter = sandbox+(i * REC_LENGTH + LATITUDE_POS - 1); float tmp_lat = atof(rec_iter); float tmp_long = atof(rec_iter+5); z[i] = sqrt(( (tmp_lat-target_lat) * (tmp_lat-target_lat) )+( (tmp_long-target_long) * (tmp_long-target_long) )); } ; const unsigned long long parallel_for_end = current_time_ns(); printf("pragma117_omp_parallel %llu ns\n", parallel_for_end - parallel_for_start); } for( i = 0 ; i < rec_count ; i++ ) { float max_dist = -1; int max_idx = 0; // find a neighbor with greatest dist and take his spot if allowed! for( j = 0 ; j < k ; j++ ) { if( neighbors[j].dist > max_dist ) { max_dist = neighbors[j].dist; max_idx = j; } } // compare each record with max value to find the nearest neighbor if( z[i] < neighbors[max_idx].dist ) { sandbox[(i+1)*REC_LENGTH-1] = '\0'; strcpy(neighbors[max_idx].entry, sandbox +i*REC_LENGTH); neighbors[max_idx].dist = z[i]; } } } ; const unsigned long long full_program_end = current_time_ns(); printf("full_program %llu ns\n", full_program_end - full_program_start); //End while loop fprintf(stderr, "The %d nearest neighbors are:\n", k); for( j = 0 ; j < k ; j++ ) { if( !(neighbors[j].dist == OPEN) ) fprintf(stderr, "%s --> %f\n", neighbors[j].entry, neighbors[j].dist); } fclose(flist); long long time1 = clock(); printf("total time : %15.12f s\n", (float) (time1 - time0) / 1000000); return 0; }
taskyield.c
#include <omp.h> void something_useful ( void ); void something_critical ( void ); void foo ( omp_lock_t*lock, int n ) { int i; for ( i = 0; i < n; i++ ) { something_useful(); while ( !omp_test_lock(lock) ) { #pragma omp taskyield } something_critical(); omp_unset_lock(lock); } }
CombinedOtherStartIndexNNeighboursWorklet.h
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). // Copyright 2014 UT-Battelle, LLC. // Copyright 2014 Los Alamos National Security. // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National // Laboratory (LANL), the U.S. Government retains certain rights in // this software. //============================================================================ // Copyright (c) 2018, The Regents of the University of California, through // Lawrence Berkeley National Laboratory (subject to receipt of any required approvals // from the U.S. Dept. of Energy). All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // (3) Neither the name of the University of California, Lawrence Berkeley National // Laboratory, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // //============================================================================= // // This code is an extension of the algorithm presented in the paper: // Parallel Peak Pruning for Scalable SMP Contour Tree Computation. // Hamish Carr, Gunther Weber, Christopher Sewell, and James Ahrens. // Proceedings of the IEEE Symposium on Large Data Analysis and Visualization // (LDAV), October 2016, Baltimore, Maryland. // // The PPP2 algorithm and software were jointly developed by // Hamish Carr (University of Leeds), Gunther H. Weber (LBNL), and // Oliver Ruebel (LBNL) //============================================================================== #ifndef vtk_m_worklet_contourtree_augmented_contourtree_mesh_inc_combined_other_start_index_nneighbours_worklet_worklet_h #define vtk_m_worklet_contourtree_augmented_contourtree_mesh_inc_combined_other_start_index_nneighbours_worklet_worklet_h #include <vtkm/worklet/WorkletMapField.h> #include <vtkm/worklet/contourtree_augmented/Types.h> namespace vtkm { namespace worklet { namespace contourtree_augmented { namespace mesh_dem_contourtree_mesh_inc { class CombinedOtherStartIndexNNeighboursWorklet : public vtkm::worklet::WorkletMapField { public: typedef void ControlSignature( FieldIn nNeighbours, // (input) nNeighbours FieldIn otherToCombinedSortOrder, // (input) otherToCombinedSortOrder WholeArrayInOut combinedNNeighbours, // (input/output) combinedNNeighbours WholeArrayInOut combinedOtherStartIndex // (input/output) combinedOthertStartIndex ); typedef void ExecutionSignature(_1, _2, _3, _4); typedef _1 InputDomain; // Default Constructor VTKM_EXEC_CONT CombinedOtherStartIndexNNeighboursWorklet() {} template <typename InOutPortalType> VTKM_EXEC void operator()(const vtkm::Id& nneighboursVal, const vtkm::Id& otherToCombinedSortOrderVal, const InOutPortalType combinedNNeighboursPortal, const InOutPortalType combinedOtherStartIndexPortal) const { combinedOtherStartIndexPortal.Set(otherToCombinedSortOrderVal, combinedNNeighboursPortal.Get(otherToCombinedSortOrderVal)); combinedNNeighboursPortal.Set(otherToCombinedSortOrderVal, combinedNNeighboursPortal.Get(otherToCombinedSortOrderVal) + nneighboursVal); // Implements in reference code // #pragma omp parallel for // The following is save since each global index is only written by one entry // for (indexVector::size_type vtx = 0; vtx < nNeighbours.size(); ++vtx) // { // combinedOtherStartIndex[otherToCombinedSortOrder[vtx]] = combinedNNeighbours[otherToCombinedSortOrder[vtx]]; // combinedNNeighbours[otherToCombinedSortOrder[vtx]] += nNeighbours[vtx]; // } } }; // CombinedOtherStartIndexNNeighboursWorklet } // namespace mesh_dem_contourtree_mesh_inc } // namespace contourtree_augmented } // namespace worklet } // namespace vtkm #endif
taskloop.c
// RUN: %libomp-compile-and-run | FileCheck %s // RUN: %libomp-compile-and-run | FileCheck --check-prefix=TASKS %s // REQUIRES: ompt // These compilers don't support the taskloop construct // UNSUPPORTED: gcc-4, gcc-5, icc-16 // GCC 6 has support for taskloops, but at least 6.3.0 is crashing on this test // UNSUPPORTED: gcc-6 #include "callback.h" #include <omp.h> int main() { unsigned int i, x; #pragma omp parallel num_threads(2) { #pragma omp barrier #pragma omp master #pragma omp taskloop for (i = 0; i < 5; i += 3) { x++; } } // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin: // CHECK-SAME: parent_task_id={{[0-9]+}} // CHECK-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]] // CHECK-SAME: requested_team_size=2 // CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: // CHECK-SAME: parallel_id=[[PARALLEL_ID]] // CHECK-SAME: task_id=[[IMPLICIT_TASK_ID1:[0-9]+]] // CHECK-SAME: team_size=2, thread_num=0 // CHECK: {{^}}[[MASTER_ID]]: ompt_event_taskgroup_begin: // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID1]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_taskloop_begin: // CHECK-SAME: parallel_id=[[PARALLEL_ID]] // CHECK-SAME: parent_task_id=[[IMPLICIT_TASK_ID1]] // CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]], count=2 // CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_create: // CHECK-SAME: parent_task_id=[[IMPLICIT_TASK_ID1]] // CHECK-SAME: new_task_id=[[TASK_ID1:[0-9]+]] // CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS]] // CHECK-SAME: task_type=ompt_task_explicit=4 // CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_create: // CHECK-SAME: parent_task_id=[[IMPLICIT_TASK_ID1]] // CHECK-SAME: new_task_id=[[TASK_ID2:[0-9]+]] // CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS]] // CHECK-SAME: task_type=ompt_task_explicit=4 // CHECK-NOT: {{^}}[[MASTER_ID]]: ompt_event_task_create: // CHECK: {{^}}[[MASTER_ID]]: ompt_event_taskloop_end: // CHECK-SAME: parallel_id=[[PARALLEL_ID]] // CHECK-SAME: parent_task_id=[[IMPLICIT_TASK_ID1]] // CHECK-SAME: count=2 // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_wait_taskgroup_begin: // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_taskgroup_end: // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID1]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_taskgroup_end: // CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID1]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: parallel_id=0 // CHECK-SAME: task_id=[[IMPLICIT_TASK_ID1]], team_size=2, thread_num=0 // CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: // CHECK-SAME: parallel_id=[[PARALLEL_ID]] // TASKS: ompt_event_initial_task_begin:{{.*}} task_id={{[0-9]+}} // TASKS: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_taskloop_begin: // TASKS: ompt_event_task_create:{{.*}} new_task_id=[[TASK_ID1:[0-9]+]] // TASKS-SAME: task_type=ompt_task_explicit // TASKS-DAG: ompt_event_task_create:{{.*}} new_task_id=[[TASK_ID2:[0-9]+]] // Schedule events: // TASKS-DAG: {{^.*}}first_task_id={{[0-9]+}}, second_task_id=[[TASK_ID1]] // TASKS-DAG: {{^.*}}first_task_id=[[TASK_ID1]], second_task_id={{[0-9]+}} // TASKS-DAG: {{^.*}}first_task_id={{[0-9]+}}, second_task_id=[[TASK_ID2]] // TASKS-DAG: {{^.*}}first_task_id=[[TASK_ID2]], second_task_id={{[0-9]+}} // TASKS-NOT: ompt_event_task_schedule return 0; }
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> namespace mxnet { namespace common { template<typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /* * \brief setup default-storage tblobs from source NDArrays. If any source NDArray has non-default * storage, it creates a temp NDArray with default storage and uses the temp tblob. The * function also records the indices of non-default source NDArrays and the indices of * their corresponding temporary NDArrays in the temp array. * \param src list of source NDArray * \param blobs list of tblobs to return * \param temp_src list of source NDArrays which requires temporary default storage representation * \param temp_dst list of temporary destination NDArrays for default storage representation * \param idx_map mapping from indices in source NDArrays to indices in temp_dst. When not set, indices are not recorded * \return true if any source NDArray need to cast storage */ inline bool SetupDefaultBlobs(const std::vector<NDArray>& src, std::vector<TBlob> *blobs, std::vector<NDArray> *temp_src, std::vector<NDArray> *temp_dst, std::unordered_map<uint32_t, uint32_t> *idx_map = nullptr) { bool require_cast = false; for (size_t i = 0; i < src.size(); i++) { auto& nd = src[i]; if (nd.storage_type() != kDefaultStorage) { if (idx_map != nullptr) { (*idx_map)[i] = temp_dst->size(); } NDArray temp(nd.shape(), nd.ctx(), false, nd.dtype()); temp_src->emplace_back(nd); temp_dst->emplace_back(temp); blobs->emplace_back(temp.data()); require_cast = true; } else { blobs->push_back(nd.data()); } } return require_cast; } /* * \brief cast the NDArrays in `src` and store the result in NDArrays in `dst`. * This is only used for storage fallback in executor. * When storage_fallback is false, and `MXNET_EXEC_STORAGE_FALLBACK` == 0, * storage fallback is disallowed. * \param src list of source NDArray to cast * \param dst list of destionation NDArray which hold the result of cast_storage operation * \param ctx operator context for cast_storage operation * \param storage_fallback whether storage_fallback is allowed. When set to false, * its value depends on `MXNET_EXEC_STORAGE_FALLBACK`. */ template <typename xpu> inline void CastNonDefaultStorage(const std::vector<NDArray>& src, const std::vector<NDArray>& dst, const OpContext& ctx, bool storage_fallback = false) { CHECK_GE(dst.size(), src.size()); if (src.size() == 0) return; if (storage_fallback == false) { storage_fallback = dmlc::GetEnv("MXNET_EXEC_STORAGE_FALLBACK", true); } if (storage_fallback == false) { LOG(FATAL) << "Storage type conversion detected during execution. " << "You are probably executing an operator which " << "doesn't support NDArray inputs with non-default storage."; } for (size_t i = 0; i < src.size(); i++) { CastStorageDispatch<xpu>(ctx, src[i], dst[i]); } } // Check if any storage type is not default storage inline bool ContainsNonDefaultStorage(const StorageTypeVector& vstorage) { for (const auto& i : vstorage) { if (i != kUndefinedStorage && i != kDefaultStorage) return true; } return false; } // Check if any NDArray in the list has non default storage inline bool ContainsNonDefaultStorage(const std::vector<NDArray*>& ndarrays) { for (const auto &nd : ndarrays) { if (nd->storage_type() != kDefaultStorage) { return true; } } return false; } // Check if any NDArray in the list has default storage inline bool ContainsDefaultStorage(const std::vector<NDArray>& ndarrays) { for (const auto &nd : ndarrays) { if (nd.storage_type() == kDefaultStorage) { return true; } } return false; } inline bool ContainsNonDefaultStorage(const std::vector<NDArray>& ndarrays) { for (const auto &nd : ndarrays) { if (nd.storage_type() != kUndefinedStorage && nd.storage_type() != kDefaultStorage) { return true; } } return false; } inline bool ContainsStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { for (const auto &nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } return false; } inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto &nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } // heuristic to dermine number of threads per GPU inline int GetNumThreadPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadPerGPU()); } template<typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first+len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp); ParallelSortHelper(first+len/2, len - len/2, grainsize, comp); thr.join(); std::inplace_merge(first, first+len/2, first+len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort(first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template<typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask"; return nullptr; } } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
fx.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF X X % % F X X % % FFF X % % F X X % % F X X % % % % % % MagickCore Image Special Effects Methods % % % % Software Design % % John Cristy % % October 1996 % % % % % % Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/annotate.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/composite.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/fx.h" #include "magick/fx-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resize.h" #include "magick/shear.h" #include "magick/splay-tree.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/transform.h" #include "magick/utility.h" /* Define declarations. */ #define LeftShiftOperator 0xf5 #define RightShiftOperator 0xf6 #define LessThanEqualOperator 0xf7 #define GreaterThanEqualOperator 0xf8 #define EqualOperator 0xf9 #define NotEqualOperator 0xfa #define LogicalAndOperator 0xfb #define LogicalOrOperator 0xfc #define ExponentialNotation 0xfd struct _FxInfo { const Image *images; char *expression; FILE *file; SplayTreeInfo *colors, *symbols; CacheView **view; RandomInfo *random_info; ExceptionInfo *exception; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e F x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireFxInfo() allocates the FxInfo structure. % % The format of the AcquireFxInfo method is: % % FxInfo *AcquireFxInfo(Image *image,const char *expression) % % A description of each parameter follows: % % o image: the image. % % o expression: the expression. % */ MagickExport FxInfo *AcquireFxInfo(const Image *image,const char *expression) { char fx_op[2]; const Image *next; FxInfo *fx_info; register ssize_t i; fx_info=(FxInfo *) AcquireMagickMemory(sizeof(*fx_info)); if (fx_info == (FxInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(fx_info,0,sizeof(*fx_info)); fx_info->exception=AcquireExceptionInfo(); fx_info->images=image; fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishMagickMemory); fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishMagickMemory); fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength( fx_info->images),sizeof(*fx_info->view)); if (fx_info->view == (CacheView **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); i=0; next=GetFirstImageInList(fx_info->images); for ( ; next != (Image *) NULL; next=next->next) { fx_info->view[i]=AcquireCacheView(next); i++; } fx_info->random_info=AcquireRandomInfo(); fx_info->expression=ConstantString(expression); fx_info->file=stderr; (void) SubstituteString(&fx_info->expression," ",""); /* compact string */ /* Force right-to-left associativity for unary negation. */ (void) SubstituteString(&fx_info->expression,"-","-1.0*"); if ((strstr(fx_info->expression,"e+") != (char *) NULL) || (strstr(fx_info->expression,"e-") != (char *) NULL)) { /* Convert scientific notation. */ (void) SubstituteString(&fx_info->expression,"0e+","0**10^"); (void) SubstituteString(&fx_info->expression,"1e+","1**10^"); (void) SubstituteString(&fx_info->expression,"2e+","2**10^"); (void) SubstituteString(&fx_info->expression,"3e+","3**10^"); (void) SubstituteString(&fx_info->expression,"4e+","4**10^"); (void) SubstituteString(&fx_info->expression,"5e+","5**10^"); (void) SubstituteString(&fx_info->expression,"6e+","6**10^"); (void) SubstituteString(&fx_info->expression,"7e+","7**10^"); (void) SubstituteString(&fx_info->expression,"8e+","8**10^"); (void) SubstituteString(&fx_info->expression,"9e+","9**10^"); (void) SubstituteString(&fx_info->expression,"0e-1.0*","0**10^-"); (void) SubstituteString(&fx_info->expression,"1e-1.0*","1**10^-"); (void) SubstituteString(&fx_info->expression,"2e-1.0*","2**10^-"); (void) SubstituteString(&fx_info->expression,"3e-1.0*","3**10^-"); (void) SubstituteString(&fx_info->expression,"4e-1.0*","4**10^-"); (void) SubstituteString(&fx_info->expression,"5e-1.0*","5**10^-"); (void) SubstituteString(&fx_info->expression,"6e-1.0*","6**10^-"); (void) SubstituteString(&fx_info->expression,"7e-1.0*","7**10^-"); (void) SubstituteString(&fx_info->expression,"8e-1.0*","8**10^-"); (void) SubstituteString(&fx_info->expression,"9e-1.0*","9**10^-"); } if ((strstr(fx_info->expression,"E+") != (char *) NULL) || (strstr(fx_info->expression,"E-") != (char *) NULL)) { /* Convert scientific notation. */ (void) SubstituteString(&fx_info->expression,"0E+","0**10^"); (void) SubstituteString(&fx_info->expression,"1E+","1**10^"); (void) SubstituteString(&fx_info->expression,"2E+","2**10^"); (void) SubstituteString(&fx_info->expression,"3E+","3**10^"); (void) SubstituteString(&fx_info->expression,"4E+","4**10^"); (void) SubstituteString(&fx_info->expression,"5E+","5**10^"); (void) SubstituteString(&fx_info->expression,"6E+","6**10^"); (void) SubstituteString(&fx_info->expression,"7E+","7**10^"); (void) SubstituteString(&fx_info->expression,"8E+","8**10^"); (void) SubstituteString(&fx_info->expression,"9E+","9**10^"); (void) SubstituteString(&fx_info->expression,"0E-1.0*","0**10^-"); (void) SubstituteString(&fx_info->expression,"1E-1.0*","1**10^-"); (void) SubstituteString(&fx_info->expression,"2E-1.0*","2**10^-"); (void) SubstituteString(&fx_info->expression,"3E-1.0*","3**10^-"); (void) SubstituteString(&fx_info->expression,"4E-1.0*","4**10^-"); (void) SubstituteString(&fx_info->expression,"5E-1.0*","5**10^-"); (void) SubstituteString(&fx_info->expression,"6E-1.0*","6**10^-"); (void) SubstituteString(&fx_info->expression,"7E-1.0*","7**10^-"); (void) SubstituteString(&fx_info->expression,"8E-1.0*","8**10^-"); (void) SubstituteString(&fx_info->expression,"9E-1.0*","9**10^-"); } /* Convert complex to simple operators. */ fx_op[1]='\0'; *fx_op=(char) LeftShiftOperator; (void) SubstituteString(&fx_info->expression,"<<",fx_op); *fx_op=(char) RightShiftOperator; (void) SubstituteString(&fx_info->expression,">>",fx_op); *fx_op=(char) LessThanEqualOperator; (void) SubstituteString(&fx_info->expression,"<=",fx_op); *fx_op=(char) GreaterThanEqualOperator; (void) SubstituteString(&fx_info->expression,">=",fx_op); *fx_op=(char) EqualOperator; (void) SubstituteString(&fx_info->expression,"==",fx_op); *fx_op=(char) NotEqualOperator; (void) SubstituteString(&fx_info->expression,"!=",fx_op); *fx_op=(char) LogicalAndOperator; (void) SubstituteString(&fx_info->expression,"&&",fx_op); *fx_op=(char) LogicalOrOperator; (void) SubstituteString(&fx_info->expression,"||",fx_op); *fx_op=(char) ExponentialNotation; (void) SubstituteString(&fx_info->expression,"**",fx_op); return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d d N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddNoiseImage() adds random noise to the image. % % The format of the AddNoiseImage method is: % % Image *AddNoiseImage(const Image *image,const NoiseType noise_type, % ExceptionInfo *exception) % Image *AddNoiseImageChannel(const Image *image,const ChannelType channel, % const NoiseType noise_type,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o noise_type: The type of noise: Uniform, Gaussian, Multiplicative, % Impulse, Laplacian, or Poisson. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type, ExceptionInfo *exception) { Image *noise_image; noise_image=AddNoiseImageChannel(image,DefaultChannels,noise_type,exception); return(noise_image); } MagickExport Image *AddNoiseImageChannel(const Image *image, const ChannelType channel,const NoiseType noise_type,ExceptionInfo *exception) { #define AddNoiseImageTag "AddNoise/Image" CacheView *image_view, *noise_view; const char *option; Image *noise_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType attenuate; RandomInfo **restrict random_info; ssize_t y; /* Initialize noise image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse) { InheritException(exception,&noise_image->exception); noise_image=DestroyImage(noise_image); return((Image *) NULL); } /* Add noise in each row. */ attenuate=1.0; option=GetImageArtifact(image,"attenuate"); if (option != (char *) NULL) attenuate=InterpretLocaleValue(option,(char **) NULL); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireCacheView(image); noise_view=AcquireCacheView(noise_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict noise_indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetRedPixelComponent(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetRedPixelComponent(p),noise_type,attenuate))); if ((channel & GreenChannel) != 0) SetGreenPixelComponent(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetGreenPixelComponent(p),noise_type,attenuate))); if ((channel & BlueChannel) != 0) SetBluePixelComponent(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetBluePixelComponent(p),noise_type,attenuate))); if ((channel & OpacityChannel) != 0) SetOpacityPixelComponent(q,ClampToQuantum(GenerateDifferentialNoise( random_info[id],GetOpacityPixelComponent(p),noise_type,attenuate))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetIndexPixelComponent(noise_indexes+x,ClampToQuantum( GenerateDifferentialNoise(random_info[id],GetIndexPixelComponent( indexes+x),noise_type,attenuate))); p++; q++; } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AddNoiseImage) #endif proceed=SetImageProgress(image,AddNoiseImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u e S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlueShiftImage() mutes the colors of the image to simulate a scene at % nighttime in the moonlight. % % The format of the BlueShiftImage method is: % % Image *BlueShiftImage(const Image *image,const double factor, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o factor: the shift factor. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlueShiftImage(const Image *image,const double factor, ExceptionInfo *exception) { #define BlueShiftImageTag "BlueShift/Image" CacheView *image_view, *shift_view; Image *shift_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate blue shift image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); shift_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (shift_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(shift_image,DirectClass) == MagickFalse) { InheritException(exception,&shift_image->exception); shift_image=DestroyImage(shift_image); return((Image *) NULL); } /* Blue-shift DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); shift_view=AcquireCacheView(shift_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket pixel; Quantum quantum; register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { quantum=GetRedPixelComponent(p); if (GetGreenPixelComponent(p) < quantum) quantum=GetGreenPixelComponent(p); if (GetBluePixelComponent(p) < quantum) quantum=GetBluePixelComponent(p); pixel.red=0.5*(GetRedPixelComponent(p)+factor*quantum); pixel.green=0.5*(GetGreenPixelComponent(p)+factor*quantum); pixel.blue=0.5*(GetBluePixelComponent(p)+factor*quantum); quantum=GetRedPixelComponent(p); if (GetGreenPixelComponent(p) > quantum) quantum=GetGreenPixelComponent(p); if (GetBluePixelComponent(p) > quantum) quantum=GetBluePixelComponent(p); pixel.red=0.5*(pixel.red+factor*quantum); pixel.green=0.5*(pixel.green+factor*quantum); pixel.blue=0.5*(pixel.blue+factor*quantum); SetRedPixelComponent(q,ClampToQuantum(pixel.red)); SetGreenPixelComponent(q,ClampToQuantum(pixel.green)); SetBluePixelComponent(q,ClampToQuantum(pixel.blue)); p++; q++; } sync=SyncCacheViewAuthenticPixels(shift_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlueShiftImage) #endif proceed=SetImageProgress(image,BlueShiftImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shift_view=DestroyCacheView(shift_view); if (status == MagickFalse) shift_image=DestroyImage(shift_image); return(shift_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a r c o a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CharcoalImage() creates a new image that is a copy of an existing one with % the edge highlighted. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the CharcoalImage method is: % % Image *CharcoalImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CharcoalImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *charcoal_image, *clone_image, *edge_image; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); (void) SetImageType(clone_image,GrayscaleType); edge_image=EdgeImage(clone_image,radius,exception); clone_image=DestroyImage(clone_image); if (edge_image == (Image *) NULL) return((Image *) NULL); charcoal_image=BlurImage(edge_image,radius,sigma,exception); edge_image=DestroyImage(edge_image); if (charcoal_image == (Image *) NULL) return((Image *) NULL); (void) NormalizeImage(charcoal_image); (void) NegateImage(charcoal_image,MagickFalse); (void) SetImageType(charcoal_image,GrayscaleType); return(charcoal_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorizeImage() blends the fill color with each pixel in the image. % A percentage blend is specified with opacity. Control the application % of different color components by specifying a different percentage for % each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue). % % The format of the ColorizeImage method is: % % Image *ColorizeImage(const Image *image,const char *opacity, % const PixelPacket colorize,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o opacity: A character string indicating the level of opacity as a % percentage. % % o colorize: A color value. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorizeImage(const Image *image,const char *opacity, const PixelPacket colorize,ExceptionInfo *exception) { #define ColorizeImageTag "Colorize/Image" CacheView *colorize_view, *image_view; GeometryInfo geometry_info; Image *colorize_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket pixel; MagickStatusType flags; ssize_t y; /* Allocate colorized image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); colorize_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (colorize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(colorize_image,DirectClass) == MagickFalse) { InheritException(exception,&colorize_image->exception); colorize_image=DestroyImage(colorize_image); return((Image *) NULL); } if (opacity == (const char *) NULL) return(colorize_image); /* Determine RGB values of the pen color. */ flags=ParseGeometry(opacity,&geometry_info); pixel.red=geometry_info.rho; pixel.green=geometry_info.rho; pixel.blue=geometry_info.rho; pixel.opacity=(MagickRealType) OpaqueOpacity; if ((flags & SigmaValue) != 0) pixel.green=geometry_info.sigma; if ((flags & XiValue) != 0) pixel.blue=geometry_info.xi; if ((flags & PsiValue) != 0) pixel.opacity=geometry_info.psi; /* Colorize DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); colorize_view=AcquireCacheView(colorize_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(colorize_view,0,y,colorize_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetRedPixelComponent(q,((GetRedPixelComponent(p)*(100.0-pixel.red)+ colorize.red*pixel.red)/100.0)); SetGreenPixelComponent(q,((GetGreenPixelComponent(p)*(100.0-pixel.green)+ colorize.green*pixel.green)/100.0)); SetBluePixelComponent(q,((GetBluePixelComponent(p)*(100.0-pixel.blue)+ colorize.blue*pixel.blue)/100.0)); SetOpacityPixelComponent(q,((GetOpacityPixelComponent(p)*(100.0- pixel.opacity)+colorize.opacity*pixel.opacity)/100.0)); p++; q++; } sync=SyncCacheViewAuthenticPixels(colorize_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorizeImage) #endif proceed=SetImageProgress(image,ColorizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); colorize_view=DestroyCacheView(colorize_view); if (status == MagickFalse) colorize_image=DestroyImage(colorize_image); return(colorize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r M a t r i x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorMatrixImage() applies color transformation to an image. This method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the ColorMatrixImage method is: % % Image *ColorMatrixImage(const Image *image, % const KernelInfo *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_matrix: the color matrix. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorMatrixImage(const Image *image, const KernelInfo *color_matrix,ExceptionInfo *exception) { #define ColorMatrixImageTag "ColorMatrix/Image" CacheView *color_view, *image_view; double ColorMatrix[6][6] = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 } }; Image *color_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t u, v, y; /* Create color matrix. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); i=0; for (v=0; v < (ssize_t) color_matrix->height; v++) for (u=0; u < (ssize_t) color_matrix->width; u++) { if ((v < 6) && (u < 6)) ColorMatrix[v][u]=color_matrix->values[i]; i++; } /* Initialize color image. */ color_image=CloneImage(image,0,0,MagickTrue,exception); if (color_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(color_image,DirectClass) == MagickFalse) { InheritException(exception,&color_image->exception); color_image=DestroyImage(color_image); return((Image *) NULL); } if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " ColorMatrix image with color matrix:"); message=AcquireString(""); for (v=0; v < 6; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < 6; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%+f ", ColorMatrix[v][u]); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } /* ColorMatrix image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); color_view=AcquireCacheView(color_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickRealType pixel; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register ssize_t x; register IndexPacket *restrict color_indexes; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); color_indexes=GetCacheViewAuthenticIndexQueue(color_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t v; size_t height; height=color_matrix->height > 6 ? 6UL : color_matrix->height; for (v=0; v < (ssize_t) height; v++) { pixel=ColorMatrix[v][0]*GetRedPixelComponent(p)+ColorMatrix[v][1]* GetGreenPixelComponent(p)+ColorMatrix[v][2]*GetBluePixelComponent(p); if (image->matte != MagickFalse) pixel+=ColorMatrix[v][3]*(QuantumRange-GetOpacityPixelComponent(p)); if (image->colorspace == CMYKColorspace) pixel+=ColorMatrix[v][4]*GetIndexPixelComponent(indexes+x); pixel+=QuantumRange*ColorMatrix[v][5]; switch (v) { case 0: SetRedPixelComponent(q,ClampToQuantum(pixel)); break; case 1: SetGreenPixelComponent(q,ClampToQuantum(pixel)); break; case 2: SetBluePixelComponent(q,ClampToQuantum(pixel)); break; case 3: { if (image->matte != MagickFalse) SetAlphaPixelComponent(q,ClampToQuantum(pixel)); break; } case 4: { if (image->colorspace == CMYKColorspace) SetIndexPixelComponent(color_indexes+x,ClampToQuantum(pixel)); break; } } } p++; q++; } if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorMatrixImage) #endif proceed=SetImageProgress(image,ColorMatrixImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } color_view=DestroyCacheView(color_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) color_image=DestroyImage(color_image); return(color_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y F x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyFxInfo() deallocates memory associated with an FxInfo structure. % % The format of the DestroyFxInfo method is: % % ImageInfo *DestroyFxInfo(ImageInfo *fx_info) % % A description of each parameter follows: % % o fx_info: the fx info. % */ MagickExport FxInfo *DestroyFxInfo(FxInfo *fx_info) { register ssize_t i; fx_info->exception=DestroyExceptionInfo(fx_info->exception); fx_info->expression=DestroyString(fx_info->expression); fx_info->symbols=DestroySplayTree(fx_info->symbols); fx_info->colors=DestroySplayTree(fx_info->colors); for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--) fx_info->view[i]=DestroyCacheView(fx_info->view[i]); fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view); fx_info->random_info=DestroyRandomInfo(fx_info->random_info); fx_info=(FxInfo *) RelinquishMagickMemory(fx_info); return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F x E v a l u a t e C h a n n e l E x p r e s s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FxEvaluateChannelExpression() evaluates an expression and returns the % results. % % The format of the FxEvaluateExpression method is: % % MagickRealType FxEvaluateChannelExpression(FxInfo *fx_info, % const ChannelType channel,const ssize_t x,const ssize_t y, % MagickRealType *alpha,Exceptioninfo *exception) % MagickRealType FxEvaluateExpression(FxInfo *fx_info, % MagickRealType *alpha,Exceptioninfo *exception) % % A description of each parameter follows: % % o fx_info: the fx info. % % o channel: the channel. % % o x,y: the pixel position. % % o alpha: the result. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } static MagickRealType FxChannelStatistics(FxInfo *fx_info,const Image *image, ChannelType channel,const char *symbol,ExceptionInfo *exception) { char key[MaxTextExtent], statistic[MaxTextExtent]; const char *value; register const char *p; for (p=symbol; (*p != '.') && (*p != '\0'); p++) ; if (*p == '.') switch (*++p) /* e.g. depth.r */ { case 'r': channel=RedChannel; break; case 'g': channel=GreenChannel; break; case 'b': channel=BlueChannel; break; case 'c': channel=CyanChannel; break; case 'm': channel=MagentaChannel; break; case 'y': channel=YellowChannel; break; case 'k': channel=BlackChannel; break; default: break; } (void) FormatLocaleString(key,MaxTextExtent,"%p.%.20g.%s",(void *) image, (double) channel,symbol); value=(const char *) GetValueFromSplayTree(fx_info->symbols,key); if (value != (const char *) NULL) return(QuantumScale*InterpretLocaleValue(value,(char **) NULL)); (void) DeleteNodeFromSplayTree(fx_info->symbols,key); if (LocaleNCompare(symbol,"depth",5) == 0) { size_t depth; depth=GetImageChannelDepth(image,channel,exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",(double) depth); } if (LocaleNCompare(symbol,"kurtosis",8) == 0) { double kurtosis, skewness; (void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%g",kurtosis); } if (LocaleNCompare(symbol,"maxima",6) == 0) { double maxima, minima; (void) GetImageChannelRange(image,channel,&minima,&maxima,exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%g",maxima); } if (LocaleNCompare(symbol,"mean",4) == 0) { double mean, standard_deviation; (void) GetImageChannelMean(image,channel,&mean,&standard_deviation, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%g",mean); } if (LocaleNCompare(symbol,"minima",6) == 0) { double maxima, minima; (void) GetImageChannelRange(image,channel,&minima,&maxima,exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%g",minima); } if (LocaleNCompare(symbol,"skewness",8) == 0) { double kurtosis, skewness; (void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%g",skewness); } if (LocaleNCompare(symbol,"standard_deviation",18) == 0) { double mean, standard_deviation; (void) GetImageChannelMean(image,channel,&mean,&standard_deviation, exception); (void) FormatLocaleString(statistic,MaxTextExtent,"%g", standard_deviation); } (void) AddValueToSplayTree(fx_info->symbols,ConstantString(key), ConstantString(statistic)); return(QuantumScale*InterpretLocaleValue(statistic,(char **) NULL)); } static MagickRealType FxEvaluateSubexpression(FxInfo *,const ChannelType,const ssize_t, const ssize_t,const char *,MagickRealType *,ExceptionInfo *); static inline MagickRealType FxMax(FxInfo *fx_info,const ChannelType channel, const ssize_t x,const ssize_t y,const char *expression, ExceptionInfo *exception) { MagickRealType alpha, beta; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression,&beta,exception); return((MagickRealType) MagickMax((double) alpha,(double) beta)); } static inline MagickRealType FxMin(FxInfo *fx_info,ChannelType channel, const ssize_t x,const ssize_t y,const char *expression, ExceptionInfo *exception) { MagickRealType alpha, beta; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression,&beta,exception); return((MagickRealType) MagickMin((double) alpha,(double) beta)); } static inline const char *FxSubexpression(const char *expression, ExceptionInfo *exception) { const char *subexpression; register ssize_t level; level=0; subexpression=expression; while ((*subexpression != '\0') && ((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL))) { if (strchr("(",(int) *subexpression) != (char *) NULL) level++; else if (strchr(")",(int) *subexpression) != (char *) NULL) level--; subexpression++; } if (*subexpression == '\0') (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnbalancedParenthesis","`%s'",expression); return(subexpression); } static MagickRealType FxGetSymbol(FxInfo *fx_info,const ChannelType channel, const ssize_t x,const ssize_t y,const char *expression, ExceptionInfo *exception) { char *q, subexpression[MaxTextExtent], symbol[MaxTextExtent]; const char *p, *value; Image *image; MagickPixelPacket pixel; MagickRealType alpha, beta; PointInfo point; register ssize_t i; size_t length; size_t level; p=expression; i=GetImageIndexInList(fx_info->images); level=0; point.x=(double) x; point.y=(double) y; if (isalpha((int) *(p+1)) == 0) { if (strchr("suv",(int) *p) != (char *) NULL) { switch (*p) { case 's': default: { i=GetImageIndexInList(fx_info->images); break; } case 'u': i=0; break; case 'v': i=1; break; } p++; if (*p == '[') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '[') level++; else if (*p == ']') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, &beta,exception); i=(ssize_t) (alpha+0.5); p++; } if (*p == '.') p++; } if ((isalpha((int) *(p+1)) == 0) && (*p == 'p')) { p++; if (*p == '{') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '{') level++; else if (*p == '}') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, &beta,exception); point.x=alpha; point.y=beta; p++; } else if (*p == '[') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '[') level++; else if (*p == ']') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, &beta,exception); point.x+=alpha; point.y+=beta; p++; } if (*p == '.') p++; } } length=GetImageListLength(fx_info->images); while (i < 0) i+=(ssize_t) length; i%=length; image=GetImageFromList(fx_info->images,i); if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "NoSuchImage","`%s'",expression); return(0.0); } GetMagickPixelPacket(image,&pixel); (void) InterpolateMagickPixelPacket(image,fx_info->view[i],image->interpolate, point.x,point.y,&pixel,exception); if ((strlen(p) > 2) && (LocaleCompare(p,"intensity") != 0) && (LocaleCompare(p,"luminance") != 0) && (LocaleCompare(p,"hue") != 0) && (LocaleCompare(p,"saturation") != 0) && (LocaleCompare(p,"lightness") != 0)) { char name[MaxTextExtent]; (void) CopyMagickString(name,p,MaxTextExtent); for (q=name+(strlen(name)-1); q > name; q--) { if (*q == ')') break; if (*q == '.') { *q='\0'; break; } } if ((strlen(name) > 2) && (GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL)) { MagickPixelPacket *color; color=(MagickPixelPacket *) GetValueFromSplayTree(fx_info->colors, name); if (color != (MagickPixelPacket *) NULL) { pixel=(*color); p+=strlen(name); } else if (QueryMagickColor(name,&pixel,fx_info->exception) != MagickFalse) { (void) AddValueToSplayTree(fx_info->colors,ConstantString(name), CloneMagickPixelPacket(&pixel)); p+=strlen(name); } } } (void) CopyMagickString(symbol,p,MaxTextExtent); StripString(symbol); if (*symbol == '\0') { switch (channel) { case RedChannel: return(QuantumScale*pixel.red); case GreenChannel: return(QuantumScale*pixel.green); case BlueChannel: return(QuantumScale*pixel.blue); case OpacityChannel: { MagickRealType alpha; if (pixel.matte == MagickFalse) return(1.0); alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(&pixel)); return(alpha); } case IndexChannel: { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.index); } case DefaultChannels: { return(QuantumScale*MagickPixelIntensityToQuantum(&pixel)); } default: break; } (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",p); return(0.0); } switch (*symbol) { case 'A': case 'a': { if (LocaleCompare(symbol,"a") == 0) return((MagickRealType) (QuantumScale*GetAlphaPixelComponent(&pixel))); break; } case 'B': case 'b': { if (LocaleCompare(symbol,"b") == 0) return(QuantumScale*pixel.blue); break; } case 'C': case 'c': { if (LocaleNCompare(symbol,"channel",7) == 0) { GeometryInfo channel_info; MagickStatusType flags; flags=ParseGeometry(symbol+7,&channel_info); if (image->colorspace == CMYKColorspace) switch (channel) { case CyanChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case MagentaChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case YellowChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case BlackChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } case OpacityChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } default: return(0.0); } switch (channel) { case RedChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case GreenChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case BlueChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case OpacityChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } case IndexChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } default: return(0.0); } return(0.0); } if (LocaleCompare(symbol,"c") == 0) return(QuantumScale*pixel.red); break; } case 'D': case 'd': { if (LocaleNCompare(symbol,"depth",5) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); break; } case 'G': case 'g': { if (LocaleCompare(symbol,"g") == 0) return(QuantumScale*pixel.green); break; } case 'K': case 'k': { if (LocaleNCompare(symbol,"kurtosis",8) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleCompare(symbol,"k") == 0) { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.index); } break; } case 'H': case 'h': { if (LocaleCompare(symbol,"h") == 0) return((MagickRealType) image->rows); if (LocaleCompare(symbol,"hue") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green), ClampToQuantum(pixel.blue),&hue,&saturation,&lightness); return(hue); } break; } case 'I': case 'i': { if ((LocaleCompare(symbol,"image.depth") == 0) || (LocaleCompare(symbol,"image.minima") == 0) || (LocaleCompare(symbol,"image.maxima") == 0) || (LocaleCompare(symbol,"image.mean") == 0) || (LocaleCompare(symbol,"image.kurtosis") == 0) || (LocaleCompare(symbol,"image.skewness") == 0) || (LocaleCompare(symbol,"image.standard_deviation") == 0)) return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception)); if (LocaleCompare(symbol,"image.resolution.x") == 0) return(image->x_resolution); if (LocaleCompare(symbol,"image.resolution.y") == 0) return(image->y_resolution); if (LocaleCompare(symbol,"intensity") == 0) return(QuantumScale*MagickPixelIntensityToQuantum(&pixel)); if (LocaleCompare(symbol,"i") == 0) return((MagickRealType) x); break; } case 'J': case 'j': { if (LocaleCompare(symbol,"j") == 0) return((MagickRealType) y); break; } case 'L': case 'l': { if (LocaleCompare(symbol,"lightness") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green), ClampToQuantum(pixel.blue),&hue,&saturation,&lightness); return(lightness); } if (LocaleCompare(symbol,"luminance") == 0) { double luminence; luminence=0.2126*pixel.red+0.7152*pixel.green+0.0722*pixel.blue; return(QuantumScale*luminence); } break; } case 'M': case 'm': { if (LocaleNCompare(symbol,"maxima",6) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"mean",4) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"minima",6) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleCompare(symbol,"m") == 0) return(QuantumScale*pixel.blue); break; } case 'N': case 'n': { if (LocaleCompare(symbol,"n") == 0) return((MagickRealType) GetImageListLength(fx_info->images)); break; } case 'O': case 'o': { if (LocaleCompare(symbol,"o") == 0) return(QuantumScale*pixel.opacity); break; } case 'P': case 'p': { if (LocaleCompare(symbol,"page.height") == 0) return((MagickRealType) image->page.height); if (LocaleCompare(symbol,"page.width") == 0) return((MagickRealType) image->page.width); if (LocaleCompare(symbol,"page.x") == 0) return((MagickRealType) image->page.x); if (LocaleCompare(symbol,"page.y") == 0) return((MagickRealType) image->page.y); break; } case 'R': case 'r': { if (LocaleCompare(symbol,"resolution.x") == 0) return(image->x_resolution); if (LocaleCompare(symbol,"resolution.y") == 0) return(image->y_resolution); if (LocaleCompare(symbol,"r") == 0) return(QuantumScale*pixel.red); break; } case 'S': case 's': { if (LocaleCompare(symbol,"saturation") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green), ClampToQuantum(pixel.blue),&hue,&saturation,&lightness); return(saturation); } if (LocaleNCompare(symbol,"skewness",8) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"standard_deviation",18) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); break; } case 'T': case 't': { if (LocaleCompare(symbol,"t") == 0) return((MagickRealType) GetImageIndexInList(fx_info->images)); break; } case 'W': case 'w': { if (LocaleCompare(symbol,"w") == 0) return((MagickRealType) image->columns); break; } case 'Y': case 'y': { if (LocaleCompare(symbol,"y") == 0) return(QuantumScale*pixel.green); break; } case 'Z': case 'z': { if (LocaleCompare(symbol,"z") == 0) { MagickRealType depth; depth=(MagickRealType) GetImageChannelDepth(image,channel, fx_info->exception); return(depth); } break; } default: break; } value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol); if (value != (const char *) NULL) return((MagickRealType) InterpretLocaleValue(value,(char **) NULL)); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",symbol); return(0.0); } static const char *FxOperatorPrecedence(const char *expression, ExceptionInfo *exception) { typedef enum { UndefinedPrecedence, NullPrecedence, BitwiseComplementPrecedence, ExponentPrecedence, ExponentialNotationPrecedence, MultiplyPrecedence, AdditionPrecedence, ShiftPrecedence, RelationalPrecedence, EquivalencyPrecedence, BitwiseAndPrecedence, BitwiseOrPrecedence, LogicalAndPrecedence, LogicalOrPrecedence, TernaryPrecedence, AssignmentPrecedence, CommaPrecedence, SeparatorPrecedence } FxPrecedence; FxPrecedence precedence, target; register const char *subexpression; register int c; size_t level; c=0; level=0; subexpression=(const char *) NULL; target=NullPrecedence; while (*expression != '\0') { precedence=UndefinedPrecedence; if ((isspace((int) ((char) *expression)) != 0) || (c == (int) '@')) { expression++; continue; } switch (*expression) { case 'A': case 'a': { if (LocaleNCompare(expression,"atan2",5) == 0) { expression+=5; break; } break; } case 'J': case 'j': { if ((LocaleNCompare(expression,"j0",2) == 0) || (LocaleNCompare(expression,"j1",2) == 0)) { expression+=2; break; } break; } case '#': { while (isxdigit((int) ((unsigned char) *(expression+1))) != 0) expression++; break; } default: break; } if ((c == (int) '{') || (c == (int) '[')) level++; else if ((c == (int) '}') || (c == (int) ']')) level--; if (level == 0) switch ((unsigned char) *expression) { case '~': case '!': { precedence=BitwiseComplementPrecedence; break; } case '^': case '@': { precedence=ExponentPrecedence; break; } default: { if (((c != 0) && ((isdigit((int) ((char) c)) != 0) || (strchr(")",c) != (char *) NULL))) && (((islower((int) ((char) *expression)) != 0) || (strchr("(",(int) *expression) != (char *) NULL)) || ((isdigit((int) ((char) c)) == 0) && (isdigit((int) ((char) *expression)) != 0))) && (strchr("xy",(int) *expression) == (char *) NULL)) precedence=MultiplyPrecedence; break; } case '*': case '/': case '%': { precedence=MultiplyPrecedence; break; } case '+': case '-': { if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) || (isalpha(c) != 0)) precedence=AdditionPrecedence; break; } case LeftShiftOperator: case RightShiftOperator: { precedence=ShiftPrecedence; break; } case '<': case LessThanEqualOperator: case GreaterThanEqualOperator: case '>': { precedence=RelationalPrecedence; break; } case EqualOperator: case NotEqualOperator: { precedence=EquivalencyPrecedence; break; } case '&': { precedence=BitwiseAndPrecedence; break; } case '|': { precedence=BitwiseOrPrecedence; break; } case LogicalAndOperator: { precedence=LogicalAndPrecedence; break; } case LogicalOrOperator: { precedence=LogicalOrPrecedence; break; } case ExponentialNotation: { precedence=ExponentialNotationPrecedence; break; } case ':': case '?': { precedence=TernaryPrecedence; break; } case '=': { precedence=AssignmentPrecedence; break; } case ',': { precedence=CommaPrecedence; break; } case ';': { precedence=SeparatorPrecedence; break; } } if ((precedence == BitwiseComplementPrecedence) || (precedence == TernaryPrecedence) || (precedence == AssignmentPrecedence)) { if (precedence > target) { /* Right-to-left associativity. */ target=precedence; subexpression=expression; } } else if (precedence >= target) { /* Left-to-right associativity. */ target=precedence; subexpression=expression; } if (strchr("(",(int) *expression) != (char *) NULL) expression=FxSubexpression(expression,exception); c=(int) (*expression++); } return(subexpression); } static MagickRealType FxEvaluateSubexpression(FxInfo *fx_info, const ChannelType channel,const ssize_t x,const ssize_t y, const char *expression,MagickRealType *beta,ExceptionInfo *exception) { char *q, subexpression[MaxTextExtent]; MagickRealType alpha, gamma; register const char *p; *beta=0.0; if (exception->severity != UndefinedException) return(0.0); while (isspace((int) *expression) != 0) expression++; if (*expression == '\0') { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "MissingExpression","`%s'",expression); return(0.0); } *subexpression='\0'; p=FxOperatorPrecedence(expression,exception); if (p != (const char *) NULL) { (void) CopyMagickString(subexpression,expression,(size_t) (p-expression+1)); alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,beta, exception); switch ((unsigned char) *p) { case '~': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(MagickRealType) (~(size_t) *beta); return(*beta); } case '!': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(*beta == 0.0 ? 1.0 : 0.0); } case '^': { *beta=pow((double) alpha,(double) FxEvaluateSubexpression(fx_info, channel,x,y,++p,beta,exception)); return(*beta); } case '*': case ExponentialNotation: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha*(*beta)); } case '/': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); if (*beta == 0.0) { if (exception->severity == UndefinedException) (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"DivideByZero","`%s'",expression); return(0.0); } return(alpha/(*beta)); } case '%': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=fabs(floor(((double) *beta)+0.5)); if (*beta == 0.0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"DivideByZero","`%s'",expression); return(0.0); } return(fmod((double) alpha,(double) *beta)); } case '+': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha+(*beta)); } case '-': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha-(*beta)); } case LeftShiftOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(MagickRealType) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5)); return(*beta); } case RightShiftOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(MagickRealType) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5)); return(*beta); } case '<': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha < *beta ? 1.0 : 0.0); } case LessThanEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha <= *beta ? 1.0 : 0.0); } case '>': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha > *beta ? 1.0 : 0.0); } case GreaterThanEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha >= *beta ? 1.0 : 0.0); } case EqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(fabs(alpha-(*beta)) <= MagickEpsilon ? 1.0 : 0.0); } case NotEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(fabs(alpha-(*beta)) > MagickEpsilon ? 1.0 : 0.0); } case '&': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(MagickRealType) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5)); return(*beta); } case '|': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(MagickRealType) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5)); return(*beta); } case LogicalAndOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(alpha > 0.0) && (gamma > 0.0) ? 1.0 : 0.0; return(*beta); } case LogicalOrOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); *beta=(alpha > 0.0) || (gamma > 0.0) ? 1.0 : 0.0; return(*beta); } case '?': { MagickRealType gamma; (void) CopyMagickString(subexpression,++p,MaxTextExtent); q=subexpression; p=StringToken(":",&q); if (q == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnableToParseExpression","`%s'",subexpression); return(0.0); } if (fabs((double) alpha) > MagickEpsilon) gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,beta,exception); else gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,beta,exception); return(gamma); } case '=': { char numeric[MaxTextExtent]; q=subexpression; while (isalpha((int) ((unsigned char) *q)) != 0) q++; if (*q != '\0') { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnableToParseExpression","`%s'",subexpression); return(0.0); } ClearMagickException(exception); *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); (void) FormatLocaleString(numeric,MaxTextExtent,"%g",(double) *beta); (void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression); (void) AddValueToSplayTree(fx_info->symbols,ConstantString( subexpression),ConstantString(numeric)); return(*beta); } case ',': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(alpha); } case ';': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,beta,exception); return(*beta); } default: { gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,p,beta, exception); return(gamma); } } } if (strchr("(",(int) *expression) != (char *) NULL) { (void) CopyMagickString(subexpression,expression+1,MaxTextExtent); subexpression[strlen(subexpression)-1]='\0'; gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,beta, exception); return(gamma); } switch (*expression) { case '+': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,beta, exception); return(1.0*gamma); } case '-': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,beta, exception); return(-1.0*gamma); } case '~': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,beta, exception); return((MagickRealType) (~(size_t) (gamma+0.5))); } case 'A': case 'a': { if (LocaleNCompare(expression,"abs",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) fabs((double) alpha)); } if (LocaleNCompare(expression,"acos",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) acos((double) alpha)); } #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"airy",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); if (alpha == 0.0) return(1.0); gamma=2.0*j1((double) (MagickPI*alpha))/(MagickPI*alpha); return(gamma*gamma); } #endif if (LocaleNCompare(expression,"asin",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) asin((double) alpha)); } if (LocaleNCompare(expression,"alt",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0); } if (LocaleNCompare(expression,"atan2",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,beta, exception); return((MagickRealType) atan2((double) alpha,(double) *beta)); } if (LocaleNCompare(expression,"atan",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) atan((double) alpha)); } if (LocaleCompare(expression,"a") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'B': case 'b': { if (LocaleCompare(expression,"b") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'C': case 'c': { if (LocaleNCompare(expression,"ceil",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) ceil((double) alpha)); } if (LocaleNCompare(expression,"cosh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) cosh((double) alpha)); } if (LocaleNCompare(expression,"cos",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) cos((double) alpha)); } if (LocaleCompare(expression,"c") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'D': case 'd': { if (LocaleNCompare(expression,"debug",5) == 0) { const char *type; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,beta, exception); if (fx_info->images->colorspace == CMYKColorspace) switch (channel) { case CyanChannel: type="cyan"; break; case MagentaChannel: type="magenta"; break; case YellowChannel: type="yellow"; break; case OpacityChannel: type="opacity"; break; case BlackChannel: type="black"; break; default: type="unknown"; break; } else switch (channel) { case RedChannel: type="red"; break; case GreenChannel: type="green"; break; case BlueChannel: type="blue"; break; case OpacityChannel: type="opacity"; break; default: type="unknown"; break; } (void) CopyMagickString(subexpression,expression+6,MaxTextExtent); if (strlen(subexpression) > 1) subexpression[strlen(subexpression)-1]='\0'; if (fx_info->file != (FILE *) NULL) (void) FormatLocaleFile(fx_info->file, "%s[%.20g,%.20g].%s: %s=%.*g\n",fx_info->images->filename, (double) x,(double) y,type,subexpression,GetMagickPrecision(), (double) alpha); return(0.0); } break; } case 'E': case 'e': { if (LocaleCompare(expression,"epsilon") == 0) return((MagickRealType) MagickEpsilon); if (LocaleNCompare(expression,"exp",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) exp((double) alpha)); } if (LocaleCompare(expression,"e") == 0) return((MagickRealType) 2.7182818284590452354); break; } case 'F': case 'f': { if (LocaleNCompare(expression,"floor",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,beta, exception); return((MagickRealType) floor((double) alpha)); } break; } case 'G': case 'g': { if (LocaleCompare(expression,"g") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'H': case 'h': { if (LocaleCompare(expression,"h") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleCompare(expression,"hue") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleNCompare(expression,"hypot",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,beta, exception); return((MagickRealType) hypot((double) alpha,(double) *beta)); } break; } case 'K': case 'k': { if (LocaleCompare(expression,"k") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'I': case 'i': { if (LocaleCompare(expression,"intensity") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleNCompare(expression,"int",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) floor(alpha)); } if (LocaleCompare(expression,"i") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'J': case 'j': { if (LocaleCompare(expression,"j") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); #if defined(MAGICKCORE_HAVE_J0) if (LocaleNCompare(expression,"j0",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,beta, exception); return((MagickRealType) j0((double) alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"j1",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,beta, exception); return((MagickRealType) j1((double) alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"jinc",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); if (alpha == 0.0) return(1.0); gamma=(MagickRealType) (2.0*j1((double) (MagickPI*alpha))/ (MagickPI*alpha)); return(gamma); } #endif break; } case 'L': case 'l': { if (LocaleNCompare(expression,"ln",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,beta, exception); return((MagickRealType) log((double) alpha)); } if (LocaleNCompare(expression,"logtwo",6) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,beta, exception); return((MagickRealType) log10((double) alpha))/log10(2.0); } if (LocaleNCompare(expression,"log",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) log10((double) alpha)); } if (LocaleCompare(expression,"lightness") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'M': case 'm': { if (LocaleCompare(expression,"MaxRGB") == 0) return((MagickRealType) QuantumRange); if (LocaleNCompare(expression,"maxima",6) == 0) break; if (LocaleNCompare(expression,"max",3) == 0) return(FxMax(fx_info,channel,x,y,expression+3,exception)); if (LocaleNCompare(expression,"minima",6) == 0) break; if (LocaleNCompare(expression,"min",3) == 0) return(FxMin(fx_info,channel,x,y,expression+3,exception)); if (LocaleNCompare(expression,"mod",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) fmod((double) alpha,(double) *beta)); } if (LocaleCompare(expression,"m") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'N': case 'n': { if (LocaleCompare(expression,"n") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'O': case 'o': { if (LocaleCompare(expression,"Opaque") == 0) return(1.0); if (LocaleCompare(expression,"o") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'P': case 'p': { if (LocaleCompare(expression,"pi") == 0) return((MagickRealType) MagickPI); if (LocaleNCompare(expression,"pow",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) pow((double) alpha,(double) *beta)); } if (LocaleCompare(expression,"p") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'Q': case 'q': { if (LocaleCompare(expression,"QuantumRange") == 0) return((MagickRealType) QuantumRange); if (LocaleCompare(expression,"QuantumScale") == 0) return((MagickRealType) QuantumScale); break; } case 'R': case 'r': { if (LocaleNCompare(expression,"rand",4) == 0) return((MagickRealType) GetPseudoRandomValue(fx_info->random_info)); if (LocaleNCompare(expression,"round",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,beta, exception); return((MagickRealType) floor((double) alpha+0.5)); } if (LocaleCompare(expression,"r") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'S': case 's': { if (LocaleCompare(expression,"saturation") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleNCompare(expression,"sign",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return(alpha < 0.0 ? -1.0 : 1.0); } if (LocaleNCompare(expression,"sinc",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); if (alpha == 0) return(1.0); gamma=(MagickRealType) (sin((double) (MagickPI*alpha))/ (MagickPI*alpha)); return(gamma); } if (LocaleNCompare(expression,"sinh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) sinh((double) alpha)); } if (LocaleNCompare(expression,"sin",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) sin((double) alpha)); } if (LocaleNCompare(expression,"sqrt",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) sqrt((double) alpha)); } if (LocaleCompare(expression,"s") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'T': case 't': { if (LocaleNCompare(expression,"tanh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,beta, exception); return((MagickRealType) tanh((double) alpha)); } if (LocaleNCompare(expression,"tan",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,beta, exception); return((MagickRealType) tan((double) alpha)); } if (LocaleCompare(expression,"Transparent") == 0) return(0.0); if (LocaleNCompare(expression,"trunc",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,beta, exception); if (alpha >= 0.0) return((MagickRealType) floor((double) alpha)); return((MagickRealType) ceil((double) alpha)); } if (LocaleCompare(expression,"t") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'U': case 'u': { if (LocaleCompare(expression,"u") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'V': case 'v': { if (LocaleCompare(expression,"v") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'W': case 'w': { if (LocaleCompare(expression,"w") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'Y': case 'y': { if (LocaleCompare(expression,"y") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'Z': case 'z': { if (LocaleCompare(expression,"z") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } default: break; } q=(char *) expression; alpha=InterpretLocaleValue(expression,&q); if (q == expression) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); return(alpha); } MagickExport MagickBooleanType FxEvaluateExpression(FxInfo *fx_info, MagickRealType *alpha,ExceptionInfo *exception) { MagickBooleanType status; status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception); return(status); } MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info, MagickRealType *alpha,ExceptionInfo *exception) { FILE *file; MagickBooleanType status; file=fx_info->file; fx_info->file=(FILE *) NULL; status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception); fx_info->file=file; return(status); } MagickExport MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info, const ChannelType channel,const ssize_t x,const ssize_t y, MagickRealType *alpha,ExceptionInfo *exception) { MagickRealType beta; beta=0.0; *alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,&beta, exception); return(exception->severity == OptionError ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FxImage() applies a mathematical expression to the specified image. % % The format of the FxImage method is: % % Image *FxImage(const Image *image,const char *expression, % ExceptionInfo *exception) % Image *FxImageChannel(const Image *image,const ChannelType channel, % const char *expression,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o expression: A mathematical expression. % % o exception: return any errors or warnings in this structure. % */ static FxInfo **DestroyFxThreadSet(FxInfo **fx_info) { register ssize_t i; assert(fx_info != (FxInfo **) NULL); for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++) if (fx_info[i] != (FxInfo *) NULL) fx_info[i]=DestroyFxInfo(fx_info[i]); fx_info=(FxInfo **) RelinquishMagickMemory(fx_info); return(fx_info); } static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression, ExceptionInfo *exception) { char *fx_expression; FxInfo **fx_info; MagickRealType alpha; register ssize_t i; size_t number_threads; number_threads=GetOpenMPMaximumThreads(); fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info)); if (fx_info == (FxInfo **) NULL) return((FxInfo **) NULL); (void) ResetMagickMemory(fx_info,0,number_threads*sizeof(*fx_info)); if (*expression != '@') fx_expression=ConstantString(expression); else fx_expression=FileToString(expression+1,~0,exception); for (i=0; i < (ssize_t) number_threads; i++) { fx_info[i]=AcquireFxInfo(image,fx_expression); if (fx_info[i] == (FxInfo *) NULL) return(DestroyFxThreadSet(fx_info)); (void) FxPreprocessExpression(fx_info[i],&alpha,fx_info[i]->exception); } fx_expression=DestroyString(fx_expression); return(fx_info); } MagickExport Image *FxImage(const Image *image,const char *expression, ExceptionInfo *exception) { Image *fx_image; fx_image=FxImageChannel(image,GrayChannel,expression,exception); return(fx_image); } MagickExport Image *FxImageChannel(const Image *image,const ChannelType channel, const char *expression,ExceptionInfo *exception) { #define FxImageTag "Fx/Image" CacheView *fx_view; FxInfo **restrict fx_info; Image *fx_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType alpha; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); fx_image=CloneImage(image,0,0,MagickTrue,exception); if (fx_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(fx_image,DirectClass) == MagickFalse) { InheritException(exception,&fx_image->exception); fx_image=DestroyImage(fx_image); return((Image *) NULL); } fx_info=AcquireFxThreadSet(image,expression,exception); if (fx_info == (FxInfo **) NULL) { fx_image=DestroyImage(fx_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } status=FxPreprocessExpression(fx_info[0],&alpha,exception); if (status == MagickFalse) { fx_image=DestroyImage(fx_image); fx_info=DestroyFxThreadSet(fx_info); return((Image *) NULL); } /* Fx image. */ status=MagickTrue; progress=0; fx_view=AcquireCacheView(fx_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) fx_image->rows; y++) { const int id = GetOpenMPThreadId(); MagickRealType alpha; register IndexPacket *restrict fx_indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } fx_indexes=GetCacheViewAuthenticIndexQueue(fx_view); alpha=0.0; for (x=0; x < (ssize_t) fx_image->columns; x++) { if ((channel & RedChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],RedChannel,x,y, &alpha,exception); SetRedPixelComponent(q,ClampToQuantum((MagickRealType) QuantumRange* alpha)); } if ((channel & GreenChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],GreenChannel,x,y, &alpha,exception); SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) QuantumRange* alpha)); } if ((channel & BlueChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],BlueChannel,x,y, &alpha,exception); SetBluePixelComponent(q,ClampToQuantum((MagickRealType) QuantumRange* alpha)); } if ((channel & OpacityChannel) != 0) { (void) FxEvaluateChannelExpression(fx_info[id],OpacityChannel,x,y, &alpha,exception); if (image->matte == MagickFalse) SetOpacityPixelComponent(q,ClampToQuantum((MagickRealType) QuantumRange*alpha)); else SetOpacityPixelComponent(q,ClampToQuantum((MagickRealType) (QuantumRange-QuantumRange*alpha))); } if (((channel & IndexChannel) != 0) && (fx_image->colorspace == CMYKColorspace)) { (void) FxEvaluateChannelExpression(fx_info[id],IndexChannel,x,y, &alpha,exception); SetIndexPixelComponent(fx_indexes+x,ClampToQuantum((MagickRealType) QuantumRange*alpha)); } q++; } if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FxImageChannel) #endif proceed=SetImageProgress(image,FxImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } fx_view=DestroyCacheView(fx_view); fx_info=DestroyFxThreadSet(fx_info); if (status == MagickFalse) fx_image=DestroyImage(fx_image); return(fx_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p l o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImplodeImage() creates a new image that is a copy of an existing % one with the image pixels "implode" by the specified percentage. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ImplodeImage method is: % % Image *ImplodeImage(const Image *image,const double amount, % ExceptionInfo *exception) % % A description of each parameter follows: % % o implode_image: Method ImplodeImage returns a pointer to the image % after it is implode. A null image is returned if there is a memory % shortage. % % o image: the image. % % o amount: Define the extent of the implosion. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ImplodeImage(const Image *image,const double amount, ExceptionInfo *exception) { #define ImplodeImageTag "Implode/Image" CacheView *image_view, *implode_view; Image *implode_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType radius; PointInfo center, scale; ssize_t y; /* Initialize implode image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); implode_image=CloneImage(image,0,0,MagickTrue,exception); if (implode_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(implode_image,DirectClass) == MagickFalse) { InheritException(exception,&implode_image->exception); implode_image=DestroyImage(implode_image); return((Image *) NULL); } if (implode_image->background_color.opacity != OpaqueOpacity) implode_image->matte=MagickTrue; /* Compute scaling factor. */ scale.x=1.0; scale.y=1.0; center.x=0.5*image->columns; center.y=0.5*image->rows; radius=center.x; if (image->columns > image->rows) scale.y=(double) image->columns/(double) image->rows; else if (image->columns < image->rows) { scale.x=(double) image->rows/(double) image->columns; radius=center.y; } /* Implode image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(implode_image,&zero); image_view=AcquireCacheView(image); implode_view=AcquireCacheView(implode_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; MagickRealType distance; PointInfo delta; register IndexPacket *restrict implode_indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } implode_indexes=GetCacheViewAuthenticIndexQueue(implode_view); delta.y=scale.y*(double) (y-center.y); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance < (radius*radius)) { double factor; /* Implode the pixel. */ factor=1.0; if (distance > 0.0) factor=pow(sin((double) (MagickPI*sqrt((double) distance)/ radius/2)),-amount); (void) InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) (factor*delta.x/scale.x+ center.x),(double) (factor*delta.y/scale.y+center.y),&pixel, exception); SetPixelPacket(implode_image,&pixel,q,implode_indexes+x); } q++; } if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ImplodeImage) #endif proceed=SetImageProgress(image,ImplodeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } implode_view=DestroyCacheView(implode_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) implode_image=DestroyImage(implode_image); return(implode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The MorphImages() method requires a minimum of two images. The first % image is transformed into the second by a number of intervening images % as specified by frames. % % The format of the MorphImage method is: % % Image *MorphImages(const Image *image,const size_t number_frames, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_frames: Define the number of in-between image to generate. % The more in-between frames, the smoother the morph. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphImages(const Image *image, const size_t number_frames,ExceptionInfo *exception) { #define MorphImageTag "Morph/Image" Image *morph_image, *morph_images; MagickBooleanType status; MagickOffsetType scene; MagickRealType alpha, beta; register const Image *next; register ssize_t i; ssize_t y; /* Clone first frame in sequence. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); morph_images=CloneImage(image,0,0,MagickTrue,exception); if (morph_images == (Image *) NULL) return((Image *) NULL); if (GetNextImageInList(image) == (Image *) NULL) { /* Morph single image. */ for (i=1; i < (ssize_t) number_frames; i++) { morph_image=CloneImage(image,0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) i, number_frames); if (proceed == MagickFalse) status=MagickFalse; } } return(GetFirstImageInList(morph_images)); } /* Morph image sequence. */ status=MagickTrue; scene=0; next=image; for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next)) { for (i=0; i < (ssize_t) number_frames; i++) { CacheView *image_view, *morph_view; beta=(MagickRealType) (i+1.0)/(MagickRealType) (number_frames+1.0); alpha=1.0-beta; morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta* GetNextImageInList(next)->columns+0.5),(size_t) (alpha* next->rows+beta*GetNextImageInList(next)->rows+0.5), next->filter,next->blur,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } if (SetImageStorageClass(morph_image,DirectClass) == MagickFalse) { InheritException(exception,&morph_image->exception); morph_image=DestroyImage(morph_image); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns, morph_images->rows,GetNextImageInList(next)->filter, GetNextImageInList(next)->blur,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } image_view=AcquireCacheView(morph_image); morph_view=AcquireCacheView(morph_images); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (ssize_t) morph_images->rows; y++) { MagickBooleanType sync; register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1, exception); q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) morph_images->columns; x++) { SetRedPixelComponent(q,ClampToQuantum(alpha* GetRedPixelComponent(q)+beta*GetRedPixelComponent(p))); SetGreenPixelComponent(q,ClampToQuantum(alpha* GetGreenPixelComponent(q)+beta*GetGreenPixelComponent(p))); SetBluePixelComponent(q,ClampToQuantum(alpha* GetBluePixelComponent(q)+beta*GetBluePixelComponent(p))); SetOpacityPixelComponent(q,ClampToQuantum(alpha* GetOpacityPixelComponent(q)+beta*GetOpacityPixelComponent(p))); p++; q++; } sync=SyncCacheViewAuthenticPixels(morph_view,exception); if (sync == MagickFalse) status=MagickFalse; } morph_view=DestroyCacheView(morph_view); image_view=DestroyCacheView(image_view); morph_image=DestroyImage(morph_image); } if (i < (ssize_t) number_frames) break; /* Clone last frame in sequence. */ morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MorphImages) #endif proceed=SetImageProgress(image,MorphImageTag,scene, GetImageListLength(image)); if (proceed == MagickFalse) status=MagickFalse; } scene++; } if (GetNextImageInList(next) != (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } return(GetFirstImageInList(morph_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P l a s m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PlasmaImage() initializes an image with plasma fractal values. The image % must be initialized with a base color and the random number generator % seeded before this method is called. % % The format of the PlasmaImage method is: % % MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment, % size_t attenuate,size_t depth) % % A description of each parameter follows: % % o image: the image. % % o segment: Define the region to apply plasma fractals values. % % o attenuate: Define the plasma attenuation factor. % % o depth: Limit the plasma recursion depth. % */ static inline Quantum PlasmaPixel(RandomInfo *random_info, const MagickRealType pixel,const MagickRealType noise) { Quantum plasma; plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)- noise/2.0); return(plasma); } MagickExport MagickBooleanType PlasmaImageProxy(Image *image, CacheView *image_view,RandomInfo *random_info,const SegmentInfo *segment, size_t attenuate,size_t depth) { ExceptionInfo *exception; MagickRealType plasma; PixelPacket u, v; ssize_t x, x_mid, y, y_mid; if (((segment->x2-segment->x1) == 0.0) && ((segment->y2-segment->y1) == 0.0)) return(MagickTrue); if (depth != 0) { SegmentInfo local_info; /* Divide the area into quadrants and recurse. */ depth--; attenuate++; x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); local_info=(*segment); local_info.x2=(double) x_mid; local_info.y2=(double) y_mid; (void) PlasmaImageProxy(image,image_view,random_info,&local_info, attenuate,depth); local_info=(*segment); local_info.y1=(double) y_mid; local_info.x2=(double) x_mid; (void) PlasmaImageProxy(image,image_view,random_info,&local_info, attenuate,depth); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y2=(double) y_mid; (void) PlasmaImageProxy(image,image_view,random_info,&local_info, attenuate,depth); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y1=(double) y_mid; return(PlasmaImageProxy(image,image_view,random_info,&local_info, attenuate,depth)); } x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); if ((segment->x1 == (double) x_mid) && (segment->x2 == (double) x_mid) && (segment->y1 == (double) y_mid) && (segment->y2 == (double) y_mid)) return(MagickFalse); /* Average pixels and apply plasma. */ exception=(&image->exception); plasma=(MagickRealType) QuantumRange/(2.0*attenuate); if ((segment->x1 != (double) x_mid) || (segment->x2 != (double) x_mid)) { register PixelPacket *restrict q; /* Left pixel. */ x=(ssize_t) ceil(segment->x1-0.5); (void) GetOneCacheViewVirtualPixel(image_view,x,(ssize_t) ceil(segment->y1-0.5),&u,exception); (void) GetOneCacheViewVirtualPixel(image_view,x,(ssize_t) ceil(segment->y2-0.5),&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetRedPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,plasma)); SetGreenPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.green+v.green)/2.0,plasma)); SetBluePixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); if (segment->x1 != segment->x2) { /* Right pixel. */ x=(ssize_t) ceil(segment->x2-0.5); (void) GetOneCacheViewVirtualPixel(image_view,x,(ssize_t) ceil(segment->y1-0.5),&u,exception); (void) GetOneCacheViewVirtualPixel(image_view,x,(ssize_t) ceil(segment->y2-0.5),&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetRedPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,plasma)); SetGreenPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.green+v.green)/2.0,plasma)); SetBluePixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } } if ((segment->y1 != (double) y_mid) || (segment->y2 != (double) y_mid)) { if ((segment->x1 != (double) x_mid) || (segment->y2 != (double) y_mid)) { register PixelPacket *restrict q; /* Bottom pixel. */ y=(ssize_t) ceil(segment->y2-0.5); (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) ceil(segment->x1-0.5),y,&u,exception); (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) ceil(segment->x2-0.5),y,&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetRedPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,plasma)); SetGreenPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.green+v.green)/2.0,plasma)); SetBluePixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } if (segment->y1 != segment->y2) { register PixelPacket *restrict q; /* Top pixel. */ y=(ssize_t) ceil(segment->y1-0.5); (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) ceil(segment->x1-0.5),y,&u,exception); (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) ceil(segment->x2-0.5),y,&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetRedPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,plasma)); SetGreenPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.green+v.green)/2.0,plasma)); SetBluePixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } } if ((segment->x1 != segment->x2) || (segment->y1 != segment->y2)) { register PixelPacket *restrict q; /* Middle pixel. */ x=(ssize_t) ceil(segment->x1-0.5); y=(ssize_t) ceil(segment->y1-0.5); (void) GetOneVirtualPixel(image,x,y,&u,exception); x=(ssize_t) ceil(segment->x2-0.5); y=(ssize_t) ceil(segment->y2-0.5); (void) GetOneCacheViewVirtualPixel(image_view,x,y,&v,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickTrue); SetRedPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,plasma)); SetGreenPixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.green+v.green)/2.0,plasma)); SetBluePixelComponent(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/2.0,plasma)); (void) SyncCacheViewAuthenticPixels(image_view,exception); } if (((segment->x2-segment->x1) < 3.0) && ((segment->y2-segment->y1) < 3.0)) return(MagickTrue); return(MagickFalse); } MagickExport MagickBooleanType PlasmaImage(Image *image, const SegmentInfo *segment,size_t attenuate,size_t depth) { CacheView *image_view; MagickBooleanType status; RandomInfo *random_info; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); image_view=AcquireCacheView(image); random_info=AcquireRandomInfo(); status=PlasmaImageProxy(image,image_view,random_info,segment,attenuate,depth); random_info=DestroyRandomInfo(random_info); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l a r o i d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolaroidImage() simulates a Polaroid picture. % % The format of the AnnotateImage method is: % % Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, % const double angle,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, const double angle,ExceptionInfo *exception) { const char *value; Image *bend_image, *caption_image, *flop_image, *picture_image, *polaroid_image, *rotate_image, *trim_image; size_t height; ssize_t quantum; /* Simulate a Polaroid picture. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double) image->rows)/25.0,10.0); height=image->rows+2*quantum; caption_image=(Image *) NULL; value=GetImageProperty(image,"Caption"); if (value != (const char *) NULL) { char *caption, geometry[MaxTextExtent]; DrawInfo *annotate_info; MagickBooleanType status; ssize_t count; TypeMetric metrics; /* Generate caption image. */ caption_image=CloneImage(image,image->columns,1,MagickTrue,exception); if (caption_image == (Image *) NULL) return((Image *) NULL); annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info); caption=InterpretImageProperties((ImageInfo *) NULL,(Image *) image, value); (void) CloneString(&annotate_info->text,caption); count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,&metrics, &caption); status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)*(metrics.ascent-metrics.descent)+0.5)); if (status == MagickFalse) caption_image=DestroyImage(caption_image); else { caption_image->background_color=image->border_color; (void) SetImageBackgroundColor(caption_image); (void) CloneString(&annotate_info->text,caption); (void) FormatLocaleString(geometry,MaxTextExtent,"+0+%g", metrics.ascent); if (annotate_info->gravity == UndefinedGravity) (void) CloneString(&annotate_info->geometry,AcquireString( geometry)); (void) AnnotateImage(caption_image,annotate_info); height+=caption_image->rows; } annotate_info=DestroyDrawInfo(annotate_info); caption=DestroyString(caption); } picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue, exception); if (picture_image == (Image *) NULL) { if (caption_image != (Image *) NULL) caption_image=DestroyImage(caption_image); return((Image *) NULL); } picture_image->background_color=image->border_color; (void) SetImageBackgroundColor(picture_image); (void) CompositeImage(picture_image,OverCompositeOp,image,quantum,quantum); if (caption_image != (Image *) NULL) { (void) CompositeImage(picture_image,OverCompositeOp,caption_image, quantum,(ssize_t) (image->rows+3*quantum/2)); caption_image=DestroyImage(caption_image); } (void) QueryColorDatabase("none",&picture_image->background_color,exception); (void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel); rotate_image=RotateImage(picture_image,90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0* picture_image->columns,exception); picture_image=DestroyImage(picture_image); if (bend_image == (Image *) NULL) return((Image *) NULL); InheritException(&bend_image->exception,exception); picture_image=bend_image; rotate_image=RotateImage(picture_image,-90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; picture_image->background_color=image->background_color; polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3, exception); if (polaroid_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } flop_image=FlopImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (flop_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } polaroid_image=flop_image; (void) CompositeImage(polaroid_image,OverCompositeOp,picture_image, (ssize_t) (-0.01*picture_image->columns/2.0),0L); picture_image=DestroyImage(picture_image); (void) QueryColorDatabase("none",&polaroid_image->background_color,exception); rotate_image=RotateImage(polaroid_image,angle,exception); polaroid_image=DestroyImage(polaroid_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); polaroid_image=rotate_image; trim_image=TrimImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (trim_image == (Image *) NULL) return((Image *) NULL); polaroid_image=trim_image; return(polaroid_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e p i a T o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSepiaToneImage() applies a special effect to the image, similar to the % effect achieved in a photo darkroom by sepia toning. Threshold ranges from % 0 to QuantumRange and is a measure of the extent of the sepia toning. A % threshold of 80% is a good starting point for a reasonable tone. % % The format of the SepiaToneImage method is: % % Image *SepiaToneImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: the tone threshold. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SepiaToneImage(const Image *image,const double threshold, ExceptionInfo *exception) { #define SepiaToneImageTag "SepiaTone/Image" CacheView *image_view, *sepia_view; Image *sepia_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize sepia-toned image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); sepia_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (sepia_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sepia_image,DirectClass) == MagickFalse) { InheritException(exception,&sepia_image->exception); sepia_image=DestroyImage(sepia_image); return((Image *) NULL); } /* Tone each row of the image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); sepia_view=AcquireCacheView(sepia_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity, tone; intensity=(MagickRealType) PixelIntensityToQuantum(p); tone=intensity > threshold ? (MagickRealType) QuantumRange : intensity+ (MagickRealType) QuantumRange-threshold; SetRedPixelComponent(q,ClampToQuantum(tone)); tone=intensity > (7.0*threshold/6.0) ? (MagickRealType) QuantumRange : intensity+(MagickRealType) QuantumRange-7.0*threshold/6.0; SetGreenPixelComponent(q,ClampToQuantum(tone)); tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0; SetBluePixelComponent(q,ClampToQuantum(tone)); tone=threshold/7.0; if ((MagickRealType) GetGreenPixelComponent(q) < tone) SetGreenPixelComponent(q,ClampToQuantum(tone)); if ((MagickRealType) GetBluePixelComponent(q) < tone) SetBluePixelComponent(q,ClampToQuantum(tone)); p++; q++; } if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SepiaToneImage) #endif proceed=SetImageProgress(image,SepiaToneImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sepia_view=DestroyCacheView(sepia_view); image_view=DestroyCacheView(image_view); (void) NormalizeImage(sepia_image); (void) ContrastImage(sepia_image,MagickTrue); if (status == MagickFalse) sepia_image=DestroyImage(sepia_image); return(sepia_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d o w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadowImage() simulates a shadow from the specified image and returns it. % % The format of the ShadowImage method is: % % Image *ShadowImage(const Image *image,const double opacity, % const double sigma,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o opacity: percentage transparency. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x_offset: the shadow x-offset. % % o y_offset: the shadow y-offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadowImage(const Image *image,const double opacity, const double sigma,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define ShadowImageTag "Shadow/Image" CacheView *image_view; Image *border_image, *clone_image, *shadow_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo border_info; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); (void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod); clone_image->compose=OverCompositeOp; border_info.width=(size_t) floor(2.0*sigma+0.5); border_info.height=(size_t) floor(2.0*sigma+0.5); border_info.x=0; border_info.y=0; (void) QueryColorDatabase("none",&clone_image->border_color,exception); border_image=BorderImage(clone_image,&border_info,exception); clone_image=DestroyImage(clone_image); if (border_image == (Image *) NULL) return((Image *) NULL); if (border_image->matte == MagickFalse) (void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel); /* Shadow image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(border_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) border_image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) border_image->columns; x++) { SetRedPixelComponent(q,border_image->background_color.red); SetGreenPixelComponent(q,border_image->background_color.green); SetBluePixelComponent(q,border_image->background_color.blue); if (border_image->matte == MagickFalse) SetOpacityPixelComponent(q,border_image->background_color.opacity); else SetOpacityPixelComponent(q,ClampToQuantum((MagickRealType) (QuantumRange-GetAlphaPixelComponent(q)*opacity/100.0))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ShadowImage) #endif proceed=SetImageProgress(image,ShadowImageTag,progress++, border_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shadow_image=BlurImageChannel(border_image,AlphaChannel,0.0,sigma,exception); border_image=DestroyImage(border_image); if (shadow_image == (Image *) NULL) return((Image *) NULL); if (shadow_image->page.width == 0) shadow_image->page.width=shadow_image->columns; if (shadow_image->page.height == 0) shadow_image->page.height=shadow_image->rows; shadow_image->page.width+=x_offset-(ssize_t) border_info.width; shadow_image->page.height+=y_offset-(ssize_t) border_info.height; shadow_image->page.x+=x_offset-(ssize_t) border_info.width; shadow_image->page.y+=y_offset-(ssize_t) border_info.height; return(shadow_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S k e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SketchImage() simulates a pencil sketch. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SketchImage() selects a suitable radius for you. Angle gives the angle % of the sketch. % % The format of the SketchImage method is: % % Image *SketchImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting % the center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SketchImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { CacheView *random_view; Image *blend_image, *blur_image, *dodge_image, *random_image, *sketch_image; MagickBooleanType status; MagickPixelPacket zero; RandomInfo **restrict random_info; ssize_t y; /* Sketch image. */ random_image=CloneImage(image,image->columns << 1,image->rows << 1, MagickTrue,exception); if (random_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; GetMagickPixelPacket(random_image,&zero); random_info=AcquireRandomInfoThreadSet(); random_view=AcquireCacheView(random_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (ssize_t) random_image->rows; y++) { const int id = GetOpenMPThreadId(); MagickPixelPacket pixel; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(random_view); pixel=zero; for (x=0; x < (ssize_t) random_image->columns; x++) { pixel.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); pixel.green=pixel.red; pixel.blue=pixel.red; if (image->colorspace == CMYKColorspace) pixel.index=pixel.red; SetPixelPacket(random_image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse) status=MagickFalse; } random_view=DestroyCacheView(random_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) { random_image=DestroyImage(random_image); return(random_image); } blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception); random_image=DestroyImage(random_image); if (blur_image == (Image *) NULL) return((Image *) NULL); dodge_image=EdgeImage(blur_image,radius,exception); blur_image=DestroyImage(blur_image); if (dodge_image == (Image *) NULL) return((Image *) NULL); (void) NormalizeImage(dodge_image); (void) NegateImage(dodge_image,MagickFalse); (void) TransformImage(&dodge_image,(char *) NULL,"50%"); sketch_image=CloneImage(image,0,0,MagickTrue,exception); if (sketch_image == (Image *) NULL) { dodge_image=DestroyImage(dodge_image); return((Image *) NULL); } (void) CompositeImage(sketch_image,ColorDodgeCompositeOp,dodge_image,0,0); dodge_image=DestroyImage(dodge_image); blend_image=CloneImage(image,0,0,MagickTrue,exception); if (blend_image == (Image *) NULL) { sketch_image=DestroyImage(sketch_image); return((Image *) NULL); } (void) SetImageArtifact(blend_image,"compose:args","20x80"); (void) CompositeImage(sketch_image,BlendCompositeOp,blend_image,0,0); blend_image=DestroyImage(blend_image); return(sketch_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o l a r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SolarizeImage() applies a special effect to the image, similar to the effect % achieved in a photo darkroom by selectively exposing areas of photo % sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a % measure of the extent of the solarization. % % The format of the SolarizeImage method is: % % MagickBooleanType SolarizeImage(Image *image,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the extent of the solarization. % */ MagickExport MagickBooleanType SolarizeImage(Image *image, const double threshold) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; /* Solarize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((MagickRealType) image->colormap[i].red > threshold) image->colormap[i].red=(Quantum) QuantumRange-image->colormap[i].red; if ((MagickRealType) image->colormap[i].green > threshold) image->colormap[i].green=(Quantum) QuantumRange- image->colormap[i].green; if ((MagickRealType) image->colormap[i].blue > threshold) image->colormap[i].blue=(Quantum) QuantumRange- image->colormap[i].blue; } } /* Solarize image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((MagickRealType) GetRedPixelComponent(q) > threshold) SetRedPixelComponent(q,QuantumRange-GetRedPixelComponent(q)); if ((MagickRealType) GetGreenPixelComponent(q) > threshold) SetGreenPixelComponent(q,QuantumRange-GetGreenPixelComponent(q)); if ((MagickRealType) GetBluePixelComponent(q) > threshold) SetBluePixelComponent(q,QuantumRange-GetBluePixelComponent(q)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SolarizeImage) #endif proceed=SetImageProgress(image,SolarizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e g a n o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SteganoImage() hides a digital watermark within the image. Recover % the hidden watermark later to prove that the authenticity of an image. % Offset defines the start position within the image to hide the watermark. % % The format of the SteganoImage method is: % % Image *SteganoImage(const Image *image,Image *watermark, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o watermark: the watermark image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SteganoImage(const Image *image,const Image *watermark, ExceptionInfo *exception) { #define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0) #define SetBit(alpha,i,set) (alpha)=(Quantum) ((set) != 0 ? (size_t) (alpha) \ | (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i))) #define SteganoImageTag "Stegano/Image" CacheView *stegano_view, *watermark_view; Image *stegano_image; int c; MagickBooleanType status; PixelPacket pixel; register PixelPacket *q; register ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize steganographic image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(watermark != (const Image *) NULL); assert(watermark->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1UL; stegano_image=CloneImage(image,0,0,MagickTrue,exception); if (stegano_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stegano_image,DirectClass) == MagickFalse) { InheritException(exception,&stegano_image->exception); stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH; /* Hide watermark in low-order bits of image. */ c=0; i=0; j=0; depth=stegano_image->depth; k=image->offset; status=MagickTrue; watermark_view=AcquireCacheView(watermark); stegano_view=AcquireCacheView(stegano_image); for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++) { for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++) { (void) GetOneCacheViewVirtualPixel(watermark_view,x,y,&pixel,exception); if ((k/(ssize_t) stegano_image->columns) >= (ssize_t) stegano_image->rows) break; q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t) stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1, exception); if (q == (PixelPacket *) NULL) break; switch (c) { case 0: { SetBit(GetRedPixelComponent(q),j,GetBit(PixelIntensityToQuantum( &pixel),i)); break; } case 1: { SetBit(GetGreenPixelComponent(q),j,GetBit(PixelIntensityToQuantum( &pixel),i)); break; } case 2: { SetBit(GetBluePixelComponent(q),j,GetBit(PixelIntensityToQuantum( &pixel),i)); break; } } if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (stegano_image->columns*stegano_image->columns)) k=0; if (k == image->offset) j++; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType) (depth-i),depth); if (proceed == MagickFalse) status=MagickFalse; } } stegano_view=DestroyCacheView(stegano_view); watermark_view=DestroyCacheView(watermark_view); if (stegano_image->storage_class == PseudoClass) (void) SyncImage(stegano_image); if (status == MagickFalse) { stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } return(stegano_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e r e o A n a g l y p h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StereoAnaglyphImage() combines two images and produces a single image that % is the composite of a left and right image of a stereo pair. Special % red-green stereo glasses are required to view this effect. % % The format of the StereoAnaglyphImage method is: % % Image *StereoImage(const Image *left_image,const Image *right_image, % ExceptionInfo *exception) % Image *StereoAnaglyphImage(const Image *left_image, % const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o left_image: the left image. % % o right_image: the right image. % % o exception: return any errors or warnings in this structure. % % o x_offset: amount, in pixels, by which the left image is offset to the % right of the right image. % % o y_offset: amount, in pixels, by which the left image is offset to the % bottom of the right image. % % */ MagickExport Image *StereoImage(const Image *left_image, const Image *right_image,ExceptionInfo *exception) { return(StereoAnaglyphImage(left_image,right_image,0,0,exception)); } MagickExport Image *StereoAnaglyphImage(const Image *left_image, const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define StereoImageTag "Stereo/Image" const Image *image; Image *stereo_image; MagickBooleanType status; ssize_t y; assert(left_image != (const Image *) NULL); assert(left_image->signature == MagickSignature); if (left_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", left_image->filename); assert(right_image != (const Image *) NULL); assert(right_image->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); assert(right_image != (const Image *) NULL); image=left_image; if ((left_image->columns != right_image->columns) || (left_image->rows != right_image->rows)) ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer"); /* Initialize stereo image attributes. */ stereo_image=CloneImage(left_image,left_image->columns,left_image->rows, MagickTrue,exception); if (stereo_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stereo_image,DirectClass) == MagickFalse) { InheritException(exception,&stereo_image->exception); stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } /* Copy left image to red channel and right image to blue channel. */ status=MagickTrue; for (y=0; y < (ssize_t) stereo_image->rows; y++) { register const PixelPacket *restrict p, *restrict q; register ssize_t x; register PixelPacket *restrict r; p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1, exception); q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception); r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL) || (r == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) stereo_image->columns; x++) { SetRedPixelComponent(r,GetRedPixelComponent(p)); SetGreenPixelComponent(r,GetGreenPixelComponent(q)); SetBluePixelComponent(r,GetBluePixelComponent(q)); SetOpacityPixelComponent(r,(GetOpacityPixelComponent(p)+q->opacity)/2); p++; q++; r++; } if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse) break; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y, stereo_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (status == MagickFalse) { stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } return(stereo_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S w i r l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SwirlImage() swirls the pixels about the center of the image, where % degrees indicates the sweep of the arc through which each pixel is moved. % You get a more dramatic effect as the degrees move from 1 to 360. % % The format of the SwirlImage method is: % % Image *SwirlImage(const Image *image,double degrees, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o degrees: Define the tightness of the swirling effect. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SwirlImage(const Image *image,double degrees, ExceptionInfo *exception) { #define SwirlImageTag "Swirl/Image" CacheView *image_view, *swirl_view; Image *swirl_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType radius; PointInfo center, scale; ssize_t y; /* Initialize swirl image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); swirl_image=CloneImage(image,0,0,MagickTrue,exception); if (swirl_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(swirl_image,DirectClass) == MagickFalse) { InheritException(exception,&swirl_image->exception); swirl_image=DestroyImage(swirl_image); return((Image *) NULL); } if (swirl_image->background_color.opacity != OpaqueOpacity) swirl_image->matte=MagickTrue; /* Compute scaling factor. */ center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; radius=MagickMax(center.x,center.y); scale.x=1.0; scale.y=1.0; if (image->columns > image->rows) scale.y=(double) image->columns/(double) image->rows; else if (image->columns < image->rows) scale.x=(double) image->rows/(double) image->columns; degrees=(double) DegreesToRadians(degrees); /* Swirl image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(swirl_image,&zero); image_view=AcquireCacheView(image); swirl_view=AcquireCacheView(swirl_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; MagickRealType distance; PointInfo delta; register IndexPacket *restrict swirl_indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } swirl_indexes=GetCacheViewAuthenticIndexQueue(swirl_view); delta.y=scale.y*(double) (y-center.y); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance < (radius*radius)) { MagickRealType cosine, factor, sine; /* Swirl the pixel. */ factor=1.0-sqrt((double) distance)/radius; sine=sin((double) (degrees*factor*factor)); cosine=cos((double) (degrees*factor*factor)); (void) InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) ((cosine*delta.x-sine*delta.y)/ scale.x+center.x),(double) ((sine*delta.x+cosine*delta.y)/scale.y+ center.y),&pixel,exception); SetPixelPacket(swirl_image,&pixel,q,swirl_indexes+x); } q++; } if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SwirlImage) #endif proceed=SetImageProgress(image,SwirlImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } swirl_view=DestroyCacheView(swirl_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) swirl_image=DestroyImage(swirl_image); return(swirl_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TintImage() applies a color vector to each pixel in the image. The length % of the vector is 0 for black and white and at its maximum for the midtones. % The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))) % % The format of the TintImage method is: % % Image *TintImage(const Image *image,const char *opacity, % const PixelPacket tint,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o opacity: A color value used for tinting. % % o tint: A color value used for tinting. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TintImage(const Image *image,const char *opacity, const PixelPacket tint,ExceptionInfo *exception) { #define TintImageTag "Tint/Image" CacheView *image_view, *tint_view; GeometryInfo geometry_info; Image *tint_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket color_vector, pixel; MagickStatusType flags; ssize_t y; /* Allocate tint image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); tint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (tint_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(tint_image,DirectClass) == MagickFalse) { InheritException(exception,&tint_image->exception); tint_image=DestroyImage(tint_image); return((Image *) NULL); } if (opacity == (const char *) NULL) return(tint_image); /* Determine RGB values of the color. */ flags=ParseGeometry(opacity,&geometry_info); pixel.red=geometry_info.rho; if ((flags & SigmaValue) != 0) pixel.green=geometry_info.sigma; else pixel.green=pixel.red; if ((flags & XiValue) != 0) pixel.blue=geometry_info.xi; else pixel.blue=pixel.red; if ((flags & PsiValue) != 0) pixel.opacity=geometry_info.psi; else pixel.opacity=(MagickRealType) OpaqueOpacity; color_vector.red=(MagickRealType) (pixel.red*tint.red/100.0- PixelIntensity(&tint)); color_vector.green=(MagickRealType) (pixel.green*tint.green/100.0- PixelIntensity(&tint)); color_vector.blue=(MagickRealType) (pixel.blue*tint.blue/100.0- PixelIntensity(&tint)); /* Tint image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); tint_view=AcquireCacheView(tint_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket pixel; MagickRealType weight; weight=QuantumScale*GetRedPixelComponent(p)-0.5; pixel.red=(MagickRealType) GetRedPixelComponent(p)+color_vector.red*(1.0-(4.0* (weight*weight))); SetRedPixelComponent(q,ClampToQuantum(pixel.red)); weight=QuantumScale*GetGreenPixelComponent(p)-0.5; pixel.green=(MagickRealType) GetGreenPixelComponent(p)+color_vector.green*(1.0-(4.0* (weight*weight))); SetGreenPixelComponent(q,ClampToQuantum(pixel.green)); weight=QuantumScale*GetBluePixelComponent(p)-0.5; pixel.blue=(MagickRealType) GetBluePixelComponent(p)+color_vector.blue*(1.0-(4.0* (weight*weight))); SetBluePixelComponent(q,ClampToQuantum(pixel.blue)); SetOpacityPixelComponent(q,GetOpacityPixelComponent(p)); p++; q++; } if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TintImage) #endif proceed=SetImageProgress(image,TintImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } tint_view=DestroyCacheView(tint_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) tint_image=DestroyImage(tint_image); return(tint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V i g n e t t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % VignetteImage() softens the edges of the image in vignette style. % % The format of the VignetteImage method is: % % Image *VignetteImage(const Image *image,const double radius, % const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x, y: Define the x and y ellipse offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *VignetteImage(const Image *image,const double radius, const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) { char ellipse[MaxTextExtent]; DrawInfo *draw_info; Image *canvas_image, *blur_image, *oval_image, *vignette_image; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(canvas_image,DirectClass) == MagickFalse) { InheritException(exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } canvas_image->matte=MagickTrue; oval_image=CloneImage(canvas_image,canvas_image->columns, canvas_image->rows,MagickTrue,exception); if (oval_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } (void) QueryColorDatabase("#000000",&oval_image->background_color,exception); (void) SetImageBackgroundColor(oval_image); draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL); (void) QueryColorDatabase("#ffffff",&draw_info->fill,exception); (void) QueryColorDatabase("#ffffff",&draw_info->stroke,exception); (void) FormatLocaleString(ellipse,MaxTextExtent, "ellipse %g,%g,%g,%g,0.0,360.0",image->columns/2.0, image->rows/2.0,image->columns/2.0-x,image->rows/2.0-y); draw_info->primitive=AcquireString(ellipse); (void) DrawImage(oval_image,draw_info); draw_info=DestroyDrawInfo(draw_info); blur_image=BlurImage(oval_image,radius,sigma,exception); oval_image=DestroyImage(oval_image); if (blur_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } blur_image->matte=MagickFalse; (void) CompositeImage(canvas_image,CopyOpacityCompositeOp,blur_image,0,0); blur_image=DestroyImage(blur_image); vignette_image=MergeImageLayers(canvas_image,FlattenLayer,exception); canvas_image=DestroyImage(canvas_image); return(vignette_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveImage() creates a "ripple" effect in the image by shifting the pixels % vertically along a sine wave whose amplitude and wavelength is specified % by the given parameters. % % The format of the WaveImage method is: % % Image *WaveImage(const Image *image,const double amplitude, % const double wave_length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o amplitude, wave_length: Define the amplitude and wave length of the % sine wave. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *image_view, *wave_view; Image *wave_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType *sine_map; register ssize_t i; ssize_t y; /* Initialize wave image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0* fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse) { InheritException(exception,&wave_image->exception); wave_image=DestroyImage(wave_image); return((Image *) NULL); } if (wave_image->background_color.opacity != OpaqueOpacity) wave_image->matte=MagickTrue; /* Allocate sine map. */ sine_map=(MagickRealType *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (MagickRealType *) NULL) { wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/ wave_length)); /* Wave image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(wave_image,&zero); image_view=AcquireCacheView(image); wave_view=AcquireCacheView(wave_image); (void) SetCacheViewVirtualPixelMethod(image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(wave_view); pixel=zero; for (x=0; x < (ssize_t) wave_image->columns; x++) { (void) InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel, exception); SetPixelPacket(wave_image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_WaveImage) #endif proceed=SetImageProgress(image,WaveImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); image_view=DestroyCacheView(image_view); sine_map=(MagickRealType *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); }
plm.c
/* * plmc * Copyright (c) 2016, John Ingraham * john.ingraham@gmail.com */ #include <stdlib.h> #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdint.h> #include <sys/time.h> #include <assert.h> #include <string.h> /* Optionally include OpenMP with the -fopenmp flag */ #if defined(_OPENMP) #include <omp.h> #endif #include "include/plm.h" #include "include/inference.h" /* Usage pattern */ const char *usage = "plmc\n" "\n" "Usage:\n" " plm [options] alignmentfile\n" " plm -c couplingsfile alignmentfile\n" " plm -o paramfile -c couplingsfile alignmentfile\n" " plm [-h | --help]\n" " \n" " Required input:\n" " alignmentfile Multiple sequence alignment in FASTA format\n" "\n" " Options, output:\n" " -c --couplings couplingsfile Save coupling scores to file (text)\n" " -o --output paramfile Save estimated parameters to file (binary)\n" "\n" " Options, alignment processing:\n" " -s --scale <value> Sequence weights: neighborhood weight [s > 0]\n" " -t --theta <value> Sequence weights: neighborhood divergence [0 < t < 1]\n" "\n" " Options, Maximum a posteriori estimation (L-BFGS, default):\n" " -lh --lambdah <value> Set L2 lambda for fields (h_i)\n" " -le --lambdae <value> Set L2 lambda for couplings (e_ij)\n" " -lg --lambdag <value> Set group L1 lambda for couplings (e_ij)\n" "\n" " Options, general:\n" " -a --alphabet alphabet Alternative character set to use for analysis\n" " -f --focus identifier Select only uppercase, non-gapped sites from a focus sequence\n" " -g --gapignore Model sequence likelihoods only by coding, non-gapped portions\n" " -m --maxiter Maximum number of iterations\n" " -n --ncores [<number>|max] Maximum number of threads to use in OpenMP\n" " -h --help Usage\n\n"; /* Internal functions to MSARead */ void MSAReadSeq(char *seq, FILE *fpAli); letter_t MSAReadCode(char c, char *alphabet, int nCodes); /* Global verbosity & profiling options */ int verbose = 2; /* Reference amino acid indexing */ const char *codesAA = "-ACDEFGHIKLMNPQRSTVWY"; /* Regularization default parameters */ const numeric_t REGULARIZATION_LAMBDA_H = 0.01; const numeric_t REGULARIZATION_LAMBDA_E = 100.0; const numeric_t REGULARIZATION_LAMBDA_GROUP = 0.0; const numeric_t REWEIGHTING_THETA = 0.20; const numeric_t REWEIGHTING_SCALE = 1.0; const int ZERO_APC_PRIORS = 0; int main(int argc, char **argv) { char *alignFile = NULL; char *outputFile = NULL; char *couplingsFile = NULL; /* Default options */ options_t *options = (options_t *) malloc(sizeof(options_t)); options->theta = REWEIGHTING_THETA; options->lambdaH = REGULARIZATION_LAMBDA_H; options->lambdaE = REGULARIZATION_LAMBDA_E; options->lambdaGroup = REGULARIZATION_LAMBDA_GROUP; options->scale = REWEIGHTING_SCALE; options->zeroAPC = 0; options->maxIter = 0; options->usePairs = 1; options->estimator = INFER_MAP; options->estimatorMAP = INFER_MAP_PLM; options->target = NULL; options->alphabet = (char *) codesAA; /* Print usage if no arguments */ if (argc == 1) { fprintf(stderr, "%s", usage); exit(1); } /* Parse command line arguments */ for (int arg = 1; arg < argc; arg++) { if ((arg < argc-1) && (strcmp(argv[arg], "--output") == 0 || strcmp(argv[arg], "-o") == 0)) { outputFile = argv[++arg]; } else if ((arg < argc-1) && (strcmp(argv[arg], "--alphabet") == 0 || strcmp(argv[arg], "-a") == 0)) { options->alphabet = argv[++arg]; } else if ((arg < argc-1) && (strcmp(argv[arg], "--couplings") == 0 || strcmp(argv[arg], "-c") == 0)) { couplingsFile = argv[++arg]; } else if ((arg < argc-1) && (strcmp(argv[arg], "--lambdah") == 0 || strcmp(argv[arg], "-lh") == 0)) { options->lambdaH = atof(argv[++arg]); } else if ((arg < argc-1) && (strcmp(argv[arg], "--lambdae") == 0 || strcmp(argv[arg], "-le") == 0)) { options->lambdaE = atof(argv[++arg]); } else if ((arg < argc-1) && (strcmp(argv[arg], "--lambdag") == 0 || strcmp(argv[arg], "-lg") == 0)) { options->lambdaGroup = atof(argv[++arg]); } else if ((arg < argc-1) && (strcmp(argv[arg], "--theta") == 0 || strcmp(argv[arg], "-t") == 0)) { options->theta = atof(argv[++arg]); } else if ((arg < argc-1) && (strcmp(argv[arg], "--scale") == 0 || strcmp(argv[arg], "-s") == 0)) { options->scale = atof(argv[++arg]); } else if ((arg < argc-1) && (strcmp(argv[arg], "--maxiter") == 0 || strcmp(argv[arg], "-m") == 0)) { options->maxIter = atoi(argv[++arg]); } else if ((arg < argc-1) && (strcmp(argv[arg], "--independent") == 0 || strcmp(argv[arg], "-i") == 0)) { options->usePairs = 0; fprintf(stderr, "Independent model not yet implemented\n"); exit(0); } else if ((arg < argc-1) && (strcmp(argv[arg], "--gapreduce") == 0 || strcmp(argv[arg], "-g") == 0)) { options->estimatorMAP = INFER_MAP_PLM_GAPREDUCE; } else if ((arg < argc-1) && (strcmp(argv[arg], "--estimatele") == 0 || strcmp(argv[arg], "-ee") == 0)) { options->zeroAPC = 1; } else if ((arg < argc-1) && (strcmp(argv[arg], "--focus") == 0 || strcmp(argv[arg], "-f") == 0)) { options->target = argv[++arg]; } else if ((arg < argc-1) && (strcmp(argv[arg], "--ncores") == 0 || strcmp(argv[arg], "-n") == 0)) { #if defined(_OPENMP) if (strcmp(argv[arg + 1], "max") == 0) { int maxThreads = omp_get_max_threads(); /* Redundant, but serves as sanity check */ omp_set_num_threads(maxThreads); fprintf(stderr, "OpenMP: Using %d of %d threads\n", maxThreads, maxThreads); } else { int numThreads = atoi(argv[arg + 1]); int maxThreads = omp_get_max_threads(); if (numThreads >= 1 && numThreads <= maxThreads) { omp_set_num_threads(numThreads); fprintf(stderr, "OpenMP: Using %d of %d threads\n", numThreads, maxThreads); } else if (numThreads > maxThreads) { omp_set_num_threads(maxThreads); fprintf(stderr, "OpenMP: More threads requested than " "available. Using %d of %d threads instead.\n", maxThreads, maxThreads); } else { omp_set_num_threads(1); fprintf(stderr, "OpenMP: Using 1 of %d threads\n", maxThreads); } } arg++; #else fprintf(stderr, "Error (-n/--ncores) only available when " "compiled with OpenMP\n"); exit(1); #endif } else if (strcmp(argv[arg], "--help") == 0 || strcmp(argv[arg], "-h") == 0) { fprintf(stderr, "%s", usage); exit(1); } } alignFile = argv[argc - 1]; /* Read multiple seqence alignment */ alignment_t *ali = MSARead(alignFile, options); /* Reweight sequences by inverse neighborhood density */ MSAReweightSequences(ali, options->theta, options->scale); /* Compute sitwise and pairwise marginal distributions */ MSACountMarginals(ali, options); /* Infer model parameters */ numeric_t *x = InferPairModel(ali, options); /* (Optionally) Output estimated parameters and coupling scores */ if (outputFile != NULL) OutputParametersFull(outputFile, x, ali, options); if (couplingsFile != NULL) OutputCouplingScores(couplingsFile, x, ali, options); /* Free alignment and options */ MSAFree(ali, options); } alignment_t *MSARead(char *alignFile, options_t *options) { /* Read FASTA-formatted alignment */ FILE *fpAli = NULL; if (alignFile != NULL) { fpAli = fopen(alignFile, "r"); } else { fprintf(stderr, "Must specify alignment file: -a ALIGN_FILE\n"); exit(1); } if (fpAli == NULL) { fprintf(stderr, "Error opening alignment file\n"); exit(1); } /* Allocate alignment */ alignment_t *ali = (alignment_t *) malloc(sizeof(alignment_t)); ali->nSeqs = ali->nSites = ali->nCodes = 0; ali->alphabet = options->alphabet; ali->names = NULL; ali->sequences = NULL; ali->target = -1; ali->offsets = NULL; ali->nEff = 0; ali->weights = ali->fi = ali->fij = NULL; ali->nParams = 0; /* Verify alignment dimensions and structure (first pass through file) */ char name[BUFFER_SIZE]; char seq[BUFFER_SIZE]; /* Read first line as name */ fgetstr(name, fpAli); if (*name == '>') { MSAReadSeq(seq, fpAli); } else { fprintf(stderr, "Error reading alignment:" " First line should start with >\n"); exit(1); } ali->nCodes = strlen(ali->alphabet); ali->nSites = strlen(seq); ali->nSeqs = 1; while (!feof(fpAli)) { char c = fgetc(fpAli); if (c == '>') { /* Read name and sequence pair */ fgetstr(name, fpAli); MSAReadSeq(seq, fpAli); } else { fprintf(stderr, "Error reading alignment:" " sequence records should start with >\n"); exit(1); } /* Validate sequence length */ if (strlen(seq) != ali->nSites) { fprintf(stderr, "Incompatible sequence length (%lu should be %d) for %s:\n%s\n", strlen(seq), ali->nSites, name, seq); exit(1); } ali->nSeqs++; } /* Encode full alignment block (second pass through file) */ ali->sequences = (letter_t *) malloc(ali->nSites * ali->nSeqs * sizeof(letter_t)); ali->names = (char **) malloc(ali->nSeqs * sizeof(char *)); for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites; i++) seq(s, i) = 0; for (int s = 0; s < ali->nSeqs; s++) ali->names[s] = NULL; rewind(fpAli); for (int s = 0; s < ali->nSeqs; s++) { /* >Name */ getc(fpAli); fgetstr(name, fpAli); ali->names[s] = (char *) malloc((strlen(name) + 1) * sizeof(char)); strcpy(ali->names[s], name); /* Sequence */ MSAReadSeq(seq, fpAli); for (int i = 0; i < ali->nSites; i++) seq(s, i) = MSAReadCode(seq[i], ali->alphabet, ali->nCodes); } /* --------------------------------_DEBUG_--------------------------------*/ /* Alignment to stderr */ // for (int s = 0; s < 10; s++) { // for (int s = 0; s < ali->nSeqs; s++) { // for (int i = 0; i < ali->nSites; i++) // if (seq(s, i) >= 0 && seq(s, i) < ali->nCodes) { // fprintf(stderr, "%c", ali->alphabet[seq(s, i)]); // } else if (seq(s, i) >= -ali->nCodes && seq(s, i) < 0) { // fprintf(stderr, "%c", // tolower(ali->alphabet[seq(s, i) + ali->nCodes])); // } else { // fprintf(stderr, "*%d*", seq(s, i)); // } // fprintf(stderr, "\n"); // } // exit(0); /* --------------------------------^DEBUG^--------------------------------*/ /* Focus mode: If a focus sequence (target) is provided, locate it */ if (options->target != NULL) { for (int s = 0; s < ali->nSeqs; s++) if (strncmp(options->target, ali->names[s], strlen(options->target)) == 0) { if (ali->target >= 0) { fprintf(stderr, "Multiple sequences start with %s, picking sequence %d\n", options->target, s + 1); } else { ali->target = s; } } if (ali->target >= 0) { fprintf(stderr, "Found focus %s as sequence %d\n", options->target, ali->target + 1); } else { fprintf(stderr, "Could not find %s, proceeding without focus sequence\n", options->target); } } /* Always discard any sequences (rows) with out-of-alphabet characters */ int* seqValid = (int *) malloc(ali->nSeqs * sizeof(int)); for (int s = 0; s < ali->nSeqs; s++) seqValid[s] = 0; for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites; i++) if ((seq(s, i) >= -ali->nCodes) && (seq(s, i) < ali->nCodes)) seqValid[s]++; int nValidSeqs = 0; for (int s = 0; s < ali->nSeqs; s++) if (seqValid[s] == ali->nSites) nValidSeqs++; fprintf(stderr, "%d valid sequences out of %d \n", nValidSeqs, ali->nSeqs); /* Recored indices of skipped sequences */ ali->nSkippedSeqs = ali->nSeqs - nValidSeqs; ali->skippedSeqs = (int *) malloc(ali->nSkippedSeqs * sizeof(int)); for (int s = 0, skipIndex = 0; s < ali->nSeqs; s++) if (seqValid[s] != ali->nSites) ali->skippedSeqs[skipIndex++] = s; /* Focus mode: select only focus columns (criteria below) */ int nValidSites = ali->nSites; int* siteValid = (int *) malloc(ali->nSites * sizeof(int)); for (int i = 0; i < ali->nSites; i++) siteValid[i] = 1; if (ali->target >= 0) { for (int i = 0; i < ali->nSites; i++) { /* For proteins, remove lower case and gap columns */ if ((ali->alphabet == codesAA) && (seq(ali->target, i) < 0)) siteValid[i] = 0; /* Discard gaps */ if ((ali->alphabet == codesAA) || (options->estimatorMAP == INFER_MAP_PLM_GAPREDUCE)) if (seq(ali->target, i) == 0) siteValid[i] = 0; } nValidSites = 0; for (int i = 0; i < ali->nSites; i++) if (siteValid[i] == 1) nValidSites++; fprintf(stderr, "%d sites out of %d\n", nValidSites, ali->nSites); } else { fprintf(stderr, "%d sites\n", ali->nSites); } /* Focus mode: parse region (NAME/START_IX-END_IX) and map offsets */ int leftOffset = 0; if (ali->target >= 0) { char *focusName = ali->names[ali->target]; /* Name should be immediately followed by '/' */ if (strlen(focusName) > strlen(options->target) + 1 && focusName[strlen(options->target)] == '/') { /* Attempt to read integer region start */ int regLeft = strlen(options->target) + 1; int ix = 0; if (isdigit(focusName[regLeft])) { while (regLeft + ix < strlen(focusName) && isdigit(focusName[regLeft + ix + 1])) ix++; int tens = 1; leftOffset = -1; for (int i = ix; i >= 0; i--) { leftOffset += tens * (focusName[regLeft + i] - '0'); tens *= 10; } fprintf(stderr, "Region starts at %d\n", leftOffset + 1); } else { fprintf(stderr, "Error parsing region, assuming start at 1"); } } /* Map the offsets */ ali->offsets = (int *) malloc(nValidSites * sizeof(int)); for (int i = 0; i < nValidSites; i++) ali->offsets[i] = i + 1; int ix = 0; for (int i = 0; i < ali->nSites; i++) if (siteValid[i] == 1) { ali->offsets[ix] = i + 1 + leftOffset; ix++; } /* Reposition the target for reduced alignment */ int targetShift = -1; for (int i = 0; i <= ali->target; i++) if (seqValid[i] == ali->nSites) targetShift++; ali->target = targetShift; } /* Copy only selected rows and columns */ if (nValidSeqs < ali->nSeqs || nValidSites < ali->nSites) { letter_t *seqsReduced = (letter_t *) malloc(nValidSites * nValidSeqs * sizeof(letter_t)); for (int i = 0; i < nValidSites * nValidSeqs; i++) seqsReduced[i] = 0; int sx = 0; for (int s = 0; s < ali->nSeqs; s++) if (seqValid[s] == ali->nSites) { int ix = 0; for (int i = 0; i < ali->nSites; i++) { if (siteValid[i] == 1) { seqsReduced[ix + sx * nValidSites] = seq(s, i); ix++; } } sx++; } /* Reallocate alignment with reduced dimensions */ free(ali->sequences); ali->nSeqs = nValidSeqs; ali->nSites = nValidSites; ali->sequences = (letter_t *) malloc(nValidSites * nValidSeqs * sizeof(letter_t)); for (int i = 0; i < nValidSites * nValidSeqs; i++) ali->sequences[i] = 0; for (int s = 0; s < nValidSeqs; s++) for (int i = 0; i < nValidSites; i++) seq(s, i) = seqsReduced[i + s * nValidSites]; free(seqsReduced); } /* Shift any lowercase codes back to uppercase */ for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites; i++) if (seq(s, i) < 0) seq(s, i) += ali->nCodes; /* Intialize weights to 1.0 */ ali->weights = (numeric_t *) malloc(ali->nSeqs * sizeof(numeric_t)); for (int s = 0; s < ali->nSeqs; s++) ali->weights[s] = 1.0; ali->nEff = (numeric_t) ali->nSeqs; /* --------------------------------_DEBUG_--------------------------------*/ /* Display offset map */ // for (int i = 0; i < ali->nSites; i++) { // fprintf(stderr, "%d : %d : %c\n", i + 1, ali->offsets[i], // ali->alphabet[seq(ali->target, i)]); // } // exit(0); /* Display target */ // for (int i = 0; i < ali->nSites; i++) { // fprintf(stderr, "%c", ali->alphabet[seq(ali->target, i)]); // } // fprintf(stderr, "\n"); // exit(0); /* --------------------------------^DEBUG^--------------------------------*/ /* --------------------------------_DEBUG_--------------------------------*/ // for (int s = 0; s < ali->nSeqs; s++) { // fprintf(stderr, ">%s\n", ali->names[s]); // for (int i = 0; i < ali->nSites; i++) // fprintf(stderr, "%c", ali->alphabet[seq(s, i)]); // fprintf(stderr, "\n"); // } /* --------------------------------^DEBUG^--------------------------------*/ return ali; } void MSAReadSeq(char *seq, FILE *fpAli) { /* Read sequence from the current line(s) */ char buf[BUFFER_SIZE]; /* Look ahead one character */ char c = fgetc(fpAli); ungetc(c, fpAli); seq[0] = '\0'; while (c != '>' && !feof(fpAli)) { fgetstr(buf, fpAli); strcat(seq, buf); /* Look ahead one character */ c = fgetc(fpAli); ungetc(c, fpAli); } } letter_t MSAReadCode(char c, char *alphabet, int nCodes) { /* Encode a character as an integer between -nCodes and +nCodes In alphabet: store index [0, nCodes - 1] Lowercase version of alphabet: downshift by nCodes [-nCodes, -1] Out of alphabet: store nCodes [nCodes] */ letter_t i = 0; /* Protein-specific treatment of '.' */ if (alphabet == codesAA) if (c == '.') c = '-'; /* Store lowercase characters as down-shifted by nCodes */ while ((i < nCodes - 1) && toupper(c) != alphabet[i]) i++; if (c != alphabet[i] && toupper(c) == alphabet[i]) i -= nCodes; /* Encode out-of-alphabet characters by [nCodes] */ if (i > 0 && toupper(c) != alphabet[i]) i = nCodes; return i; } void MSAReweightSequences(alignment_t *ali, numeric_t theta, numeric_t scale) { /* Reweight seqeuences by their inverse neighborhood size. Each sequence's weight is the inverse of the number of neighboring sequences with less than THETA percent divergence */ for (int i = 0; i < ali->nSeqs; i++) ali->weights[i] = 1.0; /* Only apply reweighting if theta is on [0,1] */ if (theta >= 0 && theta <= 1) { /* The neighborhood size of each sequence is the number of sequences in the alignment within theta percent divergence */ #if defined(_OPENMP) /* Naive parallelization is faster ignoring symmetry */ #pragma omp parallel for for (int s = 0; s < ali->nSeqs; s++) for (int t = 0; t < ali->nSeqs; t++) if (s != t) { int id = 0; for (int n = 0; n < ali->nSites; n++) id += (seq(s, n) == seq(t, n)); if (id >= ((1 - theta) * ali->nSites)) ali->weights[s] += 1.0; } #else /* For a single core, take advantage of symmetry */ for (int s = 0; s < ali->nSeqs - 1; s++) for (int t = s + 1; t < ali->nSeqs; t++) { int id = 0; for (int n = 0; n < ali->nSites; n++) id += (seq(s, n) == seq(t, n)); if (id >= ((1 - theta) * ali->nSites)) { ali->weights[s] += 1.0; ali->weights[t] += 1.0; } } #endif /* Reweight sequences by the inverse of the neighborhood size */ for (int i = 0; i < ali->nSeqs; i++) ali->weights[i] = 1.0 / ali->weights[i]; } /* Scale sets the effective number of samples per neighborhood */ for (int i = 0; i < ali->nSeqs; i++) ali->weights[i] *= scale; /* The effective number of sequences is then the sum of the weights */ ali->nEff = 0; for (int i = 0; i < ali->nSeqs; i++) ali->nEff += ali->weights[i]; if (theta >= 0 && theta <= 1) { fprintf(stderr, "Effective number of samples: %.1f\t(%.0f%% identical neighborhood = %.3f samples)\n", ali->nEff, 100 * (1 - theta), scale); } else { fprintf(stderr, "Theta not between 0 and 1, no sequence reweighting applied\n"); } } void MSACountMarginals(alignment_t *ali, options_t *options) { /* Compute first and second order marginal distributions, according to the sequence weights */ if (options->estimatorMAP == INFER_MAP_PLM_GAPREDUCE) { /* Condition the marginals on ungapped */ ali->nCodes = strlen(ali->alphabet) - 1; /* First-order marginals P_i(Ai) */ int nFi = ali->nSites * ali->nCodes; ali->fi = (numeric_t *) malloc(nFi * sizeof(numeric_t)); for (int i = 0; i < nFi; i++) ali->fi[i] = 0.0; for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites; i++) if (seq(s, i) > 0) fi(i, seq(s, i) - 1) += ali->weights[s]; /* Second-order marginals P_ij(Ai, Aj) */ int nFij = ali->nSites * (ali->nSites - 1) / 2 * ali->nCodes * ali->nCodes; ali->fij = (numeric_t *) malloc(nFij * sizeof(numeric_t)); for (int i = 0; i < nFij; i++) ali->fij[i] = 0.0; for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) if (seq(s, i) > 0) if(seq(s, j) > 0) fij(i, j, seq(s, i) - 1, seq(s, j) - 1) += ali->weights[s]; /* Normalize conditional distributions */ for (int i = 0; i < ali->nSites; i++) { double fsum = 0.0; for (int ai = 0; ai < ali->nCodes; ai++) fsum += fi(i, ai); if (fsum != 0) { double fsumInv = 1.0 / fsum; for (int ai = 0; ai < ali->nCodes; ai++) fi(i, ai) *= fsumInv; } else { /* Handle empty columns */ numeric_t flatF = 1.0 / ((numeric_t) ali->nCodes); for (int ai = 0; ai < ali->nCodes; ai++) fi(i, ai) = flatF; } } for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) { double fsum = 0.0; for (int ai = 0; ai < ali->nCodes; ai++) for (int aj = 0; aj < ali->nCodes; aj++) fsum += fij(i, j, ai, aj); if (fsum != 0) { double fsumInv = 1.0 / fsum; for (int ai = 0; ai < ali->nCodes; ai++) for (int aj = 0; aj < ali->nCodes; aj++) fij(i, j, ai, aj) *= fsumInv; } else { /* Handle pairs of empty columns */ numeric_t flatF = 1.0 / ((numeric_t) (ali->nCodes * ali->nCodes)); for (int ai = 0; ai < ali->nCodes; ai++) for (int aj = 0; aj < ali->nCodes; aj++) fij(i, j, ai, aj) = flatF; } } } else { /* Compute regular marginals */ numeric_t Zinv = 1.0 / ali->nEff; /* First-order marginals P_i(Ai) */ int nFi = ali->nSites * ali->nCodes; ali->fi = (numeric_t *) malloc(nFi * sizeof(numeric_t)); for (int i = 0; i < nFi; i++) ali->fi[i] = 0.0; for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites; i++) fi(i, seq(s, i)) += ali->weights[s] * Zinv; /* Second-order marginals P_ij(Ai, Aj) */ int nFij = ali->nSites * (ali->nSites - 1) / 2 * ali->nCodes * ali->nCodes; ali->fij = (numeric_t *) malloc(nFij * sizeof(numeric_t)); for (int i = 0; i < nFij; i++) ali->fij[i] = 0.0; for (int s = 0; s < ali->nSeqs; s++) for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) fij(i, j, seq(s, i), seq(s, j)) += ali->weights[s] * Zinv; } } void MSAFree(alignment_t *ali, options_t *options) { /* Free alignment and options */ if (ali->names && ali->names[0]) for (int i = 0; i < ali->nSeqs; i++) free(ali->names[i]); free(ali->names); free(ali->sequences); free(ali->weights); free(ali->fi); free(ali->fij); /* Note: options->target and options->alphabet are never allocated */ free(options); } #define OUTPUT_PRECISION float void OutputParametersSite(char *outputFile, const numeric_t *x, alignment_t *ali) { FILE *fpOutput = NULL; fpOutput = fopen(outputFile, "w"); if (fpOutput != NULL) { /* 1: nSites */ fwrite(&(ali->nSites), sizeof(ali->nSites), 1, fpOutput); /* 2: (Focus mode only) target sequence */ if (ali->target >= 0) { for (int i = 0; i < ali->nSites; i++) { char c = (char) ali->alphabet[seq(ali->target, i)]; fwrite(&c, sizeof(char), 1, fpOutput); } } else { char c = ali->alphabet[0]; for (int i = 0; i < ali->nSites; i++) fwrite(&c, sizeof(c), 1, fpOutput); } /* 3: (Focus mode only) offset map */ if (ali->target >= 0) { for (int i = 0; i < ali->nSites; i++) { int ix = ali->offsets[i]; fwrite(&ix, sizeof(ix), 1, fpOutput); } } else { for (int i = 0; i < ali->nSites; i++) { int ix = i + 1; fwrite(&ix, sizeof(ix), 1, fpOutput); } } /* 4,5: sitewise marginals fi, twice */ for (int x = 0; x < 2; x++) for (int i = 0; i < ali->nSites; i++) for (int ai = 0; ai < ali->nCodes; ai++) { OUTPUT_PRECISION f = (OUTPUT_PRECISION) fi(i, ai); fwrite(&f, sizeof(f), 1, fpOutput); } /* 6: sitewise parameters hi */ for (int i = 0; i < ali->nSites; i++) for (int ai = 0; ai < ali->nCodes; ai++) { OUTPUT_PRECISION h = (OUTPUT_PRECISION) xHi(i, ai); fwrite(&h, sizeof(h), 1, fpOutput); } fclose(fpOutput); } else { fprintf(stderr, "Error writing parameters\n"); exit(1); } } void OutputParametersFull(char *outputFile, const numeric_t *x, alignment_t *ali, options_t *options) { /* File format */ FILE *fpOutput = NULL; fpOutput = fopen(outputFile, "w"); if (fpOutput != NULL) { /* 1: nSites */ int32_t nSites = (int32_t) ali->nSites; fwrite(&nSites, sizeof(nSites), 1, fpOutput); /* 2: nCodes */ int32_t nCodes = (int32_t) ali->nCodes; fwrite(&nCodes, sizeof(nCodes), 1, fpOutput); /* 3: nSeqs */ int32_t nSeqs = (int32_t) ali->nSeqs; fwrite(&nSeqs, sizeof(nSeqs), 1, fpOutput); /* 4: nSkippedSeqs */ int32_t nSkippedSeqs = (int32_t) ali->nSkippedSeqs; fwrite(&nSkippedSeqs, sizeof(nSkippedSeqs), 1, fpOutput); /* 5: number of iterations */ int32_t maxIter = (int32_t) options->maxIter; fwrite(&maxIter, sizeof(maxIter), 1, fpOutput); /* 6: theta */ OUTPUT_PRECISION theta = (OUTPUT_PRECISION) options->theta; fwrite(&theta, sizeof(theta), 1, fpOutput); /* 7: lambda for fields (lh) */ OUTPUT_PRECISION lh = (OUTPUT_PRECISION) options->lambdaH; fwrite(&lh, sizeof(lh), 1, fpOutput); /* 8: lambda for couplings (le) */ OUTPUT_PRECISION le = (OUTPUT_PRECISION) options->lambdaE; fwrite(&le, sizeof(le), 1, fpOutput); /* 9: group lambda for couplings (lg) */ OUTPUT_PRECISION lg = (OUTPUT_PRECISION) options->lambdaGroup; fwrite(&lg, sizeof(lg), 1, fpOutput); /* 10: effective sample size (nEff) */ OUTPUT_PRECISION nEff = (OUTPUT_PRECISION) ali->nEff; fwrite(&nEff, sizeof(nEff), 1, fpOutput); /* 11: alphabet */ int isGapped = (options->estimatorMAP == INFER_MAP_PLM_GAPREDUCE); for (int i = 0; i < ali->nCodes; i++) { int8_t letter = (int8_t) ali->alphabet[i + isGapped]; fwrite(&letter, sizeof(letter), 1, fpOutput); } /* 12: sequence number of neighbors (self included) */ int skipix = 0, reducedix = 0; for (int s = 0; s < ali->nSeqs + ali->nSkippedSeqs; s++) { if (skipix < ali->nSkippedSeqs && s == ali->skippedSeqs[skipix]) { /* Skip skipped sequences */ OUTPUT_PRECISION w = (OUTPUT_PRECISION) 0; fwrite(&w, sizeof(w), 1, fpOutput); skipix++; } else { numeric_t nNeighbors = ali->weights[reducedix]; nNeighbors = 1.0 / (nNeighbors * options->scale); OUTPUT_PRECISION w = (OUTPUT_PRECISION) nNeighbors; fwrite(&w, sizeof(w), 1, fpOutput); reducedix++; } } /* 13: (Focus mode) target sequence */ if (ali->target >= 0) { for (int i = 0; i < ali->nSites; i++) { int8_t c = (int8_t) ali->alphabet[seq(ali->target, i)]; fwrite(&c, sizeof(c), 1, fpOutput); } } else { int8_t c = (int8_t) ali->alphabet[0]; for (int i = 0; i < ali->nSites; i++) fwrite(&c, sizeof(c), 1, fpOutput); } /* 14: (Focus mode) offset map */ if (ali->target >= 0) { for (int i = 0; i < ali->nSites; i++) { int32_t ix = (int32_t) ali->offsets[i]; fwrite(&ix, sizeof(ix), 1, fpOutput); } } else { for (int i = 0; i < ali->nSites; i++) { int32_t ix = (int32_t) i + 1; fwrite(&ix, sizeof(ix), 1, fpOutput); } } /* 15: sitewise marginals fi */ for (int i = 0; i < ali->nSites; i++) for (int ai = 0; ai < ali->nCodes; ai++) { OUTPUT_PRECISION f = (OUTPUT_PRECISION) fi(i, ai); fwrite(&f, sizeof(f), 1, fpOutput); } /* 16: sitewise parameters hi */ for (int i = 0; i < ali->nSites; i++) for (int ai = 0; ai < ali->nCodes; ai++) { OUTPUT_PRECISION h = (OUTPUT_PRECISION) xHi(i, ai); fwrite(&h, sizeof(h), 1, fpOutput); } /* 17: pairwise marginals fij */ for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) for (int ai = 0; ai < ali->nCodes; ai++) for (int aj = 0; aj < ali->nCodes; aj++) { OUTPUT_PRECISION f = (OUTPUT_PRECISION) fij(i, j, ai, aj); fwrite(&f, sizeof(f), 1, fpOutput); } /* 18: couplings eij */ for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) for (int ai = 0; ai < ali->nCodes; ai++) for (int aj = 0; aj < ali->nCodes; aj++) { OUTPUT_PRECISION e = (OUTPUT_PRECISION) xEij(i, j, ai, aj); fwrite(&e, sizeof(e), 1, fpOutput); } fclose(fpOutput); } else { fprintf(stderr, "Error writing parameters\n"); exit(1); } } #undef OUTPUT_PRECISION void OutputCouplingScores(char *couplingsFile, const numeric_t *x, alignment_t *ali, options_t *options) { FILE *fpOutput = NULL; fpOutput = fopen(couplingsFile, "w"); if (fpOutput != NULL) { /* Compute the norm of the coupling parameters between each pair */ numeric_t *couplings = (numeric_t *) malloc((ali->nSites * (ali->nSites - 1) / 2) * sizeof(numeric_t)); for (int i = 0; i < ali->nSites * (ali->nSites - 1) / 2; i++) couplings[i] = 0; for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) { /* Norm(eij) over ai, aj */ numeric_t norm = 0.0; for (int ai = 0; ai < ali->nCodes; ai++) for (int aj = 0; aj < ali->nCodes; aj++) norm += xEij(i, j, ai, aj) * xEij(i, j, ai, aj); norm = sqrt(norm); coupling(i, j) = norm; } numeric_t nPairs = ((numeric_t) ((ali->nSites) * (ali->nSites - 1))) / 2.0; /* Remove first component of the norms (Average Product Correction) */ if (!options->zeroAPC) { /* Determine the site-wise statistics of the norms */ numeric_t C_avg = 0.0; numeric_t *C_pos_avg = (numeric_t *) malloc(ali->nSites * sizeof(numeric_t)); for (int i = 0; i < ali->nSites; i++) { C_pos_avg[i] = 0.0; } for (int i = 0; i < ali->nSites - 1; i++) { for (int j = i + 1; j < ali->nSites; j++) { C_pos_avg[i] += coupling(i, j) / (numeric_t) (ali->nSites - 1); C_pos_avg[j] += coupling(i, j) / (numeric_t) (ali->nSites - 1); C_avg += coupling(i, j) / nPairs; } } /* Remove the first component */ for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) coupling(i, j) = coupling(i, j) - C_pos_avg[i] * C_pos_avg[j] / C_avg; } /* Output scores */ if (ali->target >= 0) { /* Focus mode */ for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) { char ai = (char) ali->alphabet[seq(ali->target, i)]; char aj = (char) ali->alphabet[seq(ali->target, j)]; fprintf(fpOutput, "%d %c %d %c 0 %f\n", ali->offsets[i], ai, ali->offsets[j], aj, coupling(i, j)); } } else { for (int i = 0; i < ali->nSites - 1; i++) for (int j = i + 1; j < ali->nSites; j++) fprintf(fpOutput, "%d - %d - 0 %f\n", i + 1, j + 1, coupling(i, j)); } fclose(fpOutput); } else { fprintf(stderr, "Error writing coupling scores\n"); exit(1); } }
omp_loop2.c
/* vim: set ts=4 sw=4: */ /* Filename : omp_loop2.c * Description : simple OpenMP model * Author : SunYoung Kim <sunyzero@gmail.com> * Notes : */ #include <stdio.h> #include <omp.h> int main() { int i; /* combine two clauses */ #pragma omp parallel for for (i=0; i<8; i++) { printf("[%d] Hello OpenMP\n", i); } /* implicit barrier */ return 0; }
GB_binop__band_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__band_int32) // A.*B function (eWiseMult): GB (_AemultB_08__band_int32) // A.*B function (eWiseMult): GB (_AemultB_02__band_int32) // A.*B function (eWiseMult): GB (_AemultB_04__band_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_int32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__band_int32) // C+=b function (dense accum): GB (_Cdense_accumb__band_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_int32) // C=scalar+B GB (_bind1st__band_int32) // C=scalar+B' GB (_bind1st_tran__band_int32) // C=A+scalar GB (_bind2nd__band_int32) // C=A'+scalar GB (_bind2nd_tran__band_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) & (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BAND || GxB_NO_INT32 || GxB_NO_BAND_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__band_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__band_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__band_int32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__band_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__band_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__band_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__band_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__band_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__band_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) & (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
tls-1.c
// { dg-do compile } // { dg-require-effective-target tls } int tp1; static int tp2; extern int tp3; int tp4 = 1; static int tp5 = 1; #pragma omp threadprivate (tp1, tp2, tp3, tp4, tp5) #pragma omp threadprivate (undef) // { dg-error "undeclared" } int tp6; int foo(void) { return tp6; } #pragma omp threadprivate (tp6) // { dg-error "after first use" }
stream.c
/*-----------------------------------------------------------------------*/ /* Program: STREAM */ /* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */ /* Original code developed by John D. McCalpin */ /* Programmers: John D. McCalpin */ /* Joe R. Zagar */ /* */ /* This program measures memory transfer rates in MB/s for simple */ /* computational kernels coded in C. */ /*-----------------------------------------------------------------------*/ /* Copyright 1991-2013: John D. McCalpin */ /*-----------------------------------------------------------------------*/ /* License: */ /* 1. You are free to use this program and/or to redistribute */ /* this program. */ /* 2. You are free to modify this program for your own use, */ /* including commercial use, subject to the publication */ /* restrictions in item 3. */ /* 3. You are free to publish results obtained from running this */ /* program, or from works that you derive from this program, */ /* with the following limitations: */ /* 3a. In order to be referred to as "STREAM benchmark results", */ /* published results must be in conformance to the STREAM */ /* Run Rules, (briefly reviewed below) published at */ /* http://www.cs.virginia.edu/stream/ref.html */ /* and incorporated herein by reference. */ /* As the copyright holder, John McCalpin retains the */ /* right to determine conformity with the Run Rules. */ /* 3b. Results based on modified source code or on runs not in */ /* accordance with the STREAM Run Rules must be clearly */ /* labelled whenever they are published. Examples of */ /* proper labelling include: */ /* "tuned STREAM benchmark results" */ /* "based on a variant of the STREAM benchmark code" */ /* Other comparable, clear, and reasonable labelling is */ /* acceptable. */ /* 3c. Submission of results to the STREAM benchmark web site */ /* is encouraged, but not required. */ /* 4. Use of this program or creation of derived works based on this */ /* program constitutes acceptance of these licensing restrictions. */ /* 5. Absolutely no warranty is expressed or implied. */ /*-----------------------------------------------------------------------*/ # include <stdio.h> # include <unistd.h> # include <math.h> # include <float.h> # include <limits.h> # include <sys/time.h> /*----------------------------------------------------------------------- * INSTRUCTIONS: * * 1) STREAM requires different amounts of memory to run on different * systems, depending on both the system cache size(s) and the * granularity of the system timer. * You should adjust the value of 'STREAM_ARRAY_SIZE' (below) * to meet *both* of the following criteria: * (a) Each array must be at least 4 times the size of the * available cache memory. I don't worry about the difference * between 10^6 and 2^20, so in practice the minimum array size * is about 3.8 times the cache size. * Example 1: One Xeon E3 with 8 MB L3 cache * STREAM_ARRAY_SIZE should be >= 4 million, giving * an array size of 30.5 MB and a total memory requirement * of 91.5 MB. * Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP) * STREAM_ARRAY_SIZE should be >= 20 million, giving * an array size of 153 MB and a total memory requirement * of 458 MB. * (b) The size should be large enough so that the 'timing calibration' * output by the program is at least 20 clock-ticks. * Example: most versions of Windows have a 10 millisecond timer * granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds. * If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec. * This means the each array must be at least 1 GB, or 128M elements. * * Version 5.10 increases the default array size from 2 million * elements to 10 million elements in response to the increasing * size of L3 caches. The new default size is large enough for caches * up to 20 MB. * Version 5.10 changes the loop index variables from "register int" * to "ssize_t", which allows array indices >2^32 (4 billion) * on properly configured 64-bit systems. Additional compiler options * (such as "-mcmodel=medium") may be required for large memory runs. * * Array size can be set at compile time without modifying the source * code for the (many) compilers that support preprocessor definitions * on the compile line. E.g., * gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M * will override the default size of 10M with a new size of 100M elements * per array. */ #ifndef STREAM_ARRAY_SIZE # define STREAM_ARRAY_SIZE 10000000 #endif /* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result * for any iteration after the first, therefore the minimum value * for NTIMES is 2. * There are no rules on maximum allowable values for NTIMES, but * values larger than the default are unlikely to noticeably * increase the reported performance. * NTIMES can also be set on the compile line without changing the source * code using, for example, "-DNTIMES=7". */ #ifdef NTIMES #if NTIMES<=1 # define NTIMES 10 #endif #endif #ifndef NTIMES # define NTIMES 10 #endif /* Users are allowed to modify the "OFFSET" variable, which *may* change the * relative alignment of the arrays (though compilers may change the * effective offset by making the arrays non-contiguous on some systems). * Use of non-zero values for OFFSET can be especially helpful if the * STREAM_ARRAY_SIZE is set to a value close to a large power of 2. * OFFSET can also be set on the compile line without changing the source * code using, for example, "-DOFFSET=56". */ #ifndef OFFSET # define OFFSET 0 #endif /* * 3) Compile the code with optimization. Many compilers generate * unreasonably bad code before the optimizer tightens things up. * If the results are unreasonably good, on the other hand, the * optimizer might be too smart for me! * * For a simple single-core version, try compiling with: * cc -O stream.c -o stream * This is known to work on many, many systems.... * * To use multiple cores, you need to tell the compiler to obey the OpenMP * directives in the code. This varies by compiler, but a common example is * gcc -O -fopenmp stream.c -o stream_omp * The environment variable OMP_NUM_THREADS allows runtime control of the * number of threads/cores used when the resulting "stream_omp" program * is executed. * * To run with single-precision variables and arithmetic, simply add * -DSTREAM_TYPE=float * to the compile line. * Note that this changes the minimum array sizes required --- see (1) above. * * The preprocessor directive "TUNED" does not do much -- it simply causes the * code to call separate functions to execute each kernel. Trivial versions * of these functions are provided, but they are *not* tuned -- they just * provide predefined interfaces to be replaced with tuned code. * * * 4) Optional: Mail the results to mccalpin@cs.virginia.edu * Be sure to include info that will help me understand: * a) the computer hardware configuration (e.g., processor model, memory type) * b) the compiler name/version and compilation flags * c) any run-time information (such as OMP_NUM_THREADS) * d) all of the output from the test case. * * Thanks! * *-----------------------------------------------------------------------*/ # define HLINE "-------------------------------------------------------------\n" # ifndef MIN # define MIN(x,y) ((x)<(y)?(x):(y)) # endif # ifndef MAX # define MAX(x,y) ((x)>(y)?(x):(y)) # endif #ifndef STREAM_TYPE #define STREAM_TYPE double #endif static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET], b[STREAM_ARRAY_SIZE+OFFSET], c[STREAM_ARRAY_SIZE+OFFSET]; static double avgtime[4] = {0}, maxtime[4] = {0}, mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX}; static char *label[4] = {"Copy: ", "Scale: ", "Add: ", "Triad: "}; static double bytes[4] = { 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE }; extern double mysecond(); extern void checkSTREAMresults(); #ifdef TUNED extern void tuned_STREAM_Copy(); extern void tuned_STREAM_Scale(STREAM_TYPE scalar); extern void tuned_STREAM_Add(); extern void tuned_STREAM_Triad(STREAM_TYPE scalar); #endif #ifdef _OPENMP extern int omp_get_num_threads(); #endif int main() { int quantum, checktick(); int BytesPerWord; int k; ssize_t j; STREAM_TYPE scalar; double t, times[4][NTIMES]; /* --- SETUP --- determine precision and check timing --- */ printf(HLINE); printf("STREAM version $Revision: 5.10 $\n"); printf(HLINE); BytesPerWord = sizeof(STREAM_TYPE); printf("This system uses %d bytes per array element.\n", BytesPerWord); printf(HLINE); #ifdef N printf("***** WARNING: ******\n"); printf(" It appears that you set the preprocessor variable N when compiling this code.\n"); printf(" This version of the code uses the preprocesor variable STREAM_ARRAY_SIZE to control the array size\n"); printf(" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n",(unsigned long long) STREAM_ARRAY_SIZE); printf("***** WARNING: ******\n"); #endif printf("Array size = %llu (elements), Offset = %d (elements)\n" , (unsigned long long) STREAM_ARRAY_SIZE, OFFSET); printf("Memory per array = %.1f MiB (= %.1f GiB).\n", BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0), BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0/1024.0)); printf("Total memory required = %.1f MiB (= %.1f GiB).\n", (3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.), (3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024./1024.)); printf("Each kernel will be executed %d times.\n", NTIMES); printf(" The *best* time for each kernel (excluding the first iteration)\n"); printf(" will be used to compute the reported bandwidth.\n"); #ifdef _OPENMP printf(HLINE); #pragma omp parallel { #pragma omp master { k = omp_get_num_threads(); printf ("Number of Threads requested = %i\n",k); } } #endif #ifdef _OPENMP k = 0; #pragma omp parallel #pragma omp atomic k++; printf ("Number of Threads counted = %i\n",k); #endif /* Get initial value for system clock. */ #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) { a[j] = 1.0; b[j] = 2.0; c[j] = 0.0; } printf(HLINE); if ( (quantum = checktick()) >= 1) printf("Your clock granularity/precision appears to be " "%d microseconds.\n", quantum); else { printf("Your clock granularity appears to be " "less than one microsecond.\n"); quantum = 1; } t = mysecond(); #pragma omp parallel for for (j = 0; j < STREAM_ARRAY_SIZE; j++) a[j] = 2.0E0 * a[j]; t = 1.0E6 * (mysecond() - t); printf("Each test below will take on the order" " of %d microseconds.\n", (int) t ); printf(" (= %d clock ticks)\n", (int) (t/quantum) ); printf("Increase the size of the arrays if this shows that\n"); printf("you are not getting at least 20 clock ticks per test.\n"); printf(HLINE); printf("WARNING -- The above is only a rough guideline.\n"); printf("For best results, please be sure you know the\n"); printf("precision of your system timer.\n"); printf(HLINE); /* --- MAIN LOOP --- repeat test cases NTIMES times --- */ scalar = 3.0; for (k=0; k<NTIMES; k++) { times[0][k] = mysecond(); #ifdef TUNED tuned_STREAM_Copy(); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; #endif times[0][k] = mysecond() - times[0][k]; times[1][k] = mysecond(); #ifdef TUNED tuned_STREAM_Scale(scalar); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar*c[j]; #endif times[1][k] = mysecond() - times[1][k]; times[2][k] = mysecond(); #ifdef TUNED tuned_STREAM_Add(); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]+b[j]; #endif times[2][k] = mysecond() - times[2][k]; times[3][k] = mysecond(); #ifdef TUNED tuned_STREAM_Triad(scalar); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j]+scalar*c[j]; #endif times[3][k] = mysecond() - times[3][k]; } /* --- SUMMARY --- */ for (k=1; k<NTIMES; k++) /* note -- skip first iteration */ { for (j=0; j<4; j++) { avgtime[j] = avgtime[j] + times[j][k]; mintime[j] = MIN(mintime[j], times[j][k]); maxtime[j] = MAX(maxtime[j], times[j][k]); } } printf("Function Best Rate MB/s Avg time Min time Max time\n"); for (j=0; j<4; j++) { avgtime[j] = avgtime[j]/(double)(NTIMES-1); printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j], 1.0E-06 * bytes[j]/mintime[j], avgtime[j], mintime[j], maxtime[j]); } printf(HLINE); /* --- Check Results --- */ checkSTREAMresults(); printf(HLINE); return 0; } # define M 20 int checktick() { int i, minDelta, Delta; double t1, t2, timesfound[M]; /* Collect a sequence of M unique time values from the system. */ for (i = 0; i < M; i++) { t1 = mysecond(); while( ((t2=mysecond()) - t1) < 1.0E-6 ) ; timesfound[i] = t1 = t2; } /* * Determine the minimum difference between these M values. * This result will be our estimate (in microseconds) for the * clock granularity. */ minDelta = 1000000; for (i = 1; i < M; i++) { Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1])); minDelta = MIN(minDelta, MAX(Delta,0)); } return(minDelta); } /* A gettimeofday routine to give access to the wall clock timer on most UNIX-like systems. */ #include <sys/time.h> double mysecond() { struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } #ifndef abs #define abs(a) ((a) >= 0 ? (a) : -(a)) #endif void checkSTREAMresults () { STREAM_TYPE aj,bj,cj,scalar; STREAM_TYPE aSumErr,bSumErr,cSumErr; STREAM_TYPE aAvgErr,bAvgErr,cAvgErr; double epsilon; ssize_t j; int k,ierr,err; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = 3.0; for (k=0; k<NTIMES; k++) { cj = aj; bj = scalar*cj; cj = aj+bj; aj = bj+scalar*cj; } /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { aSumErr += abs(a[j] - aj); bSumErr += abs(b[j] - bj); cSumErr += abs(c[j] - cj); // if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN } aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; if (sizeof(STREAM_TYPE) == 4) { epsilon = 1.e-6; } else if (sizeof(STREAM_TYPE) == 8) { epsilon = 1.e-13; } else { printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n",sizeof(STREAM_TYPE)); epsilon = 1.e-6; } err = 0; if (abs(aAvgErr/aj) > epsilon) { err++; printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(a[j]/aj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,aj,a[j],abs((aj-a[j])/aAvgErr)); } #endif } } printf(" For array a[], %d errors were found.\n",ierr); } if (abs(bAvgErr/bj) > epsilon) { err++; printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(b[j]/bj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,bj,b[j],abs((bj-b[j])/bAvgErr)); } #endif } } printf(" For array b[], %d errors were found.\n",ierr); } if (abs(cAvgErr/cj) > epsilon) { err++; printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(c[j]/cj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,cj,c[j],abs((cj-c[j])/cAvgErr)); } #endif } } printf(" For array c[], %d errors were found.\n",ierr); } if (err == 0) { printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon); } #ifdef VERBOSE printf ("Results Validation Verbose Results: \n"); printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj); printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]); printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj)); #endif } #ifdef TUNED /* stubs for "tuned" versions of the kernels */ void tuned_STREAM_Copy() { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; } void tuned_STREAM_Scale(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar*c[j]; } void tuned_STREAM_Add() { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]+b[j]; } void tuned_STREAM_Triad(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j]+scalar*c[j]; } /* end of stubs for the "tuned" versions of the kernels */ #endif
GB_unaryop__lnot_uint64_int32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint64_int32 // op(A') function: GB_tran__lnot_uint64_int32 // C type: uint64_t // A type: int32_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int32_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT64 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint64_int32 ( uint64_t *Cx, // Cx and Ax may be aliased int32_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint64_int32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
par_csr_matop.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_utilities.h" #include "hypre_hopscotch_hash.h" #include "_hypre_parcsr_mv.h" #include "_hypre_lapack.h" #include "_hypre_blas.h" /* The following function was formerly part of hypre_ParMatmul but was removed so it can also be used for multiplication of Boolean matrices */ void hypre_ParMatmul_RowSizes( HYPRE_Int ** C_diag_i, HYPRE_Int ** C_offd_i, /*HYPRE_Int ** B_marker,*/ HYPRE_Int * A_diag_i, HYPRE_Int * A_diag_j, HYPRE_Int * A_offd_i, HYPRE_Int * A_offd_j, HYPRE_Int * B_diag_i, HYPRE_Int * B_diag_j, HYPRE_Int * B_offd_i, HYPRE_Int * B_offd_j, HYPRE_Int * B_ext_diag_i, HYPRE_Int * B_ext_diag_j, HYPRE_Int * B_ext_offd_i, HYPRE_Int * B_ext_offd_j, HYPRE_Int * map_B_to_C, HYPRE_Int *C_diag_size, HYPRE_Int *C_offd_size, HYPRE_Int num_rows_diag_A, HYPRE_Int num_cols_offd_A, HYPRE_Int allsquare, HYPRE_Int num_cols_diag_B, HYPRE_Int num_cols_offd_B, HYPRE_Int num_cols_offd_C ) { HYPRE_Int i1, i2, i3, jj2, jj3; HYPRE_Int jj_count_diag, jj_count_offd, jj_row_begin_diag, jj_row_begin_offd; HYPRE_Int start_indexing = 0; /* start indexing for C_data at 0 */ HYPRE_Int num_threads = hypre_NumThreads(); HYPRE_Int *jj_count_diag_array; HYPRE_Int *jj_count_offd_array; HYPRE_Int ii, size, rest; /* First pass begins here. Computes sizes of C rows. Arrays computed: C_diag_i, C_offd_i, B_marker Arrays needed: (11, all HYPRE_Int*) A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_i, B_ext_j, col_map_offd_B, col_map_offd_B, B_offd_i, B_offd_j, B_ext_i, B_ext_j, Scalars computed: C_diag_size, C_offd_size Scalars needed: num_rows_diag_A, num_rows_diag_A, num_cols_offd_A, allsquare, first_col_diag_B, n_cols_B, num_cols_offd_B, num_cols_diag_B */ *C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1, HYPRE_MEMORY_SHARED); *C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1, HYPRE_MEMORY_SHARED); jj_count_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Loop over rows of A *-----------------------------------------------------------------------*/ size = num_rows_diag_A/num_threads; rest = num_rows_diag_A - size*num_threads; #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(ii, i1, jj_row_begin_diag, jj_row_begin_offd, jj_count_diag, jj_count_offd, jj2, i2, jj3, i3) #endif /*for (ii=0; ii < num_threads; ii++)*/ { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = start_indexing; jj_count_offd = start_indexing; if (num_cols_diag_B || num_cols_offd_C) B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B+num_cols_offd_C, HYPRE_MEMORY_HOST); for (i1 = 0; i1 < num_cols_diag_B+num_cols_offd_C; i1++) B_marker[i1] = -1; for (i1 = ns; i1 < ne; i1++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if ( allsquare ) { B_marker[i1] = jj_count_diag; jj_count_diag++; } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of B_offd. *-----------------------------------------------------------*/ if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } } } /*-------------------------------------------------------------------- * Set C_diag_i and C_offd_i for this row. *--------------------------------------------------------------------*/ (*C_diag_i)[i1] = jj_row_begin_diag; (*C_offd_i)[i1] = jj_row_begin_offd; } jj_count_diag_array[ii] = jj_count_diag; jj_count_offd_array[ii] = jj_count_offd; hypre_TFree(B_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { jj_count_diag = jj_count_diag_array[0]; jj_count_offd = jj_count_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { jj_count_diag += jj_count_diag_array[i1]; jj_count_offd += jj_count_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { (*C_diag_i)[i1] += jj_count_diag; (*C_offd_i)[i1] += jj_count_offd; } } else { (*C_diag_i)[num_rows_diag_A] = 0; (*C_offd_i)[num_rows_diag_A] = 0; for (i1 = 0; i1 < num_threads; i1++) { (*C_diag_i)[num_rows_diag_A] += jj_count_diag_array[i1]; (*C_offd_i)[num_rows_diag_A] += jj_count_offd_array[i1]; } } } /* end parallel loop */ /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ *C_diag_size = (*C_diag_i)[num_rows_diag_A]; *C_offd_size = (*C_offd_i)[num_rows_diag_A]; hypre_TFree(jj_count_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(jj_count_offd_array, HYPRE_MEMORY_HOST); /* End of First Pass */ } /*-------------------------------------------------------------------------- * hypre_ParMatmul : multiplies two ParCSRMatrices A and B and returns * the product in ParCSRMatrix C * Note that C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix *hypre_ParMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_BigInt *row_starts_A = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_BigInt first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_BigInt last_col_diag_B; HYPRE_BigInt *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); hypre_ParCSRMatrix *C; HYPRE_BigInt *col_map_offd_C; HYPRE_Int *map_B_to_C=NULL; hypre_CSRMatrix *C_diag; HYPRE_Complex *C_diag_data; HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j; hypre_CSRMatrix *C_offd; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_Int C_diag_size; HYPRE_Int C_offd_size; HYPRE_Int num_cols_offd_C = 0; hypre_CSRMatrix *Bs_ext; HYPRE_Complex *Bs_ext_data; HYPRE_Int *Bs_ext_i; HYPRE_BigInt *Bs_ext_j; HYPRE_Complex *B_ext_diag_data; HYPRE_Int *B_ext_diag_i; HYPRE_Int *B_ext_diag_j; HYPRE_Int B_ext_diag_size; HYPRE_Complex *B_ext_offd_data; HYPRE_Int *B_ext_offd_i; HYPRE_Int *B_ext_offd_j; HYPRE_BigInt *B_big_offd_j = NULL; HYPRE_Int B_ext_offd_size; HYPRE_BigInt n_rows_A, n_cols_A; HYPRE_BigInt n_rows_B, n_cols_B; HYPRE_Int allsquare = 0; HYPRE_Int num_procs; HYPRE_Int *my_diag_array; HYPRE_Int *my_offd_array; HYPRE_Int max_num_threads; HYPRE_Complex zero = 0.0; n_rows_A = hypre_ParCSRMatrixGlobalNumRows(A); n_cols_A = hypre_ParCSRMatrixGlobalNumCols(A); n_rows_B = hypre_ParCSRMatrixGlobalNumRows(B); n_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); max_num_threads = hypre_NumThreads(); my_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); my_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); if (n_cols_A != n_rows_B || num_cols_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } /* if globally C=A*B is square and locally C_diag should also be square */ if ( num_rows_diag_A == num_cols_diag_B && n_rows_A == n_cols_B ) { allsquare = 1; } /*----------------------------------------------------------------------- * Extract B_ext, i.e. portion of B that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); #endif if (num_procs > 1) { /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings within * hypre_ParCSRMatrixExtractBExt *--------------------------------------------------------------------*/ Bs_ext = hypre_ParCSRMatrixExtractBExt(B,A,1); Bs_ext_data = hypre_CSRMatrixData(Bs_ext); Bs_ext_i = hypre_CSRMatrixI(Bs_ext); Bs_ext_j = hypre_CSRMatrixBigJ(Bs_ext); } B_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1, HYPRE_MEMORY_HOST); B_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1, HYPRE_MEMORY_HOST); B_ext_diag_size = 0; B_ext_offd_size = 0; last_col_diag_B = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B -1; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedBigIntSet set; #pragma omp parallel { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i=ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) my_offd_size++; else my_diag_size++; } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #pragma omp barrier if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } hypre_UnorderedBigIntSetCreate(&set, B_ext_offd_size + num_cols_offd_B, 16*hypre_NumThreads()); } #pragma omp barrier cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i=ns; i < ne; i++) { for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { hypre_UnorderedBigIntSetPut(&set, Bs_ext_j[j]); B_big_offd_j[cnt_offd] = Bs_ext_j[j]; //Bs_ext_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = (HYPRE_Int)(Bs_ext_j[j] - first_col_diag_B); B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_B); for (i = i_begin; i < i_end; i++) { hypre_UnorderedBigIntSetPut(&set, col_map_offd_B[i]); } } /* omp parallel */ col_map_offd_C = hypre_UnorderedBigIntSetCopyToArray(&set, &num_cols_offd_C); hypre_UnorderedBigIntSetDestroy(&set); hypre_UnorderedBigIntMap col_map_offd_C_inverse; hypre_big_sort_and_create_inverse_map(col_map_offd_C, num_cols_offd_C, &col_map_offd_C, &col_map_offd_C_inverse); HYPRE_Int i, j; #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_A; i++) for (j=B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) //B_ext_offd_j[j] = hypre_UnorderedIntMapGet(&col_map_offd_C_inverse, B_ext_offd_j[j]); B_ext_offd_j[j] = hypre_UnorderedBigIntMapGet(&col_map_offd_C_inverse, B_big_offd_j[j]); if (num_cols_offd_C) { hypre_UnorderedBigIntMapDestroy(&col_map_offd_C_inverse); } hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); if (num_cols_offd_B) { HYPRE_Int i; map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); #pragma omp parallel private(i) { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_C); HYPRE_Int cnt; if (i_end > i_begin) { cnt = hypre_BigLowerBound(col_map_offd_B, col_map_offd_B + (HYPRE_BigInt)num_cols_offd_B, col_map_offd_C[i_begin]) - col_map_offd_B; } for (i = i_begin; i < i_end && cnt < num_cols_offd_B; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; } } } } if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ HYPRE_BigInt *temp; #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i=ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) my_offd_size++; else my_diag_size++; } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size || num_cols_offd_B) temp = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size+num_cols_offd_B, HYPRE_MEMORY_HOST); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i=ns; i < ne; i++) { for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { temp[cnt_offd] = Bs_ext_j[j]; B_big_offd_j[cnt_offd] = Bs_ext_j[j]; //Bs_ext_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = (HYPRE_Int)(Bs_ext_j[j] - first_col_diag_B); B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { HYPRE_Int cnt; if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } cnt = 0; if (B_ext_offd_size || num_cols_offd_B) { cnt = B_ext_offd_size; for (i=0; i < num_cols_offd_B; i++) temp[cnt++] = col_map_offd_B[i]; if (cnt) { HYPRE_BigInt value; hypre_BigQsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; hypre_TFree(temp, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=ns; i < ne; i++) for (j=B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, B_big_offd_j[j], //B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, Bs_ext_j[j], num_cols_offd_C); } /* end parallel region */ hypre_TFree(B_big_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); if (num_cols_offd_B) { HYPRE_Int i, cnt; map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); cnt = 0; for (i=0; i < num_cols_offd_C; i++) if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); #endif hypre_ParMatmul_RowSizes( /*&C_diag_i, &C_offd_i, &B_marker,*/ &C_diag_i, &C_offd_i, A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_diag_i, B_ext_diag_j, B_ext_offd_i, B_ext_offd_j, map_B_to_C, &C_diag_size, &C_offd_size, num_rows_diag_A, num_cols_offd_A, allsquare, num_cols_diag_B, num_cols_offd_B, num_cols_offd_C ); /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ last_col_diag_B = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B - 1; C_diag_data = hypre_CTAlloc(HYPRE_Complex, C_diag_size, HYPRE_MEMORY_SHARED); C_diag_j = hypre_CTAlloc(HYPRE_Int, C_diag_size, HYPRE_MEMORY_SHARED); if (C_offd_size) { C_offd_data = hypre_CTAlloc(HYPRE_Complex, C_offd_size, HYPRE_MEMORY_SHARED); C_offd_j = hypre_CTAlloc(HYPRE_Int, C_offd_size, HYPRE_MEMORY_SHARED); } /*----------------------------------------------------------------------- * Second Pass: Fill in C_diag_data and C_diag_j. * Second Pass: Fill in C_offd_data and C_offd_j. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, size, rest, ii; HYPRE_Int i1, i2, i3, jj2, jj3; HYPRE_Int jj_row_begin_diag, jj_count_diag; HYPRE_Int jj_row_begin_offd, jj_count_offd; HYPRE_Int num_threads; HYPRE_Complex a_entry; /*, a_b_product;*/ ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); size = num_rows_diag_A/num_threads; rest = num_rows_diag_A - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = C_diag_i[ns]; jj_count_offd = C_offd_i[ns]; if (num_cols_diag_B || num_cols_offd_C) { B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B+num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i1 = 0; i1 < num_cols_diag_B+num_cols_offd_C; i1++) { B_marker[i1] = -1; } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (i1 = ns; i1 < ne; i1++) { /*-------------------------------------------------------------------- * Create diagonal entry, C_{i1,i1} *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if ( allsquare ) { B_marker[i1] = jj_count_diag; C_diag_data[jj_count_diag] = zero; C_diag_j[jj_count_diag] = i1; jj_count_diag++; } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; a_entry = A_offd_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_ext_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else C_offd_data[B_marker[i3]] += a_entry*B_ext_offd_data[jj3]; } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_ext_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else C_diag_data[B_marker[i3]] += a_entry*B_ext_diag_data[jj3]; } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; a_entry = A_diag_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[B_marker[i3]] += a_entry*B_diag_data[jj3]; } } if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else { C_offd_data[B_marker[i3]] += a_entry*B_offd_data[jj3]; } } } } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); } /*end parallel region */ C = hypre_ParCSRMatrixCreate(comm, n_rows_A, n_cols_B, row_starts_A, col_starts_B, num_cols_offd_C, C_diag_size, C_offd_size); /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrixData(C_diag) = C_diag_data; hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixJ(C_diag) = C_diag_j; C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_CSRMatrixData(C_offd) = C_offd_data; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; } /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(B_ext_diag_i, HYPRE_MEMORY_HOST); if (B_ext_diag_size) { hypre_TFree(B_ext_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_diag_data, HYPRE_MEMORY_HOST); } hypre_TFree(B_ext_offd_i, HYPRE_MEMORY_HOST); if (B_ext_offd_size) { hypre_TFree(B_ext_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_offd_data, HYPRE_MEMORY_HOST); } if (num_cols_offd_B) hypre_TFree(map_B_to_C, HYPRE_MEMORY_HOST); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] += hypre_MPI_Wtime(); #endif return C; } /* The following function was formerly part of hypre_ParCSRMatrixExtractBExt but the code was removed so it can be used for a corresponding function for Boolean matrices JSP: to allow communication overlapping, it returns comm_handle_idx and comm_handle_data. Before accessing B, they should be destroyed (including send_data contained in the comm_handle). */ void hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( HYPRE_Int ** pB_ext_i, HYPRE_BigInt ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_BigInt ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_BigInt first_col_diag, HYPRE_BigInt * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_BigInt * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, /* 1 if only coarse points are needed */ HYPRE_Int skip_same_sign /* 1 if only points that have the same sign are needed */ // extended based long range interpolation: skip_fine = 1, skip_same_sign = 0 for S matrix, skip_fine = 1, skip_same_sign = 1 for A matrix // other interpolation: skip_fine = 0, skip_same_sign = 0 ) { hypre_ParCSRCommHandle *comm_handle, *row_map_comm_handle = NULL; hypre_ParCSRCommPkg *tmp_comm_pkg; HYPRE_Int *B_int_i; HYPRE_BigInt *B_int_j; HYPRE_Int *B_ext_i; HYPRE_BigInt * B_ext_j; HYPRE_Complex * B_ext_data; HYPRE_Complex * B_int_data; HYPRE_BigInt * B_int_row_map; HYPRE_BigInt * B_ext_row_map; HYPRE_Int num_procs, my_id; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i, j, k; HYPRE_Int start_index; /*HYPRE_Int jrow;*/ HYPRE_Int num_rows_B_ext; HYPRE_Int *prefix_sum_workspace; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_BigInt first_row_index = row_starts[0]; #else HYPRE_BigInt first_row_index = row_starts[my_id]; HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); #endif num_rows_B_ext = recv_vec_starts[num_recvs]; if ( num_rows_B_ext < 0 ) { /* no B_ext, no communication */ *pB_ext_i = NULL; *pB_ext_j = NULL; if ( data ) *pB_ext_data = NULL; if ( find_row_map ) *pB_ext_row_map = NULL; *num_nonzeros = 0; return; }; B_int_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]+1, HYPRE_MEMORY_HOST); B_ext_i = hypre_CTAlloc(HYPRE_Int, num_rows_B_ext+1, HYPRE_MEMORY_HOST); *pB_ext_i = B_ext_i; if ( find_row_map ) { B_int_row_map = hypre_CTAlloc( HYPRE_BigInt, send_map_starts[num_sends]+1 , HYPRE_MEMORY_HOST); B_ext_row_map = hypre_CTAlloc( HYPRE_BigInt, num_rows_B_ext+1 , HYPRE_MEMORY_HOST); *pB_ext_row_map = B_ext_row_map; }; /*-------------------------------------------------------------------------- * generate B_int_i through adding number of row-elements of offd and diag * for corresponding rows. B_int_i[j+1] contains the number of elements of * a row j (which is determined through send_map_elmts) *--------------------------------------------------------------------------*/ jdata_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); jdata_send_map_starts[0] = B_int_i[0] = 0; /*HYPRE_Int prefix_sum_workspace[(hypre_NumThreads() + 1)*num_sends];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, (hypre_NumThreads() + 1)*num_sends, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,k) #endif { /*HYPRE_Int counts[num_sends];*/ HYPRE_Int *counts; counts = hypre_TAlloc(HYPRE_Int, num_sends, HYPRE_MEMORY_HOST); for (i=0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = 0; if (skip_fine && skip_same_sign) { #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int send_proc = send_procs[i]; HYPRE_BigInt send_proc_first_row = row_starts[send_proc]; HYPRE_BigInt send_proc_last_row = row_starts[send_proc + 1]; #endif for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] < 0) len++; #else HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; if (offd_data[k] < 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) len++; #endif } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] > 0) len++; #else HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; if (offd_data[k] > 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) len++; #endif } } B_int_i[j + 1] = len; count += len; } } else if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) len++; } B_int_i[j + 1] = len; count += len; } } else { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = diag_i[jrow + 1] - diag_i[jrow]; len += offd_i[jrow + 1] - offd_i[jrow]; B_int_i[j + 1] = len; count += len; } } if (find_row_map) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; B_int_row_map[j] = (HYPRE_BigInt)jrow + first_row_index; } } counts[i] = count; } hypre_prefix_sum_multiple(counts, jdata_send_map_starts + 1, num_sends, prefix_sum_workspace); #ifdef HYPRE_USING_OPENMP #pragma omp master #endif { for (i = 1; i < num_sends; i++) { jdata_send_map_starts[i + 1] += jdata_send_map_starts[i]; } /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg, &B_int_i[1],&(B_ext_i[1]) ); if ( find_row_map ) { /* scatter/gather B_int row numbers to form array of B_ext row numbers */ row_map_comm_handle = hypre_ParCSRCommHandleCreate (21,comm_pkg, B_int_row_map, B_ext_row_map ); } B_int_j = hypre_TAlloc(HYPRE_BigInt, jdata_send_map_starts[num_sends], HYPRE_MEMORY_HOST); if (data) B_int_data = hypre_TAlloc(HYPRE_Complex, jdata_send_map_starts[num_sends], HYPRE_MEMORY_HOST); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = counts[i] + jdata_send_map_starts[i]; if (data) { if (skip_same_sign && skip_fine) { #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int send_proc = send_procs[i]; HYPRE_BigInt send_proc_first_row = row_starts[send_proc]; HYPRE_BigInt send_proc_last_row = row_starts[send_proc + 1]; #endif for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; /*HYPRE_Int count_begin = count;*/ if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] < 0) #else if (offd_data[k] < 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) #endif { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] > 0) #else if (offd_data[k] > 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) #endif { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k=diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } for (k=offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; B_int_data[count] = offd_data[k]; count++; } } } } // data else { if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k] + first_col_diag; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k=diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; count++; } for (k=offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } // !data } /* for each send target */ hypre_TFree(counts, HYPRE_MEMORY_HOST); } /* omp parallel. JSP: this takes most of time in this function */ hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = jdata_send_map_starts; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * after communication exchange B_ext_i[j+1] contains the number of elements * of a row j ! * evaluate B_ext_i and compute *num_nonzeros for B_ext *--------------------------------------------------------------------------*/ for (i=0; i < num_recvs; i++) for (j = recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) B_ext_i[j+1] += B_ext_i[j]; *num_nonzeros = B_ext_i[num_rows_B_ext]; *pB_ext_j = hypre_TAlloc(HYPRE_BigInt, *num_nonzeros, HYPRE_MEMORY_HOST); B_ext_j = *pB_ext_j; if (data) { *pB_ext_data = hypre_TAlloc(HYPRE_Complex, *num_nonzeros, HYPRE_MEMORY_HOST); B_ext_data = *pB_ext_data; }; for (i=0; i < num_recvs; i++) { start_index = B_ext_i[recv_vec_starts[i]]; *num_nonzeros = B_ext_i[recv_vec_starts[i+1]]-start_index; jdata_recv_vec_starts[i+1] = B_ext_i[recv_vec_starts[i+1]]; } hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = jdata_recv_vec_starts; *comm_handle_idx = hypre_ParCSRCommHandleCreate(21,tmp_comm_pkg,B_int_j,B_ext_j); if (data) { *comm_handle_data = hypre_ParCSRCommHandleCreate(1,tmp_comm_pkg,B_int_data, B_ext_data); } if (row_map_comm_handle) { hypre_ParCSRCommHandleDestroy(row_map_comm_handle); row_map_comm_handle = NULL; } hypre_TFree(jdata_send_map_starts, HYPRE_MEMORY_HOST); hypre_TFree(jdata_recv_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_comm_pkg, HYPRE_MEMORY_HOST); hypre_TFree(B_int_i, HYPRE_MEMORY_HOST); if ( find_row_map ) hypre_TFree(B_int_row_map, HYPRE_MEMORY_HOST); /* end generic part */ } void hypre_ParCSRMatrixExtractBExt_Arrays( HYPRE_Int ** pB_ext_i, HYPRE_BigInt ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_BigInt ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_BigInt first_col_diag, HYPRE_BigInt * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_BigInt * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data ) { hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( pB_ext_i, pB_ext_j, pB_ext_data, pB_ext_row_map, num_nonzeros, data, find_row_map, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx, HYPRE_MEMORY_HOST); if (data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data, HYPRE_MEMORY_HOST); } } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixExtractBExt : extracts rows from B which are located on * other processors and needed for multiplication with A locally. The rows * are returned as CSRMatrix. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt_Overlap( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, HYPRE_Int skip_same_sign ) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); HYPRE_BigInt first_col_diag = hypre_ParCSRMatrixFirstColDiag(B); /*HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(B);*/ HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(B); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_recvs; HYPRE_Int *recv_vec_starts; HYPRE_Int num_sends; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Real *diag_data = hypre_CSRMatrixData(diag); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Real *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int num_cols_B, num_nonzeros; HYPRE_Int num_rows_B_ext; hypre_CSRMatrix *B_ext; HYPRE_Int *B_ext_i; HYPRE_BigInt *B_ext_j; HYPRE_Complex *B_ext_data; HYPRE_BigInt *idummy; /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } comm_pkg = hypre_ParCSRMatrixCommPkg(A); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); num_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); num_rows_B_ext = recv_vec_starts[num_recvs]; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap ( &B_ext_i, &B_ext_j, &B_ext_data, &idummy, &num_nonzeros, data, 0, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, B->row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, comm_handle_idx, comm_handle_data, CF_marker, CF_marker_offd, skip_fine, skip_same_sign ); B_ext = hypre_CSRMatrixCreate(num_rows_B_ext,num_cols_B,num_nonzeros); hypre_CSRMatrixMemoryLocation(B_ext) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(B_ext) = B_ext_i; hypre_CSRMatrixBigJ(B_ext) = B_ext_j; if (data) hypre_CSRMatrixData(B_ext) = B_ext_data; return B_ext; } hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data ) { #if 0 hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_CSRMatrix *B_ext = hypre_ParCSRMatrixExtractBExt_Overlap(B, A, want_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx, HYPRE_MEMORY_HOST); if (want_data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data, HYPRE_MEMORY_HOST); } #else hypre_assert( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B)) == hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(B)) ); hypre_assert( hypre_GetActualMemLocation(hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B))) != HYPRE_MEMORY_DEVICE ); hypre_CSRMatrix *B_ext; void *request; if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ParcsrGetExternalRowsInit(B, hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)), hypre_ParCSRMatrixColMapOffd(A), hypre_ParCSRMatrixCommPkg(A), want_data, &request); B_ext = hypre_ParcsrGetExternalRowsWait(request); #endif return B_ext; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixTranspose( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { hypre_ParCSRCommHandle *comm_handle; MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int num_cols = hypre_ParCSRMatrixNumCols(A); HYPRE_BigInt first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_BigInt *col_starts = hypre_ParCSRMatrixColStarts(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, num_recvs, num_cols_offd_AT; HYPRE_Int i, j, k, index, counter, j_row; HYPRE_BigInt value; hypre_ParCSRMatrix *AT; hypre_CSRMatrix *AT_diag; hypre_CSRMatrix *AT_offd; hypre_CSRMatrix *AT_tmp; HYPRE_BigInt first_row_index_AT, first_col_diag_AT; HYPRE_Int local_num_rows_AT, local_num_cols_AT; HYPRE_Int *AT_tmp_i; HYPRE_Int *AT_tmp_j; HYPRE_BigInt *AT_big_j = NULL; HYPRE_Complex *AT_tmp_data; HYPRE_Int *AT_buf_i; HYPRE_BigInt *AT_buf_j; HYPRE_Complex *AT_buf_data; HYPRE_Int *AT_offd_i; HYPRE_Int *AT_offd_j; HYPRE_Complex *AT_offd_data; HYPRE_BigInt *col_map_offd_AT; HYPRE_BigInt *row_starts_AT; HYPRE_BigInt *col_starts_AT; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs; HYPRE_Int *send_procs; HYPRE_Int *recv_vec_starts; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int *tmp_recv_vec_starts; HYPRE_Int *tmp_send_map_starts; hypre_ParCSRCommPkg *tmp_comm_pkg; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_cols_offd_AT = 0; counter = 0; AT_offd_j = NULL; AT_offd_data = NULL; col_map_offd_AT = NULL; /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (num_procs > 1) { hypre_CSRMatrixTranspose (A_offd, &AT_tmp, data); AT_tmp_i = hypre_CSRMatrixI(AT_tmp); AT_tmp_j = hypre_CSRMatrixJ(AT_tmp); if (data) AT_tmp_data = hypre_CSRMatrixData(AT_tmp); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); AT_buf_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends], HYPRE_MEMORY_HOST); if (AT_tmp_i[num_cols_offd]) AT_big_j = hypre_CTAlloc(HYPRE_BigInt, AT_tmp_i[num_cols_offd], HYPRE_MEMORY_HOST); for (i=0; i < AT_tmp_i[num_cols_offd]; i++) //AT_tmp_j[i] += first_row_index; AT_big_j[i] = (HYPRE_BigInt)AT_tmp_j[i]+first_row_index; for (i=0; i < num_cols_offd; i++) AT_tmp_i[i] = AT_tmp_i[i+1]-AT_tmp_i[i]; comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, AT_tmp_i, AT_buf_i); } hypre_CSRMatrixTranspose( A_diag, &AT_diag, data); AT_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols+1, HYPRE_MEMORY_SHARED); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); tmp_send_map_starts[0] = send_map_starts[0]; for (i=0; i < num_sends; i++) { tmp_send_map_starts[i+1] = tmp_send_map_starts[i]; for (j=send_map_starts[i]; j < send_map_starts[i+1]; j++) { tmp_send_map_starts[i+1] += AT_buf_i[j]; AT_offd_i[send_map_elmts[j]+1] += AT_buf_i[j]; } } for (i=0; i < num_cols; i++) AT_offd_i[i+1] += AT_offd_i[i]; tmp_recv_vec_starts[0] = recv_vec_starts[0]; for (i=0; i < num_recvs; i++) { tmp_recv_vec_starts[i+1] = tmp_recv_vec_starts[i]; for (j=recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { tmp_recv_vec_starts[i+1] += AT_tmp_i[j]; } } tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = recv_procs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = send_procs; hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts; hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts; AT_buf_j = hypre_CTAlloc(HYPRE_BigInt, tmp_send_map_starts[num_sends], HYPRE_MEMORY_HOST); comm_handle = hypre_ParCSRCommHandleCreate(22, tmp_comm_pkg, AT_big_j, AT_buf_j); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; hypre_TFree(AT_big_j, HYPRE_MEMORY_HOST); AT_big_j = NULL; if (data) { AT_buf_data = hypre_CTAlloc(HYPRE_Complex, tmp_send_map_starts[num_sends], HYPRE_MEMORY_HOST); comm_handle = hypre_ParCSRCommHandleCreate(2,tmp_comm_pkg,AT_tmp_data, AT_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } hypre_TFree(tmp_recv_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_send_map_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_comm_pkg, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(AT_tmp); if (AT_offd_i[num_cols]) { AT_offd_j = hypre_CTAlloc(HYPRE_Int, AT_offd_i[num_cols], HYPRE_MEMORY_SHARED); AT_big_j = hypre_CTAlloc(HYPRE_BigInt, AT_offd_i[num_cols], HYPRE_MEMORY_HOST); if (data) AT_offd_data = hypre_CTAlloc(HYPRE_Complex, AT_offd_i[num_cols], HYPRE_MEMORY_SHARED); } else { AT_offd_j = NULL; AT_offd_data = NULL; } counter = 0; for (i=0; i < num_sends; i++) { for (j=send_map_starts[i]; j < send_map_starts[i+1]; j++) { j_row = send_map_elmts[j]; index = AT_offd_i[j_row]; for (k=0; k < AT_buf_i[j]; k++) { if (data) AT_offd_data[index] = AT_buf_data[counter]; AT_big_j[index++] = AT_buf_j[counter++]; } AT_offd_i[j_row] = index; } } for (i=num_cols; i > 0; i--) AT_offd_i[i] = AT_offd_i[i-1]; AT_offd_i[0] = 0; if (counter) { hypre_BigQsort0(AT_buf_j,0,counter-1); num_cols_offd_AT = 1; value = AT_buf_j[0]; for (i=1; i < counter; i++) { if (value < AT_buf_j[i]) { AT_buf_j[num_cols_offd_AT++] = AT_buf_j[i]; value = AT_buf_j[i]; } } } if (num_cols_offd_AT) col_map_offd_AT = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST); else col_map_offd_AT = NULL; for (i=0; i < num_cols_offd_AT; i++) col_map_offd_AT[i] = AT_buf_j[i]; hypre_TFree(AT_buf_i, HYPRE_MEMORY_HOST); hypre_TFree(AT_buf_j, HYPRE_MEMORY_HOST); if (data) hypre_TFree(AT_buf_data, HYPRE_MEMORY_HOST); for (i=0; i < counter; i++) AT_offd_j[i] = hypre_BigBinarySearch(col_map_offd_AT,AT_big_j[i], num_cols_offd_AT); hypre_TFree(AT_big_j, HYPRE_MEMORY_HOST); } AT_offd = hypre_CSRMatrixCreate(num_cols,num_cols_offd_AT,counter); hypre_CSRMatrixI(AT_offd) = AT_offd_i; hypre_CSRMatrixJ(AT_offd) = AT_offd_j; hypre_CSRMatrixData(AT_offd) = AT_offd_data; #ifdef HYPRE_NO_GLOBAL_PARTITION row_starts_AT = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); for (i=0; i < 2; i++) row_starts_AT[i] = col_starts[i]; if (row_starts != col_starts) { col_starts_AT = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); for (i=0; i < 2; i++) col_starts_AT[i] = row_starts[i]; } else { col_starts_AT = row_starts_AT; } first_row_index_AT = row_starts_AT[0]; first_col_diag_AT = col_starts_AT[0]; local_num_rows_AT = (HYPRE_Int)(row_starts_AT[1]-first_row_index_AT ); local_num_cols_AT = (HYPRE_Int)(col_starts_AT[1]-first_col_diag_AT); #else row_starts_AT = hypre_CTAlloc(HYPRE_BigInt, num_procs+1, HYPRE_MEMORY_HOST); for (i=0; i < num_procs+1; i++) row_starts_AT[i] = col_starts[i]; if (row_starts != col_starts) { col_starts_AT = hypre_CTAlloc(HYPRE_BigInt, num_procs+1, HYPRE_MEMORY_HOST); for (i=0; i < num_procs+1; i++) col_starts_AT[i] = row_starts[i]; } else { col_starts_AT = row_starts_AT; } first_row_index_AT = row_starts_AT[my_id]; first_col_diag_AT = col_starts_AT[my_id]; local_num_rows_AT = (HYPRE_Int)(row_starts_AT[my_id+1]-first_row_index_AT ); local_num_cols_AT = (HYPRE_Int)(col_starts_AT[my_id+1]-first_col_diag_AT); #endif AT = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixComm(AT) = comm; hypre_ParCSRMatrixDiag(AT) = AT_diag; hypre_ParCSRMatrixOffd(AT) = AT_offd; hypre_ParCSRMatrixGlobalNumRows(AT) = hypre_ParCSRMatrixGlobalNumCols(A); hypre_ParCSRMatrixGlobalNumCols(AT) = hypre_ParCSRMatrixGlobalNumRows(A); hypre_ParCSRMatrixRowStarts(AT) = row_starts_AT; hypre_ParCSRMatrixColStarts(AT) = col_starts_AT; hypre_ParCSRMatrixColMapOffd(AT) = col_map_offd_AT; hypre_ParCSRMatrixFirstRowIndex(AT) = first_row_index_AT; hypre_ParCSRMatrixFirstColDiag(AT) = first_col_diag_AT; hypre_ParCSRMatrixLastRowIndex(AT) = first_row_index_AT + local_num_rows_AT - 1; hypre_ParCSRMatrixLastColDiag(AT) = first_col_diag_AT + local_num_cols_AT - 1; hypre_ParCSRMatrixOwnsData(AT) = 1; hypre_ParCSRMatrixOwnsRowStarts(AT) = 1; hypre_ParCSRMatrixOwnsColStarts(AT) = 1; if (row_starts_AT == col_starts_AT) { hypre_ParCSRMatrixOwnsColStarts(AT) = 0; } hypre_ParCSRMatrixCommPkg(AT) = NULL; hypre_ParCSRMatrixCommPkgT(AT) = NULL; hypre_ParCSRMatrixRowindices(AT) = NULL; hypre_ParCSRMatrixRowvalues(AT) = NULL; hypre_ParCSRMatrixGetrowactive(AT) = 0; hypre_ParCSRMatrixOwnsAssumedPartition(AT) = 1; *AT_ptr = AT; return ierr; } /* ----------------------------------------------------------------------------- * generate a parallel spanning tree (for Maxwell Equation) * G_csr is the node to edge connectivity matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixGenSpanningTree( hypre_ParCSRMatrix *G_csr, HYPRE_Int **indices, HYPRE_Int G_type ) { HYPRE_BigInt nrows_G, ncols_G; HYPRE_Int *G_diag_i, *G_diag_j, *GT_diag_mat, i, j, k, edge; HYPRE_Int *nodes_marked, *edges_marked, *queue, queue_tail, queue_head, node; HYPRE_Int mypid, nprocs, n_children, *children, nsends, *send_procs, *recv_cnts; HYPRE_Int nrecvs, *recv_procs, n_proc_array, *proc_array, *pgraph_i, *pgraph_j; HYPRE_Int parent, proc, proc2, node2, found, *t_indices, tree_size, *T_diag_i; HYPRE_Int *T_diag_j, *counts, offset; MPI_Comm comm; hypre_ParCSRCommPkg *comm_pkg; hypre_CSRMatrix *G_diag; /* fetch G matrix (G_type = 0 ==> node to edge) */ if (G_type == 0) { nrows_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); G_diag_i = hypre_CSRMatrixI(G_diag); G_diag_j = hypre_CSRMatrixJ(G_diag); } else { nrows_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); T_diag_i = hypre_CSRMatrixI(G_diag); T_diag_j = hypre_CSRMatrixJ(G_diag); counts = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_G; i++) counts[i] = 0; for (i = 0; i < T_diag_i[ncols_G]; i++) counts[T_diag_j[i]]++; G_diag_i = hypre_TAlloc(HYPRE_Int, (nrows_G+1) , HYPRE_MEMORY_HOST); G_diag_j = hypre_TAlloc(HYPRE_Int, T_diag_i[ncols_G] , HYPRE_MEMORY_HOST); G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; for (i = 0; i < ncols_G; i++) { for (j = T_diag_i[i]; j < T_diag_i[i+1]; j++) { k = T_diag_j[j]; offset = G_diag_i[k]++; G_diag_j[offset] = i; } } G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; free(counts); } /* form G transpose in special form (2 nodes per edge max) */ GT_diag_mat = hypre_TAlloc(HYPRE_Int, 2 * ncols_G , HYPRE_MEMORY_HOST); for (i = 0; i < 2 * ncols_G; i++) GT_diag_mat[i] = -1; for (i = 0; i < nrows_G; i++) { for (j = G_diag_i[i]; j < G_diag_i[i+1]; j++) { edge = G_diag_j[j]; if (GT_diag_mat[edge*2] == -1) GT_diag_mat[edge*2] = i; else GT_diag_mat[edge*2+1] = i; } } /* BFS on the local matrix graph to find tree */ nodes_marked = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); edges_marked = hypre_TAlloc(HYPRE_Int, ncols_G , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_G; i++) nodes_marked[i] = 0; for (i = 0; i < ncols_G; i++) edges_marked[i] = 0; queue = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); queue_head = 0; queue_tail = 1; queue[0] = 0; nodes_marked[0] = 1; while ((queue_tail-queue_head) > 0) { node = queue[queue_tail-1]; queue_tail--; for (i = G_diag_i[node]; i < G_diag_i[node+1]; i++) { edge = G_diag_j[i]; if (edges_marked[edge] == 0) { if (GT_diag_mat[2*edge+1] != -1) { node2 = GT_diag_mat[2*edge]; if (node2 == node) node2 = GT_diag_mat[2*edge+1]; if (nodes_marked[node2] == 0) { nodes_marked[node2] = 1; edges_marked[edge] = 1; queue[queue_tail] = node2; queue_tail++; } } } } } free(nodes_marked); free(queue); free(GT_diag_mat); /* fetch the communication information from */ comm = hypre_ParCSRMatrixComm(G_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); if (nprocs == 1 && comm_pkg == NULL) { hypre_MatvecCommPkgCreate((hypre_ParCSRMatrix *) G_csr); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); } /* construct processor graph based on node-edge connection */ /* (local edges connected to neighbor processor nodes) */ n_children = 0; nrecvs = nsends = 0; if (nprocs > 1) { nsends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); nrecvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); proc_array = NULL; if ((nsends+nrecvs) > 0) { n_proc_array = 0; proc_array = hypre_TAlloc(HYPRE_Int, (nsends+nrecvs) , HYPRE_MEMORY_HOST); for (i = 0; i < nsends; i++) proc_array[i] = send_procs[i]; for (i = 0; i < nrecvs; i++) proc_array[nsends+i] = recv_procs[i]; hypre_qsort0(proc_array, 0, nsends+nrecvs-1); n_proc_array = 1; for (i = 1; i < nrecvs+nsends; i++) if (proc_array[i] != proc_array[n_proc_array]) proc_array[n_proc_array++] = proc_array[i]; } pgraph_i = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); recv_cnts = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&n_proc_array, 1, HYPRE_MPI_INT, recv_cnts, 1, HYPRE_MPI_INT, comm); pgraph_i[0] = 0; for (i = 1; i <= nprocs; i++) pgraph_i[i] = pgraph_i[i-1] + recv_cnts[i-1]; pgraph_j = hypre_TAlloc(HYPRE_Int, pgraph_i[nprocs] , HYPRE_MEMORY_HOST); hypre_MPI_Allgatherv(proc_array, n_proc_array, HYPRE_MPI_INT, pgraph_j, recv_cnts, pgraph_i, HYPRE_MPI_INT, comm); free(recv_cnts); /* BFS on the processor graph to determine parent and children */ nodes_marked = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); for (i = 0; i < nprocs; i++) nodes_marked[i] = -1; queue = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); queue_head = 0; queue_tail = 1; node = 0; queue[0] = node; while ((queue_tail-queue_head) > 0) { proc = queue[queue_tail-1]; queue_tail--; for (i = pgraph_i[proc]; i < pgraph_i[proc+1]; i++) { proc2 = pgraph_j[i]; if (nodes_marked[proc2] < 0) { nodes_marked[proc2] = proc; queue[queue_tail] = proc2; queue_tail++; } } } parent = nodes_marked[mypid]; n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) n_children++; if (n_children == 0) {n_children = 0; children = NULL;} else { children = hypre_TAlloc(HYPRE_Int, n_children , HYPRE_MEMORY_HOST); n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) children[n_children++] = i; } free(nodes_marked); free(queue); free(pgraph_i); free(pgraph_j); } /* first, connection with my parent : if the edge in my parent * * is incident to one of my nodes, then my parent will mark it */ found = 0; for (i = 0; i < nrecvs; i++) { proc = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); if (proc == parent) { found = 1; break; } } /* but if all the edges connected to my parent are on my side, * * then I will just pick one of them as tree edge */ if (found == 0) { for (i = 0; i < nsends; i++) { proc = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == parent) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } /* next, if my processor has an edge incident on one node in my * * child, put this edge on the tree. But if there is no such * * edge, then I will assume my child will pick up an edge */ for (j = 0; j < n_children; j++) { proc = children[j]; for (i = 0; i < nsends; i++) { proc2 = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == proc2) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } if (n_children > 0) free(children); /* count the size of the tree */ tree_size = 0; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) tree_size++; t_indices = hypre_TAlloc(HYPRE_Int, (tree_size+1) , HYPRE_MEMORY_HOST); t_indices[0] = tree_size; tree_size = 1; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) t_indices[tree_size++] = i; (*indices) = t_indices; free(edges_marked); if (G_type != 0) { free(G_diag_i); free(G_diag_j); } } /* ----------------------------------------------------------------------------- * extract submatrices based on given indices * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nrows_A, nindices, *indices, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *exp_indices; HYPRE_BigInt *itmp_array; HYPRE_Int nnz11, nnz12, nnz21, nnz22, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int nrows, nnz; HYPRE_BigInt global_nrows, global_ncols, *row_starts, *col_starts; HYPRE_Int *diag_i, *diag_j, row, *offd_i; HYPRE_Complex *A_diag_a, *diag_a; hypre_ParCSRMatrix *A11_csr, *A12_csr, *A21_csr, *A22_csr; hypre_CSRMatrix *A_diag, *diag, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = (HYPRE_Int) hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); if (nprocs > 1) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: cannot handle nprocs > 1 yet.\n"); exit(1); } /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); proc_offsets2 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) proc_offsets2[i] = itmp_array[i] - proc_offsets1[i]; /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = hypre_TAlloc(HYPRE_Int, nrows_A , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz12 = nnz21 = nnz22 = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; else nnz12++; } } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz21++; else nnz22++; } } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz11; #ifdef HYPRE_NO_GLOBAL_PARTITION /* This case is not yet implemented! */ global_nrows = 0; global_ncols = 0; row_starts = NULL; col_starts = NULL; #else global_nrows = proc_offsets1[nprocs]; global_ncols = proc_offsets1[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets1[i]; col_starts[i] = proc_offsets1[i]; } #endif A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A12 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz12; global_nrows = (HYPRE_BigInt)proc_offsets1[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; } A12_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } if (nnz > nnz_diag) hypre_error(HYPRE_ERROR_GENERIC); /*hypre_printf("WARNING WARNING WARNING\n");*/ diag = hypre_ParCSRMatrixDiag(A12_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A12_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A21 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz21; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets1[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A22 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz22; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; } A22_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A22_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A22_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A12_csr; (*submatrices)[2] = A21_csr; (*submatrices)[3] = A22_csr; free(proc_offsets1); free(proc_offsets2); free(exp_indices); } /* ----------------------------------------------------------------------------- * extract submatrices of a rectangular matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractRowSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nrows_A, nindices, *indices, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *exp_indices; HYPRE_Int nnz11, nnz21, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int *A_offd_i, *A_offd_j; HYPRE_Int nrows, nnz; HYPRE_BigInt global_nrows, global_ncols, *row_starts, *col_starts, *itmp_array; HYPRE_Int *diag_i, *diag_j, row, *offd_i, *offd_j, nnz11_offd, nnz21_offd; HYPRE_Complex *A_diag_a, *diag_a, *offd_a; hypre_ParCSRMatrix *A11_csr, *A21_csr; hypre_CSRMatrix *A_diag, *diag, *A_offd, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = (HYPRE_Int)hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); A_offd = hypre_ParCSRMatrixOffd(A_csr); A_offd_i = hypre_CSRMatrixI(A_offd); A_offd_j = hypre_CSRMatrixJ(A_offd); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); proc_offsets2 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) proc_offsets2[i] = (HYPRE_Int)(itmp_array[i] - proc_offsets1[i]); /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = hypre_TAlloc(HYPRE_Int, nrows_A , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractRowSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz21 = nnz11_offd = nnz21_offd = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; } nnz11_offd += A_offd_i[i+1] - A_offd_i[i]; } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) nnz21++; } nnz21_offd += A_offd_i[i+1] - A_offd_i[i]; } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_diag = nnz11; nnz_offd = nnz11_offd; global_nrows = (HYPRE_BigInt)proc_offsets1[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; col_starts[i] = itmp_array[i]; } A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd, HYPRE_MEMORY_HOST); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd, HYPRE_MEMORY_HOST); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * create A21 matrix * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_offd = nnz21_offd; nnz_diag = nnz21; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = itmp_array[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { diag_j[nnz] = A_diag_j[j]; diag_a[nnz++] = A_diag_a[j]; } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd, HYPRE_MEMORY_HOST); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd, HYPRE_MEMORY_HOST); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A21_csr; free(proc_offsets1); free(proc_offsets2); free(exp_indices); } /* ----------------------------------------------------------------------------- * return the sum of all local elements of the matrix * ----------------------------------------------------------------------------- */ HYPRE_Complex hypre_ParCSRMatrixLocalSumElts( hypre_ParCSRMatrix * A ) { hypre_CSRMatrix * A_diag = hypre_ParCSRMatrixDiag( A ); hypre_CSRMatrix * A_offd = hypre_ParCSRMatrixOffd( A ); return hypre_CSRMatrixSumElts(A_diag) + hypre_CSRMatrixSumElts(A_offd); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatAminvDB * computes C = (A - inv(D)B) where D is a diagonal matrix * Note: Data structure of A is expected to be a subset of data structure of B! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixAminvDB( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B, HYPRE_Complex *d, hypre_ParCSRMatrix **C_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_ParCSRMatrix *C = NULL; HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_ParCSRCommPkg *comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_Int num_sends_B, num_recvs_B; HYPRE_Int i, j, cnt; HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_offd = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_offd_i = NULL; HYPRE_Int *C_offd_j = NULL; HYPRE_Complex *C_offd_data = NULL; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs_B; HYPRE_Int *send_procs_B; HYPRE_Int *recv_vec_starts_B; HYPRE_Int *send_map_starts_B; HYPRE_Int *send_map_elmts_B; hypre_ParCSRCommPkg *comm_pkg_C; HYPRE_Int *recv_procs_C; HYPRE_Int *send_procs_C; HYPRE_Int *recv_vec_starts_C; HYPRE_Int *send_map_starts_C; HYPRE_Int *send_map_elmts_C; HYPRE_Int *map_to_B; /*HYPRE_Int *C_diag_array; HYPRE_Int *C_offd_array;*/ HYPRE_Complex *D_tmp; HYPRE_Int size, rest, num_threads, ii; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); /*C_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads); C_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);*/ /*--------------------------------------------------------------------- * If there exists no CommPkg for B, a CommPkg is generated *--------------------------------------------------------------------*/ if (!comm_pkg_B) { hypre_MatvecCommPkgCreate(B); comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); } C = hypre_ParCSRMatrixClone(B, 0); /*hypre_ParCSRMatrixInitialize(C);*/ C_diag = hypre_ParCSRMatrixDiag(C); C_diag_i = hypre_CSRMatrixI(C_diag); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); C_offd = hypre_ParCSRMatrixOffd(C); C_offd_i = hypre_CSRMatrixI(C_offd); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); size = num_rows/num_threads; rest = num_rows - size*num_threads; D_tmp = hypre_CTAlloc(HYPRE_Complex, num_rows, HYPRE_MEMORY_HOST); if (num_cols_offd_A) { map_to_B = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A, HYPRE_MEMORY_HOST); cnt = 0; for (i=0; i < num_cols_offd_A; i++) { while (col_map_offd_B[cnt] < col_map_offd_A[i]) { cnt++; } map_to_B[i] = cnt; cnt++; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii, i, j) #endif for (ii=0; ii < num_threads; ii++) { HYPRE_Int *A_marker = NULL; HYPRE_Int ns, ne, A_col, num_cols, nmax; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } nmax = hypre_max(num_rows, num_cols_offd_B); A_marker = hypre_CTAlloc(HYPRE_Int, nmax, HYPRE_MEMORY_HOST); for (i=0; i < num_rows; i++) A_marker[i] = -1; for (i=ns; i < ne; i++) D_tmp[i] = 1.0/d[i]; num_cols = C_diag_i[ns]; for (i=ns; i < ne; i++) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { A_col = A_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = A_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] += A_diag_data[j]; } } for (j = B_diag_i[i]; j < B_diag_i[i+1]; j++) { A_col = B_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = -D_tmp[i]*B_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] -= D_tmp[i]*B_diag_data[j]; } } } for (i=0; i < num_cols_offd_B; i++) A_marker[i] = -1; num_cols = C_offd_i[ns]; for (i=ns; i < ne; i++) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { A_col = map_to_B[A_offd_j[j]]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = A_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] += A_offd_data[j]; } } for (j = B_offd_i[i]; j < B_offd_i[i+1]; j++) { A_col = B_offd_j[j]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = -D_tmp[i]*B_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] -= D_tmp[i]*B_offd_data[j]; } } } hypre_TFree(A_marker, HYPRE_MEMORY_HOST); } /* end parallel region */ /*for (i=0; i < num_cols_offd_B; i++) col_map_offd_C[i] = col_map_offd_B[i]; */ num_sends_B = hypre_ParCSRCommPkgNumSends(comm_pkg_B); num_recvs_B = hypre_ParCSRCommPkgNumRecvs(comm_pkg_B); recv_procs_B = hypre_ParCSRCommPkgRecvProcs(comm_pkg_B); recv_vec_starts_B = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_B); send_procs_B = hypre_ParCSRCommPkgSendProcs(comm_pkg_B); send_map_starts_B = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_B); send_map_elmts_B = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_B); recv_procs_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B, HYPRE_MEMORY_HOST); recv_vec_starts_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B+1, HYPRE_MEMORY_HOST); send_procs_C = hypre_CTAlloc(HYPRE_Int, num_sends_B, HYPRE_MEMORY_HOST); send_map_starts_C = hypre_CTAlloc(HYPRE_Int, num_sends_B+1, HYPRE_MEMORY_HOST); send_map_elmts_C = hypre_CTAlloc(HYPRE_Int, send_map_starts_B[num_sends_B], HYPRE_MEMORY_HOST); for (i=0; i < num_recvs_B; i++) recv_procs_C[i] = recv_procs_B[i]; for (i=0; i < num_recvs_B+1; i++) recv_vec_starts_C[i] = recv_vec_starts_B[i]; for (i=0; i < num_sends_B; i++) send_procs_C[i] = send_procs_B[i]; for (i=0; i < num_sends_B+1; i++) send_map_starts_C[i] = send_map_starts_B[i]; for (i=0; i < send_map_starts_B[num_sends_B]; i++) send_map_elmts_C[i] = send_map_elmts_B[i]; comm_pkg_C = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_C) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg_C) = num_recvs_B; hypre_ParCSRCommPkgRecvProcs(comm_pkg_C) = recv_procs_C; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_C) = recv_vec_starts_C; hypre_ParCSRCommPkgNumSends(comm_pkg_C) = num_sends_B; hypre_ParCSRCommPkgSendProcs(comm_pkg_C) = send_procs_C; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_C) = send_map_starts_C; hypre_ParCSRCommPkgSendMapElmts(comm_pkg_C) = send_map_elmts_C; hypre_ParCSRMatrixCommPkg(C) = comm_pkg_C; hypre_TFree(D_tmp, HYPRE_MEMORY_HOST); if (num_cols_offd_A) hypre_TFree(map_to_B, HYPRE_MEMORY_HOST); *C_ptr = C; return (hypre_error_flag); } /*-------------------------------------------------------------------------- * hypre_ParTMatmul : multiplies two ParCSRMatrices transpose(A) and B and returns * the product in ParCSRMatrix C * Note that C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix *hypre_ParTMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *AT_diag = NULL; hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *AT_offd = NULL; HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_BigInt first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_BigInt *col_starts_A = hypre_ParCSRMatrixColStarts(A); HYPRE_BigInt *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); hypre_ParCSRMatrix *C; HYPRE_BigInt *col_map_offd_C = NULL; HYPRE_Int *map_B_to_C; hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_tmp_diag = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_BigInt first_col_diag_C; HYPRE_BigInt last_col_diag_C; hypre_CSRMatrix *C_offd = NULL; hypre_CSRMatrix *C_tmp_offd = NULL; hypre_CSRMatrix *C_int = NULL; hypre_CSRMatrix *C_ext = NULL; HYPRE_Int *C_ext_i; HYPRE_BigInt *C_ext_j; HYPRE_Complex *C_ext_data; HYPRE_Int *C_ext_diag_i; HYPRE_Int *C_ext_diag_j; HYPRE_Complex *C_ext_diag_data; HYPRE_Int *C_ext_offd_i; HYPRE_Int *C_ext_offd_j; HYPRE_Complex *C_ext_offd_data; HYPRE_Int C_ext_size = 0; HYPRE_Int C_ext_diag_size = 0; HYPRE_Int C_ext_offd_size = 0; HYPRE_Int *C_tmp_diag_i; HYPRE_Int *C_tmp_diag_j; HYPRE_Complex *C_tmp_diag_data; HYPRE_Int *C_tmp_offd_i; HYPRE_Int *C_tmp_offd_j; HYPRE_Complex *C_tmp_offd_data; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_BigInt *temp; HYPRE_Int *send_map_starts_A; HYPRE_Int *send_map_elmts_A; HYPRE_Int num_sends_A; HYPRE_Int num_cols_offd_C = 0; HYPRE_Int *P_marker; HYPRE_Int i, j; HYPRE_Int i1, j_indx; HYPRE_BigInt n_rows_A, n_cols_A; HYPRE_BigInt n_rows_B, n_cols_B; /*HYPRE_Int allsquare = 0;*/ HYPRE_Int cnt, cnt_offd, cnt_diag; HYPRE_BigInt value; HYPRE_Int num_procs, my_id; HYPRE_Int max_num_threads; HYPRE_Int *C_diag_array = NULL; HYPRE_Int *C_offd_array = NULL; HYPRE_BigInt first_row_index, first_col_diag; HYPRE_Int local_num_rows, local_num_cols; n_rows_A = hypre_ParCSRMatrixGlobalNumRows(A); n_cols_A = hypre_ParCSRMatrixGlobalNumCols(A); n_rows_B = hypre_ParCSRMatrixGlobalNumRows(B); n_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm, &my_id); max_num_threads = hypre_NumThreads(); if (n_rows_A != n_rows_B || num_rows_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } /*if (num_cols_diag_A == num_cols_diag_B) allsquare = 1;*/ hypre_CSRMatrixTranspose(A_diag, &AT_diag, 1); hypre_CSRMatrixTranspose(A_offd, &AT_offd, 1); C_tmp_diag = hypre_CSRMatrixMultiply(AT_diag, B_diag); C_ext_size = 0; if (num_procs > 1) { hypre_CSRMatrix *C_int_diag; hypre_CSRMatrix *C_int_offd; void *request; C_tmp_offd = hypre_CSRMatrixMultiply(AT_diag, B_offd); C_int_diag = hypre_CSRMatrixMultiply(AT_offd, B_diag); C_int_offd = hypre_CSRMatrixMultiply(AT_offd, B_offd); hypre_ParCSRMatrixDiag(B) = C_int_diag; hypre_ParCSRMatrixOffd(B) = C_int_offd; C_int = hypre_MergeDiagAndOffd(B); hypre_ParCSRMatrixDiag(B) = B_diag; hypre_ParCSRMatrixOffd(B) = B_offd; hypre_ExchangeExternalRowsInit(C_int, comm_pkg_A, &request); C_ext = hypre_ExchangeExternalRowsWait(request); C_ext_i = hypre_CSRMatrixI(C_ext); C_ext_j = hypre_CSRMatrixBigJ(C_ext); C_ext_data = hypre_CSRMatrixData(C_ext); C_ext_size = C_ext_i[hypre_CSRMatrixNumRows(C_ext)]; hypre_CSRMatrixDestroy(C_int); hypre_CSRMatrixDestroy(C_int_diag); hypre_CSRMatrixDestroy(C_int_offd); } else { C_tmp_offd = hypre_CSRMatrixCreate(num_cols_diag_A, 0, 0); hypre_CSRMatrixInitialize(C_tmp_offd); } hypre_CSRMatrixDestroy(AT_diag); hypre_CSRMatrixDestroy(AT_offd); /*----------------------------------------------------------------------- * Add contents of C_ext to C_tmp_diag and C_tmp_offd * to obtain C_diag and C_offd *-----------------------------------------------------------------------*/ /* check for new nonzero columns in C_offd generated through C_ext */ first_col_diag_C = first_col_diag_B; last_col_diag_C = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B - 1; C_tmp_diag_i = hypre_CSRMatrixI(C_tmp_diag); if (C_ext_size || num_cols_offd_B) { HYPRE_Int C_ext_num_rows; num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); send_map_starts_A = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); send_map_elmts_A = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_A); C_ext_num_rows = send_map_starts_A[num_sends_A]; C_ext_diag_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1, HYPRE_MEMORY_HOST); C_ext_offd_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1, HYPRE_MEMORY_HOST); temp = hypre_CTAlloc(HYPRE_BigInt, C_ext_size+num_cols_offd_B, HYPRE_MEMORY_HOST); C_ext_diag_size = 0; C_ext_offd_size = 0; for (i=0; i < C_ext_num_rows; i++) { for (j=C_ext_i[i]; j < C_ext_i[i+1]; j++) if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) temp[C_ext_offd_size++] = C_ext_j[j]; else C_ext_diag_size++; C_ext_diag_i[i+1] = C_ext_diag_size; C_ext_offd_i[i+1] = C_ext_offd_size; } cnt = C_ext_offd_size; for (i=0; i < num_cols_offd_B; i++) temp[cnt++] = col_map_offd_B[i]; if (cnt) { hypre_BigQsort0(temp,0,cnt-1); value = temp[0]; num_cols_offd_C = 1; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; hypre_TFree(temp, HYPRE_MEMORY_HOST); if (C_ext_diag_size) { C_ext_diag_j = hypre_CTAlloc(HYPRE_Int, C_ext_diag_size, HYPRE_MEMORY_HOST); C_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, C_ext_diag_size, HYPRE_MEMORY_HOST); } if (C_ext_offd_size) { C_ext_offd_j = hypre_CTAlloc(HYPRE_Int, C_ext_offd_size, HYPRE_MEMORY_HOST); C_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, C_ext_offd_size, HYPRE_MEMORY_HOST); } C_tmp_diag_j = hypre_CSRMatrixJ(C_tmp_diag); C_tmp_diag_data = hypre_CSRMatrixData(C_tmp_diag); C_tmp_offd_i = hypre_CSRMatrixI(C_tmp_offd); C_tmp_offd_j = hypre_CSRMatrixJ(C_tmp_offd); C_tmp_offd_data = hypre_CSRMatrixData(C_tmp_offd); cnt_offd = 0; cnt_diag = 0; for (i=0; i < C_ext_num_rows; i++) { for (j=C_ext_i[i]; j < C_ext_i[i+1]; j++) if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) { C_ext_offd_j[cnt_offd] = hypre_BigBinarySearch(col_map_offd_C, C_ext_j[j], num_cols_offd_C); C_ext_offd_data[cnt_offd++] = C_ext_data[j]; } else { C_ext_diag_j[cnt_diag] = (HYPRE_Int)(C_ext_j[j] - first_col_diag_C); C_ext_diag_data[cnt_diag++] = C_ext_data[j]; } } } if (C_ext) { hypre_CSRMatrixDestroy(C_ext); C_ext = NULL; } if (num_cols_offd_B) { map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); cnt = 0; for (i=0; i < num_cols_offd_C; i++) if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } for (i=0; i < hypre_CSRMatrixI(C_tmp_offd)[hypre_CSRMatrixNumRows(C_tmp_offd)]; i++) { j_indx = C_tmp_offd_j[i]; C_tmp_offd_j[i] = map_B_to_C[j_indx]; } } /*----------------------------------------------------------------------- * Need to compute C_diag = C_tmp_diag + C_ext_diag * and C_offd = C_tmp_offd + C_ext_offd !!!! * First generate structure *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { C_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1, HYPRE_MEMORY_SHARED); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1, HYPRE_MEMORY_SHARED); C_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); C_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int *B_marker_offd = NULL; HYPRE_Int ik, jk, j1, j2, jcol; HYPRE_Int ns, ne, ii, nnz_d, nnz_o; HYPRE_Int rest, size; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_diag_A/num_threads; rest = num_cols_diag_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B, HYPRE_MEMORY_HOST); B_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); for (ik = 0; ik < num_cols_diag_B; ik++) B_marker[ik] = -1; for (ik = 0; ik < num_cols_offd_C; ik++) B_marker_offd[ik] = -1; nnz_d = 0; nnz_o = 0; for (ik = ns; ik < ne; ik++) { for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; B_marker[jcol] = ik; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; B_marker_offd[jcol] = ik; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < ik) { B_marker[jcol] = ik; nnz_d++; } } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < ik) { B_marker_offd[jcol] = ik; nnz_o++; } } break; } C_diag_array[ii] = nnz_d; C_offd_array[ii] = nnz_o; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { nnz_d = 0; nnz_o = 0; for (ik = 0; ik < num_threads-1; ik++) { C_diag_array[ik+1] += C_diag_array[ik]; C_offd_array[ik+1] += C_offd_array[ik]; } nnz_d = C_diag_array[num_threads-1]; nnz_o = C_offd_array[num_threads-1]; C_diag_i[num_cols_diag_A] = nnz_d; C_offd_i[num_cols_diag_A] = nnz_o; C_diag = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_diag_A, nnz_d); C_offd = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_offd_C, nnz_o); hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixInitialize(C_diag); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixInitialize(C_offd); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*----------------------------------------------------------------------- * Need to compute C_diag = C_tmp_diag + C_ext_diag * and C_offd = C_tmp_offd + C_ext_offd !!!! * Now fill in values *-----------------------------------------------------------------------*/ for (ik = 0; ik < num_cols_diag_B; ik++) B_marker[ik] = -1; for (ik = 0; ik < num_cols_offd_C; ik++) B_marker_offd[ik] = -1; /*----------------------------------------------------------------------- * Populate matrices *-----------------------------------------------------------------------*/ nnz_d = 0; nnz_o = 0; nnz_o = 0; if (ii) { nnz_d = C_diag_array[ii-1]; nnz_o = C_offd_array[ii-1]; } for (ik = ns; ik < ne; ik++) { C_diag_i[ik] = nnz_d; C_offd_i[ik] = nnz_o; for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_tmp_diag_data[jk]; B_marker[jcol] = nnz_d; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_tmp_offd_data[jk]; B_marker_offd[jcol] = nnz_o; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < C_diag_i[ik]) { C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_ext_diag_data[j2]; B_marker[jcol] = nnz_d; nnz_d++; } else C_diag_data[B_marker[jcol]] += C_ext_diag_data[j2]; } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < C_offd_i[ik]) { C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_ext_offd_data[j2]; B_marker_offd[jcol] = nnz_o; nnz_o++; } else C_offd_data[B_marker_offd[jcol]] += C_ext_offd_data[j2]; } break; } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); hypre_TFree(B_marker_offd, HYPRE_MEMORY_HOST); } /*end parallel region */ hypre_TFree(C_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(C_offd_array, HYPRE_MEMORY_HOST); } /*C = hypre_ParCSRMatrixCreate(comm, n_cols_A, n_cols_B, col_starts_A, col_starts_B, num_cols_offd_C, nnz_diag, nnz_offd); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); */ #ifdef HYPRE_NO_GLOBAL_PARTITION /* row_starts[0] is start of local rows. row_starts[1] is start of next processor's rows */ first_row_index = col_starts_A[0]; local_num_rows = (HYPRE_Int)(col_starts_A[1]-first_row_index ); first_col_diag = col_starts_B[0]; local_num_cols = (HYPRE_Int)(col_starts_B[1]-first_col_diag); #else first_row_index = col_starts_A[my_id]; local_num_rows = (HYPRE_Int)(col_starts_A[my_id+1]-first_row_index); first_col_diag = col_starts_B[my_id]; local_num_cols = (HYPRE_Int)(col_starts_B[my_id+1]-first_col_diag); #endif C = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixComm(C) = comm; hypre_ParCSRMatrixGlobalNumRows(C) = n_cols_A; hypre_ParCSRMatrixGlobalNumCols(C) = n_cols_B; hypre_ParCSRMatrixFirstRowIndex(C) = first_row_index; hypre_ParCSRMatrixFirstColDiag(C) = first_col_diag; hypre_ParCSRMatrixLastRowIndex(C) = first_row_index + (HYPRE_BigInt)local_num_rows - 1; hypre_ParCSRMatrixLastColDiag(C) = first_col_diag + (HYPRE_BigInt)local_num_cols - 1; hypre_ParCSRMatrixColMapOffd(C) = NULL; hypre_ParCSRMatrixAssumedPartition(C) = NULL; hypre_ParCSRMatrixRowStarts(C) = col_starts_A; hypre_ParCSRMatrixColStarts(C) = col_starts_B; hypre_ParCSRMatrixCommPkg(C) = NULL; hypre_ParCSRMatrixCommPkgT(C) = NULL; /* set defaults */ hypre_ParCSRMatrixOwnsData(C) = 1; hypre_ParCSRMatrixRowindices(C) = NULL; hypre_ParCSRMatrixRowvalues(C) = NULL; hypre_ParCSRMatrixGetrowactive(C) = 0; /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); if (C_diag) hypre_ParCSRMatrixDiag(C) = C_diag; else hypre_ParCSRMatrixDiag(C) = C_tmp_diag; if (C_offd) hypre_ParCSRMatrixOffd(C) = C_offd; else hypre_ParCSRMatrixOffd(C) = C_tmp_offd; if (num_cols_offd_C) { HYPRE_Int jj_count_offd, nnz_offd; HYPRE_BigInt *new_col_map_offd_C = NULL; P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); for (i=0; i < num_cols_offd_C; i++) P_marker[i] = -1; jj_count_offd = 0; nnz_offd = C_offd_i[num_cols_diag_A]; for (i=0; i < nnz_offd; i++) { i1 = C_offd_j[i]; if (P_marker[i1]) { P_marker[i1] = 0; jj_count_offd++; } } if (jj_count_offd < num_cols_offd_C) { new_col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, jj_count_offd, HYPRE_MEMORY_HOST); jj_count_offd = 0; for (i=0; i < num_cols_offd_C; i++) if (!P_marker[i]) { P_marker[i] = jj_count_offd; new_col_map_offd_C[jj_count_offd++] = col_map_offd_C[i]; } for (i=0; i < nnz_offd; i++) { i1 = C_offd_j[i]; C_offd_j[i] = P_marker[i1]; } num_cols_offd_C = jj_count_offd; hypre_TFree(col_map_offd_C, HYPRE_MEMORY_HOST); col_map_offd_C = new_col_map_offd_C; hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(C)) = num_cols_offd_C; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); } hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { hypre_TFree(C_ext_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_offd_i, HYPRE_MEMORY_HOST); } if (C_ext_diag_size) { hypre_TFree(C_ext_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_diag_data, HYPRE_MEMORY_HOST); } if (C_ext_offd_size) { hypre_TFree(C_ext_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_offd_data, HYPRE_MEMORY_HOST); } if (num_cols_offd_B) hypre_TFree(map_B_to_C, HYPRE_MEMORY_HOST); if (C_diag) hypre_CSRMatrixDestroy(C_tmp_diag); if (C_offd) hypre_CSRMatrixDestroy(C_tmp_offd); return C; } HYPRE_Int hypre_ParvecBdiagInvScal( hypre_ParVector *b, HYPRE_Int blockSize, hypre_ParVector **bs, hypre_ParCSRMatrix *A) { MPI_Comm comm = hypre_ParCSRMatrixComm(b); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j, s, block_start, block_end; HYPRE_BigInt nrow_global = hypre_ParVectorGlobalSize(b); HYPRE_BigInt first_row = hypre_ParVectorFirstIndex(b); HYPRE_BigInt last_row = hypre_ParVectorLastIndex(b); HYPRE_BigInt end_row = last_row + 1; /* one past-the-last */ HYPRE_BigInt first_row_block = first_row / (HYPRE_BigInt)(blockSize) * (HYPRE_BigInt)blockSize; HYPRE_BigInt end_row_block = hypre_min( (last_row / (HYPRE_BigInt)blockSize + 1) * (HYPRE_BigInt)blockSize, nrow_global ); hypre_assert(blockSize == A->bdiag_size); HYPRE_Complex *bdiaginv = A->bdiaginv; hypre_ParCSRCommPkg *comm_pkg = A->bdiaginv_comm_pkg; HYPRE_Complex *dense = bdiaginv; //for (i=first_row_block; i < end_row; i+=blockSize) ; //printf("===[%d %d), [ %d %d ) %d === \n", first_row, end_row, first_row_block, end_row_block, i); /* local vector of b */ hypre_Vector *b_local = hypre_ParVectorLocalVector(b); HYPRE_Complex *b_local_data = hypre_VectorData(b_local); /* number of sends (#procs) */ HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ HYPRE_Int num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ HYPRE_Int num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); hypre_ParCSRCommHandle *comm_handle; #ifdef HYPRE_NO_GLOBAL_PARTITION j = 2; #else j = num_procs + 1; #endif HYPRE_BigInt *part = hypre_TAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); memcpy(part, hypre_ParVectorPartitioning(b), j*sizeof(HYPRE_BigInt)); hypre_ParVector *bnew = hypre_ParVectorCreate( hypre_ParVectorComm(b), hypre_ParVectorGlobalSize(b), part ); hypre_ParVectorInitialize(bnew); hypre_Vector *bnew_local = hypre_ParVectorLocalVector(bnew); HYPRE_Complex *bnew_local_data = hypre_VectorData(bnew_local); /* send and recv b */ HYPRE_Complex *send_b = hypre_TAlloc(HYPRE_Complex, num_rows_send, HYPRE_MEMORY_HOST); HYPRE_Complex *recv_b = hypre_TAlloc(HYPRE_Complex, num_rows_recv, HYPRE_MEMORY_HOST); for (i = 0; i < num_rows_send; i++) { j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); send_b[i] = b_local_data[j]; } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, send_b, recv_b); /* ... */ hypre_ParCSRCommHandleDestroy(comm_handle); for (block_start = first_row_block; block_start < end_row_block; block_start += blockSize) { HYPRE_BigInt big_i; block_end = hypre_min(block_start + (HYPRE_BigInt)blockSize, nrow_global); s = (HYPRE_Int)(block_end - block_start); for (big_i = block_start; big_i < block_end; big_i++) { if (big_i < first_row || big_i >= end_row) { continue; } HYPRE_Int local_i = (HYPRE_Int)(big_i - first_row); HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); bnew_local_data[local_i] = 0.0; for (j = 0; j < s; j++) { HYPRE_BigInt global_rid = block_start + (HYPRE_BigInt)j; HYPRE_Complex val = dense[block_i + j*blockSize]; if (val == 0.0) { continue; } if (global_rid >= first_row && global_rid < end_row) { HYPRE_Int rid = (HYPRE_Int)(global_rid - first_row); bnew_local_data[local_i] += val * b_local_data[rid]; } else { HYPRE_Int rid; if (global_rid < first_row) { rid = (HYPRE_Int)(global_rid - first_row_block); } else { rid = (HYPRE_Int)(first_row - first_row_block + global_rid - end_row); } bnew_local_data[local_i] += val * recv_b[rid]; } } } dense += blockSize * blockSize; } hypre_TFree(send_b, HYPRE_MEMORY_HOST); hypre_TFree(recv_b, HYPRE_MEMORY_HOST); *bs = bnew; return hypre_error_flag; } /** * @brief Compute As = B^{-1}*A, where B is the block diagonal of A * @param[in] A : * @param[in] blockSize: block size * @param[out] B : * @return * @warning */ HYPRE_Int hypre_ParcsrBdiagInvScal( hypre_ParCSRMatrix *A, HYPRE_Int blockSize, hypre_ParCSRMatrix **As) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j, k, s; HYPRE_BigInt block_start, block_end; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int nrow_local = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt first_row = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_BigInt last_row = hypre_ParCSRMatrixLastRowIndex(A); HYPRE_BigInt end_row = first_row + (HYPRE_BigInt)nrow_local; /* one past-the-last */ HYPRE_Int ncol_local = hypre_CSRMatrixNumCols(A_diag); HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); /* HYPRE_Int last_col = hypre_ParCSRMatrixLastColDiag(A); */ HYPRE_BigInt end_col = first_col + (HYPRE_BigInt)ncol_local; HYPRE_BigInt nrow_global = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt ncol_global = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); void *request; /* if square globally and locally */ HYPRE_Int square2 = (nrow_global == ncol_global) && (nrow_local == ncol_local) && (first_row == first_col); if (nrow_global != ncol_global) { hypre_printf("hypre_ParcsrBdiagInvScal: only support N_ROW == N_COL\n"); return hypre_error_flag; } /* in block diagonals, row range of the blocks this proc span */ HYPRE_BigInt first_row_block = first_row / (HYPRE_BigInt)blockSize * (HYPRE_BigInt)blockSize; HYPRE_BigInt end_row_block = hypre_min( (last_row / (HYPRE_BigInt)blockSize + 1) * (HYPRE_BigInt)blockSize, nrow_global ); HYPRE_Int num_blocks = (HYPRE_Int)(last_row / (HYPRE_BigInt)blockSize + 1 - first_row / (HYPRE_BigInt)blockSize); //for (i=first_row_block; i < end_row; i+=blockSize) ; //printf("===[%d %d), [ %d %d ) %d === \n", first_row, end_row, first_row_block, end_row_block, i); //return 0; /* number of external rows */ HYPRE_Int num_ext_rows = (HYPRE_Int)(end_row_block - first_row_block - (end_row - first_row)); HYPRE_BigInt *ext_indices; HYPRE_Int A_ext_nnz; hypre_CSRMatrix *A_ext = NULL; HYPRE_Complex *A_ext_a = NULL; HYPRE_Int *A_ext_i = NULL; HYPRE_BigInt *A_ext_j = NULL; HYPRE_Real *dense_all = hypre_CTAlloc(HYPRE_Complex, num_blocks*blockSize*blockSize, HYPRE_MEMORY_HOST); HYPRE_Real *dense = dense_all; HYPRE_Int *IPIV = hypre_TAlloc(HYPRE_Int, blockSize, HYPRE_MEMORY_HOST); HYPRE_Complex *dgetri_work = NULL; HYPRE_Int dgetri_lwork = -1, lapack_info; HYPRE_Int num_cols_A_offd_new; HYPRE_BigInt *col_map_offd_A_new; HYPRE_BigInt big_i; HYPRE_Int *offd2new = NULL; HYPRE_Int *marker_diag, *marker_newoffd; HYPRE_Int nnz_diag = A_diag_i[nrow_local]; HYPRE_Int nnz_offd = A_offd_i[nrow_local]; HYPRE_Int nnz_diag_new = 0, nnz_offd_new = 0; HYPRE_Int *A_diag_i_new, *A_diag_j_new, *A_offd_i_new, *A_offd_j_new; HYPRE_Complex *A_diag_a_new, *A_offd_a_new; /* heuristic */ HYPRE_Int nnz_diag_alloc = 2 * nnz_diag; HYPRE_Int nnz_offd_alloc = 2 * nnz_offd; A_diag_i_new = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); A_diag_j_new = hypre_CTAlloc(HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_CTAlloc(HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_offd_i_new = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); A_offd_j_new = hypre_CTAlloc(HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_CTAlloc(HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); hypre_ParCSRMatrix *Anew; hypre_CSRMatrix *Anew_diag; hypre_CSRMatrix *Anew_offd; HYPRE_BigInt *row_starts_new, *col_starts_new; HYPRE_Real eps = 2.2e-16; /* Start with extracting the external rows */ HYPRE_BigInt *ext_offd; ext_indices = hypre_CTAlloc(HYPRE_BigInt, num_ext_rows, HYPRE_MEMORY_HOST); j = 0; for (big_i = first_row_block; big_i < first_row; big_i++) { ext_indices[j++] = big_i; } for (big_i = end_row; big_i < end_row_block; big_i++) { ext_indices[j++] = big_i; } hypre_assert(j == num_ext_rows); /* create CommPkg for external rows */ hypre_ParCSRFindExtendCommPkg(comm, nrow_global, first_row, nrow_local, row_starts, hypre_ParCSRMatrixAssumedPartition(A), num_ext_rows, ext_indices, &A->bdiaginv_comm_pkg); hypre_ParcsrGetExternalRowsInit(A, num_ext_rows, ext_indices, A->bdiaginv_comm_pkg, 1, &request); A_ext = hypre_ParcsrGetExternalRowsWait(request); hypre_TFree(ext_indices, HYPRE_MEMORY_HOST); A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_a = hypre_CSRMatrixData(A_ext); A_ext_nnz = A_ext_i[num_ext_rows]; ext_offd = hypre_CTAlloc(HYPRE_BigInt, A_ext_nnz, HYPRE_MEMORY_HOST); /* fint the offd incides in A_ext */ for (i = 0, j = 0; i < A_ext_nnz; i++) { /* global index */ HYPRE_BigInt cid = A_ext_j[i]; /* keep the offd indices */ if (cid < first_col || cid >= end_col) { ext_offd[j++] = cid; } } /* remove duplicates after sorting (TODO better ways?) */ hypre_BigQsort0(ext_offd, 0, j-1); for (i = 0, k = 0; i < j; i++) { if (i == 0 || ext_offd[i] != ext_offd[i-1]) { ext_offd[k++] = ext_offd[i]; } } /* uniion these `k' new indices into col_map_offd_A */ col_map_offd_A_new = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd + k, HYPRE_MEMORY_HOST); if (k) { /* map offd to offd_new */ offd2new = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); } hypre_union2(num_cols_A_offd, col_map_offd_A, k, ext_offd, &num_cols_A_offd_new, col_map_offd_A_new, offd2new, NULL); hypre_TFree(ext_offd, HYPRE_MEMORY_HOST); /* * adjust column indices in A_ext */ for (i = 0; i < A_ext_nnz; i++) { HYPRE_BigInt cid = A_ext_j[i]; if (cid < first_col || cid >= end_col) { j = hypre_BigBinarySearch(col_map_offd_A_new, cid, num_cols_A_offd_new); /* searching must succeed */ hypre_assert(j >= 0 && j < num_cols_A_offd_new); /* trick: save ncol_local + j back */ A_ext_j[i] = ncol_local + j; } else { /* save local index: [0, ncol_local-1] */ A_ext_j[i] = cid - first_col; } } /* marker for diag */ marker_diag = hypre_TAlloc(HYPRE_Int, ncol_local, HYPRE_MEMORY_HOST); for (i = 0; i < ncol_local; i++) { marker_diag[i] = -1; } /* marker for newoffd */ marker_newoffd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd_new, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_A_offd_new; i++) { marker_newoffd[i] = -1; } /* outer most loop for blocks */ for (block_start = first_row_block; block_start < end_row_block; block_start += (HYPRE_BigInt)blockSize) { HYPRE_BigInt big_i; block_end = hypre_min(block_start + (HYPRE_BigInt)blockSize, nrow_global); s = (HYPRE_Int)(block_end - block_start); /* 1. fill the dense block diag matrix */ for (big_i = block_start; big_i < block_end; big_i++) { /* row index in this block */ HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); /* row index i: it can be local or external */ if (big_i >= first_row && big_i < end_row) { /* is a local row */ j = (HYPRE_Int)(big_i - first_row); for (k = A_diag_i[j]; k < A_diag_i[j+1]; k++) { HYPRE_BigInt cid = (HYPRE_BigInt)A_diag_j[k] + first_col; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_diag_a[k]; } } if (num_cols_A_offd) { for (k = A_offd_i[j]; k < A_offd_i[j+1]; k++) { HYPRE_BigInt cid = col_map_offd_A[A_offd_j[k]]; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_offd_a[k]; } } } } else { /* is an external row */ if (big_i < first_row) { j = (HYPRE_Int)(big_i - first_row_block); } else { j = (HYPRE_Int)(first_row - first_row_block + big_i - end_row); } for (k = A_ext_i[j]; k < A_ext_i[j+1]; k++) { HYPRE_BigInt cid = A_ext_j[k]; /* recover the global index */ cid = cid < (HYPRE_BigInt)ncol_local ? cid + first_col : col_map_offd_A_new[cid-ncol_local]; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_ext_a[k]; } } } } /* 2. invert the dense matrix */ hypre_dgetrf(&s, &s, dense, &blockSize, IPIV, &lapack_info); hypre_assert(lapack_info == 0); if (lapack_info == 0) { HYPRE_Int query = -1; HYPRE_Real lwork_opt; /* query the optimal size of work */ hypre_dgetri(&s, dense, &blockSize, IPIV, &lwork_opt, &query, &lapack_info); hypre_assert(lapack_info == 0); if (lwork_opt > dgetri_lwork) { dgetri_lwork = lwork_opt; dgetri_work = hypre_TReAlloc(dgetri_work, HYPRE_Complex, dgetri_lwork, HYPRE_MEMORY_HOST); } hypre_dgetri(&s, dense, &blockSize, IPIV, dgetri_work, &dgetri_lwork, &lapack_info); hypre_assert(lapack_info == 0); } /* filter out *zeros* */ HYPRE_Real Fnorm = 0.0; for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { HYPRE_Complex t = dense[j+i*blockSize]; Fnorm += t * t; } } Fnorm = sqrt(Fnorm); for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { if ( hypre_abs(dense[j+i*blockSize]) < eps * Fnorm ) { dense[j+i*blockSize] = 0.0; } } } /* 3. premultiplication: one-pass dynamic allocation */ for (big_i = block_start; big_i < block_end; big_i++) { /* starting points of this row in j */ HYPRE_Int diag_i_start = nnz_diag_new; HYPRE_Int offd_i_start = nnz_offd_new; /* compute a new row with global index 'i' and local index 'local_i' */ HYPRE_Int local_i = (HYPRE_Int)(big_i - first_row); /* row index in this block */ HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); if (big_i < first_row || big_i >= end_row) { continue; } /* if square^2: reserve the first space in diag part to the diag entry */ if (square2) { marker_diag[local_i] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = local_i; A_diag_a_new[nnz_diag_new] = 0.0; nnz_diag_new ++; } /* combine s rows */ for (j = 0; j < s; j++) { /* row to combine: global row id */ HYPRE_BigInt global_rid = block_start + (HYPRE_BigInt)j; /* the multipiler */ HYPRE_Complex val = dense[block_i + j*blockSize]; if (val == 0.0) { continue; } if (global_rid >= first_row && global_rid < end_row) { /* this row is local */ HYPRE_Int rid = (HYPRE_Int)(global_rid - first_row); HYPRE_Int ii; for (ii = A_diag_i[rid]; ii < A_diag_i[rid+1]; ii++) { HYPRE_Int col = A_diag_j[ii]; HYPRE_Complex vv = A_diag_a[ii]; if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = col; A_diag_a_new[nnz_diag_new] = val * vv; nnz_diag_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(A_diag_j_new[p] == col); A_diag_a_new[p] += val * vv; } } for (ii = A_offd_i[rid]; ii < A_offd_i[rid+1]; ii++) { HYPRE_Int col = A_offd_j[ii]; /* use the mapper to map to new offd */ HYPRE_Int col_new = offd2new ? offd2new[col] : col; HYPRE_Complex vv = A_offd_a[ii]; if (marker_newoffd[col_new] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_newoffd[col_new] = nnz_offd_new; if (nnz_offd_new == nnz_offd_alloc) { nnz_offd_alloc = nnz_offd_alloc * 2 + 1; A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); } A_offd_j_new[nnz_offd_new] = col_new; A_offd_a_new[nnz_offd_new] = val * vv; nnz_offd_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_newoffd[col_new]; hypre_assert(A_offd_j_new[p] == col_new); A_offd_a_new[p] += val * vv; } } } else { /* this is an external row: go to A_ext */ HYPRE_Int rid, ii; if (global_rid < first_row) { rid = (HYPRE_Int)(global_rid - first_row_block); } else { rid = (HYPRE_Int)(first_row - first_row_block + global_rid - end_row); } for (ii = A_ext_i[rid]; ii < A_ext_i[rid+1]; ii++) { HYPRE_Int col = (HYPRE_Int)A_ext_j[ii]; HYPRE_Complex vv = A_ext_a[ii]; if (col < ncol_local) { /* in diag part */ if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = col; A_diag_a_new[nnz_diag_new] = val * vv; nnz_diag_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(A_diag_j_new[p] == col); A_diag_a_new[p] += val * vv; } } else { /* in offd part */ col -= ncol_local; if (marker_newoffd[col] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_newoffd[col] = nnz_offd_new; if (nnz_offd_new == nnz_offd_alloc) { nnz_offd_alloc = nnz_offd_alloc * 2 + 1; A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); } A_offd_j_new[nnz_offd_new] = col; A_offd_a_new[nnz_offd_new] = val * vv; nnz_offd_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_newoffd[col]; hypre_assert(A_offd_j_new[p] == col); A_offd_a_new[p] += val * vv; } } } } } /* done for row local_i */ A_diag_i_new[local_i + 1] = nnz_diag_new; A_offd_i_new[local_i + 1] = nnz_offd_new; } /* for i, each row */ dense += blockSize * blockSize; } /* for each block */ /* done with all rows */ /* resize properly */ A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_new, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_new, HYPRE_MEMORY_HOST); A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_new, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_new, HYPRE_MEMORY_HOST); /* readjust col_map_offd_new */ for (i = 0; i < num_cols_A_offd_new; i++) { marker_newoffd[i] = -1; } for (i = 0; i < nnz_offd_new; i++) { j = A_offd_j_new[i]; if (marker_newoffd[j] == -1) { marker_newoffd[j] = 1; } } for (i = 0, j = 0; i < num_cols_A_offd_new; i++) { if (marker_newoffd[i] == 1) { col_map_offd_A_new[j] = col_map_offd_A_new[i]; marker_newoffd[i] = j++; } } num_cols_A_offd_new = j; for (i = 0; i < nnz_offd_new; i++) { j = marker_newoffd[A_offd_j_new[i]]; hypre_assert(j >= 0 && j < num_cols_A_offd_new); A_offd_j_new[i] = j; } #ifdef HYPRE_NO_GLOBAL_PARTITION j = 2; #else j = num_procs + 1; #endif row_starts_new = hypre_CTAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); col_starts_new = hypre_CTAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); memcpy(row_starts_new, hypre_ParCSRMatrixRowStarts(A), j*sizeof(HYPRE_BigInt)); memcpy(col_starts_new, hypre_ParCSRMatrixColStarts(A), j*sizeof(HYPRE_BigInt)); /* Now, we should have everything of Parcsr matrix As */ Anew = hypre_ParCSRMatrixCreate(comm, nrow_global, ncol_global, row_starts_new, col_starts_new, num_cols_A_offd_new, nnz_diag_new, nnz_offd_new); Anew_diag = hypre_ParCSRMatrixDiag(Anew); hypre_CSRMatrixData(Anew_diag) = A_diag_a_new; hypre_CSRMatrixI(Anew_diag) = A_diag_i_new; hypre_CSRMatrixJ(Anew_diag) = A_diag_j_new; Anew_offd = hypre_ParCSRMatrixOffd(Anew); hypre_CSRMatrixData(Anew_offd) = A_offd_a_new; hypre_CSRMatrixI(Anew_offd) = A_offd_i_new; hypre_CSRMatrixJ(Anew_offd) = A_offd_j_new; hypre_ParCSRMatrixColMapOffd(Anew) = col_map_offd_A_new; hypre_ParCSRMatrixSetNumNonzeros(Anew); hypre_ParCSRMatrixDNumNonzeros(Anew) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(Anew); //printf("nnz_diag %d --> %d, nnz_offd %d --> %d\n", nnz_diag, nnz_diag_new, nnz_offd, nnz_offd_new); /* create CommPkg of Anew */ hypre_MatvecCommPkgCreate(Anew); *As = Anew; /* if (bdiaginv) { *bdiaginv = dense_all; } else { hypre_TFree(dense_all, HYPRE_MEMORY_HOST); } */ /* save diagonal blocks in A */ A->bdiag_size = blockSize; A->bdiaginv = dense_all; /* free workspace */ hypre_TFree(IPIV, HYPRE_MEMORY_HOST); hypre_TFree(dgetri_work, HYPRE_MEMORY_HOST); hypre_TFree(marker_diag, HYPRE_MEMORY_HOST); hypre_TFree(marker_newoffd, HYPRE_MEMORY_HOST); hypre_TFree(offd2new, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_ext); return hypre_error_flag; } HYPRE_Int hypre_ParcsrGetExternalRowsInit( hypre_ParCSRMatrix *A, HYPRE_Int indices_len, HYPRE_BigInt *indices, hypre_ParCSRCommPkg *comm_pkg, HYPRE_Int want_data, void **request_ptr) { HYPRE_Int i, j, k; HYPRE_Int num_sends, num_rows_send, num_nnz_send, *send_i, num_recvs, num_rows_recv, num_nnz_recv, *recv_i, *send_jstarts, *recv_jstarts, *send_i_offset; HYPRE_BigInt *send_j, *recv_j; HYPRE_Complex *send_a = NULL, *recv_a = NULL; hypre_ParCSRCommPkg *comm_pkg_j; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; /* HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); */ /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /* HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); */ /* HYPRE_BigInt first_row = hypre_ParCSRMatrixFirstRowIndex(A); */ HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs; HYPRE_Int my_id; void **vrequest; hypre_CSRMatrix *A_ext; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /* number of sends (#procs) */ num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); /* must be true if indices contains proper offd indices */ hypre_assert(indices_len == num_rows_recv); /* send_i/recv_i: * the arrays to send and recv: we first send and recv the row lengths */ send_i = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST); recv_i = hypre_CTAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_HOST); /* fill the send array with row lengths */ for (i = 0, num_nnz_send = 0; i < num_rows_send; i++) { /* j: row index to send */ j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); send_i[i] = A_diag_i[j+1] - A_diag_i[j] + A_offd_i[j+1] - A_offd_i[j]; num_nnz_send += send_i[i]; } /* send this array out: note the shift in recv_i by one (async) */ comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_i, recv_i+1); /* prepare data to send out. overlap with the above commmunication */ send_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_send, HYPRE_MEMORY_HOST); if (want_data) { send_a = hypre_TAlloc(HYPRE_Complex, num_nnz_send, HYPRE_MEMORY_HOST); } send_i_offset = hypre_TAlloc(HYPRE_Int, num_rows_send + 1, HYPRE_MEMORY_HOST); send_i_offset[0] = 0; hypre_TMemcpy(send_i_offset + 1, send_i, HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); /* prefix sum. TODO: OMP parallelization */ for (i = 1; i <= num_rows_send; i++) { send_i_offset[i] += send_i_offset[i-1]; } hypre_assert(send_i_offset[num_rows_send] == num_nnz_send); /* pointers to each proc in send_j */ send_jstarts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = 0; i <= num_sends; i++) { send_jstarts[i] = send_i_offset[hypre_ParCSRCommPkgSendMapStart(comm_pkg, i)]; } hypre_assert(send_jstarts[num_sends] == num_nnz_send); /* fill the CSR matrix: j and a */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE private(i,j,k) #endif for (i = 0; i < num_rows_send; i++) { HYPRE_Int i1 = send_i_offset[i]; j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); /* open row j and fill ja and a to send */ for (k = A_diag_i[j]; k < A_diag_i[j+1]; k++) { send_j[i1] = first_col + A_diag_j[k]; if (want_data) { send_a[i1] = A_diag_a[k]; } i1++; } if (num_procs > 1) { for (k = A_offd_i[j]; k < A_offd_i[j+1]; k++) { send_j[i1] = col_map_offd_A[A_offd_j[k]]; if (want_data) { send_a[i1] = A_offd_a[k]; } i1++; } } hypre_assert(send_i_offset[i+1] == i1); } /* finish the above communication: send_i/recv_i */ hypre_ParCSRCommHandleDestroy(comm_handle); /* adjust recv_i to ptrs */ for (i = 1; i <= num_rows_recv; i++) { recv_i[i] += recv_i[i-1]; } num_nnz_recv = recv_i[num_rows_recv]; recv_j = hypre_CTAlloc(HYPRE_BigInt, num_nnz_recv, HYPRE_MEMORY_HOST); if (want_data) { recv_a = hypre_CTAlloc(HYPRE_Complex, num_nnz_recv, HYPRE_MEMORY_HOST); } recv_jstarts = hypre_CTAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); for (i = 1; i <= num_recvs; i++) { j = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); recv_jstarts[i] = recv_i[j]; } /* ready to send and recv: create a communication package for data */ comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm (comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends (comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs (comm_pkg_j) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = send_jstarts; hypre_ParCSRCommPkgNumRecvs (comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgRecvProcs (comm_pkg_j) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = recv_jstarts; /* init communication */ /* ja */ comm_handle_j = hypre_ParCSRCommHandleCreate(21, comm_pkg_j, send_j, recv_j); if (want_data) { /* a */ comm_handle_a = hypre_ParCSRCommHandleCreate(1, comm_pkg_j, send_a, recv_a); } else { comm_handle_a = NULL; } /* create A_ext */ A_ext = hypre_CSRMatrixCreate(num_rows_recv, hypre_ParCSRMatrixGlobalNumCols(A), num_nnz_recv); hypre_CSRMatrixMemoryLocation(A_ext) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI (A_ext) = recv_i; hypre_CSRMatrixBigJ(A_ext) = recv_j; hypre_CSRMatrixData(A_ext) = recv_a; /* output */ vrequest = hypre_TAlloc(void *, 4, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) A_ext; vrequest[3] = (void *) comm_pkg_j; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(send_i, HYPRE_MEMORY_HOST); hypre_TFree(send_i_offset, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParcsrGetExternalRowsWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *A_ext = (hypre_CSRMatrix *) request[2]; hypre_ParCSRCommPkg *comm_pkg_j = (hypre_ParCSRCommPkg *) request[3]; HYPRE_BigInt *send_j = (HYPRE_BigInt *) hypre_ParCSRCommHandleSendData(comm_handle_j); if (comm_handle_a) { HYPRE_Complex *send_a = (HYPRE_Complex *) hypre_ParCSRCommHandleSendData(comm_handle_a); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(send_a, HYPRE_MEMORY_HOST); } hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_TFree(send_j, HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); hypre_TFree(request, HYPRE_MEMORY_HOST); return A_ext; } /* C = alpha * A + beta * B * A and B are assumed to have the same row and column partitionings */ HYPRE_Int hypre_ParcsrAdd( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **Cout ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int *A2C_offd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); HYPRE_BigInt nrow_global = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt ncol_global = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_Int nrow_local = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int ncol_local = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int nnz_diag_A = A_diag_i[nrow_local]; HYPRE_Int nnz_offd_A = A_offd_i[nrow_local]; /* diag part of B */ hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Complex *B_diag_a = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); /* off-diag part of B */ hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Complex *B_offd_a = hypre_CSRMatrixData(B_offd); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Int num_cols_B_offd = hypre_CSRMatrixNumCols(B_offd); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Int *B2C_offd = hypre_TAlloc(HYPRE_Int, num_cols_B_offd, HYPRE_MEMORY_HOST); hypre_assert(nrow_global == hypre_ParCSRMatrixGlobalNumRows(B)); hypre_assert(ncol_global == hypre_ParCSRMatrixGlobalNumCols(B)); hypre_assert(nrow_local == hypre_CSRMatrixNumRows(B_diag)); hypre_assert(ncol_local == hypre_CSRMatrixNumCols(B_diag)); HYPRE_Int nnz_diag_B = B_diag_i[nrow_local]; HYPRE_Int nnz_offd_B = B_offd_i[nrow_local]; /* C */ hypre_ParCSRMatrix *C; HYPRE_BigInt *row_starts_C, *col_starts_C; hypre_CSRMatrix *C_diag; hypre_CSRMatrix *C_offd; HYPRE_Int num_cols_C_offd = num_cols_A_offd + num_cols_B_offd; HYPRE_BigInt *col_map_offd_C = hypre_TAlloc(HYPRE_BigInt, num_cols_C_offd, HYPRE_MEMORY_HOST); HYPRE_Int nnz_diag_C_alloc = nnz_diag_A + nnz_diag_B; HYPRE_Int nnz_offd_C_alloc = nnz_offd_A + nnz_offd_B; HYPRE_Int nnz_diag_C = 0, nnz_offd_C = 0; HYPRE_Int *C_diag_i = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); HYPRE_Int *C_diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag_C_alloc, HYPRE_MEMORY_HOST); HYPRE_Complex *C_diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag_C_alloc, HYPRE_MEMORY_HOST); HYPRE_Int *C_offd_i = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); HYPRE_Int *C_offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd_C_alloc, HYPRE_MEMORY_HOST); HYPRE_Complex *C_offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd_C_alloc, HYPRE_MEMORY_HOST); hypre_union2( num_cols_A_offd, col_map_offd_A, num_cols_B_offd, col_map_offd_B, &num_cols_C_offd, col_map_offd_C, A2C_offd, B2C_offd ); HYPRE_Int *marker_diag = hypre_TAlloc(HYPRE_Int, ncol_local, HYPRE_MEMORY_HOST); HYPRE_Int *marker_offd = hypre_TAlloc(HYPRE_Int, num_cols_C_offd, HYPRE_MEMORY_HOST); for (i = 0; i < ncol_local; i++) { marker_diag[i] = -1; } for (i = 0; i < num_cols_C_offd; i++) { marker_offd[i] = -1; } /* main loop for each row i */ for (i = 0; i < nrow_local; i++) { HYPRE_Int diag_i_start = nnz_diag_C; HYPRE_Int offd_i_start = nnz_offd_C; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { HYPRE_Int col = A_diag_j[j]; HYPRE_Complex val = A_diag_a[j]; if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_C; C_diag_j[nnz_diag_C] = col; C_diag_a[nnz_diag_C] = alpha * val; nnz_diag_C ++; } else { /* this should not happen */ hypre_printf("hypre warning: invalid ParCSR matrix %s %s %d\n", __FILE__, __func__, __LINE__); } } for (j = B_diag_i[i]; j < B_diag_i[i+1]; j++) { HYPRE_Int col = B_diag_j[j]; HYPRE_Complex val = B_diag_a[j]; if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_C; C_diag_j[nnz_diag_C] = col; C_diag_a[nnz_diag_C] = beta * val; nnz_diag_C ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(C_diag_j[p] == col); C_diag_a[p] += beta * val; } } C_diag_i[i+1] = nnz_diag_C; if (num_procs <= 1) { continue; } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { HYPRE_Int colA = A_offd_j[j]; HYPRE_Int colC = A2C_offd[colA]; HYPRE_Complex val = A_offd_a[j]; if (marker_offd[colC] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_offd[colC] = nnz_offd_C; C_offd_j[nnz_offd_C] = colC; C_offd_a[nnz_offd_C] = alpha * val; nnz_offd_C ++; } else { /* this should not happen */ hypre_printf("hypre warning: invalid ParCSR matrix %s %s %d\n", __FILE__, __func__, __LINE__); } } for (j = B_offd_i[i]; j < B_offd_i[i+1]; j++) { HYPRE_Int colB = B_offd_j[j]; HYPRE_Int colC = B2C_offd[colB]; HYPRE_Complex val = B_offd_a[j]; if (marker_offd[colC] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_offd[colC] = nnz_offd_C; C_offd_j[nnz_offd_C] = colC; C_offd_a[nnz_offd_C] = beta * val; nnz_offd_C ++; } else { /* existing entry, update */ HYPRE_Int p = marker_offd[colC]; hypre_assert(C_offd_j[p] == colC); C_offd_a[p] += beta * val; } } C_offd_i[i+1] = nnz_offd_C; } #ifdef HYPRE_NO_GLOBAL_PARTITION j = 2; #else j = num_procs + 1; #endif row_starts_C = hypre_TAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); col_starts_C = hypre_TAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); memcpy(row_starts_C, hypre_ParCSRMatrixRowStarts(A), j*sizeof(HYPRE_BigInt)); memcpy(col_starts_C, hypre_ParCSRMatrixColStarts(A), j*sizeof(HYPRE_BigInt)); /* Now, we should have everything of Parcsr matrix C */ C = hypre_ParCSRMatrixCreate(comm, nrow_global, ncol_global, row_starts_C, col_starts_C, num_cols_C_offd, nnz_diag_C, nnz_offd_C); C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrixData(C_diag) = C_diag_a; hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixJ(C_diag) = C_diag_j; hypre_CSRMatrixMemoryLocation(C_diag) = HYPRE_MEMORY_HOST; C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrixData(C_offd) = C_offd_a; hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_CSRMatrixMemoryLocation(C_offd) = HYPRE_MEMORY_HOST; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; hypre_ParCSRMatrixSetNumNonzeros(C); hypre_ParCSRMatrixDNumNonzeros(C) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(C); /* create CommPkg of C */ hypre_MatvecCommPkgCreate(C); *Cout = C; /* done */ hypre_TFree(A2C_offd, HYPRE_MEMORY_HOST); hypre_TFree(B2C_offd, HYPRE_MEMORY_HOST); hypre_TFree(marker_diag, HYPRE_MEMORY_HOST); hypre_TFree(marker_offd, HYPRE_MEMORY_HOST); return hypre_error_flag; } HYPRE_Real hypre_ParCSRMatrixFnorm( hypre_ParCSRMatrix *A ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Real f_diag, f_offd, local_result, result; f_diag = hypre_CSRMatrixFnorm(hypre_ParCSRMatrixDiag(A)); f_offd = hypre_CSRMatrixFnorm(hypre_ParCSRMatrixOffd(A)); local_result = f_diag * f_diag + f_offd * f_offd; hypre_MPI_Allreduce(&local_result, &result, 1, HYPRE_MPI_REAL, hypre_MPI_SUM, comm); return sqrt(result); } HYPRE_Int hypre_ExchangeExternalRowsInit( hypre_CSRMatrix *B_ext, hypre_ParCSRCommPkg *comm_pkg_A, void **request_ptr) { MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_A); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int num_elmts_send = send_map_starts[num_sends]; HYPRE_Int num_elmts_recv = recv_vec_starts[num_recvs]; HYPRE_Int *B_ext_i = B_ext ? hypre_CSRMatrixI(B_ext) : NULL; HYPRE_BigInt *B_ext_j = B_ext ? hypre_CSRMatrixBigJ(B_ext) : NULL; HYPRE_Complex *B_ext_data = B_ext ? hypre_CSRMatrixData(B_ext) : NULL; HYPRE_Int B_ext_ncols = B_ext ? hypre_CSRMatrixNumCols(B_ext) : 0; HYPRE_Int B_ext_nrows = B_ext ? hypre_CSRMatrixNumRows(B_ext) : 0; HYPRE_Int *B_ext_rownnz = hypre_CTAlloc(HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST); hypre_assert(num_elmts_recv == B_ext_nrows); /* output matrix */ hypre_CSRMatrix *B_int; HYPRE_Int B_int_nrows = num_elmts_send; HYPRE_Int B_int_ncols = B_ext_ncols; HYPRE_Int *B_int_i = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_HOST); HYPRE_BigInt *B_int_j = NULL; HYPRE_Complex *B_int_data = NULL; HYPRE_Int B_int_nnz; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; hypre_ParCSRCommPkg *comm_pkg_j; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i; HYPRE_Int num_procs; void **vrequest; hypre_MPI_Comm_size(comm, &num_procs); jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); /*-------------------------------------------------------------------------- * B_ext_rownnz contains the number of elements of row j * (to be determined through send_map_elmnts on the receiving end) *--------------------------------------------------------------------------*/ for (i = 0; i < B_ext_nrows; i++) { B_ext_rownnz[i] = B_ext_i[i+1] - B_ext_i[i]; } /*-------------------------------------------------------------------------- * initialize communication: send/recv the row nnz * (note the use of comm_pkg_A, mode 12, as in transpose matvec *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_A, B_ext_rownnz, B_int_i + 1); jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts[0] = 0; for (i = 1; i <= num_recvs; i++) { jdata_recv_vec_starts[i] = B_ext_i[recv_vec_starts[i]]; } comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgNumRecvs(comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg_j) = recv_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg_j) = send_procs; hypre_ParCSRCommHandleDestroy(comm_handle); /*-------------------------------------------------------------------------- * compute B_int: row nnz to row ptrs *--------------------------------------------------------------------------*/ B_int_i[0] = 0; for (i = 1; i <= B_int_nrows; i++) { B_int_i[i] += B_int_i[i-1]; } B_int_nnz = B_int_i[B_int_nrows]; B_int_j = hypre_TAlloc(HYPRE_BigInt, B_int_nnz, HYPRE_MEMORY_HOST); B_int_data = hypre_TAlloc(HYPRE_Complex, B_int_nnz, HYPRE_MEMORY_HOST); for (i = 0; i <= num_sends; i++) { jdata_send_map_starts[i] = B_int_i[send_map_starts[i]]; } /* note the order of send/recv is reversed */ hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = jdata_send_map_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = jdata_recv_vec_starts; /* send/recv CSR rows */ comm_handle_a = hypre_ParCSRCommHandleCreate( 1, comm_pkg_j, B_ext_data, B_int_data); comm_handle_j = hypre_ParCSRCommHandleCreate(21, comm_pkg_j, B_ext_j, B_int_j); /* create CSR */ B_int = hypre_CSRMatrixCreate(B_int_nrows, B_int_ncols, B_int_nnz); hypre_CSRMatrixMemoryLocation(B_int) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(B_int) = B_int_i; hypre_CSRMatrixBigJ(B_int) = B_int_j; hypre_CSRMatrixData(B_int) = B_int_data; /* output */ vrequest = hypre_TAlloc(void *, 4, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) B_int; vrequest[3] = (void *) comm_pkg_j; *request_ptr = (void *) vrequest; hypre_TFree(B_ext_rownnz, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ExchangeExternalRowsWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *B_int = (hypre_CSRMatrix *) request[2]; hypre_ParCSRCommPkg *comm_pkg_j = (hypre_ParCSRCommPkg *) request[3]; /* communication done */ hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); hypre_TFree(request, HYPRE_MEMORY_HOST); return B_int; } /* ----------------------------------------------------------------------------- * extract submatrix A_{FF}, A_{FC}, A_{CF} or A_{CC} * char job[2] = "FF", "FC", "CF" or "CC" * ----------------------------------------------------------------------------- */ HYPRE_Int hypre_ParCSRMatrixExtractSubmatrixFC( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, HYPRE_BigInt *cpts_starts_in, const char *job, hypre_ParCSRMatrix **B_ptr, HYPRE_Real strength_thresh) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); //HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); hypre_ParCSRMatrix *B; hypre_CSRMatrix *B_diag, *B_offd; HYPRE_Real *B_maxel_row; HYPRE_Int *B_diag_i, *B_diag_j, *B_offd_i, *B_offd_j; HYPRE_Complex *B_diag_a, *B_offd_a; HYPRE_Int num_cols_B_offd; HYPRE_BigInt *col_map_offd_B; HYPRE_Int i, j, k, k1, k2; HYPRE_BigInt B_nrow_global, B_ncol_global; HYPRE_Int A_nlocal, B_nrow_local, B_ncol_local, B_nnz_diag, B_nnz_offd; HYPRE_BigInt total_global_fpts, total_global_cpts, *fpts_starts, *cpts_starts; HYPRE_Int nf_local, nc_local; HYPRE_Int row_set, col_set; HYPRE_BigInt *B_row_starts, *B_col_starts, B_first_col; HYPRE_Int my_id, num_procs, *sub_idx_diag, *sub_idx_offd; HYPRE_Int num_sends, *send_buf_data; /* MPI size and rank*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); row_set = job[0] == 'F' ? -1 : 1; col_set = job[1] == 'F' ? -1 : 1; A_nlocal = hypre_CSRMatrixNumRows(A_diag); /*-------------- global number of C points and local C points * assuming cpts_starts is given */ if (row_set == 1 || col_set == 1) { /* copy cpts_starts first */ HYPRE_Int len; #ifdef HYPRE_NO_GLOBAL_PARTITION len = 2; #else len = num_procs + 1; #endif cpts_starts = hypre_TAlloc(HYPRE_BigInt, len, HYPRE_MEMORY_HOST); memcpy(cpts_starts, cpts_starts_in, len*sizeof(HYPRE_BigInt)); #ifdef HYPRE_NO_GLOBAL_PARTITION if (my_id == (num_procs -1)) { total_global_cpts = cpts_starts[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); nc_local = (HYPRE_Int)(cpts_starts[1] - cpts_starts[0]); #else total_global_cpts = cpts_starts[num_procs]; nc_local = (HYPRE_Int)(cpts_starts[my_id+1] - cpts_starts[my_id]); #endif } /*-------------- global number of F points, local F points, and F starts */ if (row_set == -1 || col_set == -1) { nf_local = 0; for (i = 0; i < A_nlocal; i++) { if (CF_marker[i] < 0) { nf_local++; } } #ifdef HYPRE_NO_GLOBAL_PARTITION fpts_starts = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_MPI_Scan(&nf_local, fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); fpts_starts[0] = fpts_starts[1] - nf_local; if (my_id == num_procs - 1) { total_global_fpts = fpts_starts[1]; } hypre_MPI_Bcast(&total_global_fpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else fpts_starts = hypre_TAlloc(HYPRE_BigInt, num_procs+1, HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nf_local, 1, HYPRE_MPI_BIG_INT, &fpts_starts[1], 1, HYPRE_MPI_INT, comm); for (i = 2; i < num_procs+1; i++) { fpts_starts[i] += fpts_starts[i-1]; } total_global_fpts = fpts_starts[num_procs]; #endif } if (row_set == -1 && col_set == -1) { /* FF */ B_nrow_local = nf_local; B_ncol_local = nf_local; B_nrow_global = total_global_fpts; B_ncol_global = total_global_fpts; B_row_starts = B_col_starts = fpts_starts; } else if (row_set == -1 && col_set == 1) { /* FC */ B_nrow_local = nf_local; B_ncol_local = nc_local; B_nrow_global = total_global_fpts; B_ncol_global = total_global_cpts; B_row_starts = fpts_starts; B_col_starts = cpts_starts; } else if (row_set == 1 && col_set == -1) { /* CF */ B_nrow_local = nc_local; B_ncol_local = nf_local; B_nrow_global = total_global_cpts; B_ncol_global = total_global_fpts; B_row_starts = cpts_starts; B_col_starts = fpts_starts; } else { /* CC */ B_nrow_local = nc_local; B_ncol_local = nc_local; B_nrow_global = total_global_cpts; B_ncol_global = total_global_cpts; B_row_starts = B_col_starts = cpts_starts; } /* global index of my first col */ #ifdef HYPRE_NO_GLOBAL_PARTITION B_first_col = B_col_starts[0]; #else B_first_col = B_col_starts[my_id]; #endif /* sub_idx_diag: [local] mapping from F+C to F/C, if not selected, be -1 */ sub_idx_diag = hypre_TAlloc(HYPRE_Int, A_nlocal, HYPRE_MEMORY_HOST); for (i = 0, k = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i == col_set) { sub_idx_diag[i] = k++; } else { sub_idx_diag[i] = -1; } } hypre_assert(k == B_ncol_local); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_buf_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); k = 0; for (i = 0; i < num_sends; i++) { /* start pos of elements sent to send_proc[i] */ HYPRE_Int si = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int ei = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); /* loop through all elems to send_proc[i] */ for (j = si; j < ei; j++) { /* j1: local idx */ HYPRE_Int j1 = sub_idx_diag[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; if (j1 != -1) { /* adjust j1 to B global idx */ j1 += B_first_col; } send_buf_data[k++] = j1; } } hypre_assert(k == hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); /* recv buffer */ sub_idx_offd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); /* create a handle to start communication. 11: for integer */ comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_buf_data, sub_idx_offd); /* destroy the handle to finish communication */ hypre_ParCSRCommHandleDestroy(comm_handle); for (i = 0, num_cols_B_offd = 0; i < num_cols_A_offd; i++) { if (sub_idx_offd[i] != -1) { num_cols_B_offd ++; } } col_map_offd_B = hypre_TAlloc(HYPRE_BigInt, num_cols_B_offd, HYPRE_MEMORY_HOST); for (i = 0, k = 0; i < num_cols_A_offd; i++) { if (sub_idx_offd[i] != -1) { col_map_offd_B[k] = sub_idx_offd[i]; sub_idx_offd[i] = k++; } } hypre_assert(k == num_cols_B_offd); /* count nnz and set ia */ B_nnz_diag = B_nnz_offd = 0; B_maxel_row = hypre_TAlloc(HYPRE_Real, B_nrow_local, HYPRE_MEMORY_HOST); B_diag_i = hypre_TAlloc(HYPRE_Int, B_nrow_local+1, HYPRE_MEMORY_HOST); B_offd_i = hypre_TAlloc(HYPRE_Int, B_nrow_local+1, HYPRE_MEMORY_HOST); B_diag_i[0] = B_offd_i[0] = 0; for (i = 0, k = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i != row_set) { continue; } k++; // Get max abs-value element of this row HYPRE_Real temp_max = 0; if (strength_thresh > 0) { for (j = A_diag_i[i]+1; j < A_diag_i[i+1]; j++) { if (hypre_cabs(A_diag_a[j]) > temp_max) { temp_max = hypre_cabs(A_diag_a[j]); } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { if (hypre_cabs(A_offd_a[j]) > temp_max) { temp_max = hypre_cabs(A_offd_a[j]); } } } B_maxel_row[k-1] = temp_max; // add one for diagonal element j = A_diag_i[i]; if (sub_idx_diag[A_diag_j[j]] != -1) { B_nnz_diag++; } // Count nnzs larger than tolerance times max row element for (j = A_diag_i[i]+1; j < A_diag_i[i+1]; j++) { if ( (sub_idx_diag[A_diag_j[j]] != -1) && (hypre_cabs(A_diag_a[j]) > (strength_thresh*temp_max)) ) { B_nnz_diag++; } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { if ( (sub_idx_offd[A_offd_j[j]] != -1) && (hypre_cabs(A_offd_a[j]) > (strength_thresh*temp_max)) ) { B_nnz_offd++; } } B_diag_i[k] = B_nnz_diag; B_offd_i[k] = B_nnz_offd; } hypre_assert(k == B_nrow_local); B_diag_j = hypre_TAlloc(HYPRE_Int, B_nnz_diag, HYPRE_MEMORY_HOST); B_diag_a = hypre_TAlloc(HYPRE_Complex, B_nnz_diag, HYPRE_MEMORY_HOST); B_offd_j = hypre_TAlloc(HYPRE_Int, B_nnz_offd, HYPRE_MEMORY_HOST); B_offd_a = hypre_TAlloc(HYPRE_Complex, B_nnz_offd, HYPRE_MEMORY_HOST); for (i = 0, k=0, k1 = 0, k2 = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i != row_set) { continue; } HYPRE_Real maxel = B_maxel_row[k]; k++; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { HYPRE_Int j1 = sub_idx_diag[A_diag_j[j]]; if ( (j1 != -1) && ( (hypre_cabs(A_diag_a[j]) > (strength_thresh*maxel)) || j==A_diag_i[i] ) ) { B_diag_j[k1] = j1; B_diag_a[k1] = A_diag_a[j]; k1++; } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { HYPRE_Int j1 = sub_idx_offd[A_offd_j[j]]; if ((j1 != -1) && (hypre_cabs(A_offd_a[j]) > (strength_thresh*maxel))) { hypre_assert(j1 >= 0 && j1 < num_cols_B_offd); B_offd_j[k2] = j1; B_offd_a[k2] = A_offd_a[j]; k2++; } } } hypre_assert(k1 == B_nnz_diag && k2 == B_nnz_offd); /* ready to create B = A(rowset, colset) */ B = hypre_ParCSRMatrixCreate(comm, B_nrow_global, B_ncol_global, B_row_starts, B_col_starts, num_cols_B_offd, B_nnz_diag, B_nnz_offd); B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrixData(B_diag) = B_diag_a; hypre_CSRMatrixI(B_diag) = B_diag_i; hypre_CSRMatrixJ(B_diag) = B_diag_j; B_offd = hypre_ParCSRMatrixOffd(B); hypre_CSRMatrixData(B_offd) = B_offd_a; hypre_CSRMatrixI(B_offd) = B_offd_i; hypre_CSRMatrixJ(B_offd) = B_offd_j; hypre_ParCSRMatrixColMapOffd(B) = col_map_offd_B; hypre_ParCSRMatrixSetNumNonzeros(B); hypre_ParCSRMatrixDNumNonzeros(B) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(B); hypre_MatvecCommPkgCreate(B); *B_ptr = B; hypre_TFree(B_maxel_row, HYPRE_MEMORY_HOST); hypre_TFree(send_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(sub_idx_diag, HYPRE_MEMORY_HOST); hypre_TFree(sub_idx_offd, HYPRE_MEMORY_HOST); return hypre_error_flag; }
advec_mom_kernel_c.c
/*Crown Copyright 2012 AWE. * * This file is part of CloverLeaf. * * CloverLeaf is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * CloverLeaf is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * CloverLeaf. If not, see http://www.gnu.org/licenses/. */ /** * @brief C momentum advection kernel * @author Wayne Gaudin * @details Performs a second order advective remap on the vertex momentum * using van-Leer limiting and directional splitting. * Note that although pre_vol is only set and not used in the update, please * leave it in the method. */ #include <stdio.h> #include <stdlib.h> #include "ftocmacros.h" #include <math.h> void advec_mom_kernel_c_(int *xmin,int *xmax,int *ymin,int *ymax, double *vel1, double *mass_flux_x, double *vol_flux_x, double *mass_flux_y, double *vol_flux_y, double *volume, double *density1, double *node_flux, double *node_mass_post, double *node_mass_pre, double *mom_flux, double *pre_vol, double *post_vol, double *celldx, double *celldy, int *whch_vl, int *swp_nmbr, int *drctn) { int x_min=*xmin; int x_max=*xmax; int y_min=*ymin; int y_max=*ymax; int which_vel=*whch_vl; int sweep_number=*swp_nmbr; int direction=*drctn; int j,k,mom_sweep; int upwind,donor,downwind,dif; double sigma,wind,width; double vdiffuw,vdiffdw,auw,adw,limiter; double advec_vel_s; mom_sweep=direction+2*(sweep_number-1); #pragma omp parallel { if(mom_sweep==1){ #pragma omp for private(j) for (k=y_min-2;k<=y_max+2;k++) { #pragma ivdep for (j=x_min-2;j<=x_max+2;j++) { post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=volume[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)] +vol_flux_y[FTNREF2D(j ,k+1,x_max+4,x_min-2,y_min-2)] -vol_flux_y[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]; pre_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +vol_flux_x[FTNREF2D(j+1,k ,x_max+5,x_min-2,y_min-2)] -vol_flux_x[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } } else if(mom_sweep==2){ #pragma omp for private(j) for (k=y_min-2;k<=y_max+2;k++) { #pragma ivdep for (j=x_min-2;j<=x_max+2;j++) { post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=volume[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)] +vol_flux_x[FTNREF2D(j+1,k ,x_max+5,x_min-2,y_min-2)] -vol_flux_x[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; pre_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +vol_flux_y[FTNREF2D(j ,k+1,x_max+4,x_min-2,y_min-2)] -vol_flux_y[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]; } } } else if(mom_sweep==3){ #pragma omp for private(j) for (k=y_min-2;k<=y_max+2;k++) { #pragma ivdep for (j=x_min-2;j<=x_max+2;j++) { post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=volume[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]; pre_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +vol_flux_y[FTNREF2D(j ,k+1,x_max+4,x_min-2,y_min-2)] -vol_flux_y[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]; } } } else if(mom_sweep==4){ #pragma omp for private(j) for (k=y_min-2;k<=y_max+2;k++) { #pragma ivdep for (j=x_min-2;j<=x_max+2;j++) { post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=volume[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]; pre_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +vol_flux_x[FTNREF2D(j+1,k ,x_max+5,x_min-2,y_min-2)] -vol_flux_x[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } } if(direction==1) { #pragma omp for private(j) for (k=y_min;k<=y_max+1;k++) { #pragma ivdep for (j=x_min-2;j<=x_max+2;j++) { node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=0.25 *(mass_flux_x[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)] +mass_flux_x[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +mass_flux_x[FTNREF2D(j+1,k-1,x_max+5,x_min-2,y_min-2)] +mass_flux_x[FTNREF2D(j+1,k ,x_max+5,x_min-2,y_min-2)]); } } #pragma omp for private(j) for (k=y_min;k<=y_max+1;k++) { #pragma ivdep for (j=x_min-1;j<=x_max+2;j++) { node_mass_post[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=0.25 *(density1[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)] +density1[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +density1[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j-1,k-1,x_max+5,x_min-2,y_min-2)] +density1[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j-1,k ,x_max+5,x_min-2,y_min-2)]); } } #pragma omp for private(j) for (k=y_min;k<=y_max+1;k++) { #pragma ivdep for (j=x_min-1;j<=x_max+2;j++) { node_mass_pre[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=node_mass_post[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] -node_flux[FTNREF2D(j-1,k ,x_max+5,x_min-2,y_min-2)]+node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } #pragma omp for private(upwind,downwind,donor,dif,sigma,width,limiter,vdiffuw,vdiffdw,auw,adw,wind,j,advec_vel_s) for (k=y_min;k<=y_max+1;k++) { for (j=x_min-1;j<=x_max+1;j++) { if(node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]<0.0){ upwind=j+2; donor=j+1; downwind=j; dif=donor; } else{ upwind=j-1; donor=j; downwind=j+1; dif=upwind; } sigma=fabs(node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)])/(node_mass_pre[FTNREF2D(donor,k ,x_max+5,x_min-2,y_min-2)]); width=celldx[FTNREF1D(j,x_min-2)]; vdiffuw=vel1[FTNREF2D(donor,k ,x_max+5,x_min-2,y_min-2)]-vel1[FTNREF2D(upwind,k ,x_max+5,x_min-2,y_min-2)]; vdiffdw=vel1[FTNREF2D(downwind,k ,x_max+5,x_min-2,y_min-2)]-vel1[FTNREF2D(donor,k ,x_max+5,x_min-2,y_min-2)]; limiter=0.0; if(vdiffuw*vdiffdw>0.0){ auw=fabs(vdiffuw); adw=fabs(vdiffdw); wind=1.0; if(vdiffdw<=0.0) wind=-1.0; limiter=wind*MIN(width*((2.0-sigma)*adw/width+(1.0+sigma)*auw/celldx[FTNREF1D(dif,x_min-2)])/6.0,MIN(auw,adw)); } advec_vel_s=vel1[FTNREF2D(donor,k ,x_max+5,x_min-2,y_min-2)]+(1.0-sigma)*limiter; mom_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=advec_vel_s *node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } #pragma omp for private(j) for (k=y_min;k<=y_max+1;k++) { #pragma ivdep for (j=x_min;j<=x_max+1;j++) { vel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=(vel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] *node_mass_pre[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +mom_flux[FTNREF2D(j-1,k ,x_max+5,x_min-2,y_min-2)] -mom_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]) /node_mass_post[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } } else if(direction==2){ #pragma omp for private(j) for (k=y_min-2;k<=y_max+2;k++) { #pragma ivdep for (j=x_min;j<=x_max+1;j++) { node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=0.25 *(mass_flux_y[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)] +mass_flux_y[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)] +mass_flux_y[FTNREF2D(j-1,k+1,x_max+4,x_min-2,y_min-2)] +mass_flux_y[FTNREF2D(j ,k+1,x_max+4,x_min-2,y_min-2)]); } } #pragma omp for private(j) for (k=y_min-1;k<=y_max+2;k++) { #pragma ivdep for (j=x_min;j<=x_max+1;j++) { node_mass_post[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=0.25 *(density1[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)] +density1[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +density1[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j-1,k-1,x_max+5,x_min-2,y_min-2)] +density1[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)] *post_vol[FTNREF2D(j-1,k ,x_max+5,x_min-2,y_min-2)]); } } #pragma omp for private(j) for (k=y_min-1;k<=y_max+2;k++) { #pragma ivdep for (j=x_min;j<=x_max+1;j++) { node_mass_pre[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=node_mass_post[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] -node_flux[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)]+node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } #pragma omp for private(upwind,downwind,donor,dif,sigma,width,limiter,vdiffuw,vdiffdw,auw,adw,wind,j,advec_vel_s) for (k=y_min-1;k<=y_max+1;k++) { for (j=x_min;j<=x_max+1;j++) { if(node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]<0.0){ upwind=k+2; donor=k+1; downwind=k; dif=donor; } else{ upwind=k-1; donor=k; downwind=k+1; dif=upwind; } sigma=fabs(node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)])/(node_mass_pre[FTNREF2D(j ,donor,x_max+5,x_min-2,y_min-2)]); width=celldy[FTNREF1D(k,y_min-2)]; vdiffuw=vel1[FTNREF2D(j ,donor,x_max+5,x_min-2,y_min-2)]-vel1[FTNREF2D(j ,upwind,x_max+5,x_min-2,y_min-2)]; vdiffdw=vel1[FTNREF2D(j ,downwind ,x_max+5,x_min-2,y_min-2)]-vel1[FTNREF2D(j ,donor,x_max+5,x_min-2,y_min-2)]; limiter=0.0; if(vdiffuw*vdiffdw>0.0){ auw=fabs(vdiffuw); adw=fabs(vdiffdw); wind=1.0; if(vdiffdw<=0.0) wind=-1.0; limiter=wind*MIN(width*((2.0-sigma)*adw/width+(1.0+sigma)*auw/celldy[FTNREF1D(dif,y_min-2)])/6.0,MIN(auw,adw)); } advec_vel_s=vel1[FTNREF2D(j ,donor,x_max+5,x_min-2,y_min-2)]+(1.0-sigma)*limiter; mom_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=advec_vel_s *node_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } #pragma omp for private(j) for (k=y_min;k<=y_max+1;k++) { #pragma ivdep for (j=x_min;j<=x_max+1;j++) { vel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=(vel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] *node_mass_pre[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)] +mom_flux[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)] -mom_flux[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]) /node_mass_post[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]; } } } } }
task1_omp.c
#include <math.h> #include <string.h> #include "timer.h" #define NN 1024 #define NM 1024 float A[NN][NM]; float Anew[NN][NM]; int main(int argc, char** argv) { const int n = NN; const int m = NM; const int iter_max = 1000; const double tol = 1.0e-6; double error = 1.0; memset(A, 0, n * m * sizeof(float)); memset(Anew, 0, n * m * sizeof(float)); for (int j = 0; j < n; j++) { A[j][0] = 1.0; Anew[j][0] = 1.0; } printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m); StartTimer(); int iter = 0; while ( error > tol && iter < iter_max ) { error = 0.0; #pragma omp parallel for reduction(max:error) for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1] + A[j-1][i] + A[j+1][i]); error = fmax( error, fabs(Anew[j][i] - A[j][i])); } } #pragma omp parallel for for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { A[j][i] = Anew[j][i]; } } if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error); iter++; } double runtime = GetTimer(); printf(" total: %f s\n", runtime / 1000); return 0; }
cryptocontext.h
/** * @file cryptocontext.h -- Control for encryption operations. * @author TPOC: contact@palisade-crypto.org * * @section LICENSE * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SRC_DEMO_PRE_CRYPTOCONTEXT_H_ #define SRC_DEMO_PRE_CRYPTOCONTEXT_H_ #include "palisade.h" #include "cryptocontexthelper.h" #include "cryptotiming.h" namespace lbcrypto { template<typename Element> class CryptoContextFactory; template<typename Element> class CryptoContextImpl; template<typename Element> using CryptoContext = shared_ptr<CryptoContextImpl<Element>>; /** * @brief CryptoContextImpl * * A CryptoContextImpl is the object used to access the PALISADE library * * All PALISADE functionality is accessed by way of an instance of a CryptoContextImpl; we say that various objects are * "created in" a context, and can only be used in the context in which they were created * * All PALISADE methods are accessed through CryptoContextImpl methods. Guards are implemented to make certain that * only valid objects that have been created in the context are used * * Contexts are created using the CryptoContextFactory, and can be serialized and recovered from a serialization */ template<typename Element> class CryptoContextImpl : public Serializable { friend class CryptoContextFactory<Element>; private: shared_ptr<LPCryptoParameters<Element>> params; /*!< crypto parameters used for this context */ shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme; /*!< algorithm used; accesses all crypto methods */ static std::map<string,std::vector<LPEvalKey<Element>>> evalMultKeyMap; /*!< cached evalmult keys, by secret key UID */ static std::map<string,shared_ptr<std::map<usint,LPEvalKey<Element>>>> evalSumKeyMap; /*!< cached evalsum keys, by secret key UID */ static std::map<string,shared_ptr<std::map<usint,LPEvalKey<Element>>>> evalAutomorphismKeyMap; /*!< cached evalautomorphism keys, by secret key UID */ bool doTiming; vector<TimingInfo>* timeSamples; /** * TypeCheck makes sure that an operation between two ciphertexts is permitted * @param a * @param b */ void TypeCheck(ConstCiphertext<Element> a, ConstCiphertext<Element> b) const { if( a == NULL || b == NULL ) PALISADE_THROW( type_error, "Null Ciphertext"); if( a->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContext"); if( a->GetCryptoContext() != b->GetCryptoContext() ) PALISADE_THROW( type_error, "Ciphertexts were not created in the same CryptoContext"); if( a->GetKeyTag() != b->GetKeyTag() ) PALISADE_THROW( type_error, "Ciphertexts were not encrypted with same keys" ); if( a->GetEncodingType() != b->GetEncodingType() ) { stringstream ss; ss << "Ciphertext encoding types " << a->GetEncodingType(); ss << " and " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted * @param a * @param b */ void TypeCheck(ConstCiphertext<Element> a, ConstPlaintext b) const { if( a == NULL ) PALISADE_THROW( type_error, "Null Ciphertext"); if( b == NULL ) PALISADE_THROW( type_error, "Null Plaintext"); if( a->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContext"); if( a->GetEncodingType() != b->GetEncodingType() ) { stringstream ss; ss << "Ciphertext encoding type " << a->GetEncodingType(); ss << " and Plaintext encoding type " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between two ciphertexts is permitted * @param a * @param b */ void TypeCheck(const RationalCiphertext<Element>& a, const RationalCiphertext<Element>& b) const { if( a.GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( a.GetCryptoContext() != b.GetCryptoContext() ) PALISADE_THROW( type_error, "Ciphertexts were not created in the same CryptoContextImpl"); if( a.GetKeyTag() != b.GetKeyTag() ) PALISADE_THROW( type_error, "Ciphertexts were not encrypted with same keys" ); if( a.GetNumerator()->GetEncodingType() != b.GetNumerator()->GetEncodingType() ) { stringstream ss; ss << "RationalCiphertext encoding types " << a.GetNumerator()->GetEncodingType(); ss << " and " << b.GetNumerator()->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted * @param a * @param b */ void TypeCheck(const RationalCiphertext<Element>& a, ConstPlaintext b) const { if( b == NULL ) PALISADE_THROW( type_error, "Null Plaintext"); if( a.GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( a.GetNumerator()->GetEncodingType() != b->GetEncodingType() ){ stringstream ss; ss << "RationalCiphertext encoding type " << a.GetNumerator()->GetEncodingType(); ss << " and Plaintext encoding type " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } bool Mismatched(const CryptoContext<Element> a) const { if( a.get() != this ) { return true; } return false; } public: /** * CryptoContextImpl constructor from pointers to parameters and scheme * @param params - pointer to CryptoParameters * @param scheme - pointer to Crypto Scheme */ CryptoContextImpl(LPCryptoParameters<Element> *params = 0, LPPublicKeyEncryptionScheme<Element> *scheme = 0) { this->params.reset(params); this->scheme.reset(scheme); this->doTiming = false; this->timeSamples = 0; } /** * CryptoContextImpl constructor from shared pointers to parameters and scheme * @param params - shared pointer to CryptoParameters * @param scheme - sharedpointer to Crypto Scheme */ CryptoContextImpl(shared_ptr<LPCryptoParameters<Element>> params, shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme) { this->params = params; this->scheme = scheme; this->doTiming = false; this->timeSamples = 0; } /** * Copy constructor * @param c - source */ CryptoContextImpl(const CryptoContextImpl<Element>& c) { params = c.params; scheme = c.scheme; doTiming = c.doTiming; timeSamples = c.timeSamples; } /** * Assignment * @param rhs - assigning from * @return this */ CryptoContextImpl<Element>& operator=(const CryptoContextImpl<Element>& rhs) { params = rhs.params; scheme = rhs.scheme; doTiming = rhs.doTiming; timeSamples = rhs.timeSamples; return *this; } /** * A CryptoContextImpl is only valid if the shared pointers are both valid */ operator bool() const { return bool(params) && bool(scheme); } /** * Private methods to compare two contexts; this is only used internally and is not generally available * @param a - operand 1 * @param b - operand 2 * @return true if the implementations have identical parms and scheme */ friend bool operator==(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) { // Identical if the parameters and the schemes are identical... the exact same object, // OR the same type and the same values if( a.params.get() == b.params.get() ) { return true; } else { if( typeid(*a.params.get()) != typeid(*b.params.get()) ) { return false; } if( *a.params.get() != *b.params.get() ) return false; } if( a.scheme.get() == b.scheme.get() ) { return true; } else { if( typeid(*a.scheme.get()) != typeid(*b.scheme.get()) ) { return false; } if( *a.scheme.get() != *b.scheme.get() ) return false; } return true; } friend bool operator!=(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) { return !( a == b ); } // TIMING METHODS /** * StartTiming method activates timing of CryptoMethods * * @param timeSamples points to a vector in which timing samples will be stored */ void StartTiming(vector<TimingInfo>* timeSamples) { this->timeSamples = timeSamples; doTiming = true; } /* * StopTiming - turns off timing */ void StopTiming() { doTiming = false; } /** * ResumeTiming - re-enables timing with existing TimingInfo vector */ void ResumeTiming() { doTiming = true; } /** * ResetTiming - erases measurements */ void ResetTiming() { this->timeSamples->clear(); } static bool SerializeEvalMultKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalMultKey(Serialized* serObj, const string& id) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalMultKey(Serialized* serObj, const CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool DeserializeEvalMultKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * SerializeEvalMultKey for a single EvalMult key or all EvalMult keys * * @param ser - stream to serialize to * @param sertype - type of serialization * @param id for key to serialize - if empty string, serialize them all * @return true on success */ template<typename ST> static bool SerializeEvalMultKey(std::ostream& ser, const ST&, string id = ""); /** * SerializeEvalMultKey for all EvalMultKeys made in a given context * * @param cc whose keys should be serialized * @param ser - stream to serialize to * @param sertype - type of serialization * @return true on success (false on failure or no keys found) */ template<typename ST> static bool SerializeEvalMultKey(std::ostream& ser, const ST&, const CryptoContext<Element> cc); /** * DeserializeEvalMultKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param serObj - stream with a serialization * @return true on success */ template<typename ST> static bool DeserializeEvalMultKey(std::istream& ser, const ST&); /** * ClearEvalMultKeys - flush EvalMultKey cache */ static void ClearEvalMultKeys(); /** * ClearEvalMultKeys - flush EvalMultKey cache for a given id * @param id */ static void ClearEvalMultKeys(const string& id); /** * ClearEvalMultKeys - flush EvalMultKey cache for a given context * @param cc */ static void ClearEvalMultKeys(const CryptoContext<Element> cc); /** * InsertEvalMultKey - add the given vector of keys to the map, replacing the existing vector if there * @param vectorToInsert */ static void InsertEvalMultKey(const std::vector<LPEvalKey<Element>>& vectorToInsert); static bool SerializeEvalSumKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalSumKey(Serialized* serObj, const string& id) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalSumKey(Serialized* serObj, const CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool DeserializeEvalSumKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * SerializeEvalSumKey for a single EvalSum key or all of the EvalSum keys * * @param ser - stream to serialize to * @param sertype - type of serialization * @param id - key to serialize; empty string means all keys * @return true on success */ template<typename ST> static bool SerializeEvalSumKey(std::ostream& ser, const ST& sertype, string id = ""); /** * SerializeEvalSumKey for all of the EvalSum keys for a context * * @param ser - stream to serialize to * @param sertype - type of serialization * @param cc - context * @return true on success */ template<typename ST> static bool SerializeEvalSumKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc); /** * DeserializeEvalSumKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param ser - stream to serialize from * @param sertype - type of serialization * @return true on success */ template<typename ST> static bool DeserializeEvalSumKey(std::istream& ser, const ST& sertype); /** * ClearEvalSumKeys - flush EvalSumKey cache */ static void ClearEvalSumKeys(); /** * ClearEvalSumKeys - flush EvalSumKey cache for a given id * @param id */ static void ClearEvalSumKeys(const string& id); /** * ClearEvalSumKeys - flush EvalSumKey cache for a given context * @param cc */ static void ClearEvalSumKeys(const CryptoContext<Element> cc); /** * InsertEvalSumKey - add the given map of keys to the map, replacing the existing map if there * @param mapToInsert */ static void InsertEvalSumKey(const shared_ptr<std::map<usint,LPEvalKey<Element>>> mapToInsert); static bool SerializeEvalAutomorphismKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalAutomorphismKey(Serialized* serObj, const string& id) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalAutomorphismKey(Serialized* serObj, const CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool DeserializeEvalAutomorphismKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * SerializeEvalAutomorphismKey for a single EvalAuto key or all of the EvalAuto keys * * @param ser - stream to serialize to * @param sertype - type of serialization * @param id - key to serialize; empty string means all keys * @return true on success */ template<typename ST> static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, string id = ""); /** * SerializeEvalAutomorphismKey for all of the EvalAuto keys for a context * * @param ser - stream to serialize to * @param sertype - type of serialization * @param cc - context * @return true on success */ template<typename ST> static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc); /** * DeserializeEvalAutomorphismKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param ser - stream to serialize from * @param sertype - type of serialization * @return true on success */ template<typename ST> static bool DeserializeEvalAutomorphismKey(std::istream& ser, const ST& sertype); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache */ static void ClearEvalAutomorphismKeys(); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache for a given id * @param id */ static void ClearEvalAutomorphismKeys(const string& id); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache for a given context * @param cc */ static void ClearEvalAutomorphismKeys(const CryptoContext<Element> cc); /** * InsertEvalAutomorphismKey - add the given map of keys to the map, replacing the existing map if there * @param mapToInsert */ static void InsertEvalAutomorphismKey(const shared_ptr<std::map<usint,LPEvalKey<Element>>> mapToInsert); // TURN FEATURES ON /** * Enable a particular feature for use with this CryptoContextImpl * @param feature - the feature that should be enabled */ void Enable(PKESchemeFeature feature) { scheme->Enable(feature); } /** * Enable several features at once * @param featureMask - bitwise or of several PKESchemeFeatures */ void Enable(usint featureMask) { scheme->Enable(featureMask); } // GETTERS /** * Getter for Scheme * @return scheme */ const shared_ptr<LPPublicKeyEncryptionScheme<Element>> GetEncryptionAlgorithm() const { return scheme; } /** * Getter for CryptoParams * @return params */ const shared_ptr<LPCryptoParameters<Element>> GetCryptoParameters() const { return params; } /** * Getter for element params * @return */ const shared_ptr<typename Element::Params> GetElementParams() const { return params->GetElementParams(); } /** * Getter for encoding params * @return */ const EncodingParams GetEncodingParams() const { return params->GetEncodingParams(); } /** * Get the cyclotomic order used for this context * * @return */ const usint GetCyclotomicOrder() const { return params->GetElementParams()->GetCyclotomicOrder(); } /** * Get the ring dimension used for this context * * @return */ const usint GetRingDimension() const { return params->GetElementParams()->GetRingDimension(); } /** * Get the ciphertext modulus used for this context * * @return */ const typename Element::Integer& GetModulus() const { return params->GetElementParams()->GetModulus(); } /** * Get the ciphertext modulus used for this context * * @return */ const typename Element::Integer& GetRootOfUnity() const { return params->GetElementParams()->GetRootOfUnity(); } /** * KeyGen generates a key pair using this algorithm's KeyGen method * @return a public/secret key pair */ LPKeyPair<Element> KeyGen() { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), false); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeyGen, TOC_US(t)) ); } return r; } /** * KeyGen generates a Multiparty key pair using this algorithm's KeyGen method from two keys * @param pk first public key used to coordinate the creation of later public keys. * @return a public/secret key pair */ LPKeyPair<Element> MultipartyKeyGen( const LPPublicKey<Element> pk, bool makeSparse=false, bool pre=false) { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->MultipartyKeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), pk, makeSparse, pre); if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyKeyGenKey, TOC_US(t)) ); } return r; } /** * KeyGen generates a Multiparty key pair using a vector of secret keys * @param secretKeys a vector of the secret keys to be used for multiparty computation. * @return a public/secret key pair */ LPKeyPair<Element> MultipartyKeyGen( const vector<LPPrivateKey<Element>>& secretKeys) { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->MultipartyKeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), secretKeys, false); if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyKeyGenKeyvec, TOC_US(t)) ); } return r; } /** * Lead Multiparty Decryption method for PALISADE multiparty operations. * This should be performed by exactly one of the clients. * All other clients should perform the MultipartyDecryptMain operation. * @param privateKey the secret key of the lead decryption client * @param ciphertext vector of encrypted ciphertext * @return vector of partially decrypted ciphertexts */ vector<Ciphertext<Element>> MultipartyDecryptLead( const LPPrivateKey<Element> privateKey, const vector<Ciphertext<Element>>& ciphertext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to MultipartyDecryptLead was not generated with this crypto context"); vector<Ciphertext<Element>> newCiphertext; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < ciphertext.size(); i++ ) { if( ciphertext[i] == NULL || Mismatched(ciphertext[i]->GetCryptoContext()) ) throw std::logic_error("A ciphertext passed to MultipartyDecryptLead was not generated with this crypto context"); newCiphertext.push_back( GetEncryptionAlgorithm()->MultipartyDecryptLead(privateKey, ciphertext[i]) ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptLead, TOC_US(t)) ); } return newCiphertext; } /** * Multiparty decryption method for PALISADE multiparty operations. * The lead multiparty decryption operation should be performed by exactly one of the clients. * All other clients should perform this MultipartyDecryptMain operation. * @param privateKey - for decryption * @param ciphertext - vector of encrypted ciphertext * @return vector of partially decrypted ciphertexts */ vector<Ciphertext<Element>> MultipartyDecryptMain( const LPPrivateKey<Element> privateKey, const vector<Ciphertext<Element>>& ciphertext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to MultipartyDecryptMain was not generated with this crypto context"); vector<Ciphertext<Element>> newCiphertext; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < ciphertext.size(); i++ ) { if( ciphertext[i] == NULL || Mismatched(ciphertext[i]->GetCryptoContext()) ) throw std::logic_error("A ciphertext passed to MultipartyDecryptMain was not generated with this crypto context"); newCiphertext.push_back( GetEncryptionAlgorithm()->MultipartyDecryptMain(privateKey, ciphertext[i]) ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptMain, TOC_US(t)) ); } return newCiphertext; } /** * Final multiparty decryption method to fuse the partially decrypted ciphertexts into a decrypted plaintext. * The lead multiparty decryption operation should be performed by exactly one of the clients. * All other clients should perform the MultipartyDecryptMain operation. * @param partialCiphertextVec - vector of partially decrypted ciphertexts. * @param plaintext - pointer to destination for the result of decryption * @param doPadding - true if input plaintext was padded; causes unpadding on last piece of ciphertext * @return size of plaintext */ DecryptResult MultipartyDecryptFusion( const vector<Ciphertext<Element>>& partialCiphertextVec, Plaintext *plaintext) const { DecryptResult result; //Make sure we're processing ciphertexts. size_t last_ciphertext = partialCiphertextVec.size(); if ( last_ciphertext < 1 ) return result; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < last_ciphertext; i++ ) { if (partialCiphertextVec[i] == NULL || Mismatched(partialCiphertextVec[i]->GetCryptoContext())) throw std::logic_error("A ciphertext passed to MultipartyDecryptFusion was not generated with this crypto context"); if (partialCiphertextVec[i]->GetEncodingType() != partialCiphertextVec[0]->GetEncodingType()) throw std::logic_error("Ciphertexts passed to MultipartyDecryptFusion have mismatched encoding types"); } // determine which type of plaintext that you need to decrypt into Plaintext decrypted = GetPlaintextForDecrypt(partialCiphertextVec[0]->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); result = GetEncryptionAlgorithm()->MultipartyDecryptFusion(partialCiphertextVec, &decrypted->GetElement<NativePoly>()); if (result.isValid == false) return result; decrypted->Decode(); *plaintext = decrypted; if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptFusion, TOC_US(t)) ); } return result; } /** * SparseKeyGen generates a key pair with special structure, and without full entropy, * for use in special cases like Ring Reduction * @return a public/secret key pair */ LPKeyPair<Element> SparseKeyGen() { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), true); if( doTiming ) { timeSamples->push_back( TimingInfo(OpSparseKeyGen, TOC_US(t)) ); } return r; } /** * ReKeyGen produces an Eval Key that PALISADE can use for Proxy Re Encryption * @param newKey (public) * @param oldKey (private) * @return new evaluation key */ LPEvalKey<Element> ReKeyGen( const LPPublicKey<Element> newKey, const LPPrivateKey<Element> oldKey) const { if( newKey == NULL || oldKey == NULL || Mismatched(newKey->GetCryptoContext()) || Mismatched(oldKey->GetCryptoContext()) ) throw std::logic_error("Keys passed to ReKeyGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->ReKeyGen(newKey, oldKey); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReKeyGenPubPri, TOC_US(t)) ); } return r; } /** * ReKeyGen produces an Eval Key that PALISADE can use for Proxy Re Encryption * NOTE this functionality has been completely removed from PALISADE * @param newKey (private) * @param oldKey (private) * @return new evaluation key */ LPEvalKey<Element> ReKeyGen( const LPPrivateKey<Element> newKey, const LPPrivateKey<Element> oldKey) const __attribute__ ((deprecated("functionality removed from PALISADE"))); /** * EvalMultKeyGen creates a key that can be used with the PALISADE EvalMult operator * @param key * @return new evaluation key */ void EvalMultKeyGen(const LPPrivateKey<Element> key); /** * EvalMultsKeyGen creates a vector evalmult keys that can be used with the PALISADE EvalMult operator * 1st key (for s^2) is used for multiplication of ciphertexts of depth 1 * 2nd key (for s^3) is used for multiplication of ciphertexts of depth 2, etc. * * @param key * @return a vector of evaluation keys */ void EvalMultKeysGen(const LPPrivateKey<Element> key); /** * GetEvalMultKeyVector fetches the eval mult keys for a given KeyID * @param keyID * @return key vector from ID */ static const vector<LPEvalKey<Element>>& GetEvalMultKeyVector(const string& keyID); /** * GetEvalMultKeys * @return map of all the keys */ static const std::map<string,std::vector<LPEvalKey<Element>>>& GetAllEvalMultKeys(); /** * KeySwitchGen creates a key that can be used with the PALISADE KeySwitch operation * @param key1 * @param key2 * @return new evaluation key */ LPEvalKey<Element> KeySwitchGen( const LPPrivateKey<Element> key1, const LPPrivateKey<Element> key2) const { if( key1 == NULL || key2 == NULL || Mismatched(key1->GetCryptoContext()) || Mismatched(key2->GetCryptoContext()) ) throw std::logic_error("Keys passed to KeySwitchGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeySwitchGen(key1, key2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeySwitchGen, TOC_US(t)) ); } return r; } /** * Encrypt a plaintext using a given public key * @param publicKey * @param plaintext * @return ciphertext (or null on failure) */ Ciphertext<Element> Encrypt( const LPPublicKey<Element> publicKey, Plaintext plaintext) { if( publicKey == NULL ) throw std::logic_error("null key passed to Encrypt"); if( plaintext == NULL ) throw std::logic_error("null plaintext passed to Encrypt"); if( Mismatched(publicKey->GetCryptoContext()) ) throw std::logic_error("key passed to Encrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext->GetEncodingType() ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptPub, TOC_US(t)) ); } return ciphertext; } /** * Encrypt a plaintext using a given private key * @param privateKey * @param plaintext * @return ciphertext (or null on failure) */ Ciphertext<Element> Encrypt( const LPPrivateKey<Element> privateKey, Plaintext plaintext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("key passed to Encrypt was not generated with this crypto context"); if( plaintext == NULL ) throw std::logic_error("null plaintext passed to Encrypt"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(privateKey, plaintext->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext->GetEncodingType() ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptPriv, TOC_US(t)) ); } return ciphertext; } /** * Encrypt a matrix of Plaintext * @param publicKey - for encryption * @param plaintext - to encrypt * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return a vector of pointers to Ciphertexts created by encrypting the plaintext */ shared_ptr<Matrix<RationalCiphertext<Element>>> EncryptMatrix( const LPPublicKey<Element> publicKey, Matrix<Plaintext> &plaintext) { if (publicKey == NULL || Mismatched(publicKey->GetCryptoContext())) throw std::logic_error("key passed to EncryptMatrix was not generated with this crypto context"); auto zeroAlloc = [=]() { return RationalCiphertext<Element>(publicKey->GetCryptoContext(), true); }; shared_ptr<Matrix<RationalCiphertext<Element>>> cipherResults(new Matrix<RationalCiphertext<Element>> (zeroAlloc, plaintext.GetRows(), plaintext.GetCols())); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < plaintext.GetRows(); row++) { for (size_t col = 0; col < plaintext.GetCols(); col++) { if( plaintext(row,col)->Encode() == false ) return 0; Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext(row,col)->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext(row,col)->GetEncodingType() ); } (*cipherResults)(row, col).SetNumerator(ciphertext); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptMatrixPlain, TOC_US(t)) ); } return cipherResults; } /** * Encrypt a matrix of Plaintext * @param publicKey - for encryption * @param plaintext - to encrypt * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return a vector of pointers to Ciphertexts created by encrypting the plaintext */ Matrix<Ciphertext<Element>> EncryptMatrixCiphertext( const LPPublicKey<Element> publicKey, Matrix<Plaintext> &plaintext) { if (publicKey == NULL || Mismatched(publicKey->GetCryptoContext())) throw std::logic_error("key passed to EncryptMatrix was not generated with this crypto context"); auto zeroAlloc = [=]() { return Ciphertext<Element>(new CiphertextImpl<Element>(publicKey->GetCryptoContext())); }; Matrix<Ciphertext<Element>> cipherResults(zeroAlloc, plaintext.GetRows(), plaintext.GetCols()); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < plaintext.GetRows(); row++) { for (size_t col = 0; col < plaintext.GetCols(); col++) { if( plaintext(row,col)->Encode() == false ) throw std::logic_error("Plaintext is not encoded"); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext(row,col)->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext(row,col)->GetEncodingType() ); } cipherResults(row, col) = (ciphertext); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptMatrixPlain, TOC_US(t)) ); } return cipherResults; } /** * Perform an encryption by reading plaintext from a stream, serializing each piece of ciphertext, * and writing the serializations to an output stream * @param publicKey - the encryption key in use * @param instream - where to read the input from * @param ostream - where to write the serialization to * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return */ void EncryptStream( const LPPublicKey<Element> publicKey, std::istream& instream, std::ostream& outstream) const __attribute__ ((deprecated("serialization changed, see wiki for details"))); // PLAINTEXT FACTORY METHODS // FIXME to be deprecated in 2.0 /** * MakeScalarPlaintext constructs a ScalarEncoding in this context * @param value * @param isSigned * @return plaintext */ Plaintext MakeScalarPlaintext(int64_t value) const { auto p = PlaintextFactory::MakePlaintext( Scalar, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakeStringPlaintext constructs a StringEncoding in this context * @param str * @return plaintext */ Plaintext MakeStringPlaintext(const string& str) const { auto p = PlaintextFactory::MakePlaintext( String, this->GetElementParams(), this->GetEncodingParams(), str ); return p; } /** * MakeIntegerPlaintext constructs an IntegerEncoding in this context * @param value * @return plaintext */ Plaintext MakeIntegerPlaintext(int64_t value) const { auto p = PlaintextFactory::MakePlaintext( Integer, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakeIntegerPlaintext constructs a FractionalEncoding in this context * @param value * @param truncatedBits limit on fractional * @return plaintext */ Plaintext MakeFractionalPlaintext(int64_t value, size_t truncatedBits = 0) const { auto p = PlaintextFactory::MakePlaintext( Fractional, this->GetElementParams(), this->GetEncodingParams(), value, truncatedBits ); return p; } /** * MakeCoefPackedPlaintext constructs a CoefPackedEncoding in this context * @param value * @return plaintext */ Plaintext MakeCoefPackedPlaintext(const vector<int64_t>& value) const { auto p = PlaintextFactory::MakePlaintext( CoefPacked, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakePackedPlaintext constructs a PackedEncoding in this context * @param value * @return plaintext */ Plaintext MakePackedPlaintext(const vector<int64_t>& value) const { auto p = PlaintextFactory::MakePlaintext( Packed, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakePlaintext static that takes a cc and calls the Plaintext Factory * @param encoding * @param cc * @param value * @return */ template<typename Value1> static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value) { return PlaintextFactory::MakePlaintext( encoding, cc->GetElementParams(), cc->GetEncodingParams(), value ); } template<typename Value1, typename Value2> static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value, const Value2& value2) { return PlaintextFactory::MakePlaintext( encoding, cc->GetElementParams(), cc->GetEncodingParams(), value, value2 ); } static Plaintext GetPlaintextForDecrypt(PlaintextEncodings pte, shared_ptr<typename Element::Params> evp, EncodingParams ep) { shared_ptr<typename NativePoly::Params> vp( new typename NativePoly::Params(evp->GetCyclotomicOrder(), ep->GetPlaintextModulus(), 1) ); return PlaintextFactory::MakePlaintext(pte, vp, ep); } public: /** * Decrypt a single ciphertext into the appropriate plaintext * * @param privateKey - decryption key * @param ciphertext - ciphertext to decrypt * @param plaintext - resulting plaintext object pointer is here * @return */ DecryptResult Decrypt( const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, Plaintext* plaintext) { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to Decrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); // determine which type of plaintext that you need to decrypt into Plaintext decrypted = GetPlaintextForDecrypt(ciphertext->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult result = GetEncryptionAlgorithm()->Decrypt(privateKey, ciphertext, &decrypted->GetElement<NativePoly>()); if (result.isValid == false) return result; decrypted->Decode(); if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecrypt, TOC_US(t)) ); } *plaintext = decrypted; return result; } /** * Decrypt method for a matrix of ciphertexts * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrix( const LPPrivateKey<Element> privateKey, const shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext, shared_ptr<Matrix<Plaintext>> *numerator, shared_ptr<Matrix<Plaintext>> *denominator) const { // edge case if ((ciphertext->GetCols()== 0) && (ciphertext->GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(0, 0).GetNumerator(); // need to build matrices for the result Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; *numerator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); *denominator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < ciphertext->GetRows(); row++) { for (size_t col = 0; col < ciphertext->GetCols(); col++) { if (Mismatched((*ciphertext)(row, col).GetCryptoContext())) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(row, col).GetNumerator(); // determine which type of plaintext that you need to decrypt into Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (**numerator)(row,col) = decryptedNumerator; (**numerator)(row,col)->Decode(); Plaintext decryptedDenominator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); if( (*ciphertext)(row,col).GetIntegerFlag() == true ) { decryptedDenominator->GetElement<Poly>().SetValuesToZero(); decryptedDenominator->GetElement<Poly>().at(0) = 1; } else { const Ciphertext<Element> ctD = (*ciphertext)(row, col).GetDenominator(); DecryptResult resultD = GetEncryptionAlgorithm()->Decrypt(privateKey, ctD, &decryptedDenominator->GetElement<NativePoly>()); if (resultD.isValid == false) return resultD; (**denominator)(row,col) = decryptedDenominator; } (**denominator)(row, col)->Decode(); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecryptMatrixPlain, TOC_US(t)) ); } return DecryptResult((**numerator)((*numerator)->GetRows()-1,(*numerator)->GetCols()-1)->GetLength()); } /** * Decrypt method for a matrix of ciphertexts * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrixCiphertext( const LPPrivateKey<Element> privateKey, const Matrix<Ciphertext<Element>> ciphertext, Matrix<Plaintext> *numerator) const { // edge case if ((ciphertext.GetCols()== 0) && (ciphertext.GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (ciphertext)(0, 0); // need to build matrices for the result // Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); // auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; // numerator = new Matrix<Plaintext>(zeroPackingAlloc, ciphertext.GetRows(), ciphertext.GetCols()); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < ciphertext.GetRows(); row++) { for (size_t col = 0; col < ciphertext.GetCols(); col++) { if (Mismatched( (ciphertext(row, col))->GetCryptoContext() )) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (ciphertext)(row, col); // determine which type of plaintext that you need to decrypt into Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (*numerator)(row,col) = decryptedNumerator; (*numerator)(row,col)->Decode(); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecryptMatrixPlain, TOC_US(t)) ); } return DecryptResult((*numerator)( numerator->GetRows()-1, numerator->GetCols()-1)->GetLength()); } /** * Decrypt method for numerators in a matrix of ciphertexts (packed encoding) * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrixNumerator( const LPPrivateKey<Element> privateKey, const shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext, shared_ptr<Matrix<Plaintext>> *numerator) const { // edge case if ((ciphertext->GetCols() == 0) && (ciphertext->GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); TimeVar t; if (doTiming) TIC(t); //force all precomputations to take place in advance if( Mismatched((*ciphertext)(0, 0).GetCryptoContext()) ) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(0, 0).GetNumerator(); // need to build a numerator matrix for the result Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; *numerator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (**numerator)(0, 0) = decryptedNumerator; (**numerator)(0, 0)->Decode(); for (size_t row = 0; row < ciphertext->GetRows(); row++) { #pragma omp parallel for for (size_t col = 0; col < ciphertext->GetCols(); col++) { if (row + col > 0) { if( Mismatched((*ciphertext)(row, col).GetCryptoContext()) ) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(row, col).GetNumerator(); Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); (**numerator)(row, col) = decryptedNumerator; (**numerator)(row, col)->Decode(); } } } if (doTiming) { timeSamples->push_back(TimingInfo(OpDecryptMatrixPacked, TOC_US(t))); } return DecryptResult((**numerator)((*numerator)->GetRows() - 1, (*numerator)->GetCols() - 1)->GetLength()); } /** * read instream for a sequence of serialized ciphertext; deserialize it, decrypt it, and write it to outstream * @param privateKey - reference to the decryption key * @param instream - input stream with sequence of serialized ciphertexts * @param outstream - output stream for plaintext * @return total bytes processed */ size_t DecryptStream( const LPPrivateKey<Element> privateKey, std::istream& instream, std::ostream& outstream) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * ReEncrypt - Proxy Re Encryption mechanism for PALISADE * @param evalKey - evaluation key from the PRE keygen method * @param ciphertext - vector of shared pointers to encrypted Ciphertext * @param publicKey the public key of the recipient of the re-encrypted ciphertext. * @return vector of shared pointers to re-encrypted ciphertexts */ Ciphertext<Element> ReEncrypt( LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext, const LPPublicKey<Element> publicKey = nullptr) const { if( evalKey == NULL || Mismatched(evalKey->GetCryptoContext()) ) throw std::logic_error("Information passed to ReEncrypt was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("The ciphertext passed to ReEncrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> newCiphertext = GetEncryptionAlgorithm()->ReEncrypt(evalKey, ciphertext, publicKey); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReEncrypt, TOC_US(t)) ); } return newCiphertext; } /** * read instream for a serialized ciphertext. deserialize, re-encrypt, serialize, and write to outstream * @param evalKey - reference to the re-encryption key * @param instream - input stream with sequence of serialized ciphertext * @param outstream - output stream with sequence of serialized re-encrypted ciphertext */ void ReEncryptStream( const LPEvalKey<Element> evalKey, std::istream& instream, std::ostream& outstream, const LPPublicKey<Element> publicKey = nullptr) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * EvalAdd - PALISADE EvalAdd method for a pair of ciphertexts * @param ct1 * @param ct2 * @return new ciphertext for ct1 + ct2 */ Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAdd(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAdd, TOC_US(t)) ); } return rv; } /** * EvalAddMatrix - PALISADE EvalAdd method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalAddMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 + *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalAddMatrix - PALISADE EvalAdd method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ Matrix<Ciphertext<Element>> EvalAddMatrix(const Matrix<Ciphertext<Element>> &ct1, const Matrix<Ciphertext<Element>> &ct2) const { TypeCheck(ct1(0,0), ct2(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<Ciphertext<Element>> rv = ct1 + ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddMatrix, TOC_US(t)) ); } // Matrix<Ciphertext<Element>> a(rv); return rv; } /** * EvalSub - PALISADE EvalSub method for a pair of ciphertexts * @param ct1 * @param ct2 * @return new ciphertext for ct1 - ct2 */ Ciphertext<Element> EvalSub(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalSub(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSub, TOC_US(t)) ); } return rv; } /** * EvalSubMatrix - PALISADE EvalSub method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalSubMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 - *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalSubMatrix - PALISADE EvalSub method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ Matrix<Ciphertext<Element>> EvalSubMatrix(const Matrix<Ciphertext<Element>> &ct1, const Matrix<Ciphertext<Element>> &ct2) const { TypeCheck(ct1(0,0), ct2(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<Ciphertext<Element>> rv = ct1 - ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubMatrix, TOC_US(t)) ); } Matrix<Ciphertext<Element>> a(rv); return a; } /** * EvalAdd - PALISADE EvalAdd method for a ciphertext and plaintext * @param ciphertext * @param plaintext * @return new ciphertext for ciphertext + plaintext */ Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { TypeCheck(ciphertext, plaintext); TimeVar t; if( doTiming ) TIC(t); plaintext->SetFormat(EVALUATION); auto rv = GetEncryptionAlgorithm()->EvalAdd(ciphertext, plaintext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddPlain, TOC_US(t)) ); } return rv; } inline Ciphertext<Element> EvalAdd(ConstPlaintext plaintext, ConstCiphertext<Element> ciphertext) const { return EvalAdd(ciphertext, plaintext); } /** * EvalSubPlain - PALISADE EvalSub method for a ciphertext and plaintext * @param ciphertext * @param plaintext * @return new ciphertext for ciphertext - plaintext */ Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { TypeCheck(ciphertext, plaintext); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalSub(ciphertext, plaintext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubPlain, TOC_US(t)) ); } return rv; } inline Ciphertext<Element> EvalSub(ConstPlaintext plaintext, ConstCiphertext<Element> ciphertext) const { return EvalSub(ciphertext, plaintext); } /** * EvalMult - PALISADE EvalMult method for a pair of ciphertexts - with key switching * @param ct1 * @param ct2 * @return new ciphertext for ct1 * ct2 */ Ciphertext<Element> EvalMult(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); auto ek = GetEvalMultKeyVector(ct1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, ct2, ek[0]); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for a pair of ciphertexts - no key switching (relinearization) * @param ct1 * @param ct2 * @return new ciphertext for ct1 * ct2 */ Ciphertext<Element> EvalMultNoRelin(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMultMany - PALISADE function for evaluating multiplication on ciphertext followed by relinearization operation (at the end). * It computes the multiplication in a binary tree manner. Also, it reduces the number of * elements in the ciphertext to two after each multiplication. * Currently it assumes that the consecutive two input arguments have * total depth smaller than the supported depth. Otherwise, it throws an error. * * @param cipherTextList is the ciphertext list. * * @return new ciphertext. */ Ciphertext<Element> EvalMultMany(const vector<Ciphertext<Element>>& ct) const{ const auto ek = GetEvalMultKeyVector(ct[0]->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMultMany(ct, ek); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMultMany, TOC_US(t)) ); } return rv; } /** * Function for evaluating multiplication on ciphertext followed by relinearization operation. * Currently it assumes that the input arguments have total depth smaller than the supported depth. Otherwise, it throws an error. * * @param ct1 first input ciphertext. * @param ct2 second input ciphertext. * * @return new ciphertext */ Ciphertext<Element> EvalMultAndRelinearize(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { const auto ek = GetEvalMultKeyVector(ct1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMultAndRelinearize(ct1, ct2, ek); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for plaintext * ciphertext * @param pt2 * @param ct1 * @return new ciphertext for ct1 * pt2 */ inline Ciphertext<Element> EvalMult(ConstPlaintext pt2, ConstCiphertext<Element> ct1) const { return EvalMult(ct1, pt2); } /** * EvalShiftRight - works only for Fractional Encoding * @param pt2 * @param ct1 * @return new ciphertext for ct1 * pt2 */ Ciphertext<Element> EvalRightShift(ConstCiphertext<Element> ct1, size_t divisor) const { if( ct1 && ct1->GetEncodingType() != Fractional ) { stringstream ss; ss << "A " << Fractional << " encoded ciphertext is required for the EvalRightShift operation"; PALISADE_THROW( type_error, ss.str() ); } Plaintext plaintextShift = MakeFractionalPlaintext(0,divisor); TypeCheck(ct1, plaintextShift); double start = 0; if( doTiming ) start = currentDateTime(); auto rv = EvalMult(ct1, plaintextShift); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalRightShift, currentDateTime() - start) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for plaintext * ciphertext * @param ct1 * @param pt2 * @return new ciphertext for ct1 * pt2 */ Ciphertext<Element> EvalMult(ConstCiphertext<Element> ct1, ConstPlaintext pt2) const { TypeCheck(ct1, pt2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, pt2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMultMatrix - PALISADE EvalMult method for two matrices of ciphertext * @param ct1 * @param ct2 * @return new matrix for ct1 * ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalMultMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 * *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMultMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalSub - PALISADE Negate method for a ciphertext * @param ct * @return new ciphertext -ct */ Ciphertext<Element> EvalNegate(ConstCiphertext<Element> ct) const { if (ct == NULL || Mismatched(ct->GetCryptoContext()) ) throw std::logic_error("Information passed to EvalNegate was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalNegate(ct); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalNeg, TOC_US(t)) ); } return rv; } /** * EvalSub - PALISADE Negate method for a ciphertext * @param ct * @return new ciphertext -ct */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalNegateMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct) const { if (ct == NULL || Mismatched((*ct)(0,0).GetCryptoContext()) ) throw std::logic_error("Information passed to EvalNegateMatrix was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); shared_ptr<Matrix<RationalCiphertext<Element>>> m( new Matrix<RationalCiphertext<Element>>(ct->GetAllocator(), ct->GetRows(), ct->GetCols())); for( size_t r = 0; r < m->GetRows(); r++ ) for( size_t c = 0; c < m->GetCols(); c++ ) (*m)(r,c) = -((*ct)(r,c)); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalNegMatrix, TOC_US(t)) ); } return m; } /** * Generate automophism keys for a given private key * * @param publicKey original public key. * @param origPrivateKey original private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys; index 0 of the vector corresponds to plaintext index 2, index 1 to plaintex index 3, etc. */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<usint> &indexList) const { if( publicKey == NULL || origPrivateKey == NULL ) PALISADE_THROW( type_error, "Null Keys"); if( publicKey->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Key was not created in this CryptoContextImpl"); if( publicKey->GetCryptoContext() != origPrivateKey->GetCryptoContext() ) PALISADE_THROW( type_error, "Keys were not created in the same CryptoContextImpl"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphismKeyGen(publicKey, origPrivateKey, indexList); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismKeyGen, TOC_US(t)) ); } return rv; } /** * Function for evaluating automorphism of ciphertext at index i * * @param ciphertext the input ciphertext. * @param i automorphism index * @param &evalKeys - reference to the vector of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalAutomorphism(ConstCiphertext<Element> ciphertext, usint i, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { auto mf = evalKeys.begin(); if( mf == evalKeys.end() ) PALISADE_THROW( type_error, "Empty key map"); auto tk = mf->second; if( ciphertext == NULL || tk == NULL ) PALISADE_THROW( type_error, "Null inputs"); if( ciphertext->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( ciphertext->GetCryptoContext() != tk->GetCryptoContext() ) PALISADE_THROW( type_error, "Items were not created in the same CryptoContextImpl"); if( ciphertext->GetKeyTag() != tk->GetKeyTag() ) PALISADE_THROW( type_error, "Items were not encrypted with same keys" ); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphism(ciphertext, i, evalKeys); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismI, TOC_US(t)) ); } return rv; } /** * Generate automophism keys for a given private key; Uses the private key for encryption * * @param privateKey private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<usint> &indexList) const { if( privateKey == NULL ) PALISADE_THROW( type_error, "Null input"); if( privateKey->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Key was not created in this CryptoContextImpl"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphismKeyGen(privateKey, indexList); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismK, TOC_US(t)) ); } return rv; } /** * EvalSumKeyGen Generates the key map to be used by evalsum * * @param privateKey private key. * @param publicKey public key (used in NTRU schemes). */ void EvalSumKeyGen( const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey = nullptr); /** * GetEvalSumKey returns the map * * @return the EvalSum key map */ static const std::map<usint, LPEvalKey<Element>>& GetEvalSumKeyMap(const string& id); static const std::map<string,shared_ptr<std::map<usint, LPEvalKey<Element>>>>& GetAllEvalSumKeys(); /** * Function for evaluating a sum of all components * * @param ciphertext the input ciphertext. * @param batchSize size of the batch * @return resulting ciphertext */ Ciphertext<Element> EvalSum(ConstCiphertext<Element> ciphertext, usint batchSize) const; /** * EvalSumKeyGen Generates the key map to be used by evalsum * * @param privateKey private key. * @param indexList list of indices. * @param publicKey public key (used in NTRU schemes). */ void EvalAtIndexKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<int32_t> &indexList, const LPPublicKey<Element> publicKey = nullptr); /** * Merges multiple ciphertexts with encrypted results in slot 0 into a single ciphertext * The slot assignment is done based on the order of ciphertexts in the vector * * @param ciphertextVector vector of ciphertexts to be merged. * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalMerge(const vector<Ciphertext<Element>> &ciphertextVector) const; /** * GetEvalAutomorphismKey returns the map * * @return the EvalAutomorphism key map */ static const std::map<usint, LPEvalKey<Element>>& GetEvalAutomorphismKeyMap(const string& id); static const std::map<string,shared_ptr<std::map<usint, LPEvalKey<Element>>>>& GetAllEvalAutomorphismKeys(); /** * Moves i-th slot to slot 0 * * @param ciphertext. * @param i the index. * @return resulting ciphertext */ Ciphertext<Element> EvalAtIndex(ConstCiphertext<Element> ciphertext, int32_t index) const; /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, usint batchSize) const; /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstPlaintext ciphertext2, usint batchSize) const; /** * EvalCrossCorrelation - Computes the sliding sum of inner products (known as * as cross-correlation, sliding inner product, or sliding dot product in * image processing * @param x - first vector of row vectors * @param y - second vector of row vectors * @param batchSize - batch size for packed encoding * @param indexStart - starting index in the vectors of row vectors * @param length - length of the slice in the vectors of row vectors; default is 0 meaning to use the full length of the vector * @return sum(x_i*y_i), i.e., a sum of inner products */ Ciphertext<Element> EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, usint indexStart = 0, usint length = 0) const; /** * EvalLinRegressBatched- Computes the parameter vector for linear regression using the least squares method * Supported only in batched mode; currently works only for two regressors * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize) const; /** * EvalLinRegression - Computes the parameter vector for linear regression using the least squares method * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const { TypeCheck((*x)(0,0), (*y)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalLinRegression(x, y); if( doTiming ) { timeSamples->push_back( TimingInfo(OpLinRegression, TOC_US(t)) ); } return rv; } /** * KeySwitch - PALISADE KeySwitch method * @param keySwitchHint - reference to KeySwitchHint * @param ciphertext - vector of ciphertext * @return new CiphertextImpl after applying key switch */ Ciphertext<Element> KeySwitch( const LPEvalKey<Element> keySwitchHint, ConstCiphertext<Element> ciphertext) const { if( keySwitchHint == NULL || Mismatched(keySwitchHint->GetCryptoContext()) ) throw std::logic_error("Key passed to KeySwitch was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Ciphertext passed to KeySwitch was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->KeySwitch(keySwitchHint, ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeySwitch, TOC_US(t)) ); } return rv; } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ Ciphertext<Element> ModReduce(ConstCiphertext<Element> ciphertext) const { if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Information passed to ModReduce was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->ModReduce(ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduce, TOC_US(t)) ); } return rv; } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ RationalCiphertext<Element> ModReduceRational(RationalCiphertext<Element> ciphertext) const { TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> n = GetEncryptionAlgorithm()->ModReduce(ciphertext.GetNumerator()); Ciphertext<Element> d = GetEncryptionAlgorithm()->ModReduce(ciphertext.GetDenominator()); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduce, TOC_US(t)) ); } return RationalCiphertext<Element>(n,d); } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ shared_ptr<Matrix<RationalCiphertext<Element>>> ModReduceMatrix(shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext) const { // needs context check TimeVar t; if( doTiming ) TIC(t); shared_ptr<Matrix<RationalCiphertext<Element>>> m( new Matrix<RationalCiphertext<Element>>(ciphertext->GetAllocator(), ciphertext->GetRows(), ciphertext->GetCols())); for( size_t r = 0; r < m->GetRows(); r++ ) for( size_t c = 0; c < m->GetCols(); c++ ) (*m)(r,c) = ModReduceRational((*ciphertext)(r,c)); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduceMatrix, TOC_US(t)) ); } return m; } /** * LevelReduce - PALISADE LevelReduce method * @param cipherText1 * @param linearKeySwitchHint * @return vector of level reduced ciphertext */ Ciphertext<Element> LevelReduce(ConstCiphertext<Element> cipherText1, const LPEvalKeyNTRU<Element> linearKeySwitchHint) const { if( cipherText1 == NULL || linearKeySwitchHint == NULL || Mismatched(cipherText1->GetCryptoContext()) || Mismatched(linearKeySwitchHint->GetCryptoContext()) ) { throw std::logic_error("Information passed to LevelReduce was not generated with this crypto context"); } TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->LevelReduce(cipherText1, linearKeySwitchHint); if( doTiming ) { timeSamples->push_back( TimingInfo(OpLevelReduce, TOC_US(t)) ); } return rv; } /** * RingReduce - PALISADE RingReduce method * @param ciphertext - vector of ciphertext * @param keySwitchHint - the keySwitchHint from original private key to sparse private key * @return vector of ring-reduced ciphertexts */ Ciphertext<Element> RingReduce( ConstCiphertext<Element> ciphertext, const LPEvalKey<Element> keySwitchHint) const { if( keySwitchHint == NULL || Mismatched(keySwitchHint->GetCryptoContext()) ) throw std::logic_error("Key passed to RingReduce was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Ciphertext passed to RingReduce was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto newCiphertext = GetEncryptionAlgorithm()->RingReduce(ciphertext, keySwitchHint); if( doTiming ) { timeSamples->push_back( TimingInfo(OpRingReduce, TOC_US(t)) ); } return newCiphertext; } /** * ComposedEvalMult - PALISADE composed evalmult * @param ciphertext1 - vector for first cipher text * @param ciphertext2 - vector for second cipher text * @param quadKeySwitchHint - is the quadratic key switch hint from original private key to the quadratic key * return vector of resulting ciphertext */ Ciphertext<Element> ComposedEvalMult( ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const { if( ciphertext1 == NULL || ciphertext2 == NULL || ciphertext1->GetKeyTag() != ciphertext2->GetKeyTag() || Mismatched(ciphertext1->GetCryptoContext()) ) throw std::logic_error("Ciphertexts passed to ComposedEvalMult were not generated with this crypto context"); auto ek = GetEvalMultKeyVector(ciphertext1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->ComposedEvalMult(ciphertext1, ciphertext2, ek[0]); if( doTiming ) { timeSamples->push_back( TimingInfo(OpComposedEvalMult, TOC_US(t)) ); } return rv; } static LPPublicKey<Element> deserializePublicKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static LPPrivateKey<Element> deserializeSecretKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static LPEvalKey<Element> deserializeEvalKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static LPEvalKey<Element> deserializeEvalKeyInContext(const Serialized& serObj, CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::make_nvp("cc", params) ); ar( ::cereal::make_nvp("kt", scheme) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::make_nvp("cc", params) ); ar( ::cereal::make_nvp("kt", scheme) ); // NOTE: a pointer to this object will be wrapped in a shared_ptr, and is a "CryptoContext". // PALISADE relies on the notion that identical CryptoContextImpls are not duplicated in memory // Once we deserialize this object, we must check to see if there is a matching object // for this object that's already existing in memory // if it DOES exist, use it. If it does NOT exist, add this to the cache of all contexts // That functionality gets handled in the Deserialize wrapper for CryptoContext } std::string SerializedObjectName() const { return "CryptoContext"; } static uint32_t SerializedVersion() { return 1; } }; /** * @brief CryptoObject * * A class to aid in referring to the crypto context that an object belongs to */ template<typename Element> class CryptoObject { protected: CryptoContext<Element> context; /*!< crypto context this object belongs to */ string keyTag; /*!< tag used to find the evaluation key needed for SHE/FHE operations */ public: CryptoObject(CryptoContext<Element> cc = 0, const string& tag = "") : context(cc), keyTag(tag) {} CryptoObject(const CryptoObject& rhs) { context = rhs.context; keyTag = rhs.keyTag; } CryptoObject(const CryptoObject&& rhs) { context = std::move(rhs.context); keyTag = std::move(rhs.keyTag); } virtual ~CryptoObject() {} const CryptoObject& operator=(const CryptoObject& rhs) { this->context = rhs.context; this->keyTag = rhs.keyTag; return *this; } const CryptoObject& operator=(const CryptoObject&& rhs) { this->context = std::move(rhs.context); this->keyTag = std::move(rhs.keyTag); return *this; } bool operator==(const CryptoObject& rhs) const { return context.get() == rhs.context.get() && keyTag == rhs.keyTag; } CryptoContext<Element> GetCryptoContext() const { return context; } const shared_ptr<LPCryptoParameters<Element>> GetCryptoParameters() const { return context->GetCryptoParameters(); } const EncodingParams GetEncodingParameters() const { return context->GetCryptoParameters()->GetEncodingParams(); } const string GetKeyTag() const { return keyTag; } void SetKeyTag(const string& tag) { keyTag = tag; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::make_nvp("cc", context) ); ar( ::cereal::make_nvp("kt", keyTag) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::make_nvp("cc", context) ); ar( ::cereal::make_nvp("kt", keyTag) ); context = CryptoContextFactory<Element>::GetContext(context->GetCryptoParameters(),context->GetEncryptionAlgorithm()); } std::string SerializedObjectName() const { return "CryptoObject"; } static uint32_t SerializedVersion() { return 1; } }; /** * @brief CryptoContextFactory * * A class that contains static methods to generate new crypto contexts from user parameters * */ template<typename Element> class CryptoContextFactory { static vector<CryptoContext<Element>> AllContexts; public: static void ReleaseAllContexts(); static int GetContextCount(); static CryptoContext<Element> GetSingleContext(); static CryptoContext<Element> GetContext( shared_ptr<LPCryptoParameters<Element>> params, shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme); static CryptoContext<Element> GetContextForPointer(CryptoContextImpl<Element>* cc); static const vector<CryptoContext<Element>>& GetAllContexts(); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param delta - the plaintext scaling parameter floor(q/t) in BFV * @param mode - mode for generating secret keys (RLWE vs OPTIMIZED) * @param bigmodulus - large modulus used in tensoring of homomorphic multiplication * @param bigrootofunity - root of unity for bigmodulus * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @param bigmodulusarb - additional large modulus for bigmoduls for the case of general (non-power-of-two) cyclotomics * @param bigrootofunityarb - root of unity for bigmodulusarb * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, const std::string& delta, MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0", int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param delta - the plaintext scaling parameter floor(q/t) in BFV * @param mode - mode for generating secret keys (RLWE vs OPTIMIZED) * @param bigmodulus - large modulus used in tensoring of homomorphic multiplication * @param bigrootofunity - root of unity for bigmodulus * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @param bigmodulusarb - additional large modulus for bigmoduls for the case of general (non-power-of-two) cyclotomics * @param bigrootofunityarb - root of unity for bigmodulusarb * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, const std::string& delta, MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0", int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( const PlaintextModulus plaintextModulus, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard security level * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( EncodingParams encodingParams, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( EncodingParams encodingParams, SecurityLevel securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window (bits in the base for digits) used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( const PlaintextModulus plaintextModulus, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard secuirity level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window (bits in the base for digits) used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( EncodingParams encodingParams, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( EncodingParams encodingParams, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( const PlaintextModulus plaintextModulus, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( EncodingParams encodingParams, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( EncodingParams encodingParams, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BGV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param depth of supported computation circuit (not used; for future use) * @return new context */ static CryptoContext<Element> genCryptoContextBGV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, MODE mode = RLWE, int depth = 1); /** * construct a PALISADE CryptoContextImpl for the BGV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param depth of supported computation circuit (not used; for future use) * @return new context */ static CryptoContext<Element> genCryptoContextBGV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, MODE mode = RLWE, int depth = 1); /** * construct a PALISADE CryptoContextImpl for the StehleSteinfeld Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param stdDev distribution parameter for secret key distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextStehleSteinfeld(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, float stDevStSt, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the StehleSteinfeld Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param stdDev distribution parameter for secret key distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextStehleSteinfeld(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, float stDevStSt, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the Null Scheme * @param m cyclotomic order (ring dimension n = m/2 for power-of-two cyclotomics) * @param plaintextModulus plaintext modulus * @return */ static CryptoContext<Element> genCryptoContextNull(unsigned int m, const PlaintextModulus ptModulus); /** * construct a PALISADE CryptoContextImpl for the Null Scheme * @param m cyclotomic order (ring dimension n = m/2 for power-of-two cyclotomics) * @param encodingParams plaintext encoding parameters * @return */ static CryptoContext<Element> genCryptoContextNull(unsigned int m, EncodingParams encodingParams); static CryptoContext<Element> DeserializeAndCreateContext(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); }; } #endif /* SRC_DEMO_PRE_CRYPTOCONTEXT_H_ */
num3omp.c
#include <stdlib.h> // C standard library include #include <stdio.h> // I/O library include #include <math.h> #include <time.h> #include <omp.h> void generic_processing_job(int, int, double *, int, double *); int main(argc,argv) int argc; char *argv[]; { double accum; double *theBuffer; int bufSize; int i; time_t startTime, endTime; int duration; int np; // Number of processes // Check the number of command-line arguments if (argc != 2) { printf(" use: num3omp np\n"); printf(" where np is the number of threads to generate, up to 20\n"); exit(-1); } // Start the timer startTime = time(NULL); // Get the number of processes entered sscanf(argv[1], "%d",&np); if ((np < 1) || (np > 20)) { printf(" Error: np = %d. Needs to be between 1 and 20 inclusive...\n", np); exit(-1); } // Allocate data buffer memory bufSize = 50000000; theBuffer = (double *)malloc(bufSize * sizeof(double)); if (!theBuffer) { printf(" Error allocating memory...\n"); exit(-1); } srand(startTime); for(i=0; i<bufSize; ++i) { theBuffer[i] = 100.0 * (rand() / (RAND_MAX + 1.0)); } omp_set_num_threads(np); #pragma omp parallel reduction(+:accum) { generic_processing_job(omp_get_thread_num(), omp_get_num_threads(), theBuffer, bufSize, &accum); } // Sumarize information from the two processing jobs printf(" %d %d ", np, bufSize); printf("%lf ", accum/(double)bufSize); // Get the end time endTime = time(NULL); duration = endTime - startTime; printf("%d\n", duration); } void generic_processing_job(int start, int increment, double *buf, int size, double *accum) { int i,j; int numVals; double localAvg; double delta; double stdDev; // Calculate sum numVals = 0; for (i=start; i<size; i+=increment) { *accum += buf[i]; numVals++; } // Calculate local aveage localAvg = *accum/(double)numVals; // Calculate local stdev -- to spend time, do it 500x for (j=0; j<500; ++j) { numVals = 0; for (i=start; i<size; i+=increment) { delta += pow((buf[i] - localAvg),2); numVals++; } stdDev = sqrt(delta/numVals); } }
GB_unaryop__minv_int8_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_int8_uint8 // op(A') function: GB_tran__minv_int8_uint8 // C type: int8_t // A type: uint8_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 8) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 8) ; // casting #define GB_CASTING(z, x) \ int8_t z = (int8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT8 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int8_uint8 ( int8_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_int8_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
dwt.c
#include "dwt.h" #include "libdwt.h" #ifdef __SSE__ #include <xmmintrin.h> #endif #include "inline-sdl.h" #ifdef _OPENMP #include <omp.h> #endif #include <assert.h> #include <math.h> #define MEASURE_FACTOR 1 #define MEASURE_PER_PIXEL #include "inline.h" #include "dwt-core.h" #ifdef __SSE__ #define op4s_sdl2_update_s_sse(c, l, r, z) \ do { \ (c) = (l); \ (l) = (r); \ (r) = (z); \ } while(0) #endif #ifdef __SSE__ #define op4s_sdl2_shuffle_input_low_s_sse(in, c, r) \ do { \ __m128 t; \ (t) = (in); \ (t) = _mm_shuffle_ps((t), (c), _MM_SHUFFLE(3,2,1,0)); \ (c) = _mm_shuffle_ps((c), (t), _MM_SHUFFLE(0,3,2,1)); \ (t) = _mm_shuffle_ps((t), (r), _MM_SHUFFLE(3,2,1,0)); \ (r) = _mm_shuffle_ps((r), (t), _MM_SHUFFLE(1,3,2,1)); \ } while(0) #endif #ifdef __SSE__ #define op4s_sdl2_shuffle_input_high_s_sse(in, c, r) \ do { \ (in) = _mm_shuffle_ps( (in), (c), _MM_SHUFFLE(3,2,3,2) ); \ (c) = _mm_shuffle_ps( (c), (in), _MM_SHUFFLE(0,3,2,1) ); \ (in) = _mm_shuffle_ps( (in), (r), _MM_SHUFFLE(3,2,1,0) ); \ (r) = _mm_shuffle_ps( (r), (in), _MM_SHUFFLE(1,3,2,1) ); \ } while(0) #endif #ifdef __SSE__ #define op4s_sdl2_op_s_sse(z, c, w, l, r) \ do { \ (z) = (l); \ (z) = _mm_add_ps((z), (r)); \ (z) = _mm_mul_ps((z), (w)); \ (z) = _mm_add_ps((z), (c)); \ } while(0) #endif #ifdef __SSE__ #define op4s_sdl2_output_low_s_sse(out, l, z) \ do { \ (out) = (l); \ (out) = _mm_unpacklo_ps((out), (z)); \ } while(0) #endif #ifdef __SSE__ #define op4s_sdl2_output_high_s_sse(out, l, z) \ do { \ __m128 t; \ (t) = (l); \ (t) = _mm_unpacklo_ps((t), (z)); \ (out) = _mm_shuffle_ps((out), t, _MM_SHUFFLE(1,0,1,0)); \ } while(0) #endif #ifdef __SSE__ #define op4s_sdl2_scale_s_sse(out, v) \ do { \ (out) = _mm_mul_ps((out), (v)); \ } while(0) #endif static void op4s_sdl2_update_s_ref(float *c, float *l, float *r, const float *z) { c[0] = l[0]; c[1] = l[1]; c[2] = l[2]; c[3] = l[3]; l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; r[0] = z[0]; r[1] = z[1]; r[2] = z[2]; r[3] = z[3]; } static void op4s_sdl2_shuffle_s_ref(float *c, float *r) { c[0]=c[1]; c[1]=c[2]; c[2]=c[3]; r[0]=r[1]; r[1]=r[2]; r[2]=r[3]; } static void op4s_sdl2_input_low_s_ref(const float *in, float *c, float *r) { c[3] = in[0]; r[3] = in[1]; } static void op4s_sdl2_input_high_s_ref(const float *in, float *c, float *r) { c[3] = in[2]; r[3] = in[3]; } static void op4s_sdl2_shuffle_input_low_s_ref(const float *in, float *c, float *r) { op4s_sdl2_shuffle_s_ref(c, r); op4s_sdl2_input_low_s_ref(in, c, r); } static void op4s_sdl2_shuffle_input_high_s_ref(const float *in, float *c, float *r) { op4s_sdl2_shuffle_s_ref(c, r); op4s_sdl2_input_high_s_ref(in, c, r); } static void op4s_sdl2_op_s_ref(float *z, const float *c, const float *w, const float *l, const float *r) { z[3] = c[3] + w[3] * ( l[3] + r[3] ); z[2] = c[2] + w[2] * ( l[2] + r[2] ); z[1] = c[1] + w[1] * ( l[1] + r[1] ); z[0] = c[0] + w[0] * ( l[0] + r[0] ); } static void op4s_sdl2_output_low_s_ref(float *out, const float *l, const float *z) { out[0] = l[0]; out[1] = z[0]; } static void op4s_sdl2_output_high_s_ref(float *out, const float *l, const float *z) { out[2] = l[0]; out[3] = z[0]; } static void op4s_sdl2_scale_s_ref(float *out, const float *v) { out[0] *= v[0]; out[1] *= v[1]; out[2] *= v[2]; out[3] *= v[3]; } int dwt_alg_shift[DWT_ALG_LAST] = { [DWT_ALG_SL_CORE_DL] = 4, [DWT_ALG_SL_CORE_DL_SSE] = 4, [DWT_ALG_SL_CORE_DL_SC] = 4, [DWT_ALG_SL_CORE_DL_SC_SSE] = 4, [DWT_ALG_SL_CORE_SDL] = 10, [DWT_ALG_SL_CORE_SDL_SSE] = 10, [DWT_ALG_SL_CORE_SDL_SC] = 10, [DWT_ALG_SL_CORE_SDL_SC_SSE] = 10, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF0] = 10, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1] = 10, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1_6X2] = 10, [DWT_ALG_SL_CORE_DL_SC_SSE_OFF1] = 4, [DWT_ALG_SL_CORE_DL_SC_SSE_OFF1_4X4] = 4, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF0_OVL1] = 10, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1_OVL1] = 10, }; int dwt_alg_get_shift( enum dwt_alg alg ) { return dwt_alg_shift[alg]; } static void cdf97_fwd_core2_sdl_2x2_s( float *ptrL0, float *ptrL1, float *ptrR0, float *ptrR1, float *outL0, float *outL1, float *outR0, float *outR1, float *lAL, float *cAL, float *rAL, float *lAR, float *cAR, float *rAR, float *lBL, float *cBL, float *rBL, float *lBR, float *cBR, float *rBR ) { UNUSED(cAL); UNUSED(rAL); UNUSED(cAR); UNUSED(rAR); UNUSED(cBL); UNUSED(rBL); UNUSED(cBR); UNUSED(rBR); const float w[4] = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const float v[4] = { 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s, 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s }; float buff[4]; float z[4]; buff[0] = *ptrL0; buff[1] = *ptrL1; buff[2] = *ptrR0; buff[3] = *ptrR1; // A/L+R op4s_sdl2_shuffle_input_low_s_ref(buff, (lAL+4), (lAL+8)); op4s_sdl2_shuffle_input_high_s_ref(buff, (lAR+4), (lAR+8)); // A/L op4s_sdl2_op_s_ref(z, (lAL+4), w, (lAL+0), (lAL+8)); op4s_sdl2_output_low_s_ref(buff, (lAL+0), z); op4s_sdl2_update_s_ref((lAL+4), (lAL+0), (lAL+8), z); // A/R op4s_sdl2_op_s_ref(z, (lAR+4), w, (lAR+0), (lAR+8)); op4s_sdl2_output_high_s_ref(buff, (lAR+0), z); op4s_sdl2_update_s_ref((lAR+4), (lAR+0), (lAR+8), z); // A/L+R op4s_sdl2_scale_s_ref(buff, v); // swap, this should by done by single shuffle instruction float tmp = buff[1]; buff[1] = buff[2]; buff[2] = tmp; // B/L+R op4s_sdl2_shuffle_input_low_s_ref(buff, (lBL+4), (lBL+8)); op4s_sdl2_shuffle_input_high_s_ref(buff, (lBR+4), (lBR+8)); // B/L op4s_sdl2_op_s_ref(z, (lBL+4), w, (lBL+0), (lBL+8)); op4s_sdl2_output_low_s_ref(buff, (lBL+0), z); op4s_sdl2_update_s_ref((lBL+4), (lBL+0), (lBL+8), z); // B/R op4s_sdl2_op_s_ref(z, (lBR+4), w, (lBR+0), (lBR+8)); op4s_sdl2_output_high_s_ref(buff, (lBR+0), z); op4s_sdl2_update_s_ref((lBR+4), (lBR+0), (lBR+8), z); // B/L+R op4s_sdl2_scale_s_ref(buff, v); *outL0 = buff[0]; *outL1 = buff[1]; *outR0 = buff[2]; *outR1 = buff[3]; } #ifdef __SSE__ static void cdf97_fwd_core2_sdl_2x2_sse_s( float *ptrL0, float *ptrL1, float *ptrR0, float *ptrR1, float *outL0, float *outL1, float *outR0, float *outR1, float *lAL, float *cAL, float *rAL, float *lAR, float *cAR, float *rAR, float *lBL, float *cBL, float *rBL, float *lBR, float *cBR, float *rBR ) { UNUSED(cAL); UNUSED(rAL); UNUSED(cAR); UNUSED(rAR); UNUSED(cBL); UNUSED(rBL); UNUSED(cBR); UNUSED(rBR); const float w[4] ALIGNED(16) = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const float v[4] ALIGNED(16) = { 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s, 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s }; __m128 buff; __m128 z; buff[0] = *ptrL0; buff[1] = *ptrL1; buff[2] = *ptrR0; buff[3] = *ptrR1; // A/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lAL+4), *(__m128 *)(lAL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lAR+4), *(__m128 *)(lAR+8)); // A/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lAL+4), *(__m128 *)w, *(__m128 *)(lAL+0), *(__m128 *)(lAL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lAL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAL+4), *(__m128 *)(lAL+0), *(__m128 *)(lAL+8), z); // A/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lAR+4), *(__m128 *)w, *(__m128 *)(lAR+0), *(__m128 *)(lAR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lAR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAR+4), *(__m128 *)(lAR+0), *(__m128 *)(lAR+8), z); // A/L+R op4s_sdl2_scale_s_sse(buff, *(__m128 *)v); // swap, this should by done by single shuffle instruction buff = _mm_shuffle_ps(buff, buff, _MM_SHUFFLE(3,1,2,0)); // B/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lBL+4), *(__m128 *)(lBL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lBR+4), *(__m128 *)(lBR+8)); // B/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lBL+4), *(__m128 *)w, *(__m128 *)(lBL+0), *(__m128 *)(lBL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lBL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lBL+4), *(__m128 *)(lBL+0), *(__m128 *)(lBL+8), z); // B/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lBR+4), *(__m128 *)w, *(__m128 *)(lBR+0), *(__m128 *)(lBR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lBR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lBR+4), *(__m128 *)(lBR+0), *(__m128 *)(lBR+8), z); // B/L+R op4s_sdl2_scale_s_sse(buff, *(__m128 *)v); *outL0 = buff[0]; *outL1 = buff[1]; *outR0 = buff[2]; *outR1 = buff[3]; } #endif #ifdef __SSE__ static void cdf97_fwd_core2_sdl_2x2_sc_sse_s( float *ptrL0, float *ptrL1, float *ptrR0, float *ptrR1, float *outL0, float *outL1, float *outR0, float *outR1, float *lAL, float *cAL, float *rAL, float *lAR, float *cAR, float *rAR, float *lBL, float *cBL, float *rBL, float *lBR, float *cBR, float *rBR ) { UNUSED(cAL); UNUSED(rAL); UNUSED(cAR); UNUSED(rAR); UNUSED(cBL); UNUSED(rBL); UNUSED(cBR); UNUSED(rBR); const __m128 w = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const __m128 v_vert = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s) }; __m128 buff; __m128 z; buff[0] = *ptrL0; buff[1] = *ptrL1; buff[2] = *ptrR0; buff[3] = *ptrR1; // A/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lAL+4), *(__m128 *)(lAL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lAR+4), *(__m128 *)(lAR+8)); // A/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lAL+4), w, *(__m128 *)(lAL+0), *(__m128 *)(lAL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lAL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAL+4), *(__m128 *)(lAL+0), *(__m128 *)(lAL+8), z); // A/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lAR+4), w, *(__m128 *)(lAR+0), *(__m128 *)(lAR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lAR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAR+4), *(__m128 *)(lAR+0), *(__m128 *)(lAR+8), z); // swap, this should by done by single shuffle instruction buff = _mm_shuffle_ps(buff, buff, _MM_SHUFFLE(3,1,2,0)); // B/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lBL+4), *(__m128 *)(lBL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lBR+4), *(__m128 *)(lBR+8)); // B/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lBL+4), w, *(__m128 *)(lBL+0), *(__m128 *)(lBL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lBL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lBL+4), *(__m128 *)(lBL+0), *(__m128 *)(lBL+8), z); // B/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lBR+4), w, *(__m128 *)(lBR+0), *(__m128 *)(lBR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lBR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lBR+4), *(__m128 *)(lBR+0), *(__m128 *)(lBR+8), z); // B/L+R op4s_sdl2_scale_s_sse(buff, v_vert); *outL0 = buff[0]; *outL1 = buff[1]; *outR0 = buff[2]; *outR1 = buff[3]; } #endif #ifdef __SSE__ static void cdf97_inv_core2_sdl_2x2_sc_sse_s( float *ptrL0, float *ptrL1, float *ptrR0, float *ptrR1, float *outL0, float *outL1, float *outR0, float *outR1, float *lAL, float *cAL, float *rAL, float *lAR, float *cAR, float *rAR, float *lBL, float *cBL, float *rBL, float *lBR, float *cBR, float *rBR ) { UNUSED(cAL); UNUSED(rAL); UNUSED(cAR); UNUSED(rAR); UNUSED(cBL); UNUSED(rBL); UNUSED(cBR); UNUSED(rBR); // NOTE: reversed with negative signs const __m128 w = { +dwt_cdf97_p1_s, -dwt_cdf97_u1_s, +dwt_cdf97_p2_s, -dwt_cdf97_u2_s }; const __m128 v_vert = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s) }; __m128 buff; __m128 z; buff[0] = *ptrL0; buff[1] = *ptrL1; buff[2] = *ptrR0; buff[3] = *ptrR1; // B/L+R op4s_sdl2_scale_s_sse(buff, v_vert); // A/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lAL+4), *(__m128 *)(lAL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lAR+4), *(__m128 *)(lAR+8)); // A/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lAL+4), w, *(__m128 *)(lAL+0), *(__m128 *)(lAL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lAL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAL+4), *(__m128 *)(lAL+0), *(__m128 *)(lAL+8), z); // A/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lAR+4), w, *(__m128 *)(lAR+0), *(__m128 *)(lAR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lAR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAR+4), *(__m128 *)(lAR+0), *(__m128 *)(lAR+8), z); // swap, this should by done by single shuffle instruction buff = _mm_shuffle_ps(buff, buff, _MM_SHUFFLE(3,1,2,0)); // B/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lBL+4), *(__m128 *)(lBL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lBR+4), *(__m128 *)(lBR+8)); // B/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lBL+4), w, *(__m128 *)(lBL+0), *(__m128 *)(lBL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lBL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lBL+4), *(__m128 *)(lBL+0), *(__m128 *)(lBL+8), z); // B/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lBR+4), w, *(__m128 *)(lBR+0), *(__m128 *)(lBR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lBR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lBR+4), *(__m128 *)(lBR+0), *(__m128 *)(lBR+8), z); *outL0 = buff[0]; *outL1 = buff[1]; *outR0 = buff[2]; *outR1 = buff[3]; } #endif #ifdef __SSE__ static void cdf97_fwd_core2prolog_sdl_2x2_sc_sse_s( float *ptrL0, float *ptrL1, float *ptrR0, float *ptrR1, float *outL0, float *outL1, float *outR0, float *outR1, float *lAL, float *cAL, float *rAL, float *lAR, float *cAR, float *rAR, float *lBL, float *cBL, float *rBL, float *lBR, float *cBR, float *rBR ) { UNUSED(outL0); UNUSED(outL1); UNUSED(outR0); UNUSED(outR1); UNUSED(cAL); UNUSED(rAL); UNUSED(cAR); UNUSED(rAR); UNUSED(cBL); UNUSED(rBL); UNUSED(cBR); UNUSED(rBR); const __m128 w = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; __m128 buff; __m128 z; buff[0] = *ptrL0; buff[1] = *ptrL1; buff[2] = *ptrR0; buff[3] = *ptrR1; // A/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lAL+4), *(__m128 *)(lAL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lAR+4), *(__m128 *)(lAR+8)); // A/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lAL+4), w, *(__m128 *)(lAL+0), *(__m128 *)(lAL+8)); op4s_sdl2_output_low_s_sse(buff, *(__m128 *)(lAL+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAL+4), *(__m128 *)(lAL+0), *(__m128 *)(lAL+8), z); // A/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lAR+4), w, *(__m128 *)(lAR+0), *(__m128 *)(lAR+8)); op4s_sdl2_output_high_s_sse(buff, *(__m128 *)(lAR+0), z); op4s_sdl2_update_s_sse(*(__m128 *)(lAR+4), *(__m128 *)(lAR+0), *(__m128 *)(lAR+8), z); // swap, this should by done by single shuffle instruction buff = _mm_shuffle_ps(buff, buff, _MM_SHUFFLE(3,1,2,0)); // B/L+R op4s_sdl2_shuffle_input_low_s_sse(buff, *(__m128 *)(lBL+4), *(__m128 *)(lBL+8)); op4s_sdl2_shuffle_input_high_s_sse(buff, *(__m128 *)(lBR+4), *(__m128 *)(lBR+8)); // B/L op4s_sdl2_op_s_sse(z, *(__m128 *)(lBL+4), w, *(__m128 *)(lBL+0), *(__m128 *)(lBL+8)); op4s_sdl2_update_s_sse(*(__m128 *)(lBL+4), *(__m128 *)(lBL+0), *(__m128 *)(lBL+8), z); // B/R op4s_sdl2_op_s_sse(z, *(__m128 *)(lBR+4), w, *(__m128 *)(lBR+0), *(__m128 *)(lBR+8)); op4s_sdl2_update_s_sse(*(__m128 *)(lBR+4), *(__m128 *)(lBR+0), *(__m128 *)(lBR+8), z); } #endif #ifdef __SSE__ static void cdf97_fwd_core_sdl_2x2_sse_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_fwd_core2_sdl_2x2_sse_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y1_x0, out_y0_x1, out_y1_x1, buff_y0+0, buff_y0+4, buff_y0+8, buff_y1+0, buff_y1+4, buff_y1+8, buff_x0+0, buff_x0+4, buff_x0+8, buff_x1+0, buff_x1+4, buff_x1+8 ); } #endif #ifdef __SSE__ static void cdf97_fwd_core_sdl_2x2_sc_sse_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_fwd_core2_sdl_2x2_sc_sse_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y1_x0, out_y0_x1, out_y1_x1, buff_y0+0, buff_y0+4, buff_y0+8, buff_y1+0, buff_y1+4, buff_y1+8, buff_x0+0, buff_x0+4, buff_x0+8, buff_x1+0, buff_x1+4, buff_x1+8 ); } #endif #ifdef __SSE__ static void cdf97_inv_core_sdl_2x2_sc_sse_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_inv_core2_sdl_2x2_sc_sse_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y1_x0, out_y0_x1, out_y1_x1, buff_y0+0, buff_y0+4, buff_y0+8, buff_y1+0, buff_y1+4, buff_y1+8, buff_x0+0, buff_x0+4, buff_x0+8, buff_x1+0, buff_x1+4, buff_x1+8 ); } #endif #ifdef __SSE__ void fdwt_cdf97_diag_core2x2_sse_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_fwd_core_sdl_2x2_sc_sse_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y0_x1, out_y1_x0, out_y1_x1, buff_y0, buff_y1, buff_x0, buff_x1 ); } #endif #ifdef __SSE__ void idwt_cdf97_diag_core2x2_sse_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_inv_core_sdl_2x2_sc_sse_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y0_x1, out_y1_x0, out_y1_x1, buff_y0, buff_y1, buff_x0, buff_x1 ); } #endif #ifdef __SSE__ static void cdf97_fwd_core_prolog_sdl_2x2_sc_sse_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_fwd_core2prolog_sdl_2x2_sc_sse_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y1_x0, out_y0_x1, out_y1_x1, buff_y0+0, buff_y0+4, buff_y0+8, buff_y1+0, buff_y1+4, buff_y1+8, buff_x0+0, buff_x0+4, buff_x0+8, buff_x1+0, buff_x1+4, buff_x1+8 ); } #endif static void cdf97_fwd_core_sdl_2x2_s( float *ptr_y0_x0, float *ptr_y0_x1, float *ptr_y1_x0, float *ptr_y1_x1, float *out_y0_x0, float *out_y0_x1, float *out_y1_x0, float *out_y1_x1, float *buff_y0, float *buff_y1, float *buff_x0, float *buff_x1 ) { cdf97_fwd_core2_sdl_2x2_s( ptr_y0_x0, ptr_y0_x1, ptr_y1_x0, ptr_y1_x1, out_y0_x0, out_y1_x0, out_y0_x1, out_y1_x1, buff_y0+0, buff_y0+4, buff_y0+8, buff_y1+0, buff_y1+4, buff_y1+8, buff_x0+0, buff_x0+4, buff_x0+8, buff_x1+0, buff_x1+4, buff_x1+8 ); } // SL SDL WITH-MERGED-SCALING SSE #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { const int offset = 1; float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } } #endif // SL SDL WITH*MERGED-SCALING SSE W/O OFFSET #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off0_inner_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { const int offset = 0; float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } #pragma omp barrier } } #endif // SL SDL WITH*MERGED-SCALING SSE OFFSET=1 #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off1_inner_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { const int offset = 1; float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } #pragma omp barrier } } #endif // SL SDL WITH*MERGED-SCALING SSE W/O OFFSET #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off0_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { #if 0 const int offset = 0; float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #else const int offset = 0; int threads = dwt_util_get_num_threads(); // 8, 4 // assert( is_even(size_y) ); // FIXME: really needs to be even? int thread_size_y = dwt_util_up_to_even( ceil_div(size_y, threads) ); const int prolog_y = 10+4; const int overlay_y = 4; //#pragma omp parallel for //for(int thread = 0; thread < threads; thread++) #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, offset, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, offset, dst_stride_x, dst_stride_y); void *thread_dst_null = NULL; char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; // FIXME: unnecesarry when no overlay used #if 0 cdf97_fwd_core_sdl_sc_sse_off0_inner_s( thread_src, thread_dst, src_stride_x, src_stride_y, dst_stride_x, dst_stride_y, size_x, thread_size_y+overlay_y ); #else float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+1 < offset+0; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_null, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_null, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_prolog_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+1 < offset+thread_size_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *ptr1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+1 < size_x; x += 2) { *addr1_s(out0_x, 0, dst_stride_y) = *addr1_s(ptr0_x, 0, src_stride_y); *addr1_s(out0_x, 1, dst_stride_y) = *addr1_s(ptr0_x, 1, src_stride_y); *addr1_s(out1_x, 0, dst_stride_y) = *addr1_s(ptr1_x, 0, src_stride_y); *addr1_s(out1_x, 1, dst_stride_y) = *addr1_s(ptr1_x, 1, src_stride_y); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #endif } #endif } #endif // SL SDL WITH*MERGED-SCALING SSE OFFSET=0 OVERLAY=1 #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off0_ovl1_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { #if 0 const int offset = 0; float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #else const int offset = 0; int threads = dwt_util_get_num_threads(); // 8, 4 // assert( is_even(size_y) ); // FIXME: really needs to be even? int thread_size_y = dwt_util_up_to_even( ceil_div(size_y, threads) ); const int prolog_y = 10+4; const int overlay_y = 0; //#pragma omp parallel for //for(int thread = 0; thread < threads; thread++) #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, offset, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, offset, dst_stride_x, dst_stride_y); void *thread_dst_null = NULL; char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; #if 0 cdf97_fwd_core_sdl_sc_sse_off0_inner_s( thread_src, thread_dst, src_stride_x, src_stride_y, dst_stride_x, dst_stride_y, size_x, thread_size_y+overlay_y ); #else float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+1 < offset+0; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_null, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_null, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_prolog_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+1 < offset+thread_size_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *ptr1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+1 < size_x; x += 2) { *addr1_s(out0_x, 0, dst_stride_y) = *addr1_s(ptr0_x, 0, src_stride_y); *addr1_s(out0_x, 1, dst_stride_y) = *addr1_s(ptr0_x, 1, src_stride_y); *addr1_s(out1_x, 0, dst_stride_y) = *addr1_s(ptr1_x, 0, src_stride_y); *addr1_s(out1_x, 1, dst_stride_y) = *addr1_s(ptr1_x, 1, src_stride_y); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #endif } #endif } #endif // SL SDL WITH*MERGED-SCALING SSE OFFSET=1 THREADS #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off1_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { #if 0 // NOTE: this works well const int offset = 1; float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #else const int offset = 1; int threads = dwt_util_get_num_threads(); // 8, 4 // assert( is_even(size_y) ); int thread_size_y = dwt_util_up_to_even( ceil_div(size_y, threads) ); const int prolog_y = 10+4; const int overlay_y = 4; //#pragma omp parallel for //for(int thread = 0; thread < threads; thread++) #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, 0/*offset*/, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, 0/*offset*/, dst_stride_x, dst_stride_y); void *thread_dst_null = NULL; char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; #if 0 cdf97_fwd_core_sdl_sc_sse_off1_inner_s( thread_src, thread_dst, src_stride_x, src_stride_y, dst_stride_x, dst_stride_y, size_x, thread_size_y+overlay_y ); #else float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+1 < offset+0; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_null, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_null, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_prolog_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+1 < offset+thread_size_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *ptr1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+1 < size_x; x += 2) { *addr1_s(out0_x, 0, dst_stride_y) = *addr1_s(ptr0_x, 0, src_stride_y); *addr1_s(out0_x, 1, dst_stride_y) = *addr1_s(ptr0_x, 1, src_stride_y); *addr1_s(out1_x, 0, dst_stride_y) = *addr1_s(ptr1_x, 0, src_stride_y); *addr1_s(out1_x, 1, dst_stride_y) = *addr1_s(ptr1_x, 1, src_stride_y); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #endif } #endif } #endif #ifdef __SSE__ static void cdf97_fwd_core_dl_sc_sse_2x2_s( float *ptr_y0_x0, // in float *ptr_y0_x1, // in float *ptr_y1_x0, // in float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ); #endif #ifdef __SSE__ static void cdf97_fwd_core_prolog_dl_sc_sse_2x2_s( float *ptr_y0_x0, // in float *ptr_y0_x1, // in float *ptr_y1_x0, // in float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ); #endif // SL SDL WITH*MERGED-SCALING SSE OFFSET=1 THREADS #ifdef __SSE__ void cdf97_fwd_core_dl_sc_sse_off1_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { #if 0 // NOTE: this works well const int offset = 1; const int words = 1; float long_buffer[4*words*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 4*words*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(words*4)*(offset+0); float short_buffer_0[words*4] __attribute__ ((aligned (16))); float short_buffer_1[words*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, words*4); dwt_util_zero_vec_s(short_buffer_1, words*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_sc_sse_2x2_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(words*4), long_buffer_ptr+1*(words*4) ); long_buffer_ptr += 2*(words*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #else const int offset = 1; const int words = 1; int threads = dwt_util_get_num_threads(); // 8, 4 // assert( is_even(size_y) ); int thread_size_y = dwt_util_up_to_even( ceil_div(size_y, threads) ); const int prolog_y = 4+4; const int overlay_y = 4; //#pragma omp parallel for //for(int thread = 0; thread < threads; thread++) #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, 0/*offset*/, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, 0/*offset*/, dst_stride_x, dst_stride_y); void *thread_dst_null = NULL; char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; #if 0 cdf97_fwd_core_sdl_sc_sse_off1_inner_s( thread_src, thread_dst, src_stride_x, src_stride_y, dst_stride_x, dst_stride_y, size_x, thread_size_y+overlay_y ); #else float long_buffer[4*words*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, words*4*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+1 < offset+0; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_null, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_null, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(words*4)*(offset+0); float short_buffer_0[words*4] __attribute__ ((aligned (16))); float short_buffer_1[words*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, words*4); dwt_util_zero_vec_s(short_buffer_1, words*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_prolog_dl_sc_sse_2x2_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(words*4), long_buffer_ptr+1*(words*4) ); long_buffer_ptr += 2*(words*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(words*4)*(offset+0); float short_buffer_0[words*4] __attribute__ ((aligned (16))); float short_buffer_1[words*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, words*4); dwt_util_zero_vec_s(short_buffer_1, words*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_sc_sse_2x2_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(words*4), long_buffer_ptr+1*(words*4) ); long_buffer_ptr += 2*(words*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+1 < offset+thread_size_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(words*4)*(offset+0); float short_buffer_0[words*4] __attribute__ ((aligned (16))); float short_buffer_1[words*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, words*4); dwt_util_zero_vec_s(short_buffer_1, words*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_sc_sse_2x2_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(words*4), long_buffer_ptr+1*(words*4) ); long_buffer_ptr += 2*(words*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *ptr1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+1 < size_x; x += 2) { *addr1_s(out0_x, 0, dst_stride_y) = *addr1_s(ptr0_x, 0, src_stride_y); *addr1_s(out0_x, 1, dst_stride_y) = *addr1_s(ptr0_x, 1, src_stride_y); *addr1_s(out1_x, 0, dst_stride_y) = *addr1_s(ptr1_x, 0, src_stride_y); *addr1_s(out1_x, 1, dst_stride_y) = *addr1_s(ptr1_x, 1, src_stride_y); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #endif } #endif } #endif #ifdef __SSE__ static void vert_2x4( // left input column [4] __m128 in0, // right input column [4] __m128 in1, // output 0 [4] __m128 *out0, // output 1 [4] __m128 *out1, // 4x buffer "L" with stride = (1*4) * sizeof(float) float *buff ) { // weights const __m128 w0 = { +dwt_cdf97_u2_s, +dwt_cdf97_u2_s, +dwt_cdf97_u2_s, +dwt_cdf97_u2_s }; const __m128 w1 = { -dwt_cdf97_p2_s, -dwt_cdf97_p2_s, -dwt_cdf97_p2_s, -dwt_cdf97_p2_s }; const __m128 w2 = { +dwt_cdf97_u1_s, +dwt_cdf97_u1_s, +dwt_cdf97_u1_s, +dwt_cdf97_u1_s }; const __m128 w3 = { -dwt_cdf97_p1_s, -dwt_cdf97_p1_s, -dwt_cdf97_p1_s, -dwt_cdf97_p1_s }; // variables __m128 l0, l1, l2, l3; __m128 c0, c1, c2, c3; __m128 r0, r1, r2, r3; __m128 x0, x1; __m128 y0, y1; // load "L" l0 = _mm_load_ps(&buff[0*(1*4)]); l1 = _mm_load_ps(&buff[1*(1*4)]); l2 = _mm_load_ps(&buff[2*(1*4)]); l3 = _mm_load_ps(&buff[3*(1*4)]); //_MM_TRANSPOSE4_PS(l0, l1, l2, l3); // inputs x0 = in0; x1 = in1; // shuffles y0 = l0; c0 = l1; c1 = l2; c2 = l3; c3 = x0; // operation r3 = x1; r2 = c3 + w3 * (l3 + r3); r1 = c2 + w2 * (l2 + r2); r0 = c1 + w1 * (l1 + r1); y1 = c0 + w0 * (l0 + r0); // update l0 = r0; l1 = r1; l2 = r2; l3 = r3; // outputs *out0 = y0; *out1 = y1; // store "L" //_MM_TRANSPOSE4_PS(l0, l1, l2, l3); _mm_store_ps(&buff[0*(1*4)], l0); _mm_store_ps(&buff[1*(1*4)], l1); _mm_store_ps(&buff[2*(1*4)], l2); _mm_store_ps(&buff[3*(1*4)], l3); } #endif #ifdef __SSE__ static void fdwt_cdf97_vert_cor4x4_sse_s( intptr_t ptr_y0_x0, // pointer to (0,0) intptr_t out_y0_x0, // pointer to (0-shift,0-shift) ptrdiff_t stride_x, // +1 row ptrdiff_t stride_y, // +1 col float *buff_h0, // +(0..3)*(1*4) [ y down> ] float *buff_v0 // +(0..3)*(1*4) [ x right> ] ) { // this 4x4 core approach corresponds to "transpose-SIMD" in Figure 9 in Kutil2006 (the "line-SIMD" should be 8x2 core) __m128 t0, t1, t2, t3; // load 4x4 t0 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 0*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 0*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 0*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 0*stride_y) }; t1 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 1*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 1*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 1*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 1*stride_y) }; t2 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 2*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 2*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 2*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 2*stride_y) }; t3 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 3*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 3*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 3*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 3*stride_y) }; // left horiz. vert_2x4( t0, t1, &t0, &t1, buff_h0 ); // right horiz vert_2x4( t2, t3, &t2, &t3, buff_h0 ); // shuffle t0..3 _MM_TRANSPOSE4_PS(t0, t1, t2, t3); // top vert vert_2x4( t0, t1, &t0, &t1, buff_v0 ); // bottom vert vert_2x4( t2, t3, &t2, &t3, buff_v0 ); const float z = dwt_cdf97_s1_s; t0 *= (const __m128){ 1/(z*z), 1.f, 1/(z*z), 1.f }; t1 *= (const __m128){ 1.f, (z*z), 1.f, (z*z) }; t2 *= (const __m128){ 1/(z*z), 1.f, 1/(z*z), 1.f }; t3 *= (const __m128){ 1.f, (z*z), 1.f, (z*z) }; *(float *)(out_y0_x0 + 0*stride_x + 0*stride_y) = t0[0]; *(float *)(out_y0_x0 + 1*stride_x + 0*stride_y) = t1[0]; *(float *)(out_y0_x0 + 2*stride_x + 0*stride_y) = t2[0]; *(float *)(out_y0_x0 + 3*stride_x + 0*stride_y) = t3[0]; *(float *)(out_y0_x0 + 0*stride_x + 1*stride_y) = t0[1]; *(float *)(out_y0_x0 + 1*stride_x + 1*stride_y) = t1[1]; *(float *)(out_y0_x0 + 2*stride_x + 1*stride_y) = t2[1]; *(float *)(out_y0_x0 + 3*stride_x + 1*stride_y) = t3[1]; *(float *)(out_y0_x0 + 0*stride_x + 2*stride_y) = t0[2]; *(float *)(out_y0_x0 + 1*stride_x + 2*stride_y) = t1[2]; *(float *)(out_y0_x0 + 2*stride_x + 2*stride_y) = t2[2]; *(float *)(out_y0_x0 + 3*stride_x + 2*stride_y) = t3[2]; *(float *)(out_y0_x0 + 0*stride_x + 3*stride_y) = t0[3]; *(float *)(out_y0_x0 + 1*stride_x + 3*stride_y) = t1[3]; *(float *)(out_y0_x0 + 2*stride_x + 3*stride_y) = t2[3]; *(float *)(out_y0_x0 + 3*stride_x + 3*stride_y) = t3[3]; } #endif #ifdef __SSE__ static void fdwt_cdf97_vert_pro4x4_sse_s( intptr_t ptr_y0_x0, // pointer to (0,0) intptr_t out_y0_x0, // pointer to (0-shift,0-shift) ptrdiff_t stride_x, // +1 row ptrdiff_t stride_y, // +1 col float *buff_h0, // +(0..3)*(1*4) [ y down> ] float *buff_v0 // +(0..3)*(1*4) [ x right> ] ) { // this 4x4 core approach corresponds to "transpose-SIMD" in Figure 9 in Kutil2006 (the "line-SIMD" should be 8x2 core) __m128 t0, t1, t2, t3; // load 4x4 t0 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 0*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 0*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 0*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 0*stride_y) }; t1 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 1*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 1*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 1*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 1*stride_y) }; t2 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 2*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 2*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 2*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 2*stride_y) }; t3 = (__m128){ *(float *)(ptr_y0_x0 + 0*stride_x + 3*stride_y), *(float *)(ptr_y0_x0 + 1*stride_x + 3*stride_y), *(float *)(ptr_y0_x0 + 2*stride_x + 3*stride_y), *(float *)(ptr_y0_x0 + 3*stride_x + 3*stride_y) }; // left horiz. vert_2x4( t0, t1, &t0, &t1, buff_h0 ); // right horiz vert_2x4( t2, t3, &t2, &t3, buff_h0 ); // shuffle t0..3 _MM_TRANSPOSE4_PS(t0, t1, t2, t3); // top vert vert_2x4( t0, t1, &t0, &t1, buff_v0 ); // bottom vert vert_2x4( t2, t3, &t2, &t3, buff_v0 ); } #endif // SL DL/VERT WITH*MERGED-SCALING SSE OFFSET=1 THREADS CORE=4x4 #ifdef __SSE__ void cdf97_fwd_core_dl_sc_sse_off1_4x4_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { assert( (src_stride_x == dst_stride_x) && (src_stride_y == dst_stride_y) ); #if DEBUG if(!( ((size_x % 4) == 0) && ((size_y % 4) == 0) )) dwt_util_log(LOG_WARN, "size_x=%i size_y=%i\n", size_x, size_y); #endif // assert( ((size_x % 4) == 0) && ((size_y % 4) == 0) ); const int offset = 1; const int words = 1; // vertical const int buff_elem_size = words*4; const int threads = dwt_util_get_num_threads(); // 8, 4 const int thread_size_y = /*dwt_util_up_to_even*/dwt_util_up_to_mul4( ceil_div(size_y, threads) ); const int prolog_y = 4+4; // 4+4 const int overlay_y = 4; // 4 const int step_y = 4; const int step_x = 4; #if DEBUG dwt_util_log(LOG_DBG, "threads=%i thread_size_y=%i\n", threads, thread_size_y); for(int t = 0; t < threads; t++) dwt_util_log(LOG_DBG, "thread %i: base=%i src.limit=%i (+%i) (src+dst)\n", t, t*thread_size_y, t*thread_size_y+offset+thread_size_y-1, offset+thread_size_y); #endif //#pragma omp parallel for //for(int thread = 0; thread < threads; thread++) #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, 0/*offset*/, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, 0/*offset*/, dst_stride_x, dst_stride_y); char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; assert(thread_dst_buff); float long_buffer[buff_elem_size*size_x] ALIGNED(16); assert(long_buffer); dwt_util_zero_vec_s(long_buffer, buff_elem_size*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+(step_y-1) < offset+0; y += step_y) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *out0_x = NULL; float *long_buffer_ptr = long_buffer+(buff_elem_size)*(offset+0); float short_buffer_4[step_y*buff_elem_size] ALIGNED(16); assert( short_buffer_4 ); dwt_util_zero_vec_s(short_buffer_4, step_y*buff_elem_size); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { fdwt_cdf97_vert_pro4x4_sse_s( // ptr (void *)ptr0_x, // out (void *)out0_x, src_stride_x, src_stride_y, // buffers short_buffer_4, long_buffer_ptr ); long_buffer_ptr += step_x*(buff_elem_size); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); } } #pragma omp barrier for(int y = offset+0; y+(step_y-1) < offset+overlay_y; y += step_y) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(buff_elem_size)*(offset+0); float short_buffer_4[step_y*buff_elem_size] ALIGNED(16); assert( short_buffer_4 ); dwt_util_zero_vec_s(short_buffer_4, step_y*buff_elem_size); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { fdwt_cdf97_vert_cor4x4_sse_s( // ptr (void *)ptr0_x, // out (void *)out0_x, src_stride_x, src_stride_y, // buffers short_buffer_4, long_buffer_ptr ); long_buffer_ptr += step_x*(buff_elem_size); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); out0_x = addr1_s(out0_x, +step_x, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+(step_y-1) < offset+thread_size_y; y += step_y) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(buff_elem_size)*(offset+0); float short_buffer_4[step_y*buff_elem_size] ALIGNED(16); assert( short_buffer_4 ); dwt_util_zero_vec_s(short_buffer_4, step_y*buff_elem_size); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { fdwt_cdf97_vert_cor4x4_sse_s( // ptr (void *)ptr0_x, // out (void *)out0_x, src_stride_x, src_stride_y, // buffers short_buffer_4, long_buffer_ptr ); long_buffer_ptr += step_x*(buff_elem_size); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); out0_x = addr1_s(out0_x, +step_x, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+(step_y-1) < offset+overlay_y; y += step_y) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { // TODO: copy core for(int yy = 0; yy < step_y; yy++) for(int xx = 0; xx < step_x; xx++) *addr2_s(out0_x, yy, xx, dst_stride_x, dst_stride_y) = *addr2_s(ptr0_x, yy, xx, src_stride_x, src_stride_y); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); out0_x = addr1_s(out0_x, +step_x, dst_stride_y); } } } } #endif #ifdef __SSE__ #define diag_horizontally_2x2_FAST_MACRO(in, buff_h0_0, buff_h0_4, buff_h0_8, buff_h1_0, buff_h1_4, buff_h1_8) \ do { \ const __m128 w = { \ +dwt_cdf97_u2_s, \ -dwt_cdf97_p2_s, \ +dwt_cdf97_u1_s, \ -dwt_cdf97_p1_s \ }; \ \ __m128 z; \ \ op4s_sdl2_shuffle_input_low_s_sse(in, *buff_h0_4, *buff_h0_8); \ op4s_sdl2_shuffle_input_high_s_sse(in, *buff_h1_4, *buff_h1_8); \ \ op4s_sdl2_op_s_sse(z, *buff_h0_4, w, *buff_h0_0, *buff_h0_8); \ op4s_sdl2_output_low_s_sse(in, *buff_h0_0, z); \ op4s_sdl2_update_s_sse_FAST(*buff_h0_4, *buff_h0_0, *buff_h0_8, z); \ \ op4s_sdl2_op_s_sse(z, *buff_h1_4, w, *buff_h1_0, *buff_h1_8); \ op4s_sdl2_output_high_s_sse(in, *buff_h1_0, z); \ op4s_sdl2_update_s_sse_FAST(*buff_h1_4, *buff_h1_0, *buff_h1_8, z); \ } while(0) #endif /* __SSE__ */ #ifdef __SSE__ #define diag_horizontally_2x2_MACRO(in, buff_h0_0, buff_h0_4, buff_h0_8, buff_h1_0, buff_h1_4, buff_h1_8) \ do { \ const __m128 w = { \ +dwt_cdf97_u2_s, \ -dwt_cdf97_p2_s, \ +dwt_cdf97_u1_s, \ -dwt_cdf97_p1_s \ }; \ \ __m128 z; \ \ op4s_sdl2_shuffle_input_low_s_sse(in, *buff_h0_4, *buff_h0_8); \ op4s_sdl2_shuffle_input_high_s_sse(in, *buff_h1_4, *buff_h1_8); \ \ op4s_sdl2_op_s_sse(z, *buff_h0_4, w, *buff_h0_0, *buff_h0_8); \ op4s_sdl2_output_low_s_sse(in, *buff_h0_0, z); \ op4s_sdl2_update_s_sse(*buff_h0_4, *buff_h0_0, *buff_h0_8, z); \ \ op4s_sdl2_op_s_sse(z, *buff_h1_4, w, *buff_h1_0, *buff_h1_8); \ op4s_sdl2_output_high_s_sse(in, *buff_h1_0, z); \ op4s_sdl2_update_s_sse(*buff_h1_4, *buff_h1_0, *buff_h1_8, z); \ } while(0) #endif /* __SSE__ */ #ifdef __SSE__ #define diag_horizontally_2x2_MACRO_PROLOG(in, buff_h0_0, buff_h0_4, buff_h0_8, buff_h1_0, buff_h1_4, buff_h1_8) \ do { \ const __m128 w = { \ +dwt_cdf97_u2_s, \ -dwt_cdf97_p2_s, \ +dwt_cdf97_u1_s, \ -dwt_cdf97_p1_s \ }; \ \ __m128 z; \ \ op4s_sdl2_shuffle_input_low_s_sse(in, *buff_h0_4, *buff_h0_8); \ op4s_sdl2_shuffle_input_high_s_sse(in, *buff_h1_4, *buff_h1_8); \ \ op4s_sdl2_op_s_sse(z, *buff_h0_4, w, *buff_h0_0, *buff_h0_8); \ op4s_sdl2_update_s_sse(*buff_h0_4, *buff_h0_0, *buff_h0_8, z); \ \ op4s_sdl2_op_s_sse(z, *buff_h1_4, w, *buff_h1_0, *buff_h1_8); \ op4s_sdl2_update_s_sse(*buff_h1_4, *buff_h1_0, *buff_h1_8, z); \ } while(0) #endif /* __SSE__ */ #ifdef __SSE__ static void diag_6x2( // input by 2x2 blocks in format [ y0x0 y0x1 y1x0 y1x1 ] __m128 in0, __m128 in1, __m128 in2, // output by 2x2 blocks in format [ y0x0 y1x0 y0x1 y1x1 ] __m128 *out0, __m128 *out1, __m128 *out2, // buffers with stride = (3*4)*sizeof(float) float *buff_h0, // +(0..1)*(3*4) [ y down> ] float *buff_v0 // +(0..5)*(3*4) [ x right> ] ) { float *buff_h1 = buff_h0 + 1*(3*4); float *buff_v1 = buff_v0 + 1*(3*4); float *buff_v2 = buff_v0 + 2*(3*4); float *buff_v3 = buff_v0 + 3*(3*4); float *buff_v4 = buff_v0 + 4*(3*4); float *buff_v5 = buff_v0 + 5*(3*4); const __m128 w = { +dwt_cdf97_u2_s, -dwt_cdf97_p2_s, +dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const __m128 v = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s) }; __m128 z; // ====== 2x2 y=0..1 x=0..1 ====== // iter. 1 #define H0 0 #define H4 4 #define H8 8 // horizontally diag_horizontally_2x2_FAST_MACRO( in0, (__m128 *)(buff_h0+H0), (__m128 *)(buff_h0+H4), (__m128 *)(buff_h0+H8), (__m128 *)(buff_h1+H0), (__m128 *)(buff_h1+H4), (__m128 *)(buff_h1+H8) ); _MM_TRANSPOSE1_PS(in0); // vertically diag_horizontally_2x2_MACRO( in0, (__m128 *)(buff_v0+0), (__m128 *)(buff_v0+4), (__m128 *)(buff_v0+8), (__m128 *)(buff_v1+0), (__m128 *)(buff_v1+4), (__m128 *)(buff_v1+8) ); op4s_sdl2_scale_s_sse(in0, v); *out0 = in0; #undef H0 #undef H4 #undef H8 // ====== 2x2 y=0..1 x=2..3 ====== // iter. 2 #define H0 8 #define H4 0 #define H8 4 // horizontally diag_horizontally_2x2_FAST_MACRO( in1, (__m128 *)(buff_h0+H0), (__m128 *)(buff_h0+H4), (__m128 *)(buff_h0+H8), (__m128 *)(buff_h1+H0), (__m128 *)(buff_h1+H4), (__m128 *)(buff_h1+H8) ); _MM_TRANSPOSE1_PS(in1); // vertically diag_horizontally_2x2_MACRO( in1, (__m128 *)(buff_v2+0), (__m128 *)(buff_v2+4), (__m128 *)(buff_v2+8), (__m128 *)(buff_v3+0), (__m128 *)(buff_v3+4), (__m128 *)(buff_v3+8) ); op4s_sdl2_scale_s_sse(in1, v); *out1 = in1; #undef H0 #undef H4 #undef H8 // ====== 2x2 y=0..1 x=4..5 ====== // iter. 3 #define H0 4 #define H4 8 #define H8 0 // horizontally diag_horizontally_2x2_FAST_MACRO( in2, (__m128 *)(buff_h0+H0), (__m128 *)(buff_h0+H4), (__m128 *)(buff_h0+H8), (__m128 *)(buff_h1+H0), (__m128 *)(buff_h1+H4), (__m128 *)(buff_h1+H8) ); _MM_TRANSPOSE1_PS(in2); // vertically diag_horizontally_2x2_MACRO( in2, (__m128 *)(buff_v4+0), (__m128 *)(buff_v4+4), (__m128 *)(buff_v4+8), (__m128 *)(buff_v5+0), (__m128 *)(buff_v5+4), (__m128 *)(buff_v5+8) ); op4s_sdl2_scale_s_sse(in2, v); *out2 = in2; #undef H0 #undef H4 #undef H8 } #endif #ifdef __SSE__ static void diag_6x2_prolog( // input by 2x2 blocks in format [ y0x0 y0x1 y1x0 y1x1 ] __m128 in0, __m128 in1, __m128 in2, // output by 2x2 blocks in format [ y0x0 y1x0 y0x1 y1x1 ] __m128 *out0, __m128 *out1, __m128 *out2, // buffers with stride = (3*4)*sizeof(float) float *buff_h0, // +(0..1)*(3*4) [ y down> ] float *buff_v0 // +(0..5)*(3*4) [ x right> ] ) { float *buff_h1 = buff_h0 + 1*(3*4); float *buff_v1 = buff_v0 + 1*(3*4); float *buff_v2 = buff_v0 + 2*(3*4); float *buff_v3 = buff_v0 + 3*(3*4); float *buff_v4 = buff_v0 + 4*(3*4); float *buff_v5 = buff_v0 + 5*(3*4); const __m128 w = { +dwt_cdf97_u2_s, -dwt_cdf97_p2_s, +dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const __m128 v = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s) }; __m128 z; // ====== 2x2 y=0..1 x=0..1 ====== // iter. 1 #define H0 0 #define H4 4 #define H8 8 // horizontally diag_horizontally_2x2_FAST_MACRO( in0, (__m128 *)(buff_h0+H0), (__m128 *)(buff_h0+H4), (__m128 *)(buff_h0+H8), (__m128 *)(buff_h1+H0), (__m128 *)(buff_h1+H4), (__m128 *)(buff_h1+H8) ); _MM_TRANSPOSE1_PS(in0); // vertically diag_horizontally_2x2_MACRO_PROLOG( in0, (__m128 *)(buff_v0+0), (__m128 *)(buff_v0+4), (__m128 *)(buff_v0+8), (__m128 *)(buff_v1+0), (__m128 *)(buff_v1+4), (__m128 *)(buff_v1+8) ); // op4s_sdl2_scale_s_sse(in0, v); // *out0 = in0; #undef H0 #undef H4 #undef H8 // ====== 2x2 y=0..1 x=2..3 ====== // iter. 2 #define H0 8 #define H4 0 #define H8 4 // horizontally diag_horizontally_2x2_FAST_MACRO( in1, (__m128 *)(buff_h0+H0), (__m128 *)(buff_h0+H4), (__m128 *)(buff_h0+H8), (__m128 *)(buff_h1+H0), (__m128 *)(buff_h1+H4), (__m128 *)(buff_h1+H8) ); _MM_TRANSPOSE1_PS(in1); // vertically diag_horizontally_2x2_MACRO_PROLOG( in1, (__m128 *)(buff_v2+0), (__m128 *)(buff_v2+4), (__m128 *)(buff_v2+8), (__m128 *)(buff_v3+0), (__m128 *)(buff_v3+4), (__m128 *)(buff_v3+8) ); // op4s_sdl2_scale_s_sse(in1, v); // *out1 = in1; #undef H0 #undef H4 #undef H8 // ====== 2x2 y=0..1 x=4..5 ====== // iter. 3 #define H0 4 #define H4 8 #define H8 0 // horizontally diag_horizontally_2x2_FAST_MACRO( in2, (__m128 *)(buff_h0+H0), (__m128 *)(buff_h0+H4), (__m128 *)(buff_h0+H8), (__m128 *)(buff_h1+H0), (__m128 *)(buff_h1+H4), (__m128 *)(buff_h1+H8) ); _MM_TRANSPOSE1_PS(in2); // vertically diag_horizontally_2x2_MACRO_PROLOG( in2, (__m128 *)(buff_v4+0), (__m128 *)(buff_v4+4), (__m128 *)(buff_v4+8), (__m128 *)(buff_v5+0), (__m128 *)(buff_v5+4), (__m128 *)(buff_v5+8) ); // op4s_sdl2_scale_s_sse(in2, v); // *out2 = in2; #undef H0 #undef H4 #undef H8 } #endif #ifdef __SSE__ static void fdwt_cdf97_diag_cor6x2_sse_s( intptr_t ptr_y0_x0, intptr_t out_y0_x0, ptrdiff_t stride_x, // +1 row ptrdiff_t stride_y, // +1 col float *buff_h0, // +(0..?)*(3*4) [ y down> ] float *buff_v0 // +(0..?)*(3*4) [ x right> ] ) { __m128 t0, t1, t2; t0 = (__m128){ /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 0*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 1*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 0*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 1*stride_y) }; t1 = (__m128){ /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 2*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 3*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 2*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 3*stride_y) }; t2 = (__m128){ /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 4*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 5*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 4*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 5*stride_y) }; diag_6x2( // input by 2x2 blocks in format [ y0x0 y0x1 y1x0 y1x1 ] t0, t1, t2, // output by 2x2 blocks in format [ y0x0 y1x0 y0x1 y1x1 ] &t0, &t1, &t2, // buffers with stride = (3*4)*sizeof(float) buff_h0, // +(0..1)*(3*4) [ y down> ] buff_v0 // +(0..5)*(3*4) [ x right> ] ); /* y= x= */ *(float *)(out_y0_x0 + 0*stride_x + 0*stride_y) = t0[0]; /* y= x= */ *(float *)(out_y0_x0 + 0*stride_x + 1*stride_y) = t0[2]; /* y= x= */ *(float *)(out_y0_x0 + 1*stride_x + 0*stride_y) = t0[1]; /* y= x= */ *(float *)(out_y0_x0 + 1*stride_x + 1*stride_y) = t0[3]; /* y= x= */ *(float *)(out_y0_x0 + 0*stride_x + 2*stride_y) = t1[0]; /* y= x= */ *(float *)(out_y0_x0 + 0*stride_x + 3*stride_y) = t1[2]; /* y= x= */ *(float *)(out_y0_x0 + 1*stride_x + 2*stride_y) = t1[1]; /* y= x= */ *(float *)(out_y0_x0 + 1*stride_x + 3*stride_y) = t1[3]; /* y= x= */ *(float *)(out_y0_x0 + 0*stride_x + 4*stride_y) = t2[0]; /* y= x= */ *(float *)(out_y0_x0 + 0*stride_x + 5*stride_y) = t2[2]; /* y= x= */ *(float *)(out_y0_x0 + 1*stride_x + 4*stride_y) = t2[1]; /* y= x= */ *(float *)(out_y0_x0 + 1*stride_x + 5*stride_y) = t2[3]; } #endif #ifdef __SSE__ static void fdwt_cdf97_diag_pro6x2_sse_s( intptr_t ptr_y0_x0, intptr_t out_y0_x0, ptrdiff_t stride_x, // +1 row ptrdiff_t stride_y, // +1 col float *buff_h0, // +(0..?)*(3*4) [ y down> ] float *buff_v0 // +(0..?)*(3*4) [ x right> ] ) { __m128 t0, t1, t2; t0 = (__m128){ /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 0*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 1*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 0*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 1*stride_y) }; t1 = (__m128){ /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 2*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 3*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 2*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 3*stride_y) }; t2 = (__m128){ /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 4*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 0*stride_x + 5*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 4*stride_y), /* y= x= */ *(float *)(ptr_y0_x0 + 1*stride_x + 5*stride_y) }; diag_6x2_prolog( // input by 2x2 blocks in format [ y0x0 y0x1 y1x0 y1x1 ] t0, t1, t2, // output by 2x2 blocks in format [ y0x0 y1x0 y0x1 y1x1 ] 0, 0, 0, // buffers with stride = (3*4)*sizeof(float) buff_h0, // +(0..1)*(3*4) [ y down> ] buff_v0 // +(0..5)*(3*4) [ x right> ] ); } #endif // SL DL/VERT WITH*MERGED-SCALING SSE OFFSET=1 THREADS CORE=4x4 #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off1_6x2_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { assert( (src_stride_x == dst_stride_x) && (src_stride_y == dst_stride_y) ); #if DEBUG if(!( ((size_x % 6) == 0) && ((size_y % 6) == 0) )) dwt_util_log(LOG_WARN, "size_x=%i size_y=%i\n", size_x, size_y); #endif // assert( ((size_x % 4) == 0) && ((size_y % 4) == 0) ); const int offset = 1; const int words = 3; // diagonal const int buff_elem_size = words*4; int threads = dwt_util_get_num_threads(); // 8, 4 int thread_size_y = dwt_util_up_to_even( ceil_div(size_y, threads) ); const int prolog_y = 10+4; const int overlay_y = 10; const int step_y = 2; const int step_x = 6; #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, 0/*offset*/, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, 0/*offset*/, dst_stride_x, dst_stride_y); void *thread_dst_null = NULL; char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; float long_buffer[buff_elem_size*size_x] ALIGNED(16); dwt_util_zero_vec_s(long_buffer, buff_elem_size*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+(step_y-1) < offset+0; y += step_y) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *out0_x = NULL; float *long_buffer_ptr = long_buffer+(buff_elem_size)*(offset+0); float short_buffer_4[step_y*buff_elem_size] ALIGNED(16); dwt_util_zero_vec_s(short_buffer_4, step_y*buff_elem_size); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { fdwt_cdf97_diag_pro6x2_sse_s( // ptr (void *)ptr0_x, // out (void *)out0_x, src_stride_x, src_stride_y, // buffers short_buffer_4, long_buffer_ptr ); long_buffer_ptr += step_x*(buff_elem_size); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); } } #pragma omp barrier for(int y = offset+0; y+(step_y-1) < offset+overlay_y; y += step_y) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(buff_elem_size)*(offset+0); float short_buffer_4[step_y*buff_elem_size] ALIGNED(16); dwt_util_zero_vec_s(short_buffer_4, step_y*buff_elem_size); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { fdwt_cdf97_diag_cor6x2_sse_s( // ptr (void *)ptr0_x, // out (void *)out0_x, src_stride_x, src_stride_y, // buffers short_buffer_4, long_buffer_ptr ); long_buffer_ptr += step_x*(buff_elem_size); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); out0_x = addr1_s(out0_x, +step_x, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+(step_y-1) < offset+thread_size_y; y += step_y) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(buff_elem_size)*(offset+0); float short_buffer_4[step_y*buff_elem_size] ALIGNED(16); dwt_util_zero_vec_s(short_buffer_4, step_y*buff_elem_size); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { fdwt_cdf97_diag_cor6x2_sse_s( // ptr (void *)ptr0_x, // out (void *)out0_x, src_stride_x, src_stride_y, // buffers short_buffer_4, long_buffer_ptr ); long_buffer_ptr += step_x*(buff_elem_size); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); out0_x = addr1_s(out0_x, +step_x, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+(step_y-1) < offset+overlay_y; y += step_y) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+(step_x-1) < size_x; x += step_x) { // TODO: copy core for(int yy = 0; yy < step_y; yy++) for(int xx = 0; xx < step_x; xx++) *addr2_s(out0_x, yy, xx, dst_stride_x, dst_stride_y) = *addr2_s(ptr0_x, yy, xx, src_stride_x, src_stride_y); ptr0_x = addr1_s(ptr0_x, +step_x, src_stride_y); out0_x = addr1_s(out0_x, +step_x, dst_stride_y); } } } } #endif #ifdef __SSE__ void cdf97_fwd_core_sdl_sc_sse_off1_ovl1_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { #if 0 // NOTE: this works well const int offset = 1; float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #else const int offset = 1; int threads = dwt_util_get_num_threads(); // 8, 4 // assert( is_even(size_y) ); int thread_size_y = dwt_util_up_to_even( ceil_div(size_y, threads) ); const int prolog_y = 10+4; const int overlay_y = 0; //#pragma omp parallel for //for(int thread = 0; thread < threads; thread++) #pragma omp parallel num_threads(threads) { int thread = omp_get_thread_num(); void *thread_src = addr2_s(src, /*y*/thread*thread_size_y, 0/*offset*/, src_stride_x, src_stride_y); void *thread_dst = addr2_s(dst, /*y*/thread*thread_size_y, 0/*offset*/, dst_stride_x, dst_stride_y); void *thread_dst_null = NULL; char thread_dst_buff[(offset+overlay_y)*dst_stride_x]; #if 0 cdf97_fwd_core_sdl_sc_sse_off1_inner_s( thread_src, thread_dst, src_stride_x, src_stride_y, dst_stride_x, dst_stride_y, size_x, thread_size_y+overlay_y ); #else float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); #pragma omp barrier for(int y = offset+0-prolog_y; y+1 < offset+0; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_null, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_null, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_prolog_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+overlay_y; y+1 < offset+thread_size_y; y += 2) { float *ptr0_x = addr2_s(thread_src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(thread_src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sc_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #pragma omp barrier for(int y = offset+0; y+1 < offset+overlay_y; y += 2) { float *ptr0_x = addr2_s(thread_dst_buff, y+0, offset, dst_stride_x, dst_stride_y); float *ptr1_x = addr2_s(thread_dst_buff, y+1, offset, dst_stride_x, dst_stride_y); float *out0_x = addr2_s(thread_dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(thread_dst, y+1, offset, dst_stride_x, dst_stride_y); for(int x = 0+offset; x+1 < size_x; x += 2) { *addr1_s(out0_x, 0, dst_stride_y) = *addr1_s(ptr0_x, 0, src_stride_y); *addr1_s(out0_x, 1, dst_stride_y) = *addr1_s(ptr0_x, 1, src_stride_y); *addr1_s(out1_x, 0, dst_stride_y) = *addr1_s(ptr1_x, 0, src_stride_y); *addr1_s(out1_x, 1, dst_stride_y) = *addr1_s(ptr1_x, 1, src_stride_y); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } #endif } #endif } #endif // SL SDL NO-MERGED-SCALING SSE #ifdef __SSE__ void cdf97_fwd_core_sdl_sse_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { const int offset = 1; float short_buffer_0[3*4] __attribute__ ((aligned (16))); float short_buffer_1[3*4] __attribute__ ((aligned (16))); float long_buffer[4*3*size_x] __attribute__ ((aligned (16))); dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_sse_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } } #endif // SL SDL NO-MERGED-SCALING void cdf97_fwd_core_sdl_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { // forward transform with offset = 1 const int offset = 1; float short_buffer_0[3*4]; float short_buffer_1[3*4]; float long_buffer[4*3*size_x]; dwt_util_zero_vec_s(long_buffer, 3*4*size_x); // filter src into dst using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr0_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr1_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out0_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out1_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer+(3*4)*(offset+0); dwt_util_zero_vec_s(short_buffer_0, 3*4); dwt_util_zero_vec_s(short_buffer_1, 3*4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_sdl_2x2_s( addr1_s(ptr0_x, 0, src_stride_y), addr1_s(ptr0_x, 1, src_stride_y), addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(out0_x, 0, dst_stride_y), addr1_s(out0_x, 1, dst_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), short_buffer_0, short_buffer_1, long_buffer_ptr+0*(3*4), long_buffer_ptr+1*(3*4) ); long_buffer_ptr += 2*(3*4); ptr0_x = addr1_s(ptr0_x, +2, src_stride_y); ptr1_x = addr1_s(ptr1_x, +2, src_stride_y); out0_x = addr1_s(out0_x, +2, dst_stride_y); out1_x = addr1_s(out1_x, +2, dst_stride_y); } } } static void accel_lift_op4s_fwd_main_dl_stride_pair_core_s( const float *ptr0, const float *ptr1, float *out0, float *out1, const float *w, const float *v, float *l // [4] ) { // aux. variables float x[2]; float y[2]; float r[4]; float c[4]; // inputs x[0] = *ptr0; x[1] = *ptr1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation z[] = c[] + w[] * ( l[] + r[] ) // by sequential computation from top/right to bottom/left r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scales y[0] = y[0] * v[0]; y[1] = y[1] * v[1]; // outputs *out0 = y[0]; *out1 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } static void accel_lift_op4s_uni_main_dl_stride_pair_core_s( const float *ptr0, const float *ptr1, float *out0, float *out1, float *w, float *v, float *l // [4] ) { UNUSED(v); // aux. variables float x[2]; float y[2]; float r[4]; float c[4]; // inputs x[0] = *ptr0; x[1] = *ptr1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs *out0 = y[0]; *out1 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } static void cdf97_fwd_core_dl_2x2_s( const float *ptr_y0_x0, // in const float *ptr_y0_x1, // in const float *ptr_y1_x0, // in const float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ) { #if 1 const float w[4] = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const float v[4] = { 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s, 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s }; float tmp[4]; float *tmp_y0_x0 = tmp+0; float *tmp_y0_x1 = tmp+1; float *tmp_y1_x0 = tmp+2; float *tmp_y1_x1 = tmp+3; // horizontal 0 // [y+0, x+0], [y+0, x+1] => [y+0, x+0-4], [y+0, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( ptr_y0_x0, ptr_y0_x1, tmp_y0_x0, tmp_y0_x1, w, v, buff_h0 ); // horizontal 1 // [y+1, x+0], [y+1, x+1] => [y+1, x+0-4], [y+1, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( ptr_y1_x0, ptr_y1_x1, tmp_y1_x0, tmp_y1_x1, w, v, buff_h1 ); // vertical 0 // [y+0, x+0-4] [y+1, x+0-4] => [y+0-4, x+0-4] [y+1-4, x+0-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( tmp_y0_x0, tmp_y1_x0, out_y0_x0, out_y1_x0, w, v, buff_v0 ); // vertical 1 // [y+0, x+1-4] [y+1, x+1-4] => [y+0-4, x+1-4] [y+1-4, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( tmp_y0_x1, tmp_y1_x1, out_y0_x1, out_y1_x1, w, v, buff_v1 ); #else const float w[4] = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const float v[4] = { 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s, 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s }; // temp float t[4]; // aux. variables float x[4], y[4], r[4], c[4]; // horiz 1 { float *l = buff_h0; // inputs x[0] = *ptr_y0_x0; x[1] = *ptr_y0_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v[0]; y[1] *= v[1]; // outputs t[0] = y[0]; t[1] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // horiz 2 { float *l = buff_h1; // inputs x[0] = *ptr_y1_x0; x[1] = *ptr_y1_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v[0]; y[1] *= v[1]; // outputs t[2] = y[0]; t[3] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 1 { float *l = buff_v0; // inputs x[0] = t[0]; x[1] = t[2]; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v[0]; y[1] *= v[1]; // outputs *out_y0_x0 = y[0]; *out_y1_x0 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 2 { float *l = buff_v1; // inputs x[0] = t[1]; x[1] = t[3]; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v[0]; y[1] *= v[1]; // outputs *out_y0_x1 = y[0]; *out_y1_x1 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } #endif } static void cdf97_fwd_core_dl_2x2_sse_s( float *ptr_y0_x0, // in float *ptr_y0_x1, // in float *ptr_y1_x0, // in float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ) { #if 0 const float w[4] = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const float v[4] = { 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s, 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s }; float tmp[4]; float *tmp_y0_x0 = tmp+0; float *tmp_y0_x1 = tmp+1; float *tmp_y1_x0 = tmp+2; float *tmp_y1_x1 = tmp+3; // horizontal 0 // [y+0, x+0], [y+0, x+1] => [y+0, x+0-4], [y+0, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( ptr_y0_x0, ptr_y0_x1, tmp_y0_x0, tmp_y0_x1, w, v, buff_h0 ); // horizontal 1 // [y+1, x+0], [y+1, x+1] => [y+1, x+0-4], [y+1, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( ptr_y1_x0, ptr_y1_x1, tmp_y1_x0, tmp_y1_x1, w, v, buff_h1 ); // vertical 0 // [y+0, x+0-4] [y+1, x+0-4] => [y+0-4, x+0-4] [y+1-4, x+0-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( tmp_y0_x0, tmp_y1_x0, out_y0_x0, out_y1_x0, w, v, buff_v0 ); // vertical 1 // [y+0, x+1-4] [y+1, x+1-4] => [y+0-4, x+1-4] [y+1-4, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( tmp_y0_x1, tmp_y1_x1, out_y0_x1, out_y1_x1, w, v, buff_v1 ); #else #ifdef __SSE__ const __m128 w = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const __m128 v = { 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s, 1/dwt_cdf97_s1_s, dwt_cdf97_s1_s }; // temp __m128 t; // aux. variables __m128 x, y, r, c; // horiz 1 { float *l = buff_h0; // inputs x[0] = *ptr_y0_x0; x[1] = *ptr_y0_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v[0]; y[1] *= v[1]; // outputs t[0] = y[0]; t[1] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // horiz 2 { float *l = buff_h1; // inputs x[0] = *ptr_y1_x0; x[1] = *ptr_y1_x1; // shuffles y[2] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[3] = c[0]+w[0]*(l[0]+r[0]); // scaling y[2] *= v[2]; y[3] *= v[3]; // outputs t[2] = y[2]; t[3] = y[3]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 1 { float *l = buff_v0; // inputs x[0] = t[0]; x[1] = t[2]; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v[0]; y[1] *= v[1]; // outputs *out_y0_x0 = y[0]; *out_y1_x0 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 2 { float *l = buff_v1; // inputs x[0] = t[1]; x[1] = t[3]; // shuffles y[2] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[3] = c[0]+w[0]*(l[0]+r[0]); // scaling y[2] *= v[2]; y[3] *= v[3]; // outputs *out_y0_x1 = y[2]; *out_y1_x1 = y[3]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } #endif /* __SSE__ */ #endif } static void cdf97_fwd_core_dl_sc_2x2_s( float *ptr_y0_x0, // in float *ptr_y0_x1, // in float *ptr_y1_x0, // in float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ) { #if 0 const float w[4] = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; // v_horiz can be elliminated const float v_horiz[4] = { 1.f, 1.f, 0.f, 0.f }; const float v_vertL[4] = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 0.f, 0.f }; const float v_vertR[4] = { 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s), 0.f, 0.f }; float tmp[4]; float *tmp_y0_x0 = tmp+0; float *tmp_y0_x1 = tmp+1; float *tmp_y1_x0 = tmp+2; float *tmp_y1_x1 = tmp+3; // horizontal 0 // [y+0, x+0], [y+0, x+1] => [y+0, x+0-4], [y+0, x+1-4] accel_lift_op4s_uni_main_dl_stride_pair_core_s( ptr_y0_x0, ptr_y0_x1, tmp_y0_x0, tmp_y0_x1, w, v_horiz, buff_h0 ); // horizontal 1 // [y+1, x+0], [y+1, x+1] => [y+1, x+0-4], [y+1, x+1-4] accel_lift_op4s_uni_main_dl_stride_pair_core_s( ptr_y1_x0, ptr_y1_x1, tmp_y1_x0, tmp_y1_x1, w, v_horiz, buff_h1 ); // vertical 0 // [y+0, x+0-4] [y+1, x+0-4] => [y+0-4, x+0-4] [y+1-4, x+0-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( tmp_y0_x0, tmp_y1_x0, out_y0_x0, out_y1_x0, w, v_vertL, buff_v0 ); // vertical 1 // [y+0, x+1-4] [y+1, x+1-4] => [y+0-4, x+1-4] [y+1-4, x+1-4] accel_lift_op4s_fwd_main_dl_stride_pair_core_s( tmp_y0_x1, tmp_y1_x1, out_y0_x1, out_y1_x1, w, v_vertR, buff_v1 ); #else const float w[4] = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const float v_vertL[4] = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 0.f, 0.f }; const float v_vertR[4] = { 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s), 0.f, 0.f }; // temp float t[4]; // aux. variables float x[4], y[4], r[4], c[4]; // horiz 1 { float *l = buff_h0; // inputs x[0] = *ptr_y0_x0; x[1] = *ptr_y0_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs t[0] = y[0]; t[1] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // horiz 2 { float *l = buff_h1; // inputs x[0] = *ptr_y1_x0; x[1] = *ptr_y1_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs t[2] = y[0]; t[3] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 1 { float *l = buff_v0; // inputs x[0] = t[0]; x[1] = t[2]; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v_vertL[0]; y[1] *= v_vertL[1]; // outputs *out_y0_x0 = y[0]; *out_y1_x0 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 2 { float *l = buff_v1; // inputs x[0] = t[1]; x[1] = t[3]; // shuffles y[2] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[3] = c[0]+w[0]*(l[0]+r[0]); // scaling y[2] *= v_vertR[0]; y[3] *= v_vertR[1]; // outputs *out_y0_x1 = y[2]; *out_y1_x1 = y[3]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } #endif } #ifdef __SSE__ static void cdf97_fwd_core_dl_sc_sse_2x2_s( float *ptr_y0_x0, // in float *ptr_y0_x1, // in float *ptr_y1_x0, // in float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ) { const __m128 w = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; const __m128 v_vertL = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, 0.f, 0.f }; const __m128 v_vertR = { 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s), 0.f, 0.f }; // temp __m128 t; // aux. variables __m128 x, y, r, c; // horiz 1 { float *l = buff_h0; // inputs x[0] = *ptr_y0_x0; x[1] = *ptr_y0_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs t[0] = y[0]; t[1] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // horiz 2 { float *l = buff_h1; // inputs x[0] = *ptr_y1_x0; x[1] = *ptr_y1_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs t[2] = y[0]; t[3] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 1 { float *l = buff_v0; // inputs x[0] = t[0]; x[1] = t[2]; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // scaling y[0] *= v_vertL[0]; y[1] *= v_vertL[1]; // outputs *out_y0_x0 = y[0]; *out_y1_x0 = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 2 { float *l = buff_v1; // inputs x[0] = t[1]; x[1] = t[3]; // shuffles y[2] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[3] = c[0]+w[0]*(l[0]+r[0]); // scaling y[2] *= v_vertR[0]; y[3] *= v_vertR[1]; // outputs *out_y0_x1 = y[2]; *out_y1_x1 = y[3]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } } #endif #ifdef __SSE__ static void cdf97_fwd_core_prolog_dl_sc_sse_2x2_s( float *ptr_y0_x0, // in float *ptr_y0_x1, // in float *ptr_y1_x0, // in float *ptr_y1_x1, // in float *out_y0_x0, // out float *out_y0_x1, // out float *out_y1_x0, // out float *out_y1_x1, // out float *buff_h0, // [4] float *buff_h1, // [4] float *buff_v0, // [4] float *buff_v1 // [4] ) { const __m128 w = { dwt_cdf97_u2_s, -dwt_cdf97_p2_s, dwt_cdf97_u1_s, -dwt_cdf97_p1_s }; // const __m128 v_vertL = { 1/(dwt_cdf97_s1_s*dwt_cdf97_s1_s), 1.f, // 0.f, 0.f }; // const __m128 v_vertR = { 1.f, (dwt_cdf97_s1_s*dwt_cdf97_s1_s), // 0.f, 0.f }; UNUSED(out_y0_x0); UNUSED(out_y0_x1); UNUSED(out_y1_x0); UNUSED(out_y1_x1); // temp __m128 t; // aux. variables __m128 x, y, r, c; // horiz 1 { float *l = buff_h0; // inputs x[0] = *ptr_y0_x0; x[1] = *ptr_y0_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs t[0] = y[0]; t[1] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // horiz 2 { float *l = buff_h1; // inputs x[0] = *ptr_y1_x0; x[1] = *ptr_y1_x1; // shuffles y[0] = l[0]; c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); y[1] = c[0]+w[0]*(l[0]+r[0]); // outputs t[2] = y[0]; t[3] = y[1]; // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 1 { float *l = buff_v0; // inputs x[0] = t[0]; x[1] = t[2]; // shuffles c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } // vert 2 { float *l = buff_v1; // inputs x[0] = t[1]; x[1] = t[3]; // shuffles c[0] = l[1]; c[1] = l[2]; c[2] = l[3]; c[3] = x[0]; // operation r[3] = x[1]; r[2] = c[3]+w[3]*(l[3]+r[3]); r[1] = c[2]+w[2]*(l[2]+r[2]); r[0] = c[1]+w[1]*(l[1]+r[1]); // update l[] l[0] = r[0]; l[1] = r[1]; l[2] = r[2]; l[3] = r[3]; } } #endif // SL DL NO-MERGED-SCALING void cdf97_fwd_core_dl_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { // forward transform with offset = 1 int offset = 1; float short_buffer_0[4]; float short_buffer_1[4]; float long_buffer[4*size_x]; dwt_util_zero_vec_s(long_buffer, 4 * size_x); // filter big into output using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr1_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr2_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out1_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out2_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer; dwt_util_zero_vec_s(short_buffer_0, 4); dwt_util_zero_vec_s(short_buffer_1, 4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_2x2_s( addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(ptr2_x, 0, src_stride_y), addr1_s(ptr2_x, 1, src_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), addr1_s(out2_x, 0, dst_stride_y), addr1_s(out2_x, 1, dst_stride_y), short_buffer_0, // [4] short_buffer_1, // [4] long_buffer_ptr+0*4, // [4] long_buffer_ptr+1*4 // [4] ); long_buffer_ptr += 2*4; ptr1_x = addr1_s(ptr1_x, 2, src_stride_y); ptr2_x = addr1_s(ptr2_x, 2, src_stride_y); out1_x = addr1_s(out1_x, 2, dst_stride_y); out2_x = addr1_s(out2_x, 2, dst_stride_y); } } } // SL DL NO-MERGED-SCALING SSE void cdf97_fwd_core_dl_sse_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { // forward transform with offset = 1 int offset = 1; float short_buffer_0[4]; float short_buffer_1[4]; float long_buffer[4*size_x]; dwt_util_zero_vec_s(long_buffer, 4 * size_x); // filter big into output using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr1_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr2_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out1_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out2_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer; dwt_util_zero_vec_s(short_buffer_0, 4); dwt_util_zero_vec_s(short_buffer_1, 4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_2x2_sse_s( addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(ptr2_x, 0, src_stride_y), addr1_s(ptr2_x, 1, src_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), addr1_s(out2_x, 0, dst_stride_y), addr1_s(out2_x, 1, dst_stride_y), short_buffer_0, // [4] short_buffer_1, // [4] long_buffer_ptr+0*4, // [4] long_buffer_ptr+1*4 // [4] ); long_buffer_ptr += 2*4; ptr1_x = addr1_s(ptr1_x, 2, src_stride_y); ptr2_x = addr1_s(ptr2_x, 2, src_stride_y); out1_x = addr1_s(out1_x, 2, dst_stride_y); out2_x = addr1_s(out2_x, 2, dst_stride_y); } } } // SL DL WITH-MERGED-SCALING void cdf97_fwd_core_dl_sc_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { // forward transform with offset = 1 int offset = 1; float short_buffer_0[4]; float short_buffer_1[4]; float long_buffer[4*size_x]; dwt_util_zero_vec_s(long_buffer, 4 * size_x); // filter big into output using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr1_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr2_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out1_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out2_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer; dwt_util_zero_vec_s(short_buffer_0, 4); dwt_util_zero_vec_s(short_buffer_1, 4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_sc_2x2_s( addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(ptr2_x, 0, src_stride_y), addr1_s(ptr2_x, 1, src_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), addr1_s(out2_x, 0, dst_stride_y), addr1_s(out2_x, 1, dst_stride_y), short_buffer_0, // [4] short_buffer_1, // [4] long_buffer_ptr+0*4, // [4] long_buffer_ptr+1*4 // [4] ); long_buffer_ptr += 2*4; ptr1_x = addr1_s(ptr1_x, 2, src_stride_y); ptr2_x = addr1_s(ptr2_x, 2, src_stride_y); out1_x = addr1_s(out1_x, 2, dst_stride_y); out2_x = addr1_s(out2_x, 2, dst_stride_y); } } } // SL DL WITH-MERGED-SCALING SSE void cdf97_fwd_core_dl_sc_sse_s( void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { #ifdef __SSE__ // forward transform with offset = 1 int offset = 1; float short_buffer_0[4]; float short_buffer_1[4]; float long_buffer[4*size_x]; dwt_util_zero_vec_s(long_buffer, 4 * size_x); // filter big into output using 2x2 core for(int y = 0+offset; y+1 < size_y; y += 2) { float *ptr1_x = addr2_s(src, y+0, offset, src_stride_x, src_stride_y); float *ptr2_x = addr2_s(src, y+1, offset, src_stride_x, src_stride_y); float *out1_x = addr2_s(dst, y+0, offset, dst_stride_x, dst_stride_y); float *out2_x = addr2_s(dst, y+1, offset, dst_stride_x, dst_stride_y); float *long_buffer_ptr = long_buffer; dwt_util_zero_vec_s(short_buffer_0, 4); dwt_util_zero_vec_s(short_buffer_1, 4); for(int x = 0+offset; x+1 < size_x; x += 2) { cdf97_fwd_core_dl_sc_sse_2x2_s( addr1_s(ptr1_x, 0, src_stride_y), addr1_s(ptr1_x, 1, src_stride_y), addr1_s(ptr2_x, 0, src_stride_y), addr1_s(ptr2_x, 1, src_stride_y), addr1_s(out1_x, 0, dst_stride_y), addr1_s(out1_x, 1, dst_stride_y), addr1_s(out2_x, 0, dst_stride_y), addr1_s(out2_x, 1, dst_stride_y), short_buffer_0, // [4] short_buffer_1, // [4] long_buffer_ptr+0*4, // [4] long_buffer_ptr+1*4 // [4] ); long_buffer_ptr += 2*4; ptr1_x = addr1_s(ptr1_x, 2, src_stride_y); ptr2_x = addr1_s(ptr2_x, 2, src_stride_y); out1_x = addr1_s(out1_x, 2, dst_stride_y); out2_x = addr1_s(out2_x, 2, dst_stride_y); } } #endif } void dwt_util_alloc_zero( void **ptr, int stride_x, int stride_y, int size_x, int size_y ) { assert( ptr ); // allocate image dwt_util_alloc_image( ptr, stride_x, stride_y, size_x, size_y ); if( !ptr ) dwt_util_error("unable to allocate memory!\n"); // fill dst with zeros dwt_util_test_image_zero_s( *ptr, stride_x, stride_y, size_x, size_y ); } void dwt_util_copy2_s( const void *src, int src_stride_x, int src_stride_y, void *dst, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { assert( src && dst ); for(int y = 0; y < size_y; y++) { for(int x = 0; x < size_x; x++) { *dwt_util_addr_coeff_s( dst, y, x, dst_stride_x, dst_stride_y ) = *dwt_util_addr_coeff_const_s( src, y, x, src_stride_x, src_stride_y ); } } } enum dwt_frame { DWT_FRAME_SEPARATE, // two separated memory areas DWT_FRAME_OVERLAP, // same memory area, image is transformed into same coordinates DWT_FRAME_INPLACE, // same memory area, image is shifted }; #if 0 void *dwt_util_frame_ptr_input_image( enum dwt_alg alg, enum dwt_frame frame, void *input, int stride_x, int stride_y, int size_x, int size_y ) { int shift = dwt_alg_shift[alg]; int offset = 1; return dwt_util_viewport(input, size_x, size_y, stride_x, stride_y, offset+shift, offset+shift); } #endif #if 0 // allocate input and output frame image according to "frame", "alg" and "opt_stride" void dwt_util_alloc_frames( // algorithm implies shift enum dwt_alg alg, // frame type implies memory layout enum dwt_frame frame, // stride int opt_stride, // source image const void *src, int src_stride_x, int src_stride_y, int src_size_x, int src_size_y, // input frame void **input, int *input_stride_x, int *input_stride_y, int *input_size_x, int *input_size_y, // output frame void **output, int *output_stride_x, int *output_stride_y, int *output_size_x, int *output_size_y ) { int shift = dwt_alg_shift[alg]; if( DWT_FRAME_SEPARATE == frame ) { int size_x = 1+src_size_x+shift+4; int size_y = 1+src_size_y+shift+4; int stride_y = sizeof(float); int stride_x = dwt_util_get_stride(stride_y*size_x, opt_stride); // allocate and zero input *input = NULL; *input_stride_x = stride_x; *input_stride_y = stride_y; *input_size_x = size_x; *input_size_y = size_y; dwt_util_alloc_zero( input, *input_stride_x, *input_stride_y, *input_size_x, *input_size_y ); // allocate and zero output *output = NULL; *output_stride_x = stride_x; *output_stride_y = stride_y; *output_size_x = size_x; *output_size_y = size_y; dwt_util_alloc_zero( output, *output_stride_x, *output_stride_y, *output_size_x, *output_size_y ); // get pointer to input.image // copy image into input.image } } #endif // TODO: should return pointer to src1, src, dst void dwt_util_wrap_image( void *src_ptr, int src_size_x, int src_size_y, int src_stride_x, int src_stride_y, enum dwt_alg alg, void **dst_ptr, int *dst_size_x, int *dst_size_y, int *dst_stride_x, int *dst_stride_y, int *offset_x, int *offset_y, void **view_ptr, int opt_stride ) { // TODO: assert int shift = dwt_alg_shift[alg]; *dst_size_x = src_size_x+1+shift+2+2; *dst_size_y = src_size_y+1+shift+2+2; *dst_stride_y = sizeof(float); *dst_stride_x = dwt_util_get_stride(*dst_stride_y * *dst_size_x, opt_stride); // allocate and zero dst dwt_util_alloc_zero( dst_ptr, *dst_stride_x, *dst_stride_y, *dst_size_x, *dst_size_y ); *offset_x = 1; *offset_y = 1; // viewport to src inside of dst int small_size_x = src_size_x; int small_size_y = src_size_y; int small_offset_x = *offset_x; int small_offset_y = *offset_y; int small_stride_x = *dst_stride_x; int small_stride_y = *dst_stride_y; *view_ptr = dwt_util_viewport(*dst_ptr, *dst_size_x, *dst_size_y, *dst_stride_x, *dst_stride_y, small_offset_x, small_offset_y); // place src inside of dst dwt_util_copy2_s( src_ptr, src_stride_x, src_stride_y, *view_ptr, small_stride_x, small_stride_y, small_size_x, small_size_y ); } typedef void (*core_func_t)(void *, void *, int, int, int, int, int, int); void dwt_cdf97_2f_inplace_alg_s( enum dwt_alg alg, void *src, void *dst, int src_stride_x, int src_stride_y, int dst_stride_x, int dst_stride_y, int size_x, int size_y ) { // outer frame // assert( is_even(size_x) && is_even(size_y) && "Odd sizes are not implemented yet!" ); core_func_t core_func[DWT_ALG_LAST] = { [DWT_ALG_SL_CORE_SDL] = cdf97_fwd_core_sdl_s, // 0.057469 #ifdef __SSE__ [DWT_ALG_SL_CORE_SDL_SSE] = cdf97_fwd_core_sdl_sse_s, // 0.043640 [DWT_ALG_SL_CORE_SDL_SC_SSE] = cdf97_fwd_core_sdl_sc_sse_s, // 0.041391 [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF0] = cdf97_fwd_core_sdl_sc_sse_off0_s, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1] = cdf97_fwd_core_sdl_sc_sse_off1_s, [DWT_ALG_SL_CORE_DL_SC_SSE_OFF1] = cdf97_fwd_core_dl_sc_sse_off1_s, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF0_OVL1] = cdf97_fwd_core_sdl_sc_sse_off0_ovl1_s, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1_OVL1] = cdf97_fwd_core_sdl_sc_sse_off1_ovl1_s, #endif [DWT_ALG_SL_CORE_DL] = cdf97_fwd_core_dl_s, // 0.042970 #ifdef __SSE__ [DWT_ALG_SL_CORE_DL_SSE] = cdf97_fwd_core_dl_sse_s, // 0.043767 #endif [DWT_ALG_SL_CORE_DL_SC] = cdf97_fwd_core_dl_sc_s, // 0.042255 #ifdef __SSE__ [DWT_ALG_SL_CORE_DL_SC_SSE] = cdf97_fwd_core_dl_sc_sse_s, // 0.041465 [DWT_ALG_SL_CORE_DL_SC_SSE_OFF1_4X4] = cdf97_fwd_core_dl_sc_sse_off1_4x4_s, [DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1_6X2] = cdf97_fwd_core_sdl_sc_sse_off1_6x2_s, #endif }; core_func[alg]( src, dst, src_stride_x, src_stride_y, dst_stride_x, dst_stride_y, size_x, size_y ); } // TODO: propagate "flush" void dwt_util_perf_cdf97_2_inplace_alg_s( enum dwt_alg alg, int size_x, int size_y, int opt_stride, int M, int N, int clock_type, float *fwd_secs, float *inv_secs ) { //FUNC_BEGIN; assert( M > 0 && N > 0 && fwd_secs && inv_secs ); // pointer to M pointers to image data void *ptr[M]; void *big_ptr[M]; void *out_ptr[M]; int big_size_x; int big_size_y; int big_stride_y; int big_stride_x; int offset_x; int offset_y; // template void *template; // size_x, size_y int stride_y = sizeof(float); int stride_x = dwt_util_get_stride(stride_y * size_x, opt_stride); // allocate dwt_util_alloc_image( &template, stride_x, stride_y, size_x, size_y); // fill with test pattern dwt_util_test_image_fill_s( template, stride_x, stride_y, size_x, size_y, 0); // allocate M images for(int m = 0; m < M; m++) { dwt_util_wrap_image( template, size_x, size_y, stride_x, stride_y, alg, &big_ptr[m], &big_size_x, &big_size_y, &big_stride_x, &big_stride_y, &offset_x, &offset_y, &ptr[m], opt_stride ); } int out_size_x = big_size_x; int out_size_y = big_size_y; int out_stride_y = sizeof(float); int out_stride_x = dwt_util_get_stride(out_stride_y * out_size_x, opt_stride); for(int m = 0; m < M; m++) { // allocate big output dwt_util_alloc_image( &out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); // fill dwt_util_test_image_zero_s( out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); } *fwd_secs = +INFINITY; *inv_secs = +INFINITY; // perform N test loops, select minimum for(int n = 0; n < N; n++) { #if 1 // FIXME: flush memory for(int m = 0; m < M; m++) { dwt_util_flush_cache(big_ptr[m], dwt_util_image_size(big_stride_x, big_stride_y, big_size_x, big_size_y) ); dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } #endif // start timer const dwt_clock_t time_fwd_start = dwt_util_get_clock(clock_type); // perform M fwd transforms for(int m = 0; m < M; m++) { dwt_cdf97_2f_inplace_alg_s( alg, big_ptr[m], out_ptr[m], big_stride_x, big_stride_y, out_stride_x, out_stride_y, big_size_x, big_size_y ); } // stop timer const dwt_clock_t time_fwd_stop = dwt_util_get_clock(clock_type); // calc avg const float time_fwd_secs = (float)(time_fwd_stop - time_fwd_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_fwd_secs < *fwd_secs ) *fwd_secs = time_fwd_secs; #if 1 // FIXME: flush memory for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } #endif // start timer const dwt_clock_t time_inv_start = dwt_util_get_clock(clock_type); // perform M inv transforms for(int m = 0; m < M; m++) { dwt_cdf97_2i_s( out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y, out_size_x, out_size_y, 1, 0, 0); } // stop timer const dwt_clock_t time_inv_stop = dwt_util_get_clock(clock_type); // calc avg const float time_inv_secs = (float)(time_inv_stop - time_inv_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_inv_secs < *inv_secs ) *inv_secs = time_inv_secs; } // free M images for(int m = 0; m < M; m++) { dwt_util_free_image(&big_ptr[m]); dwt_util_free_image(&out_ptr[m]); } dwt_util_free_image(&template); //FUNC_END; } extern const float g_growth_factor_s; void dwt_util_measure_perf_cdf97_2_inplace_alg_s( enum dwt_alg alg, int min_x, int max_x, int opt_stride, int M, int N, int clock_type, FILE *fwd_plot_data, FILE *inv_plot_data ) { //FUNC_BEGIN; assert( min_x > 0 && min_x < max_x ); assert( M > 0 && N > 0 ); assert( fwd_plot_data && inv_plot_data ); const float growth_factor = g_growth_factor_s; // for x = min_x to max_x for(int x = min_x; x <= max_x; x = ceilf(x * growth_factor)) { // y is equal to x const int y = x; int size_x = x; int size_y = y; dwt_util_log(LOG_DBG, "performance test for [%ix%i]...\n", size_x, size_y); float fwd_secs; float inv_secs; // call perf() dwt_util_perf_cdf97_2_inplace_alg_s( alg, size_x, size_y, opt_stride, // FIXME M, N, clock_type, &fwd_secs, &inv_secs ); #ifdef MEASURE_PER_PIXEL const int denominator = x*y; #else const int denominator = 1; #endif // printf into file fprintf(fwd_plot_data, "%i\t%.10f\n", x*y, fwd_secs/denominator); fprintf(inv_plot_data, "%i\t%.10f\n", x*y, inv_secs/denominator); } //FUNC_END; } void dwt_util_measure_perf_cdf97_2_inplace_new_s( int min_x, int max_x, int opt_stride, int M, int N, int clock_type, FILE *fwd_plot_data, FILE *inv_plot_data, enum order order, int strip_x, int strip_y ) { //FUNC_BEGIN; assert( min_x > 0 && min_x < max_x ); assert( M > 0 && N > 0 ); assert( fwd_plot_data && inv_plot_data ); const float growth_factor = g_growth_factor_s; // for x = min_x to max_x for(int x = min_x; x <= max_x; x = ceilf(x * growth_factor)) { // y is equal to x const int y = x; int mod_x = (x+10+4)%6; // HACK: 10(diag)+4(decay) modulo 6 int mod_y = (y+10+4)%6; // HACK: 10(diag)+4(decay) modulo 6 int size_x = x-mod_x; // HACK int size_y = y-mod_y; // HACK dwt_util_log(LOG_DBG, "performance test for [%ix%i]...\n", size_x, size_y); float fwd_secs; float inv_secs; // call perf() dwt_util_perf_cdf97_2_inplace_new_s( size_x, size_y, opt_stride, M, N, clock_type, &fwd_secs, &inv_secs, 1, // flush order, strip_x, strip_y ); #ifdef MEASURE_PER_PIXEL const int denominator = x*y; #else const int denominator = 1; #endif // printf into file fprintf(fwd_plot_data, "%i\t%.10f\n", x*y, fwd_secs/denominator); fprintf(inv_plot_data, "%i\t%.10f\n", x*y, inv_secs/denominator); } //FUNC_END; } void dwt_util_measure_perf_cdf97_2_inplace_new_VERT_s( int min_x, int max_x, int opt_stride, int M, int N, int clock_type, FILE *fwd_plot_data, FILE *inv_plot_data, enum order order, int strip_x, int strip_y ) { //FUNC_BEGIN; assert( min_x > 0 && min_x < max_x ); assert( M > 0 && N > 0 ); assert( fwd_plot_data && inv_plot_data ); const float growth_factor = g_growth_factor_s; // for x = min_x to max_x for(int x = min_x; x <= max_x; x = ceilf(x * growth_factor)) { // y is equal to x const int y = x; #if 1 int mod_vert8_x = (x+ 4+4)%8; // HACK: 4(vert)+4(decay) modulo 8(super-core) int mod_vert8_y = (y+ 4+4)%8; // HACK: 4(vert)+4(decay) modulo 8(super-core) int size_x = /*to_even8*/(x)-mod_vert8_x; // HACK int size_y = /*to_even8*/(y)-mod_vert8_y; // HACK #else int size_x = to_even8(x); // HACK int size_y = to_even8(y); // HACK #endif dwt_util_log(LOG_DBG, "performance test for [%ix%i]...\n", size_x, size_y); float fwd_secs; float inv_secs; // call perf() dwt_util_perf_cdf97_2_inplace_new_VERT_s( size_x, size_y, opt_stride, M, N, clock_type, &fwd_secs, &inv_secs, 1, // flush order, strip_x, strip_y ); #ifdef MEASURE_PER_PIXEL const int denominator = x*y; #else const int denominator = 1; #endif // printf into file fprintf(fwd_plot_data, "%i\t%.10f\n", x*y, fwd_secs/denominator); fprintf(inv_plot_data, "%i\t%.10f\n", x*y, inv_secs/denominator); } //FUNC_END; } void dwt_util_perf_cdf97_2_inplace_diag2x2_frame4_s( enum dwt_alg alg, int size_x, int size_y, int opt_stride, int M, int N, int clock_type, float *fwd_secs, float *inv_secs, int flush ) { assert( M > 0 && N > 0 && fwd_secs && inv_secs ); // currently, only even size size_x = to_even(size_x); size_y = to_even(size_y); // declare template void *template_ptr; int template_size_x = size_x; int template_size_y = size_y; int template_stride_y = sizeof(float); int template_stride_x = dwt_util_get_stride(template_stride_y * template_size_x, opt_stride); // allocate template dwt_util_alloc_image( &template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y); // fill template with test pattern dwt_util_test_image_fill2_s( template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y, 0, 0); // offset int offset = 1; // decay int border = 4; // declare frame void *frame_ptr[M]; int frame_size_x = offset+border+size_x+border+offset; // FIXME: stačí pouze 1x +offset int frame_size_y = offset+border+size_y+border+offset; // FIXME: stačí pouze 1x +offset int frame_stride_y = sizeof(float); int frame_stride_x = dwt_util_get_stride(frame_stride_y * frame_size_x, opt_stride); // log dwt_util_log(LOG_DBG, "frame: size=(%i,%i) stride=(%i,%i) image=(%i,%i)\n", frame_size_x, frame_size_y, frame_stride_y, frame_stride_x, size_x, size_y); // allocate M images for(int m = 0; m < M; m++) { dwt_util_alloc_image( &frame_ptr[m], frame_stride_x, frame_stride_y, frame_size_x, frame_size_y ); } // frame.image void *image_ptr[M]; for(int m = 0; m < M; m++) { image_ptr[m] = dwt_util_viewport( frame_ptr[m], frame_size_x, frame_size_y, frame_stride_x, frame_stride_y, offset+border, offset+border); } *fwd_secs = +INFINITY; *inv_secs = +INFINITY; // perform N test loops, select minimum for(int n = 0; n < N; n++) { // copy template into frame.src_img for(int m = 0; m < M; m++) { // zero dwt_util_test_image_zero_s( frame_ptr[m], frame_stride_x, frame_stride_y, frame_size_x, frame_size_y ); // copy dwt_util_copy2_s( template_ptr, template_stride_x, template_stride_y, image_ptr[m], frame_stride_x, frame_stride_y, template_size_x, template_size_y ); } // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(frame_ptr[m], dwt_util_image_size(frame_stride_x, frame_stride_y, frame_size_x, frame_size_y) ); } } // start timer const dwt_clock_t time_fwd_start = dwt_util_get_clock(clock_type); // perform M fwd transforms for(int m = 0; m < M; m++) { // forward transform fdwt_diag_2x2( //fdwt_diag_2x2_full( //fdwt_diag_2x2_test( addr2_s(frame_ptr[m], offset, offset, frame_stride_x, frame_stride_y), frame_stride_x, frame_stride_y, frame_size_x-2*offset, // FIXME frame_size_y-2*offset ); } // stop timer const dwt_clock_t time_fwd_stop = dwt_util_get_clock(clock_type); // calc avg const float time_fwd_secs = (float)(time_fwd_stop - time_fwd_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_fwd_secs < *fwd_secs ) *fwd_secs = time_fwd_secs; // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(frame_ptr[m], dwt_util_image_size(frame_stride_x, frame_stride_y, frame_size_x, frame_size_y) ); } } int inv_offset = 1-offset; // start timer const dwt_clock_t time_inv_start = dwt_util_get_clock(clock_type); // perform M inv transforms for(int m = 0; m < M; m++) { // inverse transform dwt_cdf97_2i_inplace_s( frame_ptr[m], frame_stride_x, frame_stride_y, frame_size_x-0, // FIXME frame_size_y-0, // FIXME frame_size_x-0, // FIXME frame_size_y-0, // FIXME /*j*/1, 0, 0 ); } // stop timer const dwt_clock_t time_inv_stop = dwt_util_get_clock(clock_type); // calc avg const float time_inv_secs = (float)(time_inv_stop - time_inv_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_inv_secs < *inv_secs ) *inv_secs = time_inv_secs; // compare template and dst_img for(int m = 0; m < M; m++) { // compare if( dwt_util_compare2_s( image_ptr[m], // 1 template_ptr, // 2 frame_stride_x, frame_stride_y, template_stride_x, template_stride_y, template_size_x, template_size_y ) ) { dwt_util_log(LOG_INFO, "compare: fails\n"); } } } // free for(int m = 0; m < M; m++) { dwt_util_free_image(&frame_ptr[m]); } dwt_util_free_image(&template_ptr); } // TODO: duplicate this! // core transform with overlapping src/dst areas void dwt_util_perf_cdf97_2_inplaceB_alg_s( enum dwt_alg alg, int size_x, int size_y, int opt_stride, int M, int N, int clock_type, float *fwd_secs, float *inv_secs, int flush, int overlap // 0 = B, 1 = C ) { //FUNC_BEGIN; assert( M > 0 && N > 0 && fwd_secs && inv_secs ); // HACK #if 1 int mod_diag6_x = (size_x+10+4)%6; int mod_diag6_y = (size_y+10+4)%6; int mod_vert8_x = (size_x+ 4+4)%8; int mod_vert8_y = (size_y+ 4+4)%8; if( DWT_ALG_SL_CORE_DL_SC_SSE_OFF1_4X4 == alg ) { size_x -= mod_vert8_x; size_y -= mod_vert8_y; } if( DWT_ALG_SL_CORE_SDL_SC_SSE_OFF1_6X2 == alg ) { size_x -= mod_diag6_x; size_y -= mod_diag6_y; } #endif // template void *template_ptr; int template_size_x = size_x; int template_size_y = size_y; int template_stride_y = sizeof(float); int template_stride_x = dwt_util_get_stride(template_stride_y * template_size_x, opt_stride); // allocate template dwt_util_alloc_image( &template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y); // fill template with test pattern dwt_util_test_image_fill_s( template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y, 0); // shift int shift = dwt_alg_get_shift(alg); // offset //int offset = 1; int offset = ( DWT_ALG_SL_CORE_SDL_SC_SSE_OFF0!=alg && DWT_ALG_SL_CORE_SDL_SC_SSE_OFF0_OVL1!=alg ) ? 1 : 0; int decay = 4; #if 0 dwt_util_log(LOG_DBG, "shift=%i offset=%i\n", shift, offset); dwt_util_log(LOG_DBG, "size_x=%i size_y=%i\n", size_x, size_y); #endif // frame void *out_ptr[M]; int out_size_x = offset+shift+size_x+shift+decay; int out_size_y = offset+shift+size_y+shift+decay; int out_stride_y = sizeof(float); int out_stride_x = dwt_util_get_stride(out_stride_y * out_size_x, opt_stride); // pointers void *src_img[M]; // image size_x x size_y void *src_ptr[M]; // transform 1+img_size_x+shift+2+2 x 1+img_size_y+shift+2+2 void *dst_img[M]; // image size_x x size_y void *dst_ptr[M]; // transform 1+img_size_x+shift+2+2 x 1+img_size_y+shift+2+2 #define HACK_1 21 #define HACK_2 20 // allocate M images for(int m = 0; m < M; m++) { // allocate dwt_util_alloc_image( &out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y*2+HACK_1 // HACK: splitting among threads causes access up to up_to_even( Y/(Y-1) ) ~= Y*2 rows ); // HACK: read area have to be filled with zeros dwt_util_test_image_zero_s( out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y*2+HACK_1 ); out_ptr[m] += out_stride_x*HACK_2; // HACK: need to read some area before image beginning (threads) src_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, shift, shift); src_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); if( !overlap ) { dst_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, 0, 0); dst_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); } else { dst_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, shift, shift); dst_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+2*shift, offset+2*shift); } } *fwd_secs = +INFINITY; *inv_secs = +INFINITY; // perform N test loops, select minimum for(int n = 0; n < N; n++) { // copy template into frame.src_img for(int m = 0; m < M; m++) { // TODO: this is necessary dwt_util_test_image_zero_s( out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); dwt_util_copy2_s( template_ptr, template_stride_x, template_stride_y, src_img[m], out_stride_x, out_stride_y, template_size_x, template_size_y ); } // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } } // start timer const dwt_clock_t time_fwd_start = dwt_util_get_clock(clock_type); // perform M fwd transforms for(int m = 0; m < M; m++) { #if 1 dwt_cdf97_2f_inplace_alg_s( alg, src_ptr[m], dst_ptr[m], out_stride_x, out_stride_y, out_stride_x, out_stride_y, offset+size_x+shift+decay, offset+size_y+shift+decay ); #else fdwt_diag_2x2_full( addr2_s(dst_ptr[m],1,1,out_stride_x,out_stride_y), out_stride_x, out_stride_y, size_x+shift+decay, size_y+shift+decay ); #endif } // stop timer const dwt_clock_t time_fwd_stop = dwt_util_get_clock(clock_type); // calc avg const float time_fwd_secs = (float)(time_fwd_stop - time_fwd_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_fwd_secs < *fwd_secs ) *fwd_secs = time_fwd_secs; #if 0 // HACK dwt_util_save_to_pgm_s("hack.pgm", 1.0, dst_img[0], out_stride_x, out_stride_y, size_x, size_y); #endif // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } } int inv_offset = 1-offset; // start timer const dwt_clock_t time_inv_start = dwt_util_get_clock(clock_type); // perform M inv transforms for(int m = 0; m < M; m++) { // dwt_cdf97_2i_inplace_s( // out_ptr[m], // out_stride_x, // out_stride_y, // out_size_x, // out_size_y, // out_size_x, // out_size_y, // 1, // 0, // 0 // ); dwt_cdf97_2i_inplace_s( dwt_util_addr_coeff_s(out_ptr[m],inv_offset,inv_offset,out_stride_x,out_stride_y), out_stride_x, out_stride_y, out_size_x-inv_offset, out_size_y-inv_offset, out_size_x-inv_offset, out_size_y-inv_offset, 1, 0, 0 ); } // stop timer const dwt_clock_t time_inv_stop = dwt_util_get_clock(clock_type); // calc avg const float time_inv_secs = (float)(time_inv_stop - time_inv_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_inv_secs < *inv_secs ) *inv_secs = time_inv_secs; // compare template and dst_img for(int m = 0; m < M; m++) { if( dwt_util_compare2_s(dst_img[m], template_ptr, out_stride_x, out_stride_y, template_stride_x, template_stride_y, size_x, size_y) ) { dwt_util_log(LOG_ERR, "images differs (%i,%i) overlap=%i alg=%i\n", size_x, size_y, overlap, (int)alg); dwt_util_save_to_pgm_s("debug.pgm", 1.0, dst_img[m], out_stride_x, out_stride_y, size_x, size_y); dwt_util_save_to_pgm_s("ref.pgm", 1.0, template_ptr, template_stride_x, template_stride_y, size_x, size_y); } } } // free M images for(int m = 0; m < M; m++) { out_ptr[m] -= out_stride_x*HACK_2; // HACK dwt_util_free_image(&out_ptr[m]); } dwt_util_free_image(&template_ptr); //FUNC_END; } void dwt_util_perf_cdf97_2_inplace_new_s( int size_x, int size_y, int opt_stride, int M, int N, int clock_type, float *fwd_secs, float *inv_secs, int flush, // new enum order order, int strip_x, int strip_y ) { //FUNC_BEGIN; extern int g_strip_x; g_strip_x = strip_x; extern int g_strip_y; g_strip_y = strip_y; assert( M > 0 && N > 0 && fwd_secs && inv_secs ); // template void *template_ptr; int template_size_x = size_x; int template_size_y = size_y; int template_stride_y = sizeof(float); int template_stride_x = dwt_util_get_stride(template_stride_y * template_size_x, opt_stride); // allocate template dwt_util_alloc_image( &template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y ); // fill template with test pattern dwt_util_test_image_fill2_s( template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y, 0, 0 // NOTE: type ); // shift int shift = 10; // FIXME: diagonal/SDL // offset int offset = 1; // FIXME // border int decay = 4; // FIXME: CDF 9/7 // frame void *out_ptr[M]; int out_size_x = offset+(shift+size_x+shift+decay); int out_size_y = offset+(shift+size_y+shift+decay); int out_stride_y = sizeof(float); int out_stride_x = dwt_util_get_stride(out_stride_y * out_size_x, opt_stride); // pointers void *src_img[M]; // image (size_x, size_y) void *src_ptr[M]; // transform void *dst_img[M]; // image (size_x, size_y) void *dst_ptr[M]; // transform // allocate M images for(int m = 0; m < M; m++) { // allocate dwt_util_alloc_image( &out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); src_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); src_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); dst_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, 0, 0); dst_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); } *fwd_secs = +INFINITY; *inv_secs = +INFINITY; // perform N test loops, select minimum for(int n = 0; n < N; n++) { // copy template into frame.src_img for(int m = 0; m < M; m++) { // this is necessary dwt_util_test_image_zero_s( out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); dwt_util_copy2_s( template_ptr, template_stride_x, template_stride_y, src_img[m], out_stride_x, out_stride_y, template_size_x, template_size_y ); } // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } } // select the proper function fdwt_diag_2x2_func_t func = get_fdwt_diag_2x2_func(order); // start timer const dwt_clock_t time_fwd_start = dwt_util_get_clock(clock_type); // perform M fwd transforms for(int m = 0; m < M; m++) { func( src_ptr[m], out_stride_x, out_stride_y, size_x+shift+decay, size_y+shift+decay ); } // stop timer const dwt_clock_t time_fwd_stop = dwt_util_get_clock(clock_type); // calc avg const float time_fwd_secs = (float)(time_fwd_stop - time_fwd_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_fwd_secs < *fwd_secs ) *fwd_secs = time_fwd_secs; // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } } // start timer const dwt_clock_t time_inv_start = dwt_util_get_clock(clock_type); // perform M inv transforms for(int m = 0; m < M; m++) { dwt_cdf97_2i_inplace_s( dst_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y, out_size_x, out_size_y, 1, 0, 0 ); } // stop timer const dwt_clock_t time_inv_stop = dwt_util_get_clock(clock_type); // calc avg const float time_inv_secs = (float)(time_inv_stop - time_inv_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_inv_secs < *inv_secs ) *inv_secs = time_inv_secs; // compare template and dst_img for(int m = 0; m < M; m++) { if( dwt_util_compare2_s(dst_img[m], template_ptr, out_stride_x, out_stride_y, template_stride_x, template_stride_y, size_x, size_y) ) { dwt_util_log(LOG_INFO, "images differs (%i,%i)\n", size_x, size_y); dwt_util_save_to_pgm_s("debug.pgm", 1.0, dst_img[m], out_stride_x, out_stride_y, size_x, size_y); dwt_util_save_to_pgm_s("template.pgm", 1.0, template_ptr, template_stride_x, template_stride_y, size_x, size_y); } } } // free M images for(int m = 0; m < M; m++) { dwt_util_free_image(&out_ptr[m]); } dwt_util_free_image(&template_ptr); //FUNC_END; } void dwt_util_perf_cdf97_2_inplace_new_VERT_s( int size_x, int size_y, int opt_stride, int M, int N, int clock_type, float *fwd_secs, float *inv_secs, int flush, // new enum order order, int strip_x, int strip_y ) { //FUNC_BEGIN; extern int g_strip_x; g_strip_x = strip_x; extern int g_strip_y; g_strip_y = strip_y; assert( M > 0 && N > 0 && fwd_secs && inv_secs ); // template void *template_ptr; int template_size_x = size_x; int template_size_y = size_y; int template_stride_y = sizeof(float); int template_stride_x = dwt_util_get_stride(template_stride_y * template_size_x, opt_stride); // allocate template dwt_util_alloc_image( &template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y ); #if 1 // fill template with test pattern dwt_util_test_image_fill2_s( template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y, 0, 0 // NOTE: type ); #else // fill template with test pattern dwt_util_test_image_fill_s( template_ptr, template_stride_x, template_stride_y, template_size_x, template_size_y, 0 ); #endif // shift int shift = 4; // FIXME: vertical/DL // offset int offset = 1; // FIXME // border int decay = 4; // FIXME: CDF 9/7 // frame void *out_ptr[M]; int out_size_x = offset+(shift+size_x+shift+decay); int out_size_y = offset+(shift+size_y+shift+decay); int out_stride_y = sizeof(float); int out_stride_x = dwt_util_get_stride(out_stride_y * out_size_x, opt_stride); // pointers void *src_img[M]; // image (size_x, size_y) void *src_ptr[M]; // transform void *dst_img[M]; // image (size_x, size_y) void *dst_ptr[M]; // transform // allocate M images for(int m = 0; m < M; m++) { // allocate dwt_util_alloc_image( &out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); src_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); src_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); dst_ptr[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, 0, 0); dst_img[m] = dwt_util_viewport(out_ptr[m], out_size_x, out_size_y, out_stride_x, out_stride_y, offset+shift, offset+shift); } *fwd_secs = +INFINITY; *inv_secs = +INFINITY; // perform N test loops, select minimum for(int n = 0; n < N; n++) { // copy template into frame.src_img for(int m = 0; m < M; m++) { // this is necessary dwt_util_test_image_zero_s( out_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y ); dwt_util_copy2_s( template_ptr, template_stride_x, template_stride_y, src_img[m], out_stride_x, out_stride_y, template_size_x, template_size_y ); } // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } } // select the proper function fdwt_vert_2x2_func_t func = get_fdwt_vert_2x2_func(order); // start timer const dwt_clock_t time_fwd_start = dwt_util_get_clock(clock_type); // perform M fwd transforms for(int m = 0; m < M; m++) { func( //fdwt_vert_2x2_HORIZ_test( src_ptr[m], out_stride_x, out_stride_y, size_x+shift+decay, size_y+shift+decay ); } // stop timer const dwt_clock_t time_fwd_stop = dwt_util_get_clock(clock_type); // calc avg const float time_fwd_secs = (float)(time_fwd_stop - time_fwd_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_fwd_secs < *fwd_secs ) *fwd_secs = time_fwd_secs; // HACK #if 0 { dwt_util_log(LOG_DBG, "saving transform...\n"); void *show; dwt_util_alloc_image( &show, out_stride_x, out_stride_y, size_x, size_y ); dwt_util_conv_show_s( dst_img[0], show, out_stride_x, out_stride_y, size_x, size_y ); dwt_util_save_to_pgm_s("transform.pgm", 1.0, show, out_stride_x, out_stride_y, size_x, size_y); dwt_util_save_to_pgm_s("frame.pgm", 1.0, out_ptr[0], out_stride_x, out_stride_y, out_size_x, out_size_y); } #endif // flush memory if( flush ) { for(int m = 0; m < M; m++) { dwt_util_flush_cache(out_ptr[m], dwt_util_image_size(out_stride_x, out_stride_y, out_size_x, out_size_y) ); } } // start timer const dwt_clock_t time_inv_start = dwt_util_get_clock(clock_type); // perform M inv transforms for(int m = 0; m < M; m++) { dwt_cdf97_2i_inplace_s( dst_ptr[m], out_stride_x, out_stride_y, out_size_x, out_size_y, out_size_x, out_size_y, 1, 0, 0 ); } // stop timer const dwt_clock_t time_inv_stop = dwt_util_get_clock(clock_type); // calc avg const float time_inv_secs = (float)(time_inv_stop - time_inv_start) / M * MEASURE_FACTOR / dwt_util_get_frequency(clock_type); // select min if( time_inv_secs < *inv_secs ) *inv_secs = time_inv_secs; // compare template and dst_img for(int m = 0; m < M; m++) { if( dwt_util_compare2_s(dst_img[m], template_ptr, out_stride_x, out_stride_y, template_stride_x, template_stride_y, size_x, size_y) ) { dwt_util_log(LOG_INFO, "images differs (%i,%i)\n", size_x, size_y); dwt_util_save_to_pgm_s("debug.pgm", 1.0, dst_img[m], out_stride_x, out_stride_y, size_x, size_y); dwt_util_save_to_pgm_s("template.pgm", 1.0, template_ptr, template_stride_x, template_stride_y, size_x, size_y); } } } // free M images for(int m = 0; m < M; m++) { dwt_util_free_image(&out_ptr[m]); } dwt_util_free_image(&template_ptr); //FUNC_END; } void dwt_util_measure_perf_cdf97_2_inplaceB_alg_s( enum dwt_alg alg, int min_x, int max_x, int opt_stride, int M, int N, int clock_type, FILE *fwd_plot_data, FILE *inv_plot_data, int flush, int overlap ) { //FUNC_BEGIN; assert( min_x > 0 && min_x < max_x ); assert( M > 0 && N > 0 ); assert( fwd_plot_data && inv_plot_data ); const float growth_factor = g_growth_factor_s; // for x = min_x to max_x for(int x = min_x; x <= max_x; x = ceilf(x * growth_factor)) { // y is equal to x const int y = x; int size_x = x; int size_y = y; dwt_util_log(LOG_DBG, "performance test for [%ix%i]...\n", size_x, size_y); float fwd_secs; float inv_secs; // call perf() dwt_util_perf_cdf97_2_inplaceB_alg_s( alg, size_x, size_y, opt_stride, M, N, clock_type, &fwd_secs, &inv_secs, flush, overlap ); #ifdef MEASURE_PER_PIXEL const int denominator = x*y; #else const int denominator = 1; #endif // printf into file fprintf(fwd_plot_data, "%i\t%.10f\n", x*y, fwd_secs/denominator); fprintf(inv_plot_data, "%i\t%.10f\n", x*y, inv_secs/denominator); } //FUNC_END; } void dwt_util_perf_cdf97_2_inplaceABC_alg_s( enum dwt_alg alg, int size_x, int size_y, int opt_stride, int M, int N, int clock_type, float *fwd_secs, float *inv_secs, int overlap // 0 = B, 1 = C, -1 = A ) { // HACK size_x = dwt_util_to_even(size_x); size_y = dwt_util_to_even(size_y); int flush = 1; if( -1 == overlap ) dwt_util_perf_cdf97_2_inplace_alg_s( alg, size_x, size_y, opt_stride, M, N, clock_type, fwd_secs, inv_secs ); else dwt_util_perf_cdf97_2_inplaceB_alg_s( alg, size_x, size_y, opt_stride, M, N, clock_type, fwd_secs, inv_secs, flush, overlap // 0 = B, 1 = C ); } void dwt_util_measure_perf_cdf97_2_inplaceABC_alg_s( enum dwt_alg alg, int min_x, int max_x, int opt_stride, int M, int N, int clock_type, FILE *fwd_plot_data, FILE *inv_plot_data, int overlap // -1=A 0=B 1=C ) { //FUNC_BEGIN; assert( min_x > 0 && min_x < max_x ); assert( M > 0 && N > 0 ); assert( fwd_plot_data && inv_plot_data ); const float growth_factor = g_growth_factor_s; // for x = min_x to max_x for(int x = min_x; x <= max_x; x = ceilf(x * growth_factor)) { // y is equal to x const int y = x; int size_x = x; int size_y = y; dwt_util_log(LOG_DBG, "performance test for [%ix%i]...\n", size_x, size_y); float fwd_secs; float inv_secs; // call perf() dwt_util_perf_cdf97_2_inplaceABC_alg_s( alg, size_x, size_y, opt_stride, M, N, clock_type, &fwd_secs, &inv_secs, overlap ); #ifdef MEASURE_PER_PIXEL const int denominator = x*y; #else const int denominator = 1; #endif // printf into file fprintf(fwd_plot_data, "%i\t%.10f\n", x*y, fwd_secs/denominator); fprintf(inv_plot_data, "%i\t%.10f\n", x*y, inv_secs/denominator); } //FUNC_END; }
GB_unop__tgamma_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__tgamma_fp32_fp32 // op(A') function: GB_unop_tran__tgamma_fp32_fp32 // C type: float // A type: float // cast: float cij = aij // unaryop: cij = tgammaf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = tgammaf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = tgammaf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TGAMMA || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__tgamma_fp32_fp32 ( float *Cx, // Cx and Ax may be aliased const float *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = tgammaf (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__tgamma_fp32_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
residualbased_block_builder_and_solver.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Collaborators: Vicente Mataix // // #if !defined(KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER ) #define KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER /* System includes */ #include <unordered_set> /* External includes */ #ifdef KRATOS_SMP_OPENMP #include <omp.h> #endif /* Project includes */ #include "includes/define.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" #include "includes/key_hash.h" #include "utilities/timer.h" #include "utilities/variable_utils.h" #include "includes/kratos_flags.h" #include "includes/lock_object.h" #include "utilities/sparse_matrix_multiplication_utility.h" #include "utilities/builtin_timer.h" #include "utilities/atomic_utilities.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedEliminationBuilderAndSolver * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * @tparam TSparseSpace The sparse system considered * @tparam TDenseSpace The dense system considered * @tparam TLinearSolver The linear solver considered * @author Riccardo Rossi */ template<class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class ResidualBasedBlockBuilderAndSolver : public BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver > { public: ///@name Type Definitions ///@{ /// Definition of the flags KRATOS_DEFINE_LOCAL_FLAG( SILENT_WARNINGS ); // Scaling enum enum class SCALING_DIAGONAL {NO_SCALING = 0, CONSIDER_NORM_DIAGONAL = 1, CONSIDER_MAX_DIAGONAL = 2, CONSIDER_PRESCRIBED_DIAGONAL = 3}; /// Definition of the pointer KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedBlockBuilderAndSolver); /// Definition of the base class typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; /// The definition of the current class typedef ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> ClassType; // The size_t types typedef std::size_t SizeType; typedef std::size_t IndexType; /// Definition of the classes from the base class typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; /// Additional definitions typedef PointerVectorSet<Element, IndexedObject> ElementsContainerType; typedef Element::EquationIdVectorType EquationIdVectorType; typedef Element::DofsVectorType DofsVectorType; typedef boost::numeric::ublas::compressed_matrix<double> CompressedMatrixType; /// DoF types definition typedef Node<3> NodeType; typedef typename NodeType::DofType DofType; typedef typename DofType::Pointer DofPointerType; ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor */ explicit ResidualBasedBlockBuilderAndSolver() : BaseType() { } /** * @brief Default constructor. (with parameters) */ explicit ResidualBasedBlockBuilderAndSolver( typename TLinearSolver::Pointer pNewLinearSystemSolver, Parameters ThisParameters ) : BaseType(pNewLinearSystemSolver) { // Validate and assign defaults ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters()); this->AssignSettings(ThisParameters); } /** * @brief Default constructor. */ explicit ResidualBasedBlockBuilderAndSolver(typename TLinearSolver::Pointer pNewLinearSystemSolver) : BaseType(pNewLinearSystemSolver) { mScalingDiagonal = SCALING_DIAGONAL::NO_SCALING; } /** Destructor. */ ~ResidualBasedBlockBuilderAndSolver() override { } /** * @brief Create method * @param pNewLinearSystemSolver The linear solver for the system of equations * @param ThisParameters The configuration parameters */ typename BaseType::Pointer Create( typename TLinearSolver::Pointer pNewLinearSystemSolver, Parameters ThisParameters ) const override { return Kratos::make_shared<ClassType>(pNewLinearSystemSolver,ThisParameters); } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Function to perform the build of the RHS. The vector could be sized as the total number * of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param b The RHS vector */ void Build( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) override { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; // Getting the elements from the model const int nelements = static_cast<int>(rModelPart.Elements().size()); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin(); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements const auto timer = BuiltinTimer(); #pragma omp parallel firstprivate(nelements,nconditions, LHS_Contribution, RHS_Contribution, EquationId ) { # pragma omp for schedule(guided, 512) nowait for (int k = 0; k < nelements; k++) { ModelPart::ElementsContainerType::iterator it = el_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if ((it)->IsDefined(ACTIVE)) element_is_active = (it)->Is(ACTIVE); if (element_is_active) { //calculate elemental contribution pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); } } #pragma omp for schedule(guided, 512) for (int k = 0; k < nconditions; k++) { ModelPart::ConditionsContainerType::iterator it = cond_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if ((it)->IsDefined(ACTIVE)) condition_is_active = (it)->Is(ACTIVE); if (condition_is_active) { //calculate elemental contribution pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); } } } KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >= 1) << "Build time: " << timer.ElapsedSeconds() << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building of the LHS * @details Depending on the implementation choosen the size of the matrix could * be equal to the total number of Dofs or to the number of unrestrained dofs * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix */ void BuildLHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA ) override { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; // Getting the elements from the model const int nelements = static_cast<int>(rModelPart.Elements().size()); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); const auto it_elem_begin = rModelPart.ElementsBegin(); const auto it_cond_begin = rModelPart.ConditionsBegin(); // Contributions to the system LocalSystemMatrixType lhs_contribution(0, 0); // Vector containing the localization in the system of the different terms Element::EquationIdVectorType equation_id; // Assemble all elements const auto timer = BuiltinTimer(); #pragma omp parallel firstprivate(nelements, nconditions, lhs_contribution, equation_id ) { # pragma omp for schedule(guided, 512) nowait for (int k = 0; k < nelements; ++k) { auto it_elem = it_elem_begin + k; // Detect if the element is active or not. If the user did not make any choice the element is active by default bool element_is_active = true; if (it_elem->IsDefined(ACTIVE)) element_is_active = it_elem->Is(ACTIVE); if (element_is_active) { // Calculate elemental contribution pScheme->CalculateLHSContribution(*it_elem, lhs_contribution, equation_id, r_current_process_info); // Assemble the elemental contribution AssembleLHS(rA, lhs_contribution, equation_id); } } #pragma omp for schedule(guided, 512) for (int k = 0; k < nconditions; ++k) { auto it_cond = it_cond_begin + k; // Detect if the element is active or not. If the user did not make any choice the element is active by default bool condition_is_active = true; if (it_cond->IsDefined(ACTIVE)) condition_is_active = it_cond->Is(ACTIVE); if (condition_is_active) { // Calculate elemental contribution pScheme->CalculateLHSContribution(*it_cond, lhs_contribution, equation_id, r_current_process_info); // Assemble the elemental contribution AssembleLHS(rA, lhs_contribution, equation_id); } } } KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >= 1) << "Build time LHS: " << timer.ElapsedSeconds() << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 2) << "Finished parallel building LHS" << std::endl; KRATOS_CATCH("") } /** * @brief Build a rectangular matrix of size n*N where "n" is the number of unrestrained degrees of freedom * and "N" is the total number of degrees of freedom involved. * @details This matrix is obtained by building the total matrix without the lines corresponding to the fixed * degrees of freedom (but keeping the columns!!) * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix */ void BuildLHS_CompleteOnFreeRows( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A) override { KRATOS_TRY TSystemVectorType tmp(A.size1(), 0.0); this->Build(pScheme, rModelPart, A, tmp); KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void SystemSolve( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b ) override { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else TSparseSpace::SetToZero(Dx); if(mT.size1() != 0) //if there are master-slave constraints { //recover solution of the original problem TSystemVectorType Dxmodified = Dx; TSparseSpace::Mult(mT, Dxmodified, Dx); } //prints informations about the current time KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector * @param rModelPart The model part of the problem to solve */ virtual void SystemSolveWithPhysics( TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb, ModelPart& rModelPart ) { if(rModelPart.MasterSlaveConstraints().size() != 0) { TSystemVectorType Dxmodified(rb.size()); InternalSystemSolveWithPhysics(rA, Dxmodified, rb, rModelPart); //recover solution of the original problem TSparseSpace::Mult(mT, Dxmodified, rDx); } else { InternalSystemSolveWithPhysics(rA, rDx, rb, rModelPart); } } /** *@brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector * @param rModelPart The model part of the problem to solve */ void InternalSystemSolveWithPhysics( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b, ModelPart& rModelPart ) { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //provide physical data as needed if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded() ) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart); //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else { TSparseSpace::SetToZero(Dx); KRATOS_WARNING_IF("ResidualBasedBlockBuilderAndSolver", mOptions.IsNot(SILENT_WARNINGS)) << "ATTENTION! setting the RHS to zero!" << std::endl; } // Prints informations about the current time KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY Timer::Start("Build"); Build(pScheme, rModelPart, A, b); Timer::Stop("Build"); if(rModelPart.MasterSlaveConstraints().size() != 0) { Timer::Start("ApplyConstraints"); ApplyConstraints(pScheme, rModelPart, A, b); Timer::Stop("ApplyConstraints"); } ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; const auto timer = BuiltinTimer(); Timer::Start("Solve"); SystemSolveWithPhysics(A, Dx, b, rModelPart); Timer::Stop("Solve"); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "System solve time: " << timer.ElapsedSeconds() << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time Linearizing with the database at the old iteration * @details It is ideally the fastest and safer function to use when it is possible to solve just after building * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rA The LHS matrix of the system of equations * @param rDx The vector of unkowns * @param rb The RHS vector of the system of equations * @param MoveMesh tells if the update of the scheme needs to be performed when calling the Update of the scheme */ void BuildAndSolveLinearizedOnPreviousIteration( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb, const bool MoveMesh ) override { KRATOS_INFO_IF("BlockBuilderAndSolver", this->GetEchoLevel() > 0) << "Linearizing on Old iteration" << std::endl; KRATOS_ERROR_IF(rModelPart.GetBufferSize() == 1) << "BlockBuilderAndSolver: \n" << "The buffer size needs to be at least 2 in order to use \n" << "BuildAndSolveLinearizedOnPreviousIteration \n" << "current buffer size for modelpart: " << rModelPart.Name() << std::endl << "is :" << rModelPart.GetBufferSize() << " Please set IN THE STRATEGY SETTINGS " << " UseOldStiffnessInFirstIteration=false " << std::endl; DofsArrayType fixed_dofs; for(auto& r_dof : BaseType::mDofSet){ if(r_dof.IsFixed()){ fixed_dofs.push_back(&r_dof); r_dof.FreeDof(); } } //TODO: Here we need to take the vector from other ones because // We cannot create a trilinos vector without a communicator. To be improved! TSystemVectorType dx_prediction(rDx); TSystemVectorType rhs_addition(rb); //we know it is zero here, so we do not need to set it // Here we bring back the database to before the prediction, // but we store the prediction increment in dx_prediction. // The goal is that the stiffness is computed with the // converged configuration at the end of the previous step. block_for_each(BaseType::mDofSet, [&](Dof<double>& rDof){ // NOTE: this is initialzed to - the value of dx prediction dx_prediction[rDof.EquationId()] = -(rDof.GetSolutionStepValue() - rDof.GetSolutionStepValue(1)); }); // Use UpdateDatabase to bring back the solution to how it was at the end of the previous step pScheme->Update(rModelPart, BaseType::mDofSet, rA, dx_prediction, rb); if (MoveMesh) { VariableUtils().UpdateCurrentPosition(rModelPart.Nodes(),DISPLACEMENT,0); } this->Build(pScheme, rModelPart, rA, rb); // Put back the prediction into the database TSparseSpace::InplaceMult(dx_prediction, -1.0); //change sign to dx_prediction TSparseSpace::UnaliasedAdd(rDx, 1.0, dx_prediction); // Use UpdateDatabase to bring back the solution // to where it was taking into account BCs // it is done here so that constraints are correctly taken into account right after pScheme->Update(rModelPart, BaseType::mDofSet, rA, dx_prediction, rb); if (MoveMesh) { VariableUtils().UpdateCurrentPosition(rModelPart.Nodes(),DISPLACEMENT,0); } // Apply rb -= A*dx_prediction TSparseSpace::Mult(rA, dx_prediction, rhs_addition); TSparseSpace::UnaliasedAdd(rb, -1.0, rhs_addition); for(auto& dof : fixed_dofs) dof.FixDof(); if (!rModelPart.MasterSlaveConstraints().empty()) { this->ApplyConstraints(pScheme, rModelPart, rA, rb); } this->ApplyDirichletConditions(pScheme, rModelPart, rA, rDx, rb); this->SystemSolveWithPhysics(rA, rDx, rb, rModelPart); } /** * @brief Corresponds to the previews, but the System's matrix is considered already built and only the RHS is built again * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void BuildRHSAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY BuildRHS(pScheme, rModelPart, rb); if(rModelPart.MasterSlaveConstraints().size() != 0) { Timer::Start("ApplyRHSConstraints"); ApplyRHSConstraints(pScheme, rModelPart, rb); Timer::Stop("ApplyRHSConstraints"); } ApplyDirichletConditions(pScheme, rModelPart, rA, rDx, rb); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl; const auto timer = BuiltinTimer(); Timer::Start("Solve"); SystemSolveWithPhysics(rA, rDx, rb, rModelPart); Timer::Stop("Solve"); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "System solve time: " << timer.ElapsedSeconds() << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the build of the RHS. * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) override { KRATOS_TRY Timer::Start("BuildRHS"); BuildRHSNoDirichlet(pScheme,rModelPart,b); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver block_for_each(BaseType::mDofSet, [&](Dof<double>& rDof){ const std::size_t i = rDof.EquationId(); if (rDof.IsFixed()) b[i] = 0.0; }); Timer::Stop("BuildRHS"); KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart ) override { KRATOS_TRY; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl; //Gets the array of elements from the modeler ElementsArrayType& r_elements_array = rModelPart.Elements(); const int number_of_elements = static_cast<int>(r_elements_array.size()); DofsVectorType dof_list, second_dof_list; // NOTE: The second dof list is only used on constraints to include master/slave relations unsigned int nthreads = ParallelUtilities::GetNumThreads(); typedef std::unordered_set < NodeType::DofType::Pointer, DofPointerHasher> set_type; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Number of threads" << nthreads << "\n" << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing element loop" << std::endl; /** * Here we declare three sets. * - The global set: Contains all the DoF of the system * - The slave set: The DoF that are not going to be solved, due to MPC formulation */ set_type dof_global_set; dof_global_set.reserve(number_of_elements*20); #pragma omp parallel firstprivate(dof_list, second_dof_list) { const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // We cleate the temporal set and we reserve some space on them set_type dofs_tmp_set; dofs_tmp_set.reserve(20000); // Gets the array of elements from the modeler #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < number_of_elements; ++i) { auto it_elem = r_elements_array.begin() + i; // Gets list of Dof involved on every element pScheme->GetDofList(*it_elem, dof_list, r_current_process_info); dofs_tmp_set.insert(dof_list.begin(), dof_list.end()); } // Gets the array of conditions from the modeler ConditionsArrayType& r_conditions_array = rModelPart.Conditions(); const int number_of_conditions = static_cast<int>(r_conditions_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < number_of_conditions; ++i) { auto it_cond = r_conditions_array.begin() + i; // Gets list of Dof involved on every element pScheme->GetDofList(*it_cond, dof_list, r_current_process_info); dofs_tmp_set.insert(dof_list.begin(), dof_list.end()); } // Gets the array of constraints from the modeler auto& r_constraints_array = rModelPart.MasterSlaveConstraints(); const int number_of_constraints = static_cast<int>(r_constraints_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < number_of_constraints; ++i) { auto it_const = r_constraints_array.begin() + i; // Gets list of Dof involved on every element it_const->GetDofList(dof_list, second_dof_list, r_current_process_info); dofs_tmp_set.insert(dof_list.begin(), dof_list.end()); dofs_tmp_set.insert(second_dof_list.begin(), second_dof_list.end()); } // We merge all the sets in one thread #pragma omp critical { dof_global_set.insert(dofs_tmp_set.begin(), dofs_tmp_set.end()); } } KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl; DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); Doftemp.reserve(dof_global_set.size()); for (auto it= dof_global_set.begin(); it!= dof_global_set.end(); it++) { Doftemp.push_back( *it ); } Doftemp.Sort(); BaseType::mDofSet = Doftemp; //Throws an exception if there are no Degrees Of Freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl; #ifdef KRATOS_DEBUG // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode if (BaseType::GetCalculateReactionsFlag()) { for (auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " <<std::endl << "Node : "<<dof_iterator->Id()<< std::endl << "Dof : "<<(*dof_iterator)<<std::endl<<"Not possible to calculate reactions."<<std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief Organises the dofset in order to speed up the building phase * @param rModelPart The model part of the problem to solve */ void SetUpSystem( ModelPart& rModelPart ) override { //int free_id = 0; BaseType::mEquationSystemSize = BaseType::mDofSet.size(); IndexPartition<std::size_t>(BaseType::mDofSet.size()).for_each([&, this](std::size_t Index){ typename DofsArrayType::iterator dof_iterator = this->mDofSet.begin() + Index; dof_iterator->SetEquationId(Index); }); } //************************************************************************** //************************************************************************** void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType& pA, TSystemVectorPointerType& pDx, TSystemVectorPointerType& pb, ModelPart& rModelPart ) override { KRATOS_TRY if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } TSystemMatrixType& A = *pA; TSystemVectorType& Dx = *pDx; TSystemVectorType& b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl; A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); TSparseSpace::SetToZero(Dx); if (b.size() != BaseType::mEquationSystemSize) { b.resize(BaseType::mEquationSystemSize, false); } TSparseSpace::SetToZero(b); ConstructMasterSlaveConstraintsStructure(rModelPart); KRATOS_CATCH("") } //************************************************************************** //************************************************************************** void CalculateReactions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { TSparseSpace::SetToZero(b); //refresh RHS to have the correct reactions BuildRHSNoDirichlet(pScheme, rModelPart, b); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver block_for_each(BaseType::mDofSet, [&](Dof<double>& rDof){ const std::size_t i = rDof.EquationId(); rDof.GetSolutionStepReactionValue() = -b[i]; }); } /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely * unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details For explanation of how it works for a particular implementation the user * should refer to the particular Builder And Solver choosen * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { const std::size_t system_size = rA.size1(); Vector scaling_factors (system_size); const auto it_dof_iterator_begin = BaseType::mDofSet.begin(); // NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver IndexPartition<std::size_t>(BaseType::mDofSet.size()).for_each([&](std::size_t Index){ auto it_dof_iterator = it_dof_iterator_begin + Index; if (it_dof_iterator->IsFixed()) { scaling_factors[Index] = 0.0; } else { scaling_factors[Index] = 1.0; } }); double* Avalues = rA.value_data().begin(); std::size_t* Arow_indices = rA.index1_data().begin(); std::size_t* Acol_indices = rA.index2_data().begin(); // The diagonal considered mScaleFactor = GetScaleNorm(rModelPart, rA); // Detect if there is a line of all zeros and set the diagonal to a 1 if this happens IndexPartition<std::size_t>(system_size).for_each([&](std::size_t Index){ bool empty = true; const std::size_t col_begin = Arow_indices[Index]; const std::size_t col_end = Arow_indices[Index + 1]; for (std::size_t j = col_begin; j < col_end; ++j) { if(Avalues[j] != 0.0) { empty = false; break; } } if(empty) { rA(Index, Index) = mScaleFactor; rb[Index] = 0.0; } }); IndexPartition<std::size_t>(system_size).for_each([&](std::size_t Index){ const std::size_t col_begin = Arow_indices[Index]; const std::size_t col_end = Arow_indices[Index+1]; const double k_factor = scaling_factors[Index]; if (k_factor == 0.0) { // Zero out the whole row, except the diagonal for (std::size_t j = col_begin; j < col_end; ++j) if (Acol_indices[j] != Index ) Avalues[j] = 0.0; // Zero out the RHS rb[Index] = 0.0; } else { // Zero out the column which is associated with the zero'ed row for (std::size_t j = col_begin; j < col_end; ++j) if(scaling_factors[ Acol_indices[j] ] == 0 ) Avalues[j] = 0.0; } }); } /** * @brief Applies the constraints with master-slave relation matrix (RHS only) * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rb The RHS vector */ void ApplyRHSConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) override { KRATOS_TRY if (rModelPart.MasterSlaveConstraints().size() != 0) { BuildMasterSlaveConstraints(rModelPart); // We compute the transposed matrix of the global relation matrix TSystemMatrixType T_transpose_matrix(mT.size2(), mT.size1()); SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, mT, 1.0); TSystemVectorType b_modified(rb.size()); TSparseSpace::Mult(T_transpose_matrix, rb, b_modified); TSparseSpace::Copy(b_modified, rb); // Apply diagonal values on slaves IndexPartition<std::size_t>(mSlaveIds.size()).for_each([&](std::size_t Index){ const IndexType slave_equation_id = mSlaveIds[Index]; if (mInactiveSlaveDofs.find(slave_equation_id) == mInactiveSlaveDofs.end()) { rb[slave_equation_id] = 0.0; } }); } KRATOS_CATCH("") } /** * @brief Applies the constraints with master-slave relation matrix * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rb The RHS vector */ void ApplyConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rb ) override { KRATOS_TRY if (rModelPart.MasterSlaveConstraints().size() != 0) { BuildMasterSlaveConstraints(rModelPart); // We compute the transposed matrix of the global relation matrix TSystemMatrixType T_transpose_matrix(mT.size2(), mT.size1()); SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, mT, 1.0); TSystemVectorType b_modified(rb.size()); TSparseSpace::Mult(T_transpose_matrix, rb, b_modified); TSparseSpace::Copy(b_modified, rb); TSystemMatrixType auxiliar_A_matrix(mT.size2(), rA.size2()); SparseMatrixMultiplicationUtility::MatrixMultiplication(T_transpose_matrix, rA, auxiliar_A_matrix); //auxiliar = T_transpose * rA T_transpose_matrix.resize(0, 0, false); //free memory SparseMatrixMultiplicationUtility::MatrixMultiplication(auxiliar_A_matrix, mT, rA); //A = auxilar * T NOTE: here we are overwriting the old A matrix! auxiliar_A_matrix.resize(0, 0, false); //free memory const double max_diag = GetMaxDiagonal(rA); // Apply diagonal values on slaves IndexPartition<std::size_t>(mSlaveIds.size()).for_each([&](std::size_t Index){ const IndexType slave_equation_id = mSlaveIds[Index]; if (mInactiveSlaveDofs.find(slave_equation_id) == mInactiveSlaveDofs.end()) { rA(slave_equation_id, slave_equation_id) = max_diag; rb[slave_equation_id] = 0.0; } }); } KRATOS_CATCH("") } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { BaseType::Clear(); mSlaveIds.clear(); mMasterIds.clear(); mInactiveSlaveDofs.clear(); mT.resize(0,0,false); mConstantVector.resize(0,false); } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model part of the problem to solve * @return 0 all ok */ int Check(ModelPart& rModelPart) override { KRATOS_TRY return 0; KRATOS_CATCH(""); } /** * @brief This method provides the defaults parameters to avoid conflicts between the different constructors * @return The default parameters */ Parameters GetDefaultParameters() const override { Parameters default_parameters = Parameters(R"( { "name" : "block_builder_and_solver", "block_builder" : true, "diagonal_values_for_dirichlet_dofs" : "use_max_diagonal", "silent_warnings" : false })"); // Getting base class default parameters const Parameters base_default_parameters = BaseType::GetDefaultParameters(); default_parameters.RecursivelyAddMissingParameters(base_default_parameters); return default_parameters; } /** * @brief Returns the name of the class as used in the settings (snake_case format) * @return The name of the class */ static std::string Name() { return "block_builder_and_solver"; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedBlockBuilderAndSolver"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ TSystemMatrixType mT; /// This is matrix containing the global relation for the constraints TSystemVectorType mConstantVector; /// This is vector containing the rigid movement of the constraint std::vector<IndexType> mSlaveIds; /// The equation ids of the slaves std::vector<IndexType> mMasterIds; /// The equation ids of the master std::unordered_set<IndexType> mInactiveSlaveDofs; /// The set containing the inactive slave dofs double mScaleFactor = 1.0; /// The manuallyset scale factor SCALING_DIAGONAL mScalingDiagonal; /// We identify the scaling considered for the dirichlet dofs Flags mOptions; /// Some flags used internally ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ void BuildRHSNoDirichlet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) { KRATOS_TRY //Getting the Elements ElementsArrayType& pElements = rModelPart.Elements(); //getting the array of the conditions ConditionsArrayType& ConditionsArray = rModelPart.Conditions(); const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements //for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) const int nelements = static_cast<int>(pElements.size()); #pragma omp parallel firstprivate(nelements, RHS_Contribution, EquationId) { #pragma omp for schedule(guided, 512) nowait for (int i=0; i<nelements; i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if( (it)->IsDefined(ACTIVE) ) { element_is_active = (it)->Is(ACTIVE); } if(element_is_active) { //calculate elemental Right Hand Side Contribution pScheme->CalculateRHSContribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } } LHS_Contribution.resize(0, 0, false); RHS_Contribution.resize(0, false); // assemble all conditions const int nconditions = static_cast<int>(ConditionsArray.size()); #pragma omp for schedule(guided, 512) for (int i = 0; i<nconditions; i++) { auto it = ConditionsArray.begin() + i; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if( (it)->IsDefined(ACTIVE) ) { condition_is_active = (it)->Is(ACTIVE); } if(condition_is_active) { //calculate elemental contribution pScheme->CalculateRHSContribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } } } KRATOS_CATCH("") } virtual void ConstructMasterSlaveConstraintsStructure(ModelPart& rModelPart) { if (rModelPart.MasterSlaveConstraints().size() > 0) { Timer::Start("ConstraintsRelationMatrixStructure"); const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Vector containing the localization in the system of the different terms DofsVectorType slave_dof_list, master_dof_list; // Constraint initial iterator const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin(); std::vector<std::unordered_set<IndexType>> indices(BaseType::mDofSet.size()); std::vector<LockObject> lock_array(indices.size()); #pragma omp parallel firstprivate(slave_dof_list, master_dof_list) { Element::EquationIdVectorType slave_ids(3); Element::EquationIdVectorType master_ids(3); std::unordered_map<IndexType, std::unordered_set<IndexType>> temp_indices; #pragma omp for schedule(guided, 512) nowait for (int i_const = 0; i_const < static_cast<int>(rModelPart.MasterSlaveConstraints().size()); ++i_const) { auto it_const = it_const_begin + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if( it_const->IsDefined(ACTIVE) ) { constraint_is_active = it_const->Is(ACTIVE); } if(constraint_is_active) { it_const->EquationIdVector(slave_ids, master_ids, r_current_process_info); // Slave DoFs for (auto &id_i : slave_ids) { temp_indices[id_i].insert(master_ids.begin(), master_ids.end()); } } } // Merging all the temporal indexes for (int i = 0; i < static_cast<int>(temp_indices.size()); ++i) { lock_array[i].lock(); indices[i].insert(temp_indices[i].begin(), temp_indices[i].end()); lock_array[i].unlock(); } } mSlaveIds.clear(); mMasterIds.clear(); for (int i = 0; i < static_cast<int>(indices.size()); ++i) { if (indices[i].size() == 0) // Master dof! mMasterIds.push_back(i); else // Slave dof mSlaveIds.push_back(i); indices[i].insert(i); // Ensure that the diagonal is there in T } // Count the row sizes std::size_t nnz = 0; for (IndexType i = 0; i < indices.size(); ++i) nnz += indices[i].size(); mT = TSystemMatrixType(indices.size(), indices.size(), nnz); mConstantVector.resize(indices.size(), false); double *Tvalues = mT.value_data().begin(); IndexType *Trow_indices = mT.index1_data().begin(); IndexType *Tcol_indices = mT.index2_data().begin(); // Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Trow_indices[0] = 0; for (int i = 0; i < static_cast<int>(mT.size1()); i++) Trow_indices[i + 1] = Trow_indices[i] + indices[i].size(); IndexPartition<std::size_t>(mT.size1()).for_each([&](std::size_t Index){ const IndexType row_begin = Trow_indices[Index]; const IndexType row_end = Trow_indices[Index + 1]; IndexType k = row_begin; for (auto it = indices[Index].begin(); it != indices[Index].end(); ++it) { Tcol_indices[k] = *it; Tvalues[k] = 0.0; k++; } indices[Index].clear(); //deallocating the memory std::sort(&Tcol_indices[row_begin], &Tcol_indices[row_end]); }); mT.set_filled(indices.size() + 1, nnz); Timer::Stop("ConstraintsRelationMatrixStructure"); } } virtual void BuildMasterSlaveConstraints(ModelPart& rModelPart) { KRATOS_TRY TSparseSpace::SetToZero(mT); TSparseSpace::SetToZero(mConstantVector); // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Vector containing the localization in the system of the different terms DofsVectorType slave_dof_list, master_dof_list; // Contributions to the system Matrix transformation_matrix = LocalSystemMatrixType(0, 0); Vector constant_vector = LocalSystemVectorType(0); // Vector containing the localization in the system of the different terms Element::EquationIdVectorType slave_equation_ids, master_equation_ids; const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size()); // We clear the set mInactiveSlaveDofs.clear(); #pragma omp parallel firstprivate(transformation_matrix, constant_vector, slave_equation_ids, master_equation_ids) { std::unordered_set<IndexType> auxiliar_inactive_slave_dofs; #pragma omp for schedule(guided, 512) for (int i_const = 0; i_const < number_of_constraints; ++i_const) { auto it_const = rModelPart.MasterSlaveConstraints().begin() + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if (it_const->IsDefined(ACTIVE)) constraint_is_active = it_const->Is(ACTIVE); if (constraint_is_active) { it_const->CalculateLocalSystem(transformation_matrix, constant_vector, r_current_process_info); it_const->EquationIdVector(slave_equation_ids, master_equation_ids, r_current_process_info); for (IndexType i = 0; i < slave_equation_ids.size(); ++i) { const IndexType i_global = slave_equation_ids[i]; // Assemble matrix row AssembleRowContribution(mT, transformation_matrix, i_global, i, master_equation_ids); // Assemble constant vector const double constant_value = constant_vector[i]; double& r_value = mConstantVector[i_global]; AtomicAdd(r_value, constant_value); } } else { // Taking into account inactive constraints it_const->EquationIdVector(slave_equation_ids, master_equation_ids, r_current_process_info); auxiliar_inactive_slave_dofs.insert(slave_equation_ids.begin(), slave_equation_ids.end()); } } // We merge all the sets in one thread #pragma omp critical { mInactiveSlaveDofs.insert(auxiliar_inactive_slave_dofs.begin(), auxiliar_inactive_slave_dofs.end()); } } // Setting the master dofs into the T and C system for (auto eq_id : mMasterIds) { mConstantVector[eq_id] = 0.0; mT(eq_id, eq_id) = 1.0; } // Setting inactive slave dofs in the T and C system for (auto eq_id : mInactiveSlaveDofs) { mConstantVector[eq_id] = 0.0; mT(eq_id, eq_id) = 1.0; } KRATOS_CATCH("") } virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType& A, ModelPart& rModelPart) { //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); const std::size_t equation_size = BaseType::mEquationSystemSize; std::vector< LockObject > lock_array(equation_size); std::vector<std::unordered_set<std::size_t> > indices(equation_size); block_for_each(indices, [](std::unordered_set<std::size_t>& rIndices){ rIndices.reserve(40); }); Element::EquationIdVectorType ids(3, 0); block_for_each(rModelPart.Elements(), ids, [&](Element& rElem, Element::EquationIdVectorType& rIdsTLS){ pScheme->EquationId(rElem, rIdsTLS, CurrentProcessInfo); for (std::size_t i = 0; i < rIdsTLS.size(); i++) { lock_array[rIdsTLS[i]].lock(); auto& row_indices = indices[rIdsTLS[i]]; row_indices.insert(rIdsTLS.begin(), rIdsTLS.end()); lock_array[rIdsTLS[i]].unlock(); } }); block_for_each(rModelPart.Conditions(), ids, [&](Condition& rCond, Element::EquationIdVectorType& rIdsTLS){ pScheme->EquationId(rCond, rIdsTLS, CurrentProcessInfo); for (std::size_t i = 0; i < rIdsTLS.size(); i++) { lock_array[rIdsTLS[i]].lock(); auto& row_indices = indices[rIdsTLS[i]]; row_indices.insert(rIdsTLS.begin(), rIdsTLS.end()); lock_array[rIdsTLS[i]].unlock(); } }); if (rModelPart.MasterSlaveConstraints().size() != 0) { struct TLS { Element::EquationIdVectorType master_ids = Element::EquationIdVectorType(3,0); Element::EquationIdVectorType slave_ids = Element::EquationIdVectorType(3,0); }; TLS tls; block_for_each(rModelPart.MasterSlaveConstraints(), tls, [&](MasterSlaveConstraint& rConst, TLS& rTls){ rConst.EquationIdVector(rTls.slave_ids, rTls.master_ids, CurrentProcessInfo); for (std::size_t i = 0; i < rTls.slave_ids.size(); i++) { lock_array[rTls.slave_ids[i]].lock(); auto& row_indices = indices[rTls.slave_ids[i]]; row_indices.insert(rTls.slave_ids[i]); lock_array[rTls.slave_ids[i]].unlock(); } for (std::size_t i = 0; i < rTls.master_ids.size(); i++) { lock_array[rTls.master_ids[i]].lock(); auto& row_indices = indices[rTls.master_ids[i]]; row_indices.insert(rTls.master_ids[i]); lock_array[rTls.master_ids[i]].unlock(); } }); } //destroy locks lock_array = std::vector< LockObject >(); //count the row sizes unsigned int nnz = 0; for (unsigned int i = 0; i < indices.size(); i++) { nnz += indices[i].size(); } A = CompressedMatrixType(indices.size(), indices.size(), nnz); double* Avalues = A.value_data().begin(); std::size_t* Arow_indices = A.index1_data().begin(); std::size_t* Acol_indices = A.index2_data().begin(); //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(A.size1()); i++) { Arow_indices[i+1] = Arow_indices[i] + indices[i].size(); } IndexPartition<std::size_t>(A.size1()).for_each([&](std::size_t i){ const unsigned int row_begin = Arow_indices[i]; const unsigned int row_end = Arow_indices[i+1]; unsigned int k = row_begin; for (auto it = indices[i].begin(); it != indices[i].end(); it++) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } indices[i].clear(); //deallocating the memory std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); }); A.set_filled(indices.size()+1, nnz); Timer::Stop("MatrixStructure"); } void Assemble( TSystemMatrixType& A, TSystemVectorType& b, const LocalSystemMatrixType& LHS_Contribution, const LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; double& r_a = b[i_global]; const double& v_a = RHS_Contribution(i_local); AtomicAdd(r_a, v_a); AssembleRowContribution(A, LHS_Contribution, i_global, i_local, EquationId); } } //************************************************************************** void AssembleLHS( TSystemMatrixType& rA, const LocalSystemMatrixType& rLHSContribution, Element::EquationIdVectorType& rEquationId ) { const SizeType local_size = rLHSContribution.size1(); for (IndexType i_local = 0; i_local < local_size; i_local++) { const IndexType i_global = rEquationId[i_local]; AssembleRowContribution(rA, rLHSContribution, i_global, i_local, rEquationId); } } //************************************************************************** void AssembleRHS( TSystemVectorType& b, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId ) { unsigned int local_size = RHS_Contribution.size(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; // ASSEMBLING THE SYSTEM VECTOR double& b_value = b[i_global]; const double& rhs_value = RHS_Contribution[i_local]; AtomicAdd(b_value, rhs_value); } } inline void AssembleRowContribution(TSystemMatrixType& A, const Matrix& Alocal, const unsigned int i, const unsigned int i_local, Element::EquationIdVectorType& EquationId) { double* values_vector = A.value_data().begin(); std::size_t* index1_vector = A.index1_data().begin(); std::size_t* index2_vector = A.index2_data().begin(); size_t left_limit = index1_vector[i]; // size_t right_limit = index1_vector[i+1]; //find the first entry size_t last_pos = ForwardFind(EquationId[0],left_limit,index2_vector); size_t last_found = EquationId[0]; double& r_a = values_vector[last_pos]; const double& v_a = Alocal(i_local,0); AtomicAdd(r_a, v_a); //now find all of the other entries size_t pos = 0; for (unsigned int j=1; j<EquationId.size(); j++) { unsigned int id_to_find = EquationId[j]; if(id_to_find > last_found) { pos = ForwardFind(id_to_find,last_pos+1,index2_vector); } else if(id_to_find < last_found) { pos = BackwardFind(id_to_find,last_pos-1,index2_vector); } else { pos = last_pos; } double& r = values_vector[pos]; const double& v = Alocal(i_local,j); AtomicAdd(r, v); last_found = id_to_find; last_pos = pos; } } /** * @brief This method returns the scale norm considering for scaling the diagonal * @param rModelPart The problem model part * @param rA The LHS matrix * @return The scale norm */ double GetScaleNorm( ModelPart& rModelPart, TSystemMatrixType& rA ) { switch (mScalingDiagonal) { case SCALING_DIAGONAL::NO_SCALING: return 1.0; case SCALING_DIAGONAL::CONSIDER_PRESCRIBED_DIAGONAL: { const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); KRATOS_ERROR_IF_NOT(r_current_process_info.Has(BUILD_SCALE_FACTOR)) << "Scale factor not defined at process info" << std::endl; return r_current_process_info.GetValue(BUILD_SCALE_FACTOR); } case SCALING_DIAGONAL::CONSIDER_NORM_DIAGONAL: return GetDiagonalNorm(rA)/static_cast<double>(rA.size1()); case SCALING_DIAGONAL::CONSIDER_MAX_DIAGONAL: return GetMaxDiagonal(rA); // return TSparseSpace::TwoNorm(rA)/static_cast<double>(rA.size1()); default: return GetMaxDiagonal(rA); } } /** * @brief This method returns the diagonal norm considering for scaling the diagonal * @param rA The LHS matrix * @return The diagonal norm */ double GetDiagonalNorm(TSystemMatrixType& rA) { double diagonal_norm = 0.0; diagonal_norm = IndexPartition<std::size_t>(TSparseSpace::Size1(rA)).for_each<SumReduction<double>>([&](std::size_t Index){ return std::pow(rA(Index,Index), 2); }); return std::sqrt(diagonal_norm); } /** * @brief This method returns the diagonal max value * @param rA The LHS matrix * @return The diagonal max value */ double GetAveragevalueDiagonal(TSystemMatrixType& rA) { return 0.5 * (GetMaxDiagonal(rA) + GetMinDiagonal(rA)); } /** * @brief This method returns the diagonal max value * @param rA The LHS matrix * @return The diagonal max value */ double GetMaxDiagonal(TSystemMatrixType& rA) { // // NOTE: Reduction failing in MSVC // double max_diag = 0.0; // #pragma omp parallel for reduction(max:max_diag) // for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) { // max_diag = std::max(max_diag, std::abs(rA(i,i))); // } // return max_diag; // Creating a buffer for parallel vector fill const int num_threads = ParallelUtilities::GetNumThreads(); Vector max_vector(num_threads, 0.0); #pragma omp parallel for for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) { const int id = OpenMPUtils::ThisThread(); const double abs_value_ii = std::abs(rA(i,i)); if (abs_value_ii > max_vector[id]) max_vector[id] = abs_value_ii; } double max_diag = 0.0; for(int i = 0; i < num_threads; ++i) { max_diag = std::max(max_diag, max_vector[i]); } return max_diag; } /** * @brief This method returns the diagonal min value * @param rA The LHS matrix * @return The diagonal min value */ double GetMinDiagonal(TSystemMatrixType& rA) { // // NOTE: Reduction failing in MSVC // double min_diag = std::numeric_limits<double>::max(); // #pragma omp parallel for reduction(min:min_diag) // for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) { // min_diag = std::min(min_diag, std::abs(rA(i,i))); // } // return min_diag; // Creating a buffer for parallel vector fill const int num_threads = ParallelUtilities::GetNumThreads(); Vector min_vector(num_threads, std::numeric_limits<double>::max()); #pragma omp parallel for for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) { const int id = OpenMPUtils::ThisThread(); const double abs_value_ii = std::abs(rA(i,i)); if (abs_value_ii < min_vector[id]) min_vector[id] = abs_value_ii; } double min_diag = std::numeric_limits<double>::max(); for(int i = 0; i < num_threads; ++i) { min_diag = std::min(min_diag, min_vector[i]); } return min_diag; } /** * @brief This method assigns settings to member variables * @param ThisParameters Parameters that are assigned to the member variables */ void AssignSettings(const Parameters ThisParameters) override { BaseType::AssignSettings(ThisParameters); // Setting flags< const std::string& r_diagonal_values_for_dirichlet_dofs = ThisParameters["diagonal_values_for_dirichlet_dofs"].GetString(); std::set<std::string> available_options_for_diagonal = {"no_scaling","use_max_diagonal","use_diagonal_norm","defined_in_process_info"}; if (available_options_for_diagonal.find(r_diagonal_values_for_dirichlet_dofs) == available_options_for_diagonal.end()) { std::stringstream msg; msg << "Currently prescribed diagonal values for dirichlet dofs : " << r_diagonal_values_for_dirichlet_dofs << "\n"; msg << "Admissible values for the diagonal scaling are : no_scaling, use_max_diagonal, use_diagonal_norm, or defined_in_process_info" << "\n"; KRATOS_ERROR << msg.str() << std::endl; } // The first option will not consider any scaling (the diagonal values will be replaced with 1) if (r_diagonal_values_for_dirichlet_dofs == "no_scaling") { mScalingDiagonal = SCALING_DIAGONAL::NO_SCALING; } else if (r_diagonal_values_for_dirichlet_dofs == "use_max_diagonal") { mScalingDiagonal = SCALING_DIAGONAL::CONSIDER_MAX_DIAGONAL; } else if (r_diagonal_values_for_dirichlet_dofs == "use_diagonal_norm") { // On this case the norm of the diagonal will be considered mScalingDiagonal = SCALING_DIAGONAL::CONSIDER_NORM_DIAGONAL; } else { // Otherwise we will assume we impose a numerical value mScalingDiagonal = SCALING_DIAGONAL::CONSIDER_PRESCRIBED_DIAGONAL; } mOptions.Set(SILENT_WARNINGS, ThisParameters["silent_warnings"].GetBool()); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ inline void AddUnique(std::vector<std::size_t>& v, const std::size_t& candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } //****************************************************************************************** //****************************************************************************************** inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, DenseVector<unsigned int>& partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) { partitions[i] = partitions[i - 1] + partition_size; } } inline unsigned int ForwardFind(const unsigned int id_to_find, const unsigned int start, const size_t* index_vector) { unsigned int pos = start; while(id_to_find != index_vector[pos]) pos++; return pos; } inline unsigned int BackwardFind(const unsigned int id_to_find, const unsigned int start, const size_t* index_vector) { unsigned int pos = start; while(id_to_find != index_vector[pos]) pos--; return pos; } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedBlockBuilderAndSolver */ ///@} ///@name Type Definitions ///@{ // Here one should use the KRATOS_CREATE_LOCAL_FLAG, but it does not play nice with template parameters template<class TSparseSpace, class TDenseSpace, class TLinearSolver> const Kratos::Flags ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>::SILENT_WARNINGS(Kratos::Flags::Create(0)); ///@} } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
support_classes.h
#include <chrono> #include<set> #include "support_func.h" using namespace std; class StopW { std::chrono::steady_clock::time_point time_begin; public: StopW() { time_begin = std::chrono::steady_clock::now(); } float getElapsedTimeMicro() { std::chrono::steady_clock::time_point time_end = std::chrono::steady_clock::now(); return (std::chrono::duration_cast<std::chrono::microseconds>(time_end - time_begin).count()); } void reset() { time_begin = std::chrono::steady_clock::now(); } }; class KLgraph { public: int L; vector< vector <uint32_t> > longmatrixNN; void BuildByNumber(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric); void BuildByNumberCustom(int l, vector<float> dataset, size_t N, size_t d, size_t sqrtN, std::mt19937 random_gen, Metric *metric); void BuildByDist(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric); }; void KLgraph::BuildByNumber(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric){ L = l; vector<uint32_t> sloy; for (int i=0; i < N; ++i) { longmatrixNN.push_back(sloy); } vector<float> custom_prob; for (int i=0; i < N - 1; ++i) { custom_prob.push_back(1. / (i+ 1) ); } discrete_distribution<int> custom_distr (custom_prob.begin(), custom_prob.end()); #pragma omp parallel for for(int i=0; i < N; ++i) { int num; const float *point_i = dataset.data() + i*d; vector<Neighbor> chosen_neigs; set<Neighbor> chn_neigs; for (int j = 0; j < N; ++j) { if (i != j) { const float *point_j = dataset.data() + j * d; float dist = metric->Dist(point_i, point_j, d); Neighbor neig{j, dist}; chosen_neigs.push_back(neig); } } sort(chosen_neigs.begin(), chosen_neigs.end()); unordered_set <int> ll; while (ll.size() < L) { num = custom_distr(random_gen); ll.insert(num); } for (auto el : ll) { longmatrixNN[i].push_back(chosen_neigs[el].number); } } } void KLgraph::BuildByNumberCustom(int l, vector<float> dataset, size_t N, size_t d, size_t sqrtN, std::mt19937 random_gen, Metric *metric){ cout << sqrtN << ' ' << N << endl; L = l; vector<uint32_t> sloy; for (int i=0; i < N; ++i) { longmatrixNN.push_back(sloy); } vector<float> custom_prob; for (int i=0; i < sqrtN; ++i) { custom_prob.push_back(1. / (i+ 1) ); } discrete_distribution<int> custom_distr (custom_prob.begin(), custom_prob.end()); uniform_int_distribution<int> uniform_distr(0, N - 1); #pragma omp parallel for for(int i=0; i < N; ++i) { int num; const float *point_i = dataset.data() + i * d; vector<Neighbor> chosen_neigs; set<Neighbor> chn_neigs; while (chn_neigs.size() < sqrtN) { num = uniform_distr(random_gen); if (num != i) { const float *point_num = dataset.data() + num * d; float dist = metric->Dist(point_i, point_num, d); Neighbor neig{num, dist}; chn_neigs.insert(neig); } } for (auto el : chn_neigs) { chosen_neigs.push_back(el); } sort(chosen_neigs.begin(), chosen_neigs.end()); unordered_set <int> ll; while (ll.size() < L) { num = custom_distr(random_gen); ll.insert(num); } for (auto el : ll) { longmatrixNN[i].push_back(chosen_neigs[el].number); } } } void KLgraph::BuildByDist(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric){ L = l; float thr = 0.03; vector<uint32_t> sloy; for (int i=0; i < N; ++i) { longmatrixNN.push_back(sloy); } #pragma omp parallel for for(int i=0; i < N; ++i) { int num; const float *point_i = dataset.data() + i*d; vector<Neighbor> chosen_neigs; for (int j = 0; j < N; ++j) { if (i != j) { const float *point_j = dataset.data() + j * d; float dist = metric->Dist(point_i, point_j, d); if (dist > thr) { Neighbor neig{j, dist}; chosen_neigs.push_back(neig); } } } unordered_set <int> ll; vector<float> custom_prob; for (int j = 0; j < chosen_neigs.size(); ++j) { float dist_cur = chosen_neigs[j].dist; custom_prob.push_back(pow(pow(dist_cur, -1), d)); } discrete_distribution<int> custom_distr (custom_prob.begin(), custom_prob.end()); while (ll.size() < L) { num = custom_distr(random_gen); ll.insert(num); } for (auto el : ll) { longmatrixNN[i].push_back(chosen_neigs[el].number); } } }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// otherwise, it is a tag declaration. bool TemplateScope : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseUniqueStableNameExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator( llvm::function_ref<void(const Designation &)> CodeCompleteCB); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewtypeAttribute(IdentifierInfo &SwiftNewtype, SourceLocation SwiftNewtypeLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); void ParsePtrauthQualifier(ParsedAttributes &Attrs); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); NamedDecl * ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); /// Parse the given string as a type. /// /// This is a dangerous utility function currently employed only by API notes. /// It is not a general entry-point for safely parsing types from strings. /// /// \param typeStr The string to be parsed as a type. /// \param context The name of the context in which this string is being /// parsed, which will be used in diagnostics. /// \param includeLoc The location at which this parse was triggered. TypeResult parseTypeFromString(StringRef typeStr, StringRef context, SourceLocation includeLoc); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); ExprResult ParseBuiltinPtrauthTypeDiscriminator(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
test.c
#include <stdio.h> #include <omp.h> #pragma omp requires unified_shared_memory #include "../utilities/check.h" #include "../utilities/utilities.h" #define TRIALS (1) #define N (992) #define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;}) #define ZERO(X) ZERO_ARRAY(N, X) int main(void) { check_offloading(); double A[N], B[N], C[N], D[N], E[N]; int fail = 0; INIT(); // ************************** // Series 1: no dist_schedule // ************************** // // Test: #iterations == #teams // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // **************************** // Series 2: with dist_schedule // **************************** // // Test: #iterations == #teams, dist_schedule(1) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,1) num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations == #teams, dist_schedule(#iterations) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,512) num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations == #teams, dist_schedule(#iterations/10), variable chunk size // ZERO(A); int ten = 10; int chunkSize = 512/ten; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,chunkSize) num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams, dist_schedule(1) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,1) num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams, dist_schedule(#iterations) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,500) num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams, dist_schedule(#iterations/10), variable chunk size // ZERO(A); ten = 10; chunkSize = 500/ten; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,chunkSize) num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams, dist_schedule(1) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,1) num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams, dist_schedule(#iterations) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,123) num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams, dist_schedule(#iterations) // ZERO(A); ten = 10; chunkSize = 123/ten; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,chunkSize) num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // **************************** // Series 3: with ds attributes // **************************** // // Test: private // ZERO(A); ZERO(B); double p = 2.0, q = 4.0; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute private(p,q) num_teams(256) for(int i = 0 ; i < N ; i++) { p = 2; q = 3; A[i] += p; B[i] += q; } } for(int i = 0 ; i < N ; i++) { if (A[i] != TRIALS*2) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) TRIALS*2, A[i]); fail = 1; } if (B[i] != TRIALS*3) { printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) TRIALS*3, B[i]); fail = 1; } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: firstprivate // ZERO(A); ZERO(B); p = 2.0, q = 4.0; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute firstprivate(p,q) num_teams(64) for(int i = 0 ; i < 128 ; i++) { // 2 iterations for each team p += 3.0; // p and q are firstprivate to the team, and as such incremented twice (2 iterations per team) q += 7.0; A[i] += p; B[i] += q; } } for(int i = 0 ; i < 128 ; i++) { if (i % 2 == 0) { if (A[i] != (2.0+3.0)*TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]); fail = 1; } if (B[i] != (4.0+7.0)*TRIALS) { printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0)*TRIALS, B[i]); fail = 1; } } else { if (A[i] != (2.0+3.0*2)*TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0*2)*TRIALS, A[i]); fail = 1; } if (B[i] != (4.0+7.0*2)*TRIALS) { printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0*2)*TRIALS, B[i]); fail = 1; } } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: lastprivate // // requires array because scalar would be treated as implicit firstprivate by target int lastpriv[2] = {-1,-1}; #pragma omp target teams distribute lastprivate(lastpriv) num_teams(10) for(int i = 0 ; i < omp_get_num_teams() ; i++) { lastpriv[0] = omp_get_team_num(); } if(lastpriv[0] != 9) { printf("lastpriv value is %d and should have been %d\n", lastpriv[0], 9); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // *************************** // Series 4: with parallel for // *************************** // // Test: simple blocking loop // ZERO(A); ZERO(B); int nte = 32; int tl = 64; int blockSize = tl; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(nte) thread_limit(tl) for(int j = 0 ; j < 256 ; j += blockSize) { #pragma omp parallel for for(int i = j ; i < j+blockSize; i++) { A[i] += B[i] + C[i]; } } } for(int i = 0 ; i < 256 ; i++) { if (A[i] != TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]); fail = 1; } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: blocking loop where upper bound is not a multiple of tl*nte // ZERO(A); ZERO(B); nte = 32; tl = 64; blockSize = tl; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(nte) thread_limit(tl) for(int j = 0 ; j < 510 ; j += blockSize) { int ub = (j+blockSize < 510) ? (j+blockSize) : 512; #pragma omp parallel for for(int i = j ; i < ub; i++) { A[i] += B[i] + C[i]; } } } for(int i = 0 ; i < 256 ; i++) { if (A[i] != TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]); fail = 1; } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // ************************** // Series 5: collapse // ************************** // // Test: 2 loops // double * S = (double*)malloc(N*N*sizeof(double)); double * T = (double*)malloc(N*N*sizeof(double)); double * U = (double*)malloc(N*N*sizeof(double)); for (int i = 0 ; i < N ; i++) for (int j = 0 ; j < N ; j++) { S[i*N+j] = 0.0; T[i*N+j] = 1.0; U[i*N+j] = 2.0; } for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute collapse(2) map(tofrom:S[:N*N]), map(to:T[:N*N],U[:N*N]) num_teams(512) for (int i = 0 ; i < N ; i++) for (int j = 0 ; j < N ; j++) S[i*N+j] += T[i*N+j] + U[i*N+j]; // += 3 at each t } for (int i = 0 ; i < N ; i++) for (int j = 0 ; j < N ; j++) if (S[i*N+j] != TRIALS*3.0) { printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, S[i*N+j]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: 3 loops // int M = N/8; double * V = (double*)malloc(M*M*M*sizeof(double)); double * Z = (double*)malloc(M*M*M*sizeof(double)); for (int i = 0 ; i < M ; i++) for (int j = 0 ; j < M ; j++) for (int k = 0 ; k < M ; k++) { V[i*M*M+j*M+k] = 2.0; Z[i*M*M+j*M+k] = 3.0; } for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute collapse(3) map(tofrom:V[:M*M*M]), map(to:Z[:M*M*M]) num_teams(512) for (int i = 0 ; i < M ; i++) for (int j = 0 ; j < M ; j++) for (int k = 0 ; k < M ; k++) V[i*M*M+j*M+k] += Z[i*M*M+j*M+k]; // += 3 at each t } for (int i = 0 ; i < M ; i++) for (int j = 0 ; j < M ; j++) for (int k = 0 ; k < M ; k++) if (V[i*M*M+j*M+k] != 2.0+TRIALS*3.0) { printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, V[i*M*M+j*M+k]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); return 0; }
draw.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD RRRR AAA W W % % D D R R A A W W % % D D RRRR AAAAA W W W % % D D R RN A A WW WW % % DDDD R R A A W W % % % % % % MagickCore Image Drawing Methods % % % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion", % Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent % (www.appligent.com) contributed the dash pattern, linecap stroking % algorithm, and minor rendering improvements. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define BezierQuantum 200 #define PrimitiveExtentPad 2048 #define MaxBezierCoordinates 6291456 #define ThrowPointExpectedException(token,exception) \ { \ (void) ThrowMagickException(exception,GetMagickModule(),DrawError, \ "NonconformingDrawingPrimitiveDefinition","`%s'",token); \ status=MagickFalse; \ break; \ } /* Typedef declarations. */ typedef struct _EdgeInfo { SegmentInfo bounds; double scanline; PointInfo *points; size_t number_points; ssize_t direction; MagickBooleanType ghostline; size_t highwater; } EdgeInfo; typedef struct _ElementInfo { double cx, cy, major, minor, angle; } ElementInfo; typedef struct _MVGInfo { PrimitiveInfo **primitive_info; size_t *extent; ssize_t offset; PointInfo point; ExceptionInfo *exception; } MVGInfo; typedef struct _PolygonInfo { EdgeInfo *edges; size_t number_edges; } PolygonInfo; typedef enum { MoveToCode, OpenCode, GhostlineCode, LineToCode, EndCode } PathInfoCode; typedef struct _PathInfo { PointInfo point; PathInfoCode code; } PathInfo; /* Forward declarations. */ static Image *DrawClippingMask(Image *,const DrawInfo *,const char *,const char *, ExceptionInfo *); static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *, ExceptionInfo *), RenderMVGContent(Image *,const DrawInfo *,const size_t,ExceptionInfo *), TraceArc(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(MVGInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(MVGInfo *,const size_t), TraceCircle(MVGInfo *,const PointInfo,const PointInfo), TraceEllipse(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(MVGInfo *,const PointInfo,const PointInfo,PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); static PrimitiveInfo *TraceStrokePolygon(const Image *,const DrawInfo *,const PrimitiveInfo *); static size_t TracePath(MVGInfo *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireDrawInfo() returns a DrawInfo structure properly initialized. % % The format of the AcquireDrawInfo method is: % % DrawInfo *AcquireDrawInfo(void) % */ MagickExport DrawInfo *AcquireDrawInfo(void) { DrawInfo *draw_info; draw_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*draw_info)); GetDrawInfo((ImageInfo *) NULL,draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneDrawInfo() makes a copy of the given draw_info structure. If NULL % is specified, a new DrawInfo structure is created initialized to default % values. % % The format of the CloneDrawInfo method is: % % DrawInfo *CloneDrawInfo(const ImageInfo *image_info, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info. % % o draw_info: the draw info. % */ MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; ExceptionInfo *exception; clone_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (draw_info->id != (char *) NULL) (void) CloneString(&clone_info->id,draw_info->id); if (draw_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->compliance=draw_info->compliance; clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, exception); if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { register ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memset(clone_info->dash_pattern,0,(size_t) (2*x+2)* sizeof(*clone_info->dash_pattern)); (void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->gradient.stops,draw_info->gradient.stops, (size_t) number_stops*sizeof(*clone_info->gradient.stops)); } clone_info->bounds=draw_info->bounds; clone_info->fill_alpha=draw_info->fill_alpha; clone_info->stroke_alpha=draw_info->stroke_alpha; clone_info->element_reference=draw_info->element_reference; clone_info->clip_path=draw_info->clip_path; clone_info->clip_units=draw_info->clip_units; if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0, MagickTrue,exception); if (draw_info->composite_mask != (Image *) NULL) clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0, MagickTrue,exception); clone_info->render=draw_info->render; clone_info->debug=IsEventLogging(); exception=DestroyExceptionInfo(exception); return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P a t h T o P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPathToPolygon() converts a path to the more efficient sorted % rendering form. % % The format of the ConvertPathToPolygon method is: % % PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info) % % A description of each parameter follows: % % o Method ConvertPathToPolygon returns the path in a more efficient sorted % rendering form of type PolygonInfo. % % o draw_info: Specifies a pointer to an DrawInfo structure. % % o path_info: Specifies a pointer to an PathInfo structure. % % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int DrawCompareEdges(const void *p_edge,const void *q_edge) { #define DrawCompareEdge(p,q) \ { \ if (((p)-(q)) < 0.0) \ return(-1); \ if (((p)-(q)) > 0.0) \ return(1); \ } register const PointInfo *p, *q; /* Edge sorting for right-handed coordinate system. */ p=((const EdgeInfo *) p_edge)->points; q=((const EdgeInfo *) q_edge)->points; DrawCompareEdge(p[0].y,q[0].y); DrawCompareEdge(p[0].x,q[0].x); DrawCompareEdge((p[1].x-p[0].x)*(q[1].y-q[0].y),(p[1].y-p[0].y)* (q[1].x-q[0].x)); DrawCompareEdge(p[1].y,q[1].y); DrawCompareEdge(p[1].x,q[1].x); return(0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { register EdgeInfo *p; register ssize_t i, j; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge"); p=polygon_info->edges; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { (void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:", (double) i); (void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s", p->direction != MagickFalse ? "down" : "up"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s", p->ghostline != MagickFalse ? "transparent" : "opaque"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1, p->bounds.x2,p->bounds.y2); for (j=0; j < (ssize_t) p->number_points; j++) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g", p->points[j].x,p->points[j].y); p++; } (void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge"); } static void ReversePoints(PointInfo *points,const size_t number_points) { PointInfo point; register ssize_t i; for (i=0; i < (ssize_t) (number_points >> 1); i++) { point=points[i]; points[i]=points[number_points-(i+1)]; points[number_points-(i+1)]=point; } } static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; register ssize_t i, n; MagickBooleanType ghostline; size_t edge, number_edges, number_points; /* Convert a path to the more efficient sorted rendering form. */ polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info)); if (polygon_info == (PolygonInfo *) NULL) return((PolygonInfo *) NULL); number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); (void) memset(polygon_info->edges,0,number_edges* sizeof(*polygon_info->edges)); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) memset(&point,0,sizeof(point)); (void) memset(&bounds,0,sizeof(bounds)); polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=0.0; polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) direction; polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->number_edges=0; for (i=0; path_info[i].code != EndCode; i++) { if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) || (path_info[i].code == GhostlineCode)) { /* Move to. */ if ((points != (PointInfo *) NULL) && (n >= 2)) { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse; point=path_info[i].point; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; direction=0; n=1; continue; } /* Line to. */ next_direction=((path_info[i].point.y > point.y) || ((fabs(path_info[i].point.y-point.y) < MagickEpsilon) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((points != (PointInfo *) NULL) && (direction != 0) && (direction != next_direction)) { /* New edge. */ point=points[n-1]; if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); n=1; ghostline=MagickFalse; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; edge++; } direction=next_direction; if (points == (PointInfo *) NULL) continue; if (n == (ssize_t) number_points) { number_points<<=1; points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } point=path_info[i].point; points[n]=point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.x > bounds.x2) bounds.x2=point.x; n++; } if (points != (PointInfo *) NULL) { if (n < 2) points=(PointInfo *) RelinquishMagickMemory(points); else { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; ghostline=MagickFalse; edge++; } } polygon_info->number_edges=edge; qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),DrawCompareEdges); if (IsEventLogging() != MagickFalse) LogPolygonInfo(polygon_info); return(polygon_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P r i m i t i v e T o P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector % path structure. % % The format of the ConvertPrimitiveToPath method is: % % PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o Method ConvertPrimitiveToPath returns a vector path structure of type % PathInfo. % % o draw_info: a structure of type DrawInfo. % % o primitive_info: Specifies a pointer to an PrimitiveInfo structure. % % */ static void LogPathInfo(const PathInfo *path_info) { register const PathInfo *p; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path"); for (p=path_info; p->code != EndCode; p++) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ? "moveto ghostline" : p->code == OpenCode ? "moveto open" : p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" : "?"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path"); } static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info) { MagickBooleanType closed_subpath; PathInfo *path_info; PathInfoCode code; PointInfo p, q; register ssize_t i, n; ssize_t coordinates, start; /* Converts a PrimitiveInfo structure into a vector path structure. */ switch (primitive_info->primitive) { case AlphaPrimitive: case ColorPrimitive: case ImagePrimitive: case PointPrimitive: case TextPrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (3UL*i+1UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) return((PathInfo *) NULL); coordinates=0; closed_subpath=MagickFalse; n=0; p.x=(-1.0); p.y=(-1.0); q.x=(-1.0); q.y=(-1.0); start=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { code=LineToCode; if (coordinates <= 0) { /* New subpath. */ coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; closed_subpath=primitive_info[i].closed_subpath; } coordinates--; if ((code == MoveToCode) || (coordinates <= 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon)) { /* Eliminate duplicate points. */ path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; /* next point in current subpath */ if (closed_subpath != MagickFalse) { closed_subpath=MagickFalse; continue; } /* Mark the p point as open if the subpath is not closed. */ path_info[start].code=OpenCode; path_info[n].code=GhostlineCode; path_info[n].point=primitive_info[i].point; n++; path_info[n].code=LineToCode; path_info[n].point=p; n++; } path_info[n].code=EndCode; path_info[n].point.x=0.0; path_info[n].point.y=0.0; if (IsEventLogging() != MagickFalse) LogPathInfo(path_info); path_info=(PathInfo *) ResizeQuantumMemory(path_info,(size_t) (n+1), sizeof(*path_info)); return(path_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyDrawInfo() deallocates memory associated with an DrawInfo structure. % % The format of the DestroyDrawInfo method is: % % DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) % % A description of each parameter follows: % % o draw_info: the draw info. % */ MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) { assert(draw_info != (DrawInfo *) NULL); if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info->signature == MagickCoreSignature); if (draw_info->id != (char *) NULL) draw_info->id=DestroyString(draw_info->id); if (draw_info->primitive != (char *) NULL) draw_info->primitive=DestroyString(draw_info->primitive); if (draw_info->text != (char *) NULL) draw_info->text=DestroyString(draw_info->text); if (draw_info->geometry != (char *) NULL) draw_info->geometry=DestroyString(draw_info->geometry); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern); if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); if (draw_info->metrics != (char *) NULL) draw_info->metrics=DestroyString(draw_info->metrics); if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); if (draw_info->encoding != (char *) NULL) draw_info->encoding=DestroyString(draw_info->encoding); if (draw_info->density != (char *) NULL) draw_info->density=DestroyString(draw_info->density); if (draw_info->server_name != (char *) NULL) draw_info->server_name=(char *) RelinquishMagickMemory(draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) draw_info->dash_pattern=(double *) RelinquishMagickMemory( draw_info->dash_pattern); if (draw_info->gradient.stops != (StopInfo *) NULL) draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory( draw_info->gradient.stops); if (draw_info->clip_mask != (char *) NULL) draw_info->clip_mask=DestroyString(draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) draw_info->clipping_mask=DestroyImage(draw_info->clipping_mask); if (draw_info->composite_mask != (Image *) NULL) draw_info->composite_mask=DestroyImage(draw_info->composite_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y E d g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyEdge() destroys the specified polygon edge. % % The format of the DestroyEdge method is: % % ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % % o edge: the polygon edge number to destroy. % */ static size_t DestroyEdge(PolygonInfo *polygon_info, const size_t edge) { assert(edge < polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < polygon_info->number_edges) (void) memmove(polygon_info->edges+edge,polygon_info->edges+edge+1, (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges)); return(polygon_info->number_edges); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P o l y g o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPolygonInfo() destroys the PolygonInfo data structure. % % The format of the DestroyPolygonInfo method is: % % PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { register ssize_t i; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) polygon_info->edges[i].points=(PointInfo *) RelinquishMagickMemory(polygon_info->edges[i].points); polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges); return((PolygonInfo *) RelinquishMagickMemory(polygon_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w A f f i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAffineImage() composites the source over the destination image as % dictated by the affine transform. % % The format of the DrawAffineImage method is: % % MagickBooleanType DrawAffineImage(Image *image,const Image *source, % const AffineMatrix *affine,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % % o exception: return any errors or warnings in this structure. % */ static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; register double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= MagickEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -MagickEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= MagickEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -MagickEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine) { AffineMatrix inverse_affine; double determinant; determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx* affine->ry); inverse_affine.sx=determinant*affine->sy; inverse_affine.rx=determinant*(-affine->rx); inverse_affine.ry=determinant*(-affine->ry); inverse_affine.sy=determinant*affine->sx; inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty* inverse_affine.ry; inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty* inverse_affine.sy; return(inverse_affine); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine,ExceptionInfo *exception) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; MagickBooleanType status; PixelInfo zero; PointInfo extent[4], min, max; register ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickCoreSignature); assert(affine != (AffineMatrix *) NULL); extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) source->columns-1.0; extent[1].y=0.0; extent[2].x=(double) source->columns-1.0; extent[2].y=(double) source->rows-1.0; extent[3].x=0.0; extent[3].y=(double) source->rows-1.0; for (i=0; i < 4; i++) { PointInfo point; point=extent[i]; extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx; extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } /* Affine transform image. */ if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; edge.x1=MagickMax(min.x,0.0); edge.y1=MagickMax(min.y,0.0); edge.x2=MagickMin(max.x,(double) image->columns-1.0); edge.y2=MagickMin(max.y,(double) image->rows-1.0); inverse_affine=InverseAffineMatrix(affine); GetPixelInfo(image,&zero); start=(ssize_t) ceil(edge.y1-0.5); stop=(ssize_t) floor(edge.y2+0.5); source_view=AcquireVirtualCacheView(source,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source,image,stop-start,1) #endif for (y=start; y <= stop; y++) { PixelInfo composite, pixel; PointInfo point; register ssize_t x; register Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1- 0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1), 1,exception); if (q == (Quantum *) NULL) continue; pixel=zero; composite=zero; x_offset=0; for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++) { point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+ inverse_affine.tx; point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+ inverse_affine.ty; status=InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel, point.x,point.y,&pixel,exception); if (status == MagickFalse) break; GetPixelInfoPixel(image,q,&composite); CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha, &composite); SetPixelViaPixelInfo(image,&composite,q); x_offset++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w B o u n d i n g R e c t a n g l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawBoundingRectangles() draws the bounding rectangles on the image. This % is only useful for developers debugging the rendering algorithm. % % The format of the DrawBoundingRectangles method is: % % MagickBooleanType DrawBoundingRectangles(Image *image, % const DrawInfo *draw_info,PolygonInfo *polygon_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o polygon_info: Specifies a pointer to a PolygonInfo structure. % % o exception: return any errors or warnings in this structure. % */ static inline double SaneStrokeWidth(const Image *image, const DrawInfo *draw_info) { return(MagickMin((double) draw_info->stroke_width, (2.0*sqrt(2.0)+MagickEpsilon)*MagickMax(image->columns,image->rows))); } static MagickBooleanType DrawBoundingRectangles(Image *image, const DrawInfo *draw_info,const PolygonInfo *polygon_info, ExceptionInfo *exception) { double mid; DrawInfo *clone_info; MagickStatusType status; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; register ssize_t i; SegmentInfo bounds; ssize_t coordinates; (void) memset(primitive_info,0,sizeof(primitive_info)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); status=QueryColorCompliance("#000F",AllCompliance,&clone_info->fill, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } resolution.x=96.0; resolution.y=96.0; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) resolution.y=resolution.x; } mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)* SaneStrokeWidth(image,clone_info)/2.0; bounds.x1=0.0; bounds.y1=0.0; bounds.x2=0.0; bounds.y2=0.0; if (polygon_info != (PolygonInfo *) NULL) { bounds=polygon_info->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1) bounds.x1=polygon_info->edges[i].bounds.x1; if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1) bounds.y1=polygon_info->edges[i].bounds.y1; if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2) bounds.x2=polygon_info->edges[i].bounds.x2; if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2) bounds.y2=polygon_info->edges[i].bounds.y2; } bounds.x1-=mid; bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=mid; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=mid; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=mid; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows ? (double) image->rows-1 : bounds.y2; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].direction != 0) status=QueryColorCompliance("#f00",AllCompliance,&clone_info->stroke, exception); else status=QueryColorCompliance("#0f0",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) break; start.x=(double) (polygon_info->edges[i].bounds.x1-mid); start.y=(double) (polygon_info->edges[i].bounds.y1-mid); end.x=(double) (polygon_info->edges[i].bounds.x2+mid); end.y=(double) (polygon_info->edges[i].bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); if (status == MagickFalse) break; } if (i < (ssize_t) polygon_info->number_edges) { clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } } status=QueryColorCompliance("#00f",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } start.x=(double) (bounds.x1-mid); start.y=(double) (bounds.y1-mid); end.x=(double) (bounds.x2+mid); end.y=(double) (bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClipPath() draws the clip path on the image mask. % % The format of the DrawClipPath method is: % % MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info, % const char *id,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *id,ExceptionInfo *exception) { const char *clip_path; Image *clipping_mask; MagickBooleanType status; clip_path=GetImageArtifact(image,id); if (clip_path == (const char *) NULL) return(MagickFalse); clipping_mask=DrawClippingMask(image,draw_info,draw_info->clip_mask,clip_path, exception); if (clipping_mask == (Image *) NULL) return(MagickFalse); status=SetImageMask(image,WritePixelMask,clipping_mask,exception); clipping_mask=DestroyImage(clipping_mask); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p p i n g M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClippingMask() draws the clip path and returns it as an image clipping % mask. % % The format of the DrawClippingMask method is: % % Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *clip_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o clip_path: the clip path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, const char *id,const char *clip_path,ExceptionInfo *exception) { DrawInfo *clone_info; Image *clip_mask, *separate_mask; MagickStatusType status; /* Draw a clip path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); clip_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(clip_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(clip_mask)); status=SetImageMask(clip_mask,WritePixelMask,(Image *) NULL,exception); status=QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; clip_mask->background_color.alpha_trait=BlendPixelTrait; status=SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,clip_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); if (clone_info->clip_mask != (char *) NULL) clone_info->clip_mask=DestroyString(clone_info->clip_mask); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; clone_info->clip_path=MagickTrue; status=RenderMVGContent(clip_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(clip_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { clip_mask=DestroyImage(clip_mask); clip_mask=separate_mask; status=NegateImage(clip_mask,MagickFalse,exception); if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); } if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(clip_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C o m p o s i t e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawCompositeMask() draws the mask path and returns it as an image mask. % % The format of the DrawCompositeMask method is: % % Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *mask_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the mask path id. % % o mask_path: the mask path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, const char *id,const char *mask_path,ExceptionInfo *exception) { Image *composite_mask, *separate_mask; DrawInfo *clone_info; MagickStatusType status; /* Draw a mask path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); composite_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(composite_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(composite_mask)); status=SetImageMask(composite_mask,CompositePixelMask,(Image *) NULL, exception); status=QueryColorCompliance("#0000",AllCompliance, &composite_mask->background_color,exception); composite_mask->background_color.alpha=(MagickRealType) TransparentAlpha; composite_mask->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(composite_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin mask-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,mask_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; status=RenderMVGContent(composite_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(composite_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { composite_mask=DestroyImage(composite_mask); composite_mask=separate_mask; status=NegateImage(composite_mask,MagickFalse,exception); if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); } if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end mask-path"); return(composite_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w D a s h P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the % image while respecting the dash offset and dash pattern attributes. % % The format of the DrawDashPolygon method is: % % MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { double length, maximum_length, offset, scale, total_length; DrawInfo *clone_info; MagickStatusType status; PrimitiveInfo *dash_polygon; register double dx, dy; register ssize_t i; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+32UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); (void) memset(dash_polygon,0,(2UL*number_vertices+32UL)* sizeof(*dash_polygon)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*draw_info->dash_pattern[0]; offset=fabs(draw_info->dash_offset) >= MagickEpsilon ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*draw_info->dash_pattern[n]; continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot(dx,dy); if (maximum_length > MaxBezierCoordinates) break; if (fabs(length) < MagickEpsilon) { if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); j=1; } else { if ((j+1) > (ssize_t) number_vertices) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); if (status == MagickFalse) break; } if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((status != MagickFalse) && (total_length < maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGradientImage() draws a linear gradient on the image. % % The format of the DrawGradientImage method is: % % MagickBooleanType DrawGradientImage(Image *image, % const DrawInfo *draw_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline double GetStopColorOffset(const GradientInfo *gradient, const ssize_t x,const ssize_t y) { switch (gradient->type) { case UndefinedGradient: case LinearGradient: { double gamma, length, offset, scale; PointInfo p, q; const SegmentInfo *gradient_vector; gradient_vector=(&gradient->gradient_vector); p.x=gradient_vector->x2-gradient_vector->x1; p.y=gradient_vector->y2-gradient_vector->y1; q.x=(double) x-gradient_vector->x1; q.y=(double) y-gradient_vector->y1; length=sqrt(q.x*q.x+q.y*q.y); gamma=sqrt(p.x*p.x+p.y*p.y)*length; gamma=PerceptibleReciprocal(gamma); scale=p.x*q.x+p.y*q.y; offset=gamma*scale*length; return(offset); } case RadialGradient: { PointInfo v; if (gradient->spread == RepeatSpread) { v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; return(sqrt(v.x*v.x+v.y*v.y)); } v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians( gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.x); v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.y); return(sqrt(v.x*v.x+v.y*v.y)); } } return(0.0); } static int StopInfoCompare(const void *x,const void *y) { StopInfo *stop_1, *stop_2; stop_1=(StopInfo *) x; stop_2=(StopInfo *) y; if (stop_1->offset > stop_2->offset) return(1); if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon) return(0); return(-1); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; MagickBooleanType status; PixelInfo zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo), StopInfoCompare); gradient_vector=(&gradient->gradient_vector); point.x=gradient_vector->x2-gradient_vector->x1; point.y=gradient_vector->y2-gradient_vector->y1; length=sqrt(point.x*point.x+point.y*point.y); bounding_box=gradient->bounding_box; status=MagickTrue; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,bounding_box.height-bounding_box.y,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { PixelInfo composite, pixel; double alpha, offset; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t j; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { GetPixelInfoPixel(image,q,&pixel); switch (gradient->spread) { case UndefinedSpread: case PadSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if ((offset < 0.0) || (i == 0)) composite=gradient->stops[0].color; else if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops)) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case ReflectSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } if (offset < 0.0) offset=(-offset); if ((ssize_t) fmod(offset,2.0) == 0) offset=fmod(offset,1.0); else offset=1.0-fmod(offset,1.0); for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { MagickBooleanType antialias; double repeat; antialias=MagickFalse; repeat=0.0; if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type == LinearGradient) { repeat=fmod(offset,length); if (repeat < 0.0) repeat=length-fmod(-repeat,length); else repeat=fmod(offset,length); antialias=(repeat < length) && ((repeat+1.0) > length) ? MagickTrue : MagickFalse; offset=PerceptibleReciprocal(length)*repeat; } else { repeat=fmod(offset,gradient->radius); if (repeat < 0.0) repeat=gradient->radius-fmod(-repeat,gradient->radius); else repeat=fmod(offset,gradient->radius); antialias=repeat+1.0 > gradient->radius ? MagickTrue : MagickFalse; offset=repeat/gradient->radius; } } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); if (antialias != MagickFalse) { if (gradient->type == LinearGradient) alpha=length-repeat; else alpha=gradient->radius-repeat; i=0; j=(ssize_t) gradient->number_stops-1L; } CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha, &pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawImage() draws a graphic primitive on your image. The primitive % may be represented as a string or filename. Precede the filename with an % "at" sign (@) and the contents of the file are drawn on the image. You % can affect how text is drawn by setting one or more members of the draw % info structure. % % The format of the DrawImage method is: % % MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CheckPrimitiveExtent(MVGInfo *mvg_info, const size_t pad) { double extent; size_t quantum; /* Check if there is enough storage for drawing pimitives. */ extent=(double) mvg_info->offset+pad+PrimitiveExtentPad; quantum=sizeof(**mvg_info->primitive_info); if (((extent*quantum) < (double) SSIZE_MAX) && ((extent*quantum) < (double) GetMaxMemoryRequest())) { if (extent <= (double) *mvg_info->extent) return(MagickTrue); *mvg_info->primitive_info=(PrimitiveInfo *) ResizeQuantumMemory( *mvg_info->primitive_info,(size_t) extent,quantum); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) { register ssize_t i; *mvg_info->extent=(size_t) extent; for (i=mvg_info->offset+1; i < (ssize_t) extent; i++) (*mvg_info->primitive_info)[i].primitive=UndefinedPrimitive; return(MagickTrue); } } /* Reallocation failed, allocate a primitive to facilitate unwinding. */ (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) *mvg_info->primitive_info=(PrimitiveInfo *) RelinquishMagickMemory( *mvg_info->primitive_info); *mvg_info->primitive_info=(PrimitiveInfo *) AcquireCriticalMemory( PrimitiveExtentPad*quantum); (void) memset(*mvg_info->primitive_info,0,PrimitiveExtentPad*quantum); *mvg_info->extent=1; return(MagickFalse); } MagickExport int MVGMacroCompare(const void *target,const void *source) { const char *p, *q; p=(const char *) target; q=(const char *) source; return(strcmp(p,q)); } static SplayTreeInfo *GetMVGMacros(const char *primitive) { char *macro, *token; const char *q; size_t extent; SplayTreeInfo *macros; /* Scan graphic primitives for definitions and classes. */ if (primitive == (const char *) NULL) return((SplayTreeInfo *) NULL); macros=NewSplayTree(MVGMacroCompare,RelinquishMagickMemory, RelinquishMagickMemory); macro=AcquireString(primitive); token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; for (q=primitive; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare("push",token) == 0) { register const char *end, *start; (void) GetNextToken(q,&q,extent,token); if (*q == '"') { char name[MagickPathExtent]; const char *p; ssize_t n; /* Named macro (e.g. push graphic-context "wheel"). */ (void) GetNextToken(q,&q,extent,token); start=q; end=q; (void) CopyMagickString(name,token,MagickPathExtent); n=1; for (p=q; *p != '\0'; ) { if (GetNextToken(p,&p,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare(token,"pop") == 0) { end=p-strlen(token)-1; n--; } if (LocaleCompare(token,"push") == 0) n++; if ((n == 0) && (end > start)) { /* Extract macro. */ (void) GetNextToken(p,&p,extent,token); (void) CopyMagickString(macro,start,(size_t) (end-start)); (void) AddValueToSplayTree(macros,ConstantString(name), ConstantString(macro)); break; } } } } } token=DestroyString(token); macro=DestroyString(macro); return(macros); } static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=StringToDouble(point,&p); return((fabs(value) < MagickEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static inline MagickBooleanType TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->closed_subpath=MagickFalse; primitive_info->point=point; return(MagickTrue); } static MagickBooleanType RenderMVGContent(Image *image, const DrawInfo *draw_info,const size_t depth,ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], *next_token, pattern[MagickPathExtent], *primitive, *token; const char *q; double angle, coordinates, cursor, factor, primitive_extent; DrawInfo *clone_info, **graphic_context; MagickBooleanType proceed; MagickStatusType status; MVGInfo mvg_info; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t extent, number_points, number_stops; SplayTreeInfo *macros; ssize_t defsDepth, j, k, n, symbolDepth; StopInfo *stops; TypeMetric metrics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (depth > MagickMaxRecursionDepth) ThrowBinaryException(DrawError,"VectorGraphicsNestedTooDeeply", image->filename); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) { status=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); if (status == MagickFalse) return(MagickFalse); } if ((*draw_info->primitive == '@') && (strlen(draw_info->primitive) > 1) && (*(draw_info->primitive+1) != '-') && (depth == 0)) primitive=FileToString(draw_info->primitive+1,~0UL,exception); else primitive=AcquireString(draw_info->primitive); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"mvg:vector-graphics",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=PrimitiveExtentPad; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(primitive_info,0,(size_t) number_points* sizeof(*primitive_info)); (void) memset(&mvg_info,0,sizeof(mvg_info)); mvg_info.primitive_info=(&primitive_info); mvg_info.extent=(&number_points); mvg_info.exception=exception; graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; defsDepth=0; symbolDepth=0; cursor=0.0; macros=GetMVGMacros(primitive); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ if (GetNextToken(q,&q,MagickPathExtent,keyword) < 1) break; if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); *token='\0'; switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("class",keyword) == 0) { const char *mvg_class; (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } if (LocaleCompare(token,graphic_context[n]->id) == 0) break; mvg_class=(const char *) GetValueFromSplayTree(macros,token); if (mvg_class != (const char *) NULL) { char *elements; ssize_t offset; /* Inject class elements in stream. */ offset=(ssize_t) (p-primitive); elements=AcquireString(primitive); elements[offset]='\0'; (void) ConcatenateString(&elements,mvg_class); (void) ConcatenateString(&elements,"\n"); (void) ConcatenateString(&elements,q); primitive=DestroyString(primitive); primitive=elements; q=primitive+offset; } break; } if (LocaleCompare("clip-path",keyword) == 0) { const char *clip_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } (void) CloneString(&graphic_context[n]->clip_mask,token); clip_path=(const char *) GetValueFromSplayTree(macros,token); if (clip_path != (const char *) NULL) { if (graphic_context[n]->clipping_mask != (Image *) NULL) graphic_context[n]->clipping_mask= DestroyImage(graphic_context[n]->clipping_mask); graphic_context[n]->clipping_mask=DrawClippingMask(image, graphic_context[n],token,clip_path,exception); if (graphic_context[n]->compliance != SVGCompliance) { clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image, graphic_context[n]->clip_mask,clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } } break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; (void) GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } if (LocaleCompare("compliance",keyword) == 0) { /* MVG compliance associates a clipping mask with an image; SVG compliance associates a clipping mask with a graphics context. */ (void) GetNextToken(q,&q,extent,token); graphic_context[n]->compliance=(ComplianceType) ParseCommandOption( MagickComplianceOptions,MagickFalse,token); break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; (void) GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) { status=MagickFalse; break; } graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; (void) GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (graphic_context[n]->fill_alpha != OpaqueAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); graphic_context[n]->fill_alpha*=opacity; if (graphic_context[n]->fill.alpha != TransparentAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; else graphic_context[n]->fill.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory( graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; (void) GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) { status=MagickFalse; break; } graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; (void) GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) { status=MagickFalse; break; } graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; (void) GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; (void) GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) { status=MagickFalse; break; } graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; (void) GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) { status=MagickFalse; break; } graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("letter-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); clone_info->text=AcquireString(" "); status&=GetTypeMetrics(image,clone_info,&metrics,exception); graphic_context[n]->kerning=metrics.width* StringToDouble(token,&next_token); clone_info=DestroyDrawInfo(clone_info); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("line",keyword) == 0) { primitive_type=LinePrimitive; break; } status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("mask",keyword) == 0) { const char *mask_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); mask_path=(const char *) GetValueFromSplayTree(macros,token); if (mask_path != (const char *) NULL) { if (graphic_context[n]->composite_mask != (Image *) NULL) graphic_context[n]->composite_mask= DestroyImage(graphic_context[n]->composite_mask); graphic_context[n]->composite_mask=DrawCompositeMask(image, graphic_context[n],token,mask_path,exception); if (graphic_context[n]->compliance != SVGCompliance) status=SetImageMask(image,CompositePixelMask, graphic_context[n]->composite_mask,exception); } break; } break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); graphic_context[n]->fill_alpha*=opacity; graphic_context[n]->stroke_alpha*=opacity; break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) break; if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) { defsDepth--; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); status=MagickFalse; n=0; break; } if ((graphic_context[n]->clip_mask != (char *) NULL) && (graphic_context[n]->compliance != SVGCompliance)) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) status=SetImageMask(image,WritePixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("mask",token) == 0) break; if (LocaleCompare("pattern",token) == 0) break; if (LocaleCompare("symbol",token) == 0) { symbolDepth--; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) { /* Class context. */ for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"class") != 0) continue; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("clip-path",token) == 0) { (void) GetNextToken(q,&q,extent,token); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("defs",token) == 0) { defsDepth++; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (LocaleCompare(type,"radial") == 0) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); if (*q == '"') { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->id,token); } break; } if (LocaleCompare("mask",token) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo bounds; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); bounds.x=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.y=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.width=(size_t) floor(StringToDouble(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.height=(size_t) floor(StringToDouble(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double) bounds.height,(double) bounds.x,(double) bounds.y); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("symbol",token) == 0) { symbolDepth++; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("skewX",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; (void) GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; stops[number_stops-1].offset=factor*StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (graphic_context[n]->stroke_alpha != OpaqueAlpha) graphic_context[n]->stroke.alpha= graphic_context[n]->stroke_alpha; } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); status=MagickFalse; break; } (void) memset(graphic_context[n]->dash_pattern,0,(size_t) (2*x+2)*sizeof(*graphic_context[n]->dash_pattern)); for (j=0; j < x; j++) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; (void) GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) { status=MagickFalse; break; } graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; (void) GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) { status=MagickFalse; break; } graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); graphic_context[n]->stroke_alpha*=opacity; if (graphic_context[n]->stroke.alpha != TransparentAlpha) graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha; else graphic_context[n]->stroke.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("stroke-width",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; graphic_context[n]->stroke_width=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); cursor=0.0; break; } status=MagickFalse; break; } case 'u': case 'U': { if (LocaleCompare("use",keyword) == 0) { const char *use; /* Get a macro from the MVG document, and "use" it here. */ (void) GetNextToken(q,&q,extent,token); use=(const char *) GetValueFromSplayTree(macros,token); if (use != (const char *) NULL) { clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); (void) CloneString(&clone_info->primitive,use); status=RenderMVGContent(image,clone_info,depth+1,exception); clone_info=DestroyDrawInfo(clone_info); } break; } break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'w': case 'W': { if (LocaleCompare("word-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= MagickEpsilon) || (fabs(affine.rx) >= MagickEpsilon) || (fabs(affine.ry) >= MagickEpsilon) || (fabs(affine.sy-1.0) >= MagickEpsilon) || (fabs(affine.tx) >= MagickEpsilon) || (fabs(affine.ty) >= MagickEpsilon)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1),p); continue; } /* Parse the primitive attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); i=0; mvg_info.offset=i; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; primitive_info[0].coordinates=0; primitive_info[0].method=FloodfillMethod; primitive_info[0].closed_subpath=MagickFalse; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; (void) GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; primitive_info[i].closed_subpath=MagickFalse; i++; mvg_info.offset=i; if (i < (ssize_t) number_points) continue; status&=CheckPrimitiveExtent(&mvg_info,number_points); } if (status == MagickFalse) break; if ((primitive_info[j].primitive == TextPrimitive) || (primitive_info[j].primitive == ImagePrimitive)) if (primitive_info[j].text != (char *) NULL) primitive_info[j].text=DestroyString(primitive_info[j].text); primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].closed_subpath=MagickFalse; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ coordinates=(double) primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { coordinates*=5.0; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); coordinates*=5.0; coordinates+=2.0*((size_t) ceil((double) MagickPI*radius))+6.0* BezierQuantum+360.0; break; } case BezierPrimitive: { coordinates=(double) (BezierQuantum*primitive_info[j].coordinates); if (primitive_info[j].coordinates > (107*BezierQuantum)) { (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); status=MagickFalse; break; } break; } case PathPrimitive: { char *s, *t; (void) GetNextToken(q,&q,extent,token); coordinates=1.0; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } coordinates++; } for (s=token; *s != '\0'; s++) if (strspn(s,"AaCcQqSsTt") != 0) coordinates+=(20.0*BezierQuantum)+360.0; break; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot(alpha,beta); coordinates=2.0*(ceil(MagickPI*radius))+6.0*BezierQuantum+360.0; break; } default: break; } if (coordinates > MaxBezierCoordinates) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"TooManyBezierCoordinates","`%s'",token); status=MagickFalse; } if (status == MagickFalse) break; if (((size_t) (i+coordinates)) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=coordinates+1; if (number_points < (size_t) coordinates) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } mvg_info.offset=i; status&=CheckPrimitiveExtent(&mvg_info,number_points); } status&=CheckPrimitiveExtent(&mvg_info,PrimitiveExtentPad); if (status == MagickFalse) break; mvg_info.offset=j; switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } status&=TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+2].point.x < 0.0) || (primitive_info[j+2].point.y < 0.0)) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x-primitive_info[j].point.x) < 0.0) { status=MagickFalse; break; } if ((primitive_info[j+1].point.y-primitive_info[j].point.y) < 0.0) { status=MagickFalse; break; } status&=TraceRoundRectangle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { primitive_type=UndefinedPrimitive; break; } status&=TraceArc(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x < 0.0) || (primitive_info[j+1].point.y < 0.0)) { status=MagickFalse; break; } status&=TraceEllipse(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceCircle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: { if (primitive_info[j].coordinates < 1) { status=MagickFalse; break; } break; } case PolygonPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; primitive_info[j].closed_subpath=MagickTrue; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } status&=TraceBezier(&mvg_info,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { coordinates=(double) TracePath(&mvg_info,token,exception); if (coordinates == 0.0) { status=MagickFalse; break; } i=(ssize_t) (j+coordinates); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) { status=MagickFalse; break; } primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { char geometry[MagickPathExtent]; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); /* Compute text cursor offset. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); if ((fabs(mvg_info.point.x-primitive_info->point.x) < MagickEpsilon) && (fabs(mvg_info.point.y-primitive_info->point.y) < MagickEpsilon)) { mvg_info.point=primitive_info->point; primitive_info->point.x+=cursor; } else { mvg_info.point=primitive_info->point; cursor=0.0; } (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); clone_info->render=MagickFalse; clone_info->text=AcquireString(token); status&=GetTypeMetrics(image,clone_info,&metrics,exception); clone_info=DestroyDrawInfo(clone_info); cursor+=metrics.width; if (graphic_context[n]->compliance != SVGCompliance) cursor=0.0; break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); break; } } mvg_info.offset=i; if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1), p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->compliance != SVGCompliance) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) { const char *clip_path; clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image,graphic_context[n]->clip_mask, clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ macros=DestroySplayTree(macros); token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) { for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); } primitive=DestroyString(primitive); if (stops != (StopInfo *) NULL) stops=(StopInfo *) RelinquishMagickMemory(stops); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { return(RenderMVGContent(image,draw_info,0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P a t t e r n P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPatternPath() draws a pattern. % % The format of the DrawPatternPath method is: % % MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info, % const char *name,Image **pattern,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the pattern name. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern, ExceptionInfo *exception) { char property[MagickPathExtent]; const char *geometry, *path, *type; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); assert(name != (const char *) NULL); (void) FormatLocaleString(property,MagickPathExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name); geometry=GetImageArtifact(image,property); if (geometry == (const char *) NULL) return(MagickFalse); if ((*pattern) != (Image *) NULL) *pattern=DestroyImage(*pattern); image_info=AcquireImageInfo(); image_info->size=AcquireString(geometry); *pattern=AcquireImage(image_info,exception); image_info=DestroyImageInfo(image_info); (void) QueryColorCompliance("#00000000",AllCompliance, &(*pattern)->background_color,exception); (void) SetImageBackgroundColor(*pattern,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), "begin pattern-path %s %s",name,geometry); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill_pattern=NewImageList(); clone_info->stroke_pattern=NewImageList(); (void) FormatLocaleString(property,MagickPathExtent,"%s-type",name); type=GetImageArtifact(image,property); if (type != (const char *) NULL) clone_info->gradient.type=(GradientType) ParseCommandOption( MagickGradientOptions,MagickFalse,type); (void) CloneString(&clone_info->primitive,path); status=RenderMVGContent(*pattern,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w P o l y g o n P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPolygonPrimitive() draws a polygon on the image. % % The format of the DrawPolygonPrimitive method is: % % MagickBooleanType DrawPolygonPrimitive(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info) { register ssize_t i; assert(polygon_info != (PolygonInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (polygon_info[i] != (PolygonInfo *) NULL) polygon_info[i]=DestroyPolygonInfo(polygon_info[i]); polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info); return(polygon_info); } static PolygonInfo **AcquirePolygonThreadSet( const PrimitiveInfo *primitive_info) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) return((PolygonInfo **) NULL); (void) memset(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(path_info); if (polygon_info[i] == (PolygonInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_alpha) { double alpha, beta, distance, subpath_alpha; PointInfo delta; register const PointInfo *q; register EdgeInfo *p; register ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_alpha=0.0; subpath_alpha=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,(size_t) j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta <= 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta >= alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=PerceptibleReciprocal(alpha); beta=delta.x*(y-q->y)-delta.y*(x-q->x); distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_alpha < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_alpha=1.0; else { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) *stroke_alpha=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) continue; if (distance <= 0.0) { subpath_alpha=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < MagickEpsilon) { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_alpha < (alpha*alpha)) subpath_alpha=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_alpha >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) (p->number_points-1); i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_alpha); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType fill, status; double mid; PolygonInfo **magick_restrict polygon_info; register EdgeInfo *p; register ssize_t i; SegmentInfo bounds; ssize_t start_y, stop_y, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates <= 1) return(MagickTrue); /* Compute bounding box. */ polygon_info=AcquirePolygonThreadSet(primitive_info); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); DisableMSCWarning(4127) if (0) { status=DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); if (status == MagickFalse) { polygon_info=DestroyPolygonThreadSet(polygon_info); return(status); } } RestoreMSCWarning if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon"); fill=(primitive_info->method == FillToBorderMethod) || (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse; mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0; bounds=polygon_info[0]->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++) { p=polygon_info[0]->edges+i; if (p->bounds.x1 < bounds.x1) bounds.x1=p->bounds.x1; if (p->bounds.y1 < bounds.y1) bounds.y1=p->bounds.y1; if (p->bounds.x2 > bounds.x2) bounds.x2=p->bounds.x2; if (p->bounds.y2 > bounds.y2) bounds.y2=p->bounds.y2; } bounds.x1-=(mid+1.0); bounds.y1-=(mid+1.0); bounds.x2+=(mid+1.0); bounds.y2+=(mid+1.0); if ((bounds.x1 >= (double) image->columns) || (bounds.y1 >= (double) image->rows) || (bounds.x2 <= 0.0) || (bounds.y2 <= 0.0)) { polygon_info=DestroyPolygonThreadSet(polygon_info); return(MagickTrue); /* virtual polygon */ } bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x1; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y1; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x2; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y2; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); x=start_x; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= stop_x; x++) { if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) ceil(primitive_info->point.y-0.5))) { GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=start_x; x <= stop_x; x++) { double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; /* Fill and/or stroke. */ fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule, x,y,&stroke_alpha); if (draw_info->stroke_antialias == MagickFalse) { fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0; } GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception); CompositePixelOver(image,&fill_color,fill_alpha*fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception); CompositePixelOver(image,&stroke_color,stroke_alpha*stroke_color.alpha,q, (double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image. % % The format of the DrawPrimitive method is: % % MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info, % PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static inline double ConstrainCoordinate(double x) { if (x < (double) -(SSIZE_MAX-512)) return((double) -(SSIZE_MAX-512)); if (x > (double) (SSIZE_MAX-512)) return((double) (SSIZE_MAX-512)); return(x); } static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, point, q; register ssize_t i, x; ssize_t coordinates, y; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); switch (primitive_info->primitive) { case AlphaPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ColorPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.20g,%.20g",(double) x,(double) y); return; } case PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case TextPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "TextPrimitive %.20g,%.20g",(double) x,(double) y); return; } default: break; } coordinates=0; p=primitive_info[0].point; q.x=(-1.0); q.y=(-1.0); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin open (%.20g)",(double) coordinates); p=point; } point=primitive_info[i].point; if ((fabs(q.x-point.x) >= MagickEpsilon) || (fabs(q.y-point.y) >= MagickEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y); else (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y); q=point; coordinates--; if (coordinates > 0) continue; if ((fabs(p.x-point.x) >= MagickEpsilon) || (fabs(p.y-point.y) >= MagickEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)", (double) coordinates); else (void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)", (double) coordinates); } } MagickExport MagickBooleanType DrawPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickStatusType status; register ssize_t i, x; ssize_t y; if (image->debug != MagickFalse) { (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-primitive"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx, draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy, draw_info->affine.tx,draw_info->affine.ty); } status=MagickTrue; if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) status=SetImageColorspace(image,sRGBColorspace,exception); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,draw_info->clipping_mask, exception); status&=SetImageMask(image,CompositePixelMask,draw_info->composite_mask, exception); } x=(ssize_t) ceil(ConstrainCoordinate(primitive_info->point.x-0.5)); y=(ssize_t) ceil(ConstrainCoordinate(primitive_info->point.y-0.5)); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } channel_mask=SetImageChannelMask(image,AlphaChannel); status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); (void) SetImageChannelMask(image,channel_mask); break; } case ResetMethod: { MagickBooleanType sync; PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetPixelInfo(image,&pixel); GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); break; } case ResetMethod: { MagickBooleanType sync; PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MagickPathExtent]; Image *composite_image, *composite_images; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); composite_images=(Image *) NULL; if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_images=ReadInlineImage(clone_info,primitive_info->text, exception); else if (*primitive_info->text != '\0') { (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); composite_images=ReadImage(clone_info,exception); } clone_info=DestroyImageInfo(clone_info); if (composite_images == (Image *) NULL) { status=0; break; } composite_image=RemoveFirstImageFromList(&composite_images); composite_images=DestroyImageList(composite_images); (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=(ssize_t) ceil(primitive_info[1].point.x-0.5); y1=(ssize_t) ceil(primitive_info[1].point.y-0.5); if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) || ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows))) { /* Resize image. */ (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; (void) TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) (void) SetImageAlpha(composite_image,draw_info->alpha,exception); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception); affine=draw_info->affine; affine.tx=(double) geometry.x; affine.ty=(double) geometry.y; composite_image->interpolate=image->interpolate; if ((draw_info->compose == OverCompositeOp) || (draw_info->compose == SrcOverCompositeOp)) (void) DrawAffineImage(image,composite_image,&affine,exception); else (void) CompositeImage(image,composite_image,draw_info->compose, MagickTrue,geometry.x,geometry.y,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; register Quantum *q; if ((y < 0) || (y >= (ssize_t) image->rows)) break; if ((x < 0) || (x >= (ssize_t) image->columns)) break; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&fill_color,exception); CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case TextPrimitive: { char geometry[MagickPathExtent]; DrawInfo *clone_info; if (primitive_info->text == (char *) NULL) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->text,primitive_info->text); (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status&=AnnotateImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); break; } default: { double mid, scale; DrawInfo *clone_info; if (IsEventLogging() != MagickFalse) LogPrimitiveInfo(primitive_info); scale=ExpandAffine(&draw_info->affine); if ((draw_info->dash_pattern != (double *) NULL) && (fabs(draw_info->dash_pattern[0]) >= MagickEpsilon) && (fabs(scale*draw_info->stroke_width) >= MagickEpsilon) && (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); status=DrawDashPolygon(draw_info,primitive_info,image,exception); break; } mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0; if ((mid > 1.0) && ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL))) { double x, y; MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ closed_path=primitive_info[0].closed_subpath; i=(ssize_t) primitive_info[0].coordinates; x=fabs(primitive_info[i-1].point.x-primitive_info[0].point.x); y=fabs(primitive_info[i-1].point.y-primitive_info[0].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) closed_path=MagickTrue; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { status=DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); break; } } image_view=DestroyCacheView(image_view); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,(Image *) NULL,exception); status&=SetImageMask(image,CompositePixelMask,(Image *) NULL,exception); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w S t r o k e P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on % the image while respecting the line cap and join attributes. % % The format of the DrawStrokePolygon method is: % % MagickBooleanType DrawStrokePolygon(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % */ static MagickBooleanType DrawRoundLinecap(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { PrimitiveInfo linecap[5]; register ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*MagickEpsilon; linecap[2].point.x+=2.0*MagickEpsilon; linecap[2].point.y+=2.0*MagickEpsilon; linecap[3].point.y+=2.0*MagickEpsilon; linecap[4].primitive=UndefinedPrimitive; return(DrawPolygonPrimitive(image,draw_info,linecap,exception)); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { DrawInfo *clone_info; MagickBooleanType closed_path; MagickStatusType status; PrimitiveInfo *stroke_polygon; register const PrimitiveInfo *p, *q; /* Draw stroked polygon. */ if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-stroke-polygon"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill=draw_info->stroke; if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { if (p->coordinates == 1) continue; stroke_polygon=TraceStrokePolygon(image,draw_info,p); if (stroke_polygon == (PrimitiveInfo *) NULL) { status=0; break; } status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception); stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); if (status == 0) break; q=p+p->coordinates-1; closed_path=p->closed_subpath; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { status&=DrawRoundLinecap(image,draw_info,p,exception); status&=DrawRoundLinecap(image,draw_info,q,exception); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A f f i n e M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAffineMatrix() returns an AffineMatrix initialized to the identity % matrix. % % The format of the GetAffineMatrix method is: % % void GetAffineMatrix(AffineMatrix *affine_matrix) % % A description of each parameter follows: % % o affine_matrix: the affine matrix. % */ MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(affine_matrix != (AffineMatrix *) NULL); (void) memset(affine_matrix,0,sizeof(*affine_matrix)); affine_matrix->sx=1.0; affine_matrix->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetDrawInfo() initializes draw_info to default values from image_info. % % The format of the GetDrawInfo method is: % % void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info.. % % o draw_info: the draw info. % */ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { char *next_token; const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) memset(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#FFF0",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_antialias=clone_info->antialias; draw_info->stroke_width=1.0; draw_info->fill_rule=EvenOddRule; draw_info->alpha=OpaqueAlpha; draw_info->fill_alpha=OpaqueAlpha; draw_info->stroke_alpha=OpaqueAlpha; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->clip_path=MagickFalse; draw_info->debug=IsEventLogging(); if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (fabs(clone_info->pointsize) >= MagickEpsilon) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r m u t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Permutate() returns the permuation of the (n,k). % % The format of the Permutate method is: % % void Permutate(ssize_t n,ssize_t k) % % A description of each parameter follows: % % o n: % % o k: % % */ static inline double Permutate(const ssize_t n,const ssize_t k) { double r; register ssize_t i; r=1.0; for (i=k+1; i <= n; i++) r*=i; for (i=1; i <= (n-k); i++) r/=i; return(r); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a c e P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TracePrimitive is a collection of methods for generating graphic % primitives such as arcs, ellipses, paths, etc. % */ static MagickBooleanType TraceArc(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radius; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radius.x=fabs(center.x-start.x); radius.y=fabs(center.y-start.y); return(TraceEllipse(mvg_info,center,radius,degrees)); } static MagickBooleanType TraceArcPath(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo arc,const double angle, const MagickBooleanType large_arc,const MagickBooleanType sweep) { double alpha, beta, delta, factor, gamma, theta; MagickStatusType status; PointInfo center, points[3], radii; register double cosine, sine; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i; size_t arc_segments; ssize_t offset; offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) return(TracePoint(primitive_info,end)); radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((radii.x < MagickEpsilon) || (radii.y < MagickEpsilon)) return(TraceLine(primitive_info,start,end)); cosine=cos(DegreesToRadians(fmod((double) angle,360.0))); sine=sin(DegreesToRadians(fmod((double) angle,360.0))); center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2); center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2); delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/ (radii.y*radii.y); if (delta < MagickEpsilon) return(TraceLine(primitive_info,start,end)); if (delta > 1.0) { radii.x*=sqrt((double) delta); radii.y*=sqrt((double) delta); } points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x); points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y); points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x); points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y); alpha=points[1].x-points[0].x; beta=points[1].y-points[0].y; if (fabs(alpha*alpha+beta*beta) < MagickEpsilon) return(TraceLine(primitive_info,start,end)); factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25; if (factor <= 0.0) factor=0.0; else { factor=sqrt((double) factor); if (sweep == large_arc) factor=(-factor); } center.x=(double) ((points[0].x+points[1].x)/2-factor*beta); center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha); alpha=atan2(points[0].y-center.y,points[0].x-center.x); theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha; if ((theta < 0.0) && (sweep != MagickFalse)) theta+=2.0*MagickPI; else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=2.0*MagickPI; arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+ MagickEpsilon)))); status=MagickTrue; p=primitive_info; for (i=0; i < (ssize_t) arc_segments; i++) { beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments)); gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))* sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/ sin(fmod((double) beta,DegreesToRadians(360.0))); points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x; p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y; (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y* points[0].y); (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y* points[0].y); (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y* points[1].y); (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y* points[1].y); (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y* points[2].y); (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y* points[2].y); if (i == (ssize_t) (arc_segments-1)) (p+3)->point=end; status&=TraceBezier(mvg_info,4); if (status == 0) break; p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; p+=p->coordinates; } if (status == 0) return(MagickFalse); mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } static MagickBooleanType TraceCircle(MVGInfo *mvg_info,const PointInfo start, const PointInfo end) { double alpha, beta, radius; PointInfo offset, degrees; alpha=end.x-start.x; beta=end.y-start.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; return(TraceEllipse(mvg_info,start,offset,degrees)); } static MagickBooleanType TraceEllipse(MVGInfo *mvg_info,const PointInfo center, const PointInfo radii,const PointInfo arc) { double coordinates, delta, step, x, y; PointInfo angle, point; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i; /* Ellipses are just short segmented polys. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(radii.x) < MagickEpsilon) || (fabs(radii.y) < MagickEpsilon)) return(MagickTrue); delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y)); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/4.0/(MagickPI*PerceptibleReciprocal(delta)/2.0); angle.x=DegreesToRadians(arc.x); y=arc.y; while (y < arc.x) y+=360.0; angle.y=DegreesToRadians(y); coordinates=ceil((angle.y-angle.x)/step+1.0); if (coordinates > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (CheckPrimitiveExtent(mvg_info,(size_t) coordinates) == MagickFalse) return(MagickFalse); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; x=fabs(primitive_info[0].point.x- primitive_info[primitive_info->coordinates-1].point.x); y=fabs(primitive_info[0].point.y- primitive_info[primitive_info->coordinates-1].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceLine(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { if (TracePoint(primitive_info,start) == MagickFalse) return(MagickFalse); if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return(MagickTrue); } if (TracePoint(primitive_info+1,end) == MagickFalse) return(MagickFalse); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; primitive_info->closed_subpath=MagickFalse; return(MagickTrue); } static size_t TracePath(MVGInfo *mvg_info,const char *path, ExceptionInfo *exception) { char *next_token, token[MagickPathExtent]; const char *p; double x, y; int attribute, last_attribute; MagickBooleanType status; PointInfo end = {0.0, 0.0}, points[4] = { {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} }, point = {0.0, 0.0}, start = {0.0, 0.0}; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register PrimitiveInfo *q; register ssize_t i; size_t number_coordinates, z_count; ssize_t subpath_offset; subpath_offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; status=MagickTrue; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { if (status == MagickFalse) break; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == '\0') break; last_attribute=attribute; attribute=(int) (*p++); switch (attribute) { case 'a': case 'A': { double angle = 0.0; MagickBooleanType large_arc = MagickFalse, sweep = MagickFalse; PointInfo arc = {0.0, 0.0}; /* Elliptical arc. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); if (TraceArcPath(mvg_info,point,end,arc,angle,large_arc,sweep) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'c': case 'C': { /* Cubic Bézier curve. */ do { points[0]=point; for (i=1; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'C' ? x : point.x+x); end.y=(double) (attribute == (int) 'C' ? y : point.y+y); points[i]=end; } for (i=0; i < 4; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,4) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { /* Move to. */ if (mvg_info->offset != subpath_offset) { primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; } i=0; do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'M' ? x : point.x+x); point.y=(double) (attribute == (int) 'M' ? y : point.y+y); if (i == 0) start=point; i++; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Quadratic Bézier curve. */ do { points[0]=point; for (i=1; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (*p == ',') p++; end.x=(double) (attribute == (int) 'Q' ? x : point.x+x); end.y=(double) (attribute == (int) 'Q' ? y : point.y+y); points[i]=end; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Cubic Bézier curve. */ do { points[0]=points[3]; points[1].x=2.0*points[3].x-points[2].x; points[1].y=2.0*points[3].y-points[2].y; for (i=2; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (*p == ',') p++; end.x=(double) (attribute == (int) 'S' ? x : point.x+x); end.y=(double) (attribute == (int) 'S' ? y : point.y+y); points[i]=end; } if (strchr("CcSs",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 4; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,4) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Quadratic Bézier curve. */ do { points[0]=points[2]; points[1].x=2.0*points[2].x-points[1].x; points[1].y=2.0*points[2].y-points[1].y; for (i=2; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (status == MagickFalse) break; if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { /* Close path. */ point=start; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); mvg_info->offset+=q->coordinates; q+=q->coordinates; primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); primitive_info->closed_subpath=MagickTrue; number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; z_count++; break; } default: { ThrowPointExpectedException(token,exception); break; } } } if (status == MagickFalse) return(0); primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { q--; q->primitive=primitive_type; if (z_count > 1) q->method=FillToBorderMethod; } q=primitive_info; return(number_coordinates); } static MagickBooleanType TraceRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { PointInfo point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=start.x; point.y=end.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,end) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=end.x; point.y=start.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceRoundRectangle(MVGInfo *mvg_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, point, segment; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i; ssize_t offset; offset=mvg_info->offset; segment.x=fabs(end.x-start.x); segment.y=fabs(end.y-start.y); if ((segment.x < MagickEpsilon) || (segment.y < MagickEpsilon)) { (*mvg_info->primitive_info+mvg_info->offset)->coordinates=0; return(MagickTrue); } if (arc.x > (0.5*segment.x)) arc.x=0.5*segment.x; if (arc.y > (0.5*segment.y)) arc.y=0.5*segment.y; point.x=start.x+segment.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+segment.x-arc.x; point.y=start.y+segment.y-arc.y; degrees.x=0.0; degrees.y=90.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+segment.y-arc.y; degrees.x=90.0; degrees.y=180.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(p,(*mvg_info->primitive_info+offset)->point) == MagickFalse) return(MagickFalse); p+=p->coordinates; mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; register double dx, dy; register ssize_t i; ssize_t j; dx=0.0; dy=0.0; for (i=1; i < (ssize_t) number_vertices; i++) { dx=primitive_info[0].point.x-primitive_info[i].point.x; dy=primitive_info[0].point.y-primitive_info[i].point.y; if ((fabs((double) dx) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) break; } if (i == (ssize_t) number_vertices) i=(ssize_t) number_vertices-1L; distance=hypot((double) dx,(double) dy); primitive_info[0].point.x=(double) (primitive_info[i].point.x+ dx*(distance+offset)/distance); primitive_info[0].point.y=(double) (primitive_info[i].point.y+ dy*(distance+offset)/distance); for (j=(ssize_t) number_vertices-2; j >= 0; j--) { dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x; dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y; if ((fabs((double) dx) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) break; } distance=hypot((double) dx,(double) dy); primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+ dx*(distance+offset)/distance); primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+ dy*(distance+offset)/distance); return(MagickTrue); } static PrimitiveInfo *TraceStrokePolygon(const Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { #define CheckPathExtent(pad) \ if ((ssize_t) (q+(pad)) >= (ssize_t) max_strokes) \ { \ if (~max_strokes < (pad)) \ { \ path_p=(PointInfo *) RelinquishMagickMemory(path_p); \ path_q=(PointInfo *) RelinquishMagickMemory(path_q); \ } \ else \ { \ max_strokes+=(pad); \ path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes, \ sizeof(*path_p)); \ path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes, \ sizeof(*path_q)); \ } \ if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) \ { \ if (path_p != (PointInfo *) NULL) \ path_p=(PointInfo *) RelinquishMagickMemory(path_p); \ if (path_q != (PointInfo *) NULL) \ path_q=(PointInfo *) RelinquishMagickMemory(path_q); \ polygon_primitive=(PrimitiveInfo *) \ RelinquishMagickMemory(polygon_primitive); \ return((PrimitiveInfo *) NULL); \ } \ } typedef struct _LineSegment { double p, q; } LineSegment; double delta_theta, dot_product, mid, miterlimit; LineSegment dx = {0,0}, dy = {0,0}, inverse_slope = {0,0}, slope = {0,0}, theta = {0,0}; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if (polygon_primitive == (PrimitiveInfo *) NULL) return((PrimitiveInfo *) NULL); (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices* sizeof(*polygon_primitive)); closed_path=primitive_info[0].closed_subpath; if (((draw_info->linejoin == RoundJoin) || (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse)) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) { if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse)) { /* Zero length subpath. */ stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory( sizeof(*stroke_polygon)); stroke_polygon[0]=polygon_primitive[0]; stroke_polygon[0].coordinates=0; polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } n=(ssize_t) number_vertices-1L; } path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); if (path_p == (PointInfo *) NULL) { polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return((PrimitiveInfo *) NULL); } path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); if (path_q == (PointInfo *) NULL) { path_p=(PointInfo *) RelinquishMagickMemory(path_p); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return((PrimitiveInfo *) NULL); } slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < MagickEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.p) < MagickEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0/slope.p); } mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) (void) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; path_q[p++]=box_q[0]; path_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=0.0; inverse_slope.q=0.0; if (fabs(dx.q) < MagickEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.q) < MagickEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.q=dy.q/dx.q; inverse_slope.q=(-1.0/slope.q); } offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < MagickEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } CheckPathExtent(6*BezierQuantum+360); dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); CheckPathExtent(arc_segments+6*BezierQuantum+360); path_q[q].x=box_q[1].x; path_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); CheckPathExtent(arc_segments+6*BezierQuantum+360); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } path_p[p++]=box_p[1]; path_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon != (PrimitiveInfo *) NULL) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }